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 their types or on some test involving their values? For this, you 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.

mm/guard.exs
 
defmodule​ Guard ​do
 
def​ what_is(x) ​when​ is_number(x) ​do
 
IO.puts ​"#{x} is a number"
 
end
 
def​ what_is(x) ​when​ is_list(x) ​do
 
IO.puts ​"#{inspect(x)} is a list"
 
end

Get Programming Elixir 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.