typestar

Sorting in Erlang

sort takes a fun; keysort orders tagged tuples by position.

%% sort takes a fun; keysort orders tagged tuples by position.
main(_) ->
    Calls = [{"5560199", 12}, {"5560142", 3}, {"5560170", 21}],

    ByLength = lists:sort(fun({_, A}, {_, B}) -> A >= B end, Calls),
    io:format("Longest first: ~p~n", [hd(ByLength)]),

    ByNumber = lists:keysort(1, Calls),
    [io:format("~s held ~p min~n", [N, M]) || {N, M} <- ByNumber],

    io:format("Reversed: ~p~n",
              [lists:reverse(lists:sort([3, 1, 2]))]).

How it works

  1. The two-argument sort fun answers true to keep the order.
  2. lists:keysort(1, Calls) sorts by the first element.
  3. reverse flips an already-sorted list cheaply.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
419
Tokens
157
Three-star pace
60 tpm

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

Type this snippet

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

← Previous Next →

Sorting in other languages