When patterns aren't enough for matching
So far, we have seen pattern matching very basically in our functions and assignment (reading binding) expressions. However, there's more that can be done when doing pattern matches, particularly when defining functions. When a simple type decomposition pattern isn't enough, we can use guards to add an extra layer to our matches.
Guards are simply boolean expressions we can add to our function definitions to make the pattern matches that we define more strict or specific.
Here are some basic examples:
iex(1)> defmodule MyMath do ...(1)> def sqrt(x) when x >= 0, do: #implement sqrt ...(1)> end
However, we are only allowed a limited set of expressions. The following is a pretty exhaustive list of the available expressions allowed in guard clauses:
All comparison operators (
==
,!=
,===
,!==
,>
,<
,<=
,>=
)Boolean operators (
and
,or
) and negation operators (not
,!
)<>
and++
as long as the left side is a literalThe
in
operator...