Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 48 ยท Core Language

Multiple Clauses and Guards

Learn how Elixir picks a function clause by pattern matching, how guards refine a match, which expressions are allowed in guards, defguard and clause-order traps.

In most languages one function has one body, and that body is full of if and switch statements. Elixir turns this around. You write the same function several times, each time with a different pattern in the parameter list, and the runtime picks the first version that fits the arguments. Each version is called a clause. The branching moves out of the body and into the function head, so every clause stays short and says exactly which input it handles.

Patterns can only look at the shape of a value. When you also need a condition such as "an integer greater than zero", you add a guard: a small when expression after the parameters. This lesson shows how clauses and guards work together, what a guard may contain, and the mistakes that come from getting the order wrong. It builds on pattern matching and functions and modules.

You cannot run Elixir on this site, so the Elixir code below is read-only. The runnable examples are JavaScript stand-ins that copy the idea (try clauses in order, run the first match). They are not Elixir and they do not model every rule.

One function, several clauses

Clauses of the same name and arity must sit next to each other. Elixir tries them from top to bottom:

ELIXIR
defmodule Greeter do
  def greet(:morning), do: "Good morning!"
  def greet(:evening), do: "Good evening!"
  def greet({:custom, text}), do: text
  def greet(_other), do: "Hello!"
end

Greeter.greet(:morning)          # "Good morning!"
Greeter.greet({:custom, "Yo"})   # "Yo"
Greeter.greet(:noon)             # "Hello!"

The last clause uses _other, which matches anything, so it acts as the default. A name that starts with an underscore tells the compiler (and your reader) that you deliberately ignore the value. If no clause matches, the call raises a FunctionClauseError. That is often what you want: failing loudly on input you never planned for is better than guessing.

Clauses can also destructure their arguments, so the body receives the pieces it needs:

ELIXIR
defmodule Shape do
  def area({:rect, w, h}), do: w * h
  def area({:square, side}), do: side * side
  def area({:circle, r}), do: 3.14159 * r * r
end

How a call finds its clause

Call You call the function with arguments.
Match Clauses are tried top to bottom.
Guard The when test must also be true.
Run The first fitting clause runs.

No fitting clause means FunctionClauseError.

1 / 2

A stand-in: first matching clause wins

The JavaScript below stores clauses as a list of [test, body] pairs and runs the first one whose test returns true. Real Elixir does this inside the compiler, with much better speed, but the behavior you observe is the same.

JS Clause dispatch in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Guards with when

A guard follows the parameters and starts with when. The clause is chosen only if the pattern matches and the guard is true:

ELIXIR
defmodule Temperature do
  def describe(t) when is_number(t) and t < 0, do: "freezing"
  def describe(t) when is_number(t) and t < 20, do: "cool"
  def describe(t) when is_number(t), do: "warm"
  def describe(_), do: "not a temperature"
end

Temperature.describe(-3)     # "freezing"
Temperature.describe(12.5)   # "cool"
Temperature.describe("hot")  # "not a temperature"

Guards work the same way in anonymous functions, case and receive:

ELIXIR
case value do
  n when is_integer(n) and n > 0 -> "positive integer"
  n when is_integer(n) -> "zero or negative integer"
  _ -> "something else"
end

Combine conditions with and, or and not, as in when is_integer(n) and n > 0. These operators expect booleans, which is exactly what comparisons and is_* checks return.

What you may use in a guard

Guards run inside the pattern-matching machinery, so only a fixed set of side-effect-free functions is allowed. You cannot call your own functions or anything from Enum or String. The allowed set includes:

Group Examples
Comparison ==, !=, ===, !==, <, <=, >, >=
Boolean and, or, not (left side of and/or must be a boolean)
Arithmetic +, -, *, /, div/2, rem/2, abs/1
Type checks is_integer/1, is_float/1, is_number/1, is_atom/1, is_binary/1, is_list/1, is_map/1, is_tuple/1, is_nil/1, is_function/1
Size and access length/1, map_size/1, tuple_size/1, byte_size/1, hd/1, tl/1, elem/2, is_map_key/2
Membership x in [1, 2, 3] and x in 1..10 (with a literal list or range)

