Guards
Guards are constructs that we can use to increase the power of
pattern matching. Using guards, we can perform simple tests and
comparisons on the variables in a pattern. Suppose we want to write
a function max(X, Y) that computes the max of X and
Y. We can write this using a guard as follows:
| | max(X, Y) when X > Y -> X; |
| | max(X, Y) -> Y. |
The first clause matches when X is greater than
Y and the result is X.
If the first clause doesn’t match, then the second clause is
tried. The second clause always returns the second argument
Y. Y must be greater than or equal to X;
otherwise, the first clause would have matched.
You can use guards in the heads of function definitions where they are introduced by the when keyword, or you can use them ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access