October 2014
Intermediate to advanced
280 pages
7h 20m
English
So far you’ve seen how to process each element in a list, but what if we want to sum all of the elements? The difference here is that we need to remember the partial sum as we process each element in turn.
In terms of a recursive structure, it’s easy:
sum([]) → 0
sum([ head |tail ]) → total + sum(tail)
But the basic scheme gives us nowhere to record the total as we go along. Remember that one of our goals is to have immutable state, so we can’t keep the value in a global or module-local variable.
But we can pass the state in a function’s parameter.
| lists/sum.exs | |
| | defmodule MyList do |
| | def sum([], total), do: total |
| | def sum([ head | tail ], total), do: sum(tail, head+total) |
| | end |
Our sum
Read now
Unlock full access