Guards

In Elixir, a guard is a when test attached to a pattern. The pattern decides the shape of the argument, and the guard tests the values inside it: a number above zero, an age that is an integer, a state that is one of three atoms. A guard that fails moves the call to the next clause, so a function can keep its type and range checks in its head instead of in its body.

A guard on a clause

The guard follows the pattern and starts with when. It is tried only after the pattern fits, and it can use the names the pattern bound. The three clauses below split the integers into negative, zero and positive:

guards.exs

defmodule Num do def label(n) when n < 0, do: :negative def label(0), do: :zero def label(n) when n > 0, do: :positive end IO.puts(Num.label(-3)) IO.puts(Num.label(0)) IO.puts(Num.label(3))

elixir guards.exs

negative
zero
positive

The middle clause matches the literal zero; the other two compare the bound number. A value outside all three clauses, such as a binary, reaches no clause and raises FunctionClauseError, which is the function refusing the argument rather than returning a wrong answer.

Several conditions in one guard

and, or and in join conditions in one guard. The first program below asks for an integer that is old enough, with a catch-all clause that answers false for everything else, so the function is total:

checks.exs

defmodule Person do def adult?(age) when is_integer(age) and age >= 18, do: true def adult?(_age), do: false end IO.puts(Person.adult?(20)) IO.puts(Person.adult?(12)) IO.puts(Person.adult?("20"))

elixir checks.exs

true
false
false

The string "20" fails the type check and falls to the second clause, so the function answers false rather than raising in a comparison. in tests membership the same way, and a range works as the collection:

traffic.exs

defmodule Traffic do def light(state) when state in [:red, :yellow, :green], do: :known def light(_state), do: :unknown end IO.puts(Traffic.light(:red)) IO.puts(Traffic.light(:blue))

elixir traffic.exs

known
unknown

The guard in the second program is the same list of atoms the data uses, written once in the head. A state added to the list later is accepted everywhere the function is called, without a body change.

What a guard may call

A guard is evaluated in a restricted context: the compiler must be able to run it cheaply and without side effects, so only a small set of expressions is allowed. The set is:

Everything else belongs in the body. A function of your own, a call such as String.length/1, a map lookup and a process call all wait until the clause has been chosen. When a test needs one of them, the pattern gets the clause as far as it can and the body makes the final decision.

The mistake: a function call in a guard

A reader who wants "a non-empty string" reaches for String.length/1 in the guard. The compiler refuses the module, names the function and points at the call:

badguard.exs

defmodule Check do def nonempty(text) when String.length(text) > 0, do: text end IO.puts(Check.nonempty("hi"))

elixir badguard.exs

    error: cannot invoke remote function String.length/1 inside a guard
    │
  2 │ def nonempty(text) when String.length(text) > 0, do: text
    │ ^
    │
    └─ badguard.exs:2:34: Check.nonempty/1

** (CompileError) badguard.exs: cannot compile module Check (errors have been logged)

The error is a compile error, so nothing runs. The fix is a guard from the safe set, such as is_binary(text), plus the length test in the body, or a function that returns a tagged result. A guard is a fast filter, not a place for a computation.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. When is a guard evaluated?

    Answer

    After its pattern fits, before the body runs

    The pattern selects the clause and the guard decides whether that clause may run.

  2. What happens when a guard is false?

    Answer

    The call moves on to the next clause

    A failed guard is like a failed pattern: the clause is skipped and the next one is tried.

  3. Which call may appear in a guard?

    Answer

    is_integer/1

    The is_* checks are in the safe set; the other calls run only in the body.

  4. What does a catch-all clause after a guarded clause give a function?

    Answer

    A total answer for values the guard rejects

    The fallback clause handles the values the guarded clause refused, so every call has an answer.

  5. What does this program print? defmodule Num do def label(n) when n < 0, do: :negative def label(0), do: :zero def label(n) when n > 0, do: :positive end IO.puts(Num.label(0))

    Answer

    zero

    The literal 0 matches the second clause before either comparison is tried.

  6. What does this program print? defmodule Person do def adult?(age) when is_integer(age) and age >= 18, do: true def adult?(_age), do: false end IO.puts(Person.adult?("20"))

    Answer

    false

    The guard requires an integer, so the string falls through to the catch-all clause.

  7. What does this program print? defmodule Person do def adult?(age) when is_integer(age) and age >= 18, do: true def adult?(_age), do: false end IO.puts(Person.adult?(20))

    Answer

    true

    Both parts of the guard hold for 20, so the first clause returns true.

  8. What does this program print? defmodule Traffic do def light(state) when state in [:red, :yellow, :green], do: :known def light(_state), do: :unknown end IO.puts(Traffic.light(:red))

    Answer

    known

    The atom is in the list, so the first clause runs.

  9. What does this program do? defmodule Check do def nonempty(text) when String.length(text) > 0, do: text end IO.puts(Check.nonempty("hi"))

    Answer

    error: cannot invoke remote function String.length/1 inside a guard

    String.length/1 is not in the guard-safe set, so the module does not compile.

  10. Which operator joins two conditions inside one guard?

    Answer

    and

    and, or and in are allowed in guards; the work stays inside the safe set.

Автор статьи: Arthur Isaev