Guards add conditions to pattern matches with
when. They work in function heads, case, fn
and comprehensions.
Together, function clauses and guards replace most
if chains. Here is a function that handles an
HTTP-style result, written with if. x in 200..299
checks that x is in the range, both ends included:
Same answers, but the clause version reads
differently. The if version takes the value apart
by hand (elem/2, .status), and you find the
cases by tracing the nesting. The clause version
lists every case flat, with its shape visible.
Handling redirects is one more clause, not another
level of nesting.
Clauses also fail loudly on input nobody planned
for. The if version quietly sends it down the
else branch and returns a wrong answer:
{:error, 3}
no function clause matching in WithClauses.handle/1
if is still the right tool for a single yes/no
question about a value you already have, like
if temp > 30. Reach for clauses when you are
checking the shape of the data as well.
Guards can also check types, so one function
handles each kind of input in its own clause.
Only a fixed set of expressions is allowed in guards:
comparisons, boolean operators, arithmetic, type
checks (is_*) and a few functions like
length/1, map_size/1, elem/2, is_map_key/2.
Pitfall: you can't call your own functions in a
guard (when valid?(x) is a compile error). Use
defguard, or match first and check in the body.
Pitfall: an error anywhere in a guard fails the
whole guard. when map_size(x) == 0 or is_list(x)
does not match a list, because map_size/1 raises
first. Chain when clauses instead (when map_size(x) == 0 when is_list(x)): each one is
tried on its own.