typestar

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

  1. Each describe clause matches a different event shape.
  2. Clauses try top to bottom; the first match wins.
  3. io_lib:format builds the string for the caller to print.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 4 in Pattern matching, step 4 of 31 in Language basics.

← Previous Next →