Higher-order functions
| lists:map | |
| lists:filter | |
| lists:foldl | |
| lists:foreach |
lists:map
The map function applies a fun to every item and returns the list of results. The input list is untouched.
lists:map(fun(X) -> X * 2 end, [1, 2, 3]).
[2,4,6]
2> lists:map(fun atom_to_list/1, [a, b]).
<<"a","b">>
lists:filter
The filter function keeps the items where the fun answers true. The rest drop away.
lists:filter(fun(X) -> X > 1 end, [1, 2, 3]).
[2,3]
2> lists:filter(fun(S) -> length(S) < 4 end, ["hi", "there"]).
<<"hi">>
lists:foldl
The foldl function walks a list and carries one accumulator through every step. Your fun takes the item and the accumulator, and returns the next accumulator.
lists:foldl(fun(X, Acc) -> Acc + X end, 0, [1, 2, 3]).
6
2> lists:foldl(fun(X, Max) -> max(X, Max) end, 0, [3, 1, 2]).
3
lists:foreach
The foreach function runs a fun for every item and answers the atom ok. Use it for side effects only: printing, logging, sending.
lists:foreach(fun(X) -> io:format("~p~n", [X]) end, [1, 2]).
1
2
ok
Next: Keyword lists
Article author: Arthur Isaev