Guard clauses allow Elixir to determine which function to invoke
based not only on which arguments are passed, but also based on
type or some tests involving their values. Guard clauses are defined
using the when
keyword.
Examples:
defmodule Guard do def kind_of(x) when is_binary(x) do "#{x} is a binary" end def kind_of(x) when is_atom(x) do "#{x} is an atom" end def is_ten(x) when x > 10, do: "Greater than ten" def is_ten(x) when x < 10, do: "Less than ten" def is_ten(x), do: "Yes" end
max = fn x, y when x > y -> x x, y -> y end
case 42 do x when is_binary(x) -> "Nope" x -> "Yep" end
Additionally, users may define their own guards. Example: the Bitwise
module defines bnot
, ~~~
, band
, &&&
, bor
, |||
, bxor
, ^^^
,
bsl
<<<
, bsr
>>>
.
Operators
Comparison
|
|
Arithmetic
Unary operators |
|
Boolean and Negation
Short-circuiting operators |
|
Join
|
|
Membership Test membership in a list or range with Example: def is_animal(animal) when animal in [:dog, :cat, :fish] do true end def in_range(x) when x in 1..6 do true end |
Functions
Type-check See main Elixir documentation for more information.
|
|
Other See main Elixir documentation for more information.
|