Guard Clauses
Learn how to call a specific function using when as a predicate in the function definition.
We'll cover the following
When to use guard clauses
We’ve seen that pattern matching allows Elixir to decide which function to invoke based on the arguments passed. But what if we need to distinguish based on the argument types or on some test involving their values?
For this, we use guard clauses. These are predicates that are attached to a function definition using one or more when
keywords. When doing pattern matching, Elixir first does the conventional parameter-based match and then evaluates any when
predicates, executing the function only if at least one predicate is true.
Note: We call functions attached to guard clauses in the same way we did before—for example,
Guard.what_is(9)
for a number.
Get hands-on with 1400+ tech skills courses.