Kernel.defguard
You're seeing just the macro
defguard
, go back to Kernel module for more information.
Specs
Generates a macro suitable for use in guard expressions.
It raises at compile time if the definition uses expressions that aren't allowed in guards, and otherwise creates a macro that can be used both inside or outside guards.
Note the convention in Elixir is to name functions/macros allowed in
guards with the is_
prefix, such as is_list/1
. If, however, the
function/macro returns a boolean and is not allowed in guards, it should
have no prefix and end with a question mark, such as Keyword.keyword?/1
.
Example
defmodule Integer.Guards do
defguard is_even(value) when is_integer(value) and rem(value, 2) == 0
end
defmodule Collatz do
@moduledoc "Tools for working with the Collatz sequence."
import Integer.Guards
@doc "Determines the number of steps `n` takes to reach `1`."
# If this function never converges, please let me know what `n` you used.
def converge(n) when n > 0, do: step(n, 0)
defp step(1, step_count) do
step_count
end
defp step(n, step_count) when is_even(n) do
step(div(n, 2), step_count + 1)
end
defp step(n, step_count) do
step(3 * n + 1, step_count + 1)
end
end