[Expr || Pattern <- List, Filter] maps and filters in one: [X * X || X <- L, X rem 2 =:= 0].
Erlang Easy · Lesson 1 · On the house
List comprehensions
Generators, filters, multiple generators, pattern filters, and binary comprehensions. Lesson 1 is free — on the house.
Lessons · Erlang Easy · Lesson 1 of 10 · On the house
List comprehensions
Generators, filters, multiple generators, pattern filters, and binary comprehensions.

Multiple generators nest left to right: [{X, Y} || X <- [1, 2], Y <- [a, b]] gives four pairs.
A generator pattern acts as a filter: [V || {ok, V} <- Results] silently skips non-matching elements.
Binary generators use <=: [B || <<B>> <= <<1, 2, 3>>]. Build a binary with << <<(B * 2)>> || <<B>> <= Bin >>.
Comprehensions are expressions; keep them short and move complex logic into named functions.
comprehensions
main(_) ->
L = lists:seq(1, 8),
io:format("~p~n", [[X * X || X <- L, X rem 2 =:= 0]]),
io:format("~p~n", [[{X, Y} || X <- [1, 2], Y <- [a, b]]]),
Results = [{ok, 1}, {error, bad}, {ok, 3}],
io:format("~p~n", [[V || {ok, V} <- Results]]),
io:format("~p~n", [[B || <<B>> <= <<10, 20, 30>>]]),
io:format("~p~n", [<< <<(B + 1)>> || <<B>> <= <<"HAL">> >>]),
Triples = [{A, B, C} || C <- lists:seq(1, 20), B <- lists:seq(1, C), A <- lists:seq(1, B), A*A + B*B =:= C*C],
io:format("~p~n", [Triples]).
Quiz
Quiz
Quiz
Quiz
Check
Match the still for: List comprehensions.
Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.