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 `Enum.reduce/3`.
Sum [1, 2, 3, 4] with recursion and with a fold, then compare both totals.
Run this first
Run it once, change one input, and compare the new result.
Original full example
# Compare recursion with a library fold
defmodule Totals do
def sum([]), do: 0
def sum([head | tail]), do: head + sum(tail)
end
numbers = [1, 2, 3, 4]
{Totals.sum(numbers), Enum.reduce(numbers, 0, fn n, acc -> n + acc end)}Both paths return 10, so the result is {10, 10}.
Steps for the full example
- Read
sum([]): Stop at an empty list. - Read
sum([head | tail]): Handle one item and the remaining list. - Read
Enum.reduce/3: Fold values into one accumulator.
Original lesson notes
Run the example first. Predict one result, then change one input and run it again.
A recursive function needs a clause that returns without calling itself.
The recursive clause handles one piece and calls itself with a smaller input.
Symbols and terms
sum([])- Stop at an empty list.
sum([head | tail])- Handle one item and the remaining list.
Enum.reduce/3- Fold values into one accumulator.
- base clause
- A recursive function needs a clause that returns without calling itself.
- recursive clause
- The recursive clause handles one piece and calls itself with a smaller input.
- fold
Enum.reduce/3carries an accumulator through a collection.
Original full exercise
Multiply [2, 3, 4] with Enum.reduce/3.
Exercise starter
Enum.reduce([2, 3, 4], ____, fn number, acc -> ____ end)Return 24.
Show hint
Start the accumulator at 1 and multiply it by each number.
Show original answer
Reference answer
Enum.reduce([2, 3, 4], 1, fn number, acc -> number * acc end)What stops Totals.sum/1?
The sum([]) clause returns 0 without another call.
Original lesson takeaways
- Every recursion needs a stopping clause.
- Make recursive input smaller.
- Prefer clear Enum functions for common collection work.