Elixir - Multiple expressions on same line - Compiler error when using do: syntax in function definition

泪湿孤枕 提交于 2019-12-12 10:36:32

问题


In Elixir, multiple expressions can be delimited by semicolon (;).

Elixir complains in below function definition

defmodule Module2 do
    def func([c], n), do: IO.inspect(c); c + n
end

with error

** (CompileError) hello.exs:2: undefined function c/0
    (stdlib) lists.erl:1352: :lists.mapfoldl/3
    (stdlib) lists.erl:1352: :lists.mapfoldl/3
    (stdlib) lists.erl:1353: :lists.mapfoldl/3

However, Elixir is happy with below syntax.

defmodule Module1 do
    def func([c], n) do 
        IO.inspect(c); c + n
    end
end

I am not sure why one works over the other - as far as I understand both styles of function definition are equivalent.


Complete code below for reference

defmodule Module1 do
    def func([c], n) do 
        IO.inspect(c); c + n
    end
end
defmodule Module2 do
    def func([c], n), do: IO.inspect(c); c + n
end

Module1.func('r', 13)
Module2.func('r', 13)

回答1:


If you really must do this, you will need to use parentheses:

defmodule Module2 do
  def func([c], n), do: (IO.inspect(c); c + n)
end

The problem with the original is the precedence of ; vs function/macro calls, because of which it is parsed like this:

defmodule Module2 do
  (def func([c], n), do: IO.inspect(c)); c + n
end

You can verify that this gives the exact same error you mention - the compiler naturally complains because you're trying to use c outside of the context of the function.



来源:https://stackoverflow.com/questions/31763989/elixir-multiple-expressions-on-same-line-compiler-error-when-using-do-synta

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!