typestar

The lists module in Erlang

map, filter, foldl, sort: the daily kit.

%% The lists module: map, filter, foldl, sort -- the daily kit.
main(_) ->
    Durations = [12, 3, 21, 8, 15],

    Billed = lists:map(fun(M) -> M * 4 end, Durations),
    io:format("Pence per call: ~p~n", [Billed]),

    Long = lists:filter(fun(M) -> M > 10 end, Durations),
    io:format("Long calls: ~p~n", [Long]),

    Total = lists:foldl(fun(M, Acc) -> Acc + M end, 0, Durations),
    io:format("Minutes total: ~p~n", [Total]),

    io:format("Sorted: ~p~n", [lists:sort(Durations)]),
    io:format("Longest: ~p~n", [lists:max(Durations)]).

How it works

  1. lists:map and filter take funs written inline.
  2. foldl threads an accumulator left to right.
  3. sort, max, and sum answer the common questions.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
510
Tokens
170
Three-star pace
60 tpm

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

Type this snippet

Step 1 of 4 in The lists module, step 11 of 31 in Language basics.

← Previous Next →