函数具有多个子句,并且还声明了默认值。

时间:2018-09-20 04:02:41

标签: elixir

这是我的模块:

defmodule Test do
  def try(10 = num, other_num \\ 10) do
    num + other_num
  end
  def try(_num, _other_num) do
    raise "This is incorrect"
  end
end

运行iex时收到以下警告:

warning: def try/2 has multiple clauses and also declares default values. In such cases, the default values should be defined in a header. Instead of:

    def foo(:first_clause, b \\ :default) do ... end
    def foo(:second_clause, b) do ... end

one should write:

    def foo(a, b \\ :default)
    def foo(:first_clause, b) do ... end
    def foo(:second_clause, b) do ... end

老实说,我不知道这是要告诉我做什么。谁能为我分解一下,编译器要我在这里做什么?谢谢!

1 个答案:

答案 0 :(得分:7)

编译器希望您编写一个函数头(即没有主体的函数),并在其中指定默认值。

def try(num, other_num \\ 10)
def try(10 = num, other_num) do
  num + other_num
end
def try(_num, _other_num) do
  raise "This is incorrect"
end

之所以需要这样做,是因为用户无法为同一个功能指定不同的默认值,这将是模棱两可的,因为具有默认值的功能已由Elixir编译器编译为多个功能。

def a(b, c \\ 10), do: b + c

编译为:

def a(b), do: a(b, 10)
def a(b, c), do: b + c

当函数指定不同的默认值时,没有直接的翻译:

def a(b, c \\ 10), do: b
def a(b, c \\ 20), do: c