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. If the guard evaluates to true
, we say that the evaluation succeeded; otherwise, it fails.
A guard expressions is a subset of all valid Erlang expressions. The reason for restricting guard expressions to a subset of Erlang expressions is that it must be guaranteed that evaluating a guard expression is free from side effects. This means that guards cannot be user-defined boolean functions.
The following syntactic forms are legal in a guard expression:
true
==
, /=
, =<
, <
, >=
, >
, =:=
, =/=
).
+
, -
, *
, /
, div
, rem
, bnot
, band
, bor
, bxor
, bsl
, bsr
).
not
, and
, or
, xor
).
andalso
, orelse
).
Joe Armstrong.
Programming Erlang: Software for a Concurrent World.
Pragmatic Bookshelf, 2007.
ISBN: 193435600X.
pp. 65-66.