Conditions: case and if
| case of | |
| Arrows and bodies | |
| if | |
| The true branch |
case of
The case expression matches its value against patterns, one arrow at a time. The first pattern that matches runs its body.
Patterns are the same ones you used in lesson 5, so literals, variables, and tuples all work here.
case 2 of
1 -> one;
2 -> two;
_ -> other
end.
two
Arrows and bodies
Each branch is a pattern, the arrow, and a body expression. Semicolons separate branches, and the last branch has no semicolon.
The body may be any expression, including a begin block of several lines when the work needs more room.
case Status of
ok -> handle(Data);
{error, Why} -> log(Why)
end.
if
The if expression tests guard sequences instead of patterns. It fits simple value tests, and case fits shape tests.
Both select the first branch that holds, so order matters when branches overlap.
if
2 > 3 -> big;
2 < 3 -> small;
true -> equal
end.
The true branch
Every case and if needs a catch-all. When no branch matches, the runtime raises a case_clause or if_clause error with the failing value attached.
The catch-all is the pattern _ or the guard true. Make it the last line of every conditional you write.
case X of
special -> ...;
_ -> io:format("unexpected: ~p~n", [X])
end.
Next: Recursion replaces loops
Article author: Arthur Isaev