Elixir Guards
Understanding Elixir Guards
Elixir guards are special clauses in function definitions that allow you to specify conditions under which a function should be executed. Errors generated within guard clauses are silently caught and result in the guard failing, preventing the function from matching. This mechanism is crucial for controlling function behavior based on input types and values.
Elixir Guard Clause Syntax and Allowed Elements
When writing guard clauses in Elixir, it's important to know which functions and operators are permitted. These are designed to be side-effect-free and efficient. The following table outlines the allowed elements:
Comparison Operators | Logical Operators | Arithmetic Operators | Type Checking Functions | Map Functions | Tuple Functions | List Functions | Binary Functions | Kernel Functions |
---|---|---|---|---|---|---|---|---|
== |
or |
+ |
is_atom |
map_size() |
elem() |
a in b |
bit_size() |
node() |
!= |
and |
- |
is_binary |
tuple_size() |
hd() |
byte_size() |
self() |
|
=== |
not |
* |
is_bitstring |
tl() |
||||
!== |
/ |
is_boolean |
length() |
|||||
> |
abs() |
is_exception |
||||||
< |
div() |
is_float |
||||||
<= |
float() |
is_function |
||||||
>= |
rem() |
is_integer |
||||||
round() |
is_nil |
|||||||
trunc() |
is_list |
|||||||
is_number |
||||||||
is_pid |
||||||||
is_port |
||||||||
is_reference |
||||||||
is_tuple |
Important Note: Operators like
!
(negation), &&
(short-circuit
AND), and ||
(short-circuit OR) are
not allowed within Elixir guard clauses.
Understanding these restrictions is key to writing correct and
efficient Elixir code.
How Elixir Guards Handle Errors
A critical aspect of Elixir guards is their error handling. If any operation within a guard clause raises an error, that error is not propagated. Instead, the guard clause is treated as having failed, and Elixir proceeds to evaluate the next function clause or pattern. This behavior ensures that your program remains stable even if unexpected conditions arise during guard evaluation.