elixir defguard
Elixir defguard
Function
In Elixir, the defguard
macro is used to define guards, which are conditions that must be satisfied for a function to be invoked. The defguard
macro allows you to define custom guards that can be used in function clauses.
Here is an example of how to use the defguard
macro:
defmodule MyModule do
defguard is_even(number) when rem(number, 2) == 0
def my_function(number) when is_even(number) do
# Function implementation
end
end
In the example above, the defguard
macro is used to define the is_even/1
guard, which checks if a number is even. The my_function/1
function uses the is_even/1
guard to ensure that it is only invoked when the input number is even.
You can define multiple guards using the defguard
macro, and they can be used in multiple function clauses throughout your code.
I hope this helps! Let me know if you have any further questions.