gpt4 book ai didi

elixir - Elixir 函数名称中的问号和 "is_"

转载 作者:行者123 更新时间:2023-12-05 00:16:15 27 4
gpt4 key购买 nike

我正在阅读 Elixir 的命名约定。它指出:

The names of predicate functions that cannot be used within guards should have a trailing question mark (?) rather than the is_ (or similar) prefix.



那么,Guard 中不能使用哪些功能呢?

最佳答案

所有这三个函数都包含在守卫中有效的表达式;只是自定义守卫必须写成宏,而不是普通函数:

defmodule User do
defstruct age: 0

defmacro kid?(age) do
quote do
6 < unquote(age) and unquote(age) < 12
end
end

defmacro teen?(age) do
quote do
12 < unquote(age) and unquote(age) < 18
end
end

defmacro elder?(age) do
quote do
60 < unquote(age)
end
end
end

defmodule Greeting do
import User

def greet(%{age: age}) when kid?(age), do: "Hiya"
def greet(%{age: age}) when teen?(age), do: "Whatever"
def greet(%{age: age}) when elder?(age), do: "You kids get off my lawn"
def greet(_), do: "Hello"
end

for age <- [0, 5, 10, 15, 20, 90] do
IO.inspect {age, Greeting.greet(%{age: age})}
end

输出:
{0, "Hello"}
{5, "Hello"}
{10, "Hiya"}
{15, "Whatever"}
{20, "Hello"}
{90, "You kids get off my lawn"}

关于elixir - Elixir 函数名称中的问号和 "is_",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42341415/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com