September 2013
Intermediate to advanced
548 pages
12h 25m
English
Now that we’ve introduced funs, we can get back to writing
sum and map, which we’ll need for our
improved version of total (which I’m sure you haven’t
forgotten about!).
We’ll start with sum, which computes the sum of the
elements in a list.
| mylists.erl | |
| ① | sum([H|T]) -> H + sum(T); |
| ② | sum([]) -> 0. |
Note that the order of the two clauses in sum is
unimportant. This is because the first clause matches a nonempty
list and the second an empty list, and these two cases are mutually
exclusive. We can test sum as follows:
| | 1> c(mylists). %% <-- Last time I do this |
| | {ok, mylists} |
| | 2> L = [1,3,10]. |
| | [1,3,10] |
| | 3> mylists:sum(L). |
| | 14 |
Line 1 compiled the module mylists. From now on, I’ll often omit the command to compile ...
Read now
Unlock full access