Two details matter. First, &&, || and ! are not available in guards; use and, or and not. Second, if a guard expression raises an error (for example length(x) when x is not a list), the error is swallowed and the guard simply counts as false, so the next clause is tried:

ELIXIR
def size(x) when length(x) > 3, do: :long
def size(_), do: :short

size("hello")   # :short, because length("hello") raised inside the guard

That quiet failure is convenient, but it can hide a bug. Put a type check first (is_list(x) and length(x) > 3) so the intent is explicit.

Order matters

Because the first match wins, a broad clause placed too early hides everything below it:

ELIXIR
def classify(_), do: :other
def classify(0), do: :zero      # never reached

The compiler warns that this clause "will never match". Always go from the most specific clause to the most general. The same applies to guards: put the narrowest condition first.

JS Specific first, general last

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two more rules apply to clauses. All clauses of one function must have the same number of parameters (the same arity); greet/1 and greet/2 are different functions. And if you give a function default arguments while having several clauses, declare a function head first, a bodiless line that holds the defaults:

ELIXIR
def join(list, separator \\ ", ")
def join([], _separator), do: ""
def join(list, separator), do: Enum.join(list, separator)

Reusing guards with defguard

When the same condition appears in many guards, give it a name with defguard (or defguardp for a private one). It defines a macro that expands into guard-safe code:

ELIXIR
defmodule Checks do
  defguard is_adult(age) when is_integer(age) and age >= 18
end

defmodule Club do
  require Checks

  def enter(age) when Checks.is_adult(age), do: :welcome
  def enter(_), do: :too_young
end

Because defguard creates a macro, the caller must require the module or import it (import Checks lets you write is_adult(age) directly). The body of a defguard may use only what guards allow. Elixir also ships useful guards of its own, such as is_struct/1, is_exception/1 and is_non_struct_map/1.

Patterns inside the head

Combine patterns with guards for compact code. Strings can be matched by prefix with <>, maps by keys, and lists by head and tail:

ELIXIR
def handle("GET " <> path), do: {:get, path}
def handle("POST " <> path), do: {:post, path}

def first_positive([head | _]) when head > 0, do: head
def first_positive([_ | tail]), do: first_positive(tail)
def first_positive([]), do: nil

def adult?(%{age: age}) when age >= 18, do: true
def adult?(_), do: false

Notice how first_positive/1 loops with no loop construct: each clause handles one case. The recursion lesson builds on this idea.

JS Guards over a list, as a stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which clause runs when several clauses of a function could match the arguments?

    Elixir tries clauses in the order written and runs the first one whose pattern and guard both succeed. That is why specific clauses belong above general ones.
  2. 2. Which operators may you use to combine conditions inside a guard?

    Guards accept and, or and not. The relaxed operators &&, || and ! are not allowed, and only a fixed list of side-effect-free functions can be called.
  3. 3. What happens when an expression inside a guard raises an error, such as length/1 on a string?

    Errors in guards are swallowed and treated as a failed guard. This is convenient but can hide bugs, so check types explicitly first.
  4. 4. What does defguard create?

    defguard defines a macro that expands to guard-safe code. Callers must require or import the module that defines it.

Summary

  • A function can have many clauses; the first one whose pattern and guard match runs.
  • No match raises FunctionClauseError, which is usually a useful, loud failure.
  • Guards (when) add type and condition checks after the pattern has matched.
  • Only a fixed set of pure functions and operators (and, or, not, comparisons, is_*, length, map_size, in) is allowed in guards.
  • An error inside a guard makes the guard false instead of crashing.
  • Order clauses from specific to general; the compiler warns about clauses that can never match.
  • defguard names a reusable guard; callers need require or import.

Next, learn how to chain these functions into readable pipelines: The Pipe Operator.