Function-head matching in Erlang
One function, several clauses: the head does the branching.
%% One function, several clauses: the head does the branching.
describe({call, Line, _}) ->
io_lib:format("line ~p connected", [Line]);
describe({busy, Line}) ->
io_lib:format("line ~p engaged", [Line]);
describe({fault, Line, Why}) ->
io_lib:format("line ~p down: ~s", [Line, Why]).
main(_) ->
Events = [{call, 3, "5560199"}, {busy, 7},
{fault, 12, "wet pair"}],
[io:format("~s~n", [describe(E)]) || E <- Events].
How it works
- Each
describeclause matches a different event shape. - Clauses try top to bottom; the first match wins.
io_lib:formatbuilds the string for the caller to print.
Keywords and builtins used here
describeformatmain
The run, in numbers
- Lines
- 12
- Characters to type
- 415
- Tokens
- 144
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 144 seconds.
Step 1 of 4 in Pattern matching, step 4 of 31 in Language basics.