typestar

case in Erlang

Match a value against patterns, in order, as an expression.

%% case matches a value against patterns, in order, as an expression.
main(_) ->
    Board = [{3, idle}, {7, ringing}, {12, {fault, "wet pair"}}],
    [report(Line, State) || {Line, State} <- Board],
    ok.

report(Line, State) ->
    Note = case State of
        idle -> "free for traffic";
        ringing -> "attend now";
        {fault, Why} -> "out of service: " ++ Why;
        _ -> "unknown"
    end,
    io:format("Line ~p: ~s~n", [Line, Note]).

How it works

  1. case State of tries each pattern arm in turn.
  2. {fault, Why} binds from inside the matched value.
  3. The whole case answers a value bound to Note.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
398
Tokens
123
Three-star pace
65 tpm

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

Type this snippet

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

← Previous Next →

case in other languages