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.

Illustration for Erlang
Lesson 1 is on the house.

[Expr || Pattern <- List, Filter] maps and filters in one: [X * X || X <- L, X rem 2 =:= 0].

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]).
Match this when you type.

Quiz

What does [V || {ok, V} <- R] do with {error, bad}?

Quiz

How many pairs does [{X, Y} || X <- [1,2], Y <- [a,b]] produce?

Quiz

Which arrow draws from a binary?

Quiz

What does << <<(B + 1)>> || <<B>> <= <<"HAL">> >> give?

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.