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
- The two-argument sort fun answers true to keep the order.
lists:keysort(1, Calls)sorts by the first element.reverseflips an already-sorted list cheaply.
Keywords and builtins used here
endformatfunhdkeysortmainreversesort
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.
Step 4 of 4 in The lists module, step 14 of 31 in Language basics.