编译错误:"具有多个子句和默认值的定义需要函数头"

Jon*_*fer 6 functional-programming elixir

我正在使用以下代码,试图Étude 3-1: Pattern MatchingÉtudes为Elixir的书中解决.

16   def area(:rectangle, a \\ 1, b \\ 1) do
17     a * b
18   end
19
20   def area(:triangle, a, b) do
21     a * b / 2.0
22   end
23
24   def area(:shape, a, b) do
25     a * b * :math.pi()
26   end
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

** (CompileError) geom.ex:20: definitions with multiple clauses and default values require a function head.

错误消息后面有一个解释:

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    

def area/3 has multiple clauses and defines defaults in a clause with a body
    geom.ex:20: (module)
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
Run Code Online (Sandbox Code Playgroud)

显然我不能使用默认值:得到它.但为什么?

Dav*_*ulc 8

您实际上可以使用默认值,但正如错误消息所示,您需要指定一个函数头:

14   def area(shape, a \\ 1, b \\ 1)
15
16   def area(:rectangle, a, b) do
17     a * b
18   end
19
20   def area(:triangle, a, b) do
21     a * b / 2.0
22   end
23
24   def area(:shape, a, b) do
25     a * b * :math.pi()
26   end
Run Code Online (Sandbox Code Playgroud)

注意第14行指定必要的功能头.

来自https://elixirschool.com/lessons/basics/functions/:Elixir不喜欢多个匹配函数中的默认参数,这可能令人困惑.为了处理这个问题,我们使用默认参数添加一个函数头