Erlang basics · Lesson 14 (open contents)
Solve a list twice
Compare explicit recursion with `lists:foldl/3`.
Run this first
Run it once, change one input, and compare the new result.
%% Compare recursion with a library fold
Sum = fun Loop([]) -> 0; Loop([Head | Tail]) -> Head + Loop(Tail) end,
Numbers = [1,2,3,4],
{Sum(Numbers), lists:foldl(fun(Number, Acc) -> Number + Acc end, 0, Numbers)}.- Both paths return 10, so the tuple is
{10,10}.
Read from the first line down
- Read
fun Sum([]) ->: Stop at the empty list. - Read
Sum([Head | Tail]): Handle one item and recurse on the tail. - Read
lists:foldl/3: Combine a list into one accumulator.
Symbols are not secret signs
fun Sum([]) ->Stop at the empty list.
Sum([Head | Tail])Handle one item and recurse on the tail.
lists:foldl/3Combine a list into one accumulator.
Match each name to its meaning
base clause
A recursive function stops by matching an input such as the empty list.
recursive clause
The recursive clause handles one item and calls itself with a shorter tail.
fold
lists:foldl/3 carries an accumulator from left to right.
Why these forms are useful
Run the example first. Predict one result, then change one input and run it again.
A recursive function stops by matching an input such as the empty list.
The recursive clause handles one item and calls itself with a shorter tail.
Close the answer and try
Multiply [2,3,4] with lists:foldl/3.
lists:foldl(fun(Number, Acc) -> ____ end, ____, [2,3,4]).Target result: Return 24.
Stuck? Read one hint
Multiply Number by Acc and start at 1.
After you run it, see one answer
lists:foldl(fun(Number, Acc) -> Number * Acc end, 1, [2,3,4]).Think about it: What stops the recursive fun?
Its Loop([]) -> 0 clause returns without another call.
Remember these three lines
- 1
Every recursion needs a base clause.
- 2
Make each recursive input smaller.
- 3
Use standard list folds for common accumulation.