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
case State oftries each pattern arm in turn.{fault, Why}binds from inside the matched value.- The whole case answers a value bound to
Note.
Keywords and builtins used here
caseendformatmainofreport
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.
Step 3 of 4 in Pattern matching, step 6 of 31 in Language basics.