September 2013
Intermediate to advanced
548 pages
12h 25m
English
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], ... |
Read now
Unlock full access