當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Elixir Kernel.defguard用法及代碼示例

Elixir語言中 Kernel.defguard 相關用法介紹如下。

用法:

defguard(guard)
(從 1.6.0 開始) (宏)
@spec defguard(Macro.t()) :: Macro.t()

生成一個適用於保護表達式的宏。

如果定義使用了守衛中不允許的表達式,它會在編譯時引發,否則會創建一個可以在守衛內部或外部使用的宏。

請注意,Elixir 中的約定是使用 is_ 前綴命名守衛中允許的函數/宏,例如 is_list/1 。但是,如果函數/宏返回布爾值並且不允許在守衛中使用,則它應該沒有前綴並以問號結尾,例如 Keyword.keyword?/1

示例

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

相關用法


注:本文由純淨天空篩選整理自elixir-lang.org大神的英文原創作品 Kernel.defguard(guard)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。