Simple List Processing

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 ...

Get Programming Erlang, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.