← Back to lesson 14: Solve a list twice

Solve a list twice: full examples and further reading

The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.

Compare explicit recursion with `lists:foldl/3`.

Sum [1,2,3,4] with a recursive fun and with a fold.

Run this first

Run it once, change one input, and compare the new result.

Original full example
%% 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}.

Steps for the full example

  1. Read fun Sum([]) ->: Stop at the empty list.
  2. Read Sum([Head | Tail]): Handle one item and recurse on the tail.
  3. Read lists:foldl/3: Combine a list into one accumulator.

Original lesson notes

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.

Symbols and terms
fun Sum([]) ->
Stop at the empty list.
Sum([Head | Tail])
Handle one item and recurse on the tail.
lists:foldl/3
Combine a list into one accumulator.
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.

Original full exercise

Multiply [2,3,4] with lists:foldl/3.

Exercise starter
lists:foldl(fun(Number, Acc) -> ____ end, ____, [2,3,4]).

Return 24.

Show hint

Multiply Number by Acc and start at 1.

Show original answer
Reference answer
lists:foldl(fun(Number, Acc) -> Number * Acc end, 1, [2,3,4]).
What stops the recursive fun?

Its Loop([]) -> 0 clause returns without another call.

Original lesson takeaways
Design trade-offs and language comparisons
Original course references