Concurrent programming in Erlang

3.5. Functional Arguments

Passing the names of functions as arguments to other functions provides a useful method for abstracting the behaviour of a particular function. This section gives two examples of this programming technique.

3.5.1. map

The function map(Func, List) returns a list L where every element in L is obtained by applying the function Func to the corresponding element in List.

map(Func, [H|T]) ->
    [apply(F, [H])|map(Func, T)];
map(Func, []) ->
    [].

> lists:map({math,factorial}, [1,2,3,4,5,6,7,8]).
[1,2,6,24,120,720,5040,40320]

3.5.2. filter

The function filter(Pred, List) filters the elements in List, retaining only those elements for which Pred is true. Here Pred is a function which returns either true or false.

filter(Pred, [H|T]) ->
    case apply(Pred,[H]) of
        true ->
            [H|filter(Pred, T)];
        false ->
            filter(Pred, T)
    end;
filter(Pred, []) ->
    [].

Assume that math:even/1 returns true if its argument is even, otherwise false.

> lists:filter({math,even}, [1,2,3,4,5,6,7,8,9,10]).
[2,4,6,8,10]