O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required