Higher-order functions

A higher-order function takes a fun as an argument or returns one. The lists lesson shows the list cell and the functions of the module; this lesson looks at the four that drive most Erlang code: map, filter, foldl and foreach. The funs lesson explains the value they receive.

lists:map

lists:map/2 applies a fun to every item and returns a new list of the same length. The input list is untouched, like every value in Erlang. The module below wraps the four functions in named functions and runs them from main/0:

higher.erl

-module(higher). -export([main/0, squares/1, evens/1, total/1]). squares(List) -> lists:map(fun(X) -> X * X end, List). evens(List) -> lists:filter(fun is_even/1, List). total(List) -> lists:foldl(fun(X, Acc) -> Acc + X end, 0, List). is_even(X) -> X rem 2 =:= 0. main() -> io:format("~p~n", [squares([1, 2, 3])]), io:format("~p~n", [evens([1, 2, 3, 4])]), io:format("~p~n", [total([1, 2, 3])]).

erlc higher.erl

erl -noshell -eval 'higher:main(), halt().'

[1,4,9] [2,4] 6

The fun in map takes one item and returns one result. A capture works too, which is how a named function is passed without an extra wrapper:

erl

1> 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"] 3> higher:squares([1, 2, 3]). [1,4,9]

lists:filter

lists:filter/2 keeps the items for which the fun answers true. Every other item drops out, and the result is a list of the same order, possibly shorter. The fun must answer a boolean: in Erlang there is no truthiness, so a fun that returns a number or an empty list is not a filter.

erl

1> lists:filter(fun(X) -> X > 1 end, [1, 2, 3]). [2,3] 2> lists:partition(fun(X) -> X rem 2 =:= 0 end, [1, 2, 3, 4]). {[2,4],[1,3]}

lists:partition/2 is the sibling of filter: it returns both the kept items and the dropped ones, which saves a second walk when a program needs both.

lists:foldl and foldr

A fold walks a list and carries one accumulator through every step. The fun receives the item first and the accumulator second, and returns the next accumulator. The starting value follows the fun. foldl walks from the left and foldr from the right, which matters whenever the operation is not commutative:

pipeline.erl

-module(pipeline). -export([main/0]). main() -> Numbers = [1, 2, 3, 4, 5], Squares = lists:map(fun(X) -> X * X end, Numbers), Even = lists:filter(fun(X) -> X rem 2 =:= 0 end, Squares), io:format("~p~n", [Even]), io:format("~p~n", [lists:foldl(fun(X, Acc) -> [X | Acc] end, [], Numbers)]), io:format("~p~n", [lists:foldr(fun(X, Acc) -> [X | Acc] end, [], Numbers)]).

erlc pipeline.erl

erl -noshell -eval 'pipeline:main(), halt().'

[4,16] [5,4,3,2,1] [1,2,3,4,5]

The same fun reverses the list on the left and keeps it on the right. A sum cannot tell the two apart, which is why the sum is the wrong example to learn the difference from. The run also shows the pipeline: map squares every number, then filter keeps the even squares, and each step feeds the next. The list comprehensions lesson writes the same chain as one expression.

lists:foreach

lists:foreach/2 runs a fun for every item and answers the atom ok. It is for side effects only: printing, logging, sending a message. The mistake is to use it when the results are needed, because it throws them away:

foreach_mistake.erl

-module(foreach_mistake). -export([main/0]). main() -> Result = lists:foreach(fun(X) -> X * 2 end, [1, 2, 3]), io:format("~p~n", [Result]).

erlc foreach_mistake.erl

erl -noshell -eval 'foreach_mistake:main(), halt().'

ok

The program computes three doubled numbers and prints ok; the numbers are gone. The fun ran, and the value it returned was discarded by design. When the results are wanted, the function is lists:map/2, and a whole program that prints and keeps its values writes lists:foreach(fun(X) -> io:format("~p~n", [X]) end, List) for the printing and lists:map/2 for the list.

A pipeline

Every function of the module takes the list as its last argument, which is what lets a chain feed one result into the next. A reader coming from a language where the list is the receiver writes lists:map(List, Fun); that compiles, because both are terms, and fails at run time with a function_clause that names the list module. The habit to build is the other order: the fun first and the data last.

A pipeline of three passes over a long list walks it three times. When a measurement says that walk costs time, a list comprehension or one foldl that does the work in one pass is the replacement; the performance lesson shows how to measure before changing anything.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does lists:map/2 return?

    Answer

    A new list with the fun applied to every item

    map builds a new list of the same length, one result per item, and leaves the input untouched.

  2. What does lists:map(fun atom_to_list/1, [a, b]) return?

    Answer

    ["a","b"]

    The captured atom_to_list/1 turns each atom into a string, so the result is a list of two strings.

  3. Which items does lists:filter(fun(X) -> X > 1 end, [1, 2, 3]) keep?

    Answer

    [2,3]

    filter keeps the items for which the fun answers true, and 2 and 3 are greater than 1.

  4. What does the fun passed to lists:foldl/3 receive?

    Answer

    The item and the accumulator

    A fold walks the list and threads a value through the fun: item first, accumulator second.

  5. What does this module print? -module(q1). -export([main/0]). main() -> Numbers = [1, 2, 3, 4], Squares = lists:map(fun(X) -> X * X end, Numbers), io:format("~p~n", [lists:filter(fun(X) -> X > 5 end, Squares)]).

    Answer

    [9,16]

    The squares are [1,4,9,16], and only 9 and 16 are greater than 5.

  6. What does this module print? -module(q2). -export([main/0]). main() -> R = lists:foldl(fun(X, Acc) -> [X | Acc] end, [], [1, 2, 3]), io:format("~p~n", [R]).

    Answer

    [3,2,1]

    Each item is put in front of the accumulator, so the last item ends up first.

  7. What does this module print? -module(q3). -export([main/0]). main() -> R = lists:foldr(fun(X, Acc) -> [X | Acc] end, [], [1, 2, 3]), io:format("~p~n", [R]).

    Answer

    [1,2,3]

    foldr walks from the right, and each item is put in front, which rebuilds the original order.

  8. What does this module print? -module(q4). -export([main/0]). main() -> Result = lists:foreach(fun(X) -> X * 2 end, [1, 2, 3]), io:format("~p~n", [Result]).

    Answer

    ok

    foreach runs the fun for its side effect and answers ok; the doubled values are discarded.

  9. What does lists:foreach/2 answer?

    Answer

    The atom ok

    foreach is for side effects; it discards the results and answers ok.

  10. In lists:map/2, which argument is the list?

    Answer

    The second and last one

    The standard library puts the data last, so a list is the final argument of map, filter and the folds.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Автор статьи: Arthur Isaev