elixir guard
In Elixir, guards are used to add constraints to function clauses. They allow you to specify conditions that must be met for a particular function clause to be selected and executed. Guards are defined using the when
keyword followed by a Boolean expression. Here's an example of how guards can be used in Elixir:
defmodule Math do
def add(a, b) when is_number(a) and is_number(b) do
a + b
end
def add(a, b) do
IO.puts "Error: Both arguments must be numbers!"
end
end
IO.puts Math.add(1, 2) # Output: 3
IO.puts Math.add(1, "two") # Output: Error: Both arguments must be numbers!
In this example, the add/2
function has two clauses. The first clause is selected and executed when both a
and b
are numbers. The second clause, which includes a guard, is selected and executed when the arguments are not numbers.
Guards can include various conditions such as type checks (is_atom/1
, is_binary/1
, etc.), value comparisons (==
, !=
, etc.), and pattern matches (=
, ^
, etc.). You can combine multiple conditions using logical operators (and
, or
, not
, etc.).
Using guards can help improve the readability and maintainability of your code by allowing you to define clear constraints on function inputs.