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 ...

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.