在 Elixir 中,一个函数可以有多个子句。要做到这一点,需要对函数的实参进行模式匹配,并使用守卫。
# pattern matching the argument
def number(7) do
"Awesome, that's my favorite"
end
# using a guard
def number(n) when is_integer(n) do
"That's not my favorite"
end
def number(_n) do
"That's not even a number!"
end
FunctionClauseError。_,否则编译器会发出警告。fn
13 -> "Awesome, that's my favorite"
_ -> "That's not my favorite"
end
注意,不要把你从其他编程语言中可能知道的函数重载与多子句函数混为一谈。在 Elixir 中,函数仅由名称和参数个数来标识,而不是由实参的类型来标识(因为 Elixir 没有静态类型)。示例中的函数number/1无论有多少个子句,都被视为同一个函数。