case and if Expressions
So far, we’ve used pattern matching for everything. This makes Erlang code small and consistent. But sometimes defining lots of separate function clauses is inconvenient. When this happens, we can use case or if expressions.
case Expressions
case has the following syntax:
| case Expression of |
| Pattern1 [when Guard1] -> Expr_seq1; |
| Pattern2 [when Guard2] -> Expr_seq2; |
| ... |
| end |
case is evaluated as follows: First,
Expression
is evaluated; assume this evaluates to
Value.
Thereafter, Value
is matched in turn
against Pattern1
(with the optional guard
Guard1
), Pattern2
, and so on, until a match is found. As soon as a match is found, then the corresponding expression sequence is evaluated—the result of evaluating ...
Get Programming Erlang, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.