typestar

List comprehensions in Erlang

Map and filter in one bracket; generators cross like a matrix.

%% A comprehension maps and filters in one bracket.
main(_) ->
    Lines = lists:seq(1, 10),

    Odd = [L || L <- Lines, L rem 2 =:= 1],
    io:format("Odd-numbered lines: ~p~n", [Odd]),

    Jacks = [{L, L * 100} || L <- Lines, L > 7],
    io:format("High jacks: ~p~n", [Jacks]),

    %% Two generators cross like a patch matrix.
    Patches = [{A, B} || A <- [1, 2], B <- [7, 8]],
    io:format("Possible patches: ~p~n", [Patches]).

How it works

  1. [L || L <- Lines, L rem 2 =:= 1] filters as it walks.
  2. The template builds tuples as easily as values.
  3. Two generators yield every combination.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
403
Tokens
133
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 133 seconds.

Type this snippet

Step 2 of 3 in Recursion & comprehensions, step 9 of 31 in Language basics.

← Previous Next →

List comprehensions in other languages