List comprehensions

A list comprehension builds a list from the items of another: an expression, a bar, a generator and any number of filters. It is the shortest form of map and filter in Erlang, and it reads from left to right like the sentence it describes: the squares of the even numbers of this list.

A generator

[Expression || Pattern <- List] runs the expression once for each item that the pattern matches. The generator X <- [1, 2, 3] binds X to each item in turn:

erl

1> [X * 2 || X <- [1, 2, 3]]. [2,4,6] 2> [X || X <- "abc"]. "abc" 3> [{X, X * X} || X <- lists:seq(1, 3)]. [{1,1},{2,4},{3,9}]

The second line is not a special string form: a string is a list of codes, so the comprehension walks the codes and returns the same list. The third shows that the expression may build any term, here a tuple per item.

A filter

After the generator, a comma and a boolean expression keep only the items for which it is true. This module squares every number and keeps the even ones with two comprehensions:

comprehension.erl

-module(comprehension). -export([main/0, squares/1, evens/1]). squares(Numbers) -> [Number * Number || Number <- Numbers]. evens(Numbers) -> [Number || Number <- Numbers, Number rem 2 =:= 0]. main() -> io:format("~p~n", [squares([1, 2, 3, 4])]), io:format("~p~n", [evens([1, 2, 3, 4])]).

erlc comprehension.erl

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

[1,4,9,16] [2,4]

The filter is an ordinary expression, not a guard: it may call a local function or use andalso. The comprehension keeps the input order, so the rebuilt list is in the same sequence as the source.

More than one generator

A second generator runs for every item of the first, which is a cartesian product. The later generator may depend on the earlier one, which is how a triangle is written without a nested loop:

erl

1> [{X, Y} || X <- [1, 2], Y <- [a, b]]. [{1,a},{1,b},{2,a},{2,b}] 2> [{X, Y} || X <- [1, 2, 3], Y <- [1, 2, 3], X < Y]. [{1,2},{1,3},{2,3}]

The order is the order of the generators: the first one is the outer loop. This module writes the pairs out as a program that prints them:

pairs.erl

-module(pairs). -export([main/0]). main() -> Pairs = [{X, Y} || X <- [1, 2], Y <- [a, b]], io:format("~p~n", [Pairs]).

erlc pairs.erl

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

[{1,a},{1,b},{2,a},{2,b}]

A binary generator

The same syntax walks a binary when the generator uses a binary pattern and <=. The expression may build a list or a new binary, and the bit syntax of the bit syntax lesson decides the shape of the result:

erl

1> [C || <<C>> <= <<"hi">>]. "hi" 2> << <<(C + 1)>> || <<C>> <= <<"hi">> >>. <<"ij">> 3> [C - 64 || <<C>> <= <<"ABC">>]. [1,2,3]

Inside the bit syntax a comprehension is written between double angle brackets, so a binary comprehension has four of them together. The third line turns letters into alphabet positions, which is the same walk the binaries in depth lesson writes as a recursive function.

The pattern that does not match

A generator's pattern may be more specific than the list. An item that does not match is skipped without an error, which is either the feature you want or a silent bug:

erl

1> [{K, V} || {K, V} <- [{a, 1}, b, {c, 3}]]. [{a,1},{c,3}] 2> [K || {K, _} <- [{a, 1}, b, {c, 3}]]. [a,c]

The atom b fits neither pattern and disappears. A function that must reject a wrong shape needs a clause or a case instead of a comprehension, so the error is reported. The next program keeps only the people with a passing score, and it depends on every item being a pair:

winners.erl

-module(winners). -export([main/0, winners/1]). winners(People) -> [Name || {Name, Score} <- People, Score >= 90]. main() -> People = [{ada, 95}, {grace, 88}, {alan, 91}], io:format("~p~n", [winners(People)]).

erlc winners.erl

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

[ada,alan]

[ada,alan] prints without quotes because both are atoms. The comprehension is the same map and filter that lists:map/2 and lists:filter/2 do, and the lists lesson shows the functions when a comprehension would need a named helper.

Questions

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

  1. What does the generator X <- [1, 2, 3] do?

    Answer

    Binds X to each item in turn

    A generator walks the list and binds its pattern to one item per step.

  2. What separates a generator from a filter?

    Answer

    A comma

    Generators and filters are separated by commas inside the brackets.

  3. What does [X * 2 || X <- [1, 2, 3]] return?

    Answer

    [2,4,6]

    The expression doubles each item and keeps the input order.

  4. What does a second generator add?

    Answer

    A cartesian product over both lists

    The second generator runs once per item of the first, so the result is every pair.

  5. Which operator walks a binary in a comprehension?

    Answer

    <=

    A binary generator uses <=, as in [C || <<C>> <= Bin].

  6. An item of the list does not match the generator pattern. What happens?

    Answer

    The item is skipped without an error

    A non-matching item is dropped silently, which is useful for filtering tuples and dangerous for validation.

  7. What does this module print? -module(q4). -export([main/0]). main() -> Pairs = [{X, Y} || X <- [1, 2], Y <- [1, 2], X < Y], io:format("~p~n", [Pairs]).

    Answer

    [{1,2}]

    The filter keeps only the pairs where the first number is smaller, which leaves {1,2}.

  8. What does this module print? -module(q1). -export([main/0]). main() -> io:format("~p~n", [[X || X <- [1, 2, 3, 4], X rem 2 =:= 0]]).

    Answer

    [2,4]

    The filter keeps the even numbers, which are 2 and 4.

  9. What does this module print? -module(q2). -export([main/0]). main() -> io:format("~p~n", [[C - 64 || <<C>> <= <<"AB">>]]).

    Answer

    [1,2]

    The codes of A and B are 65 and 66, and the expression subtracts 64 from each.

  10. What does this module print? -module(q3). -export([main/0]). main() -> io:format("~p~n", [[{K, V} || {K, V} <- [{a, 1}, b, {c, 3}]]]).

    Answer

    [{a,1},{c,3}]

    The atom b does not match the tuple pattern and is skipped without an error.

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