In Elixir,
guard()
sequences derive from
when()
clauses in Erlang. Their main function is pattern matching augmentation. Guards allow developers to specify predicates for a given argument type, as seen in the example below:
defmodule Sum do
def to(1), do: 1
def to(n) when n > 0, do: n + to(n-1) # only nonzero positive numbers​
It’s worth noting that most expressions don’t support guard testing.
Developers mainly use guards when working in Kernel. In and not in boolean-only, and comparison operators, as well as datatype and type-check functions, support guard expressions.