Accumulators

Often we want to return two lists from a function. For example, we might want to write a function that splits a list of integers into two lists that contain the even and odd integers in the original list. Here’s one way of doing it:

lib_misc.erl
 
odds_and_evens1(L) ->
 
Odds = [X || X <- L, (X rem 2) =:= 1],
 
Evens = [X || X <- L, (X rem 2) =:= 0],
 
{Odds, Evens}.
 
5> lib_misc:odds_and_evens1([1,2,3,4,5,6]).
 
{[1,3,5],[2,4,6]}

The problem with this code is that we traverse the list twice—this doesn’t matter when the list is short, but if the list is very long, it might be a problem.

To avoid traversing the list twice, we can re-code this as follows:

lib_misc.erl
 
odds_and_evens2(L) ->
 
odds_and_evens_acc(L, [], []).
 
 
odds_and_evens_acc([H|T], ...

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.