Elixir-同一行上有多个表达式-函数定义中使用do:语法时出现编译器错误 [英] Elixir - Multiple expressions on same line - Compiler error when using do: syntax in function definition

查看:59
本文介绍了Elixir-同一行上有多个表达式-函数定义中使用do:语法时出现编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Elixir中,可以用分号(; )分隔多个表达式。

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

Elixir在以下函数中抱怨定义

Elixir complains in below function definition

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

有错误

** (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

但是,Elixir对以下语法感到满意。

However, Elixir is happy with below syntax.

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

我不确定为什么要解决

下面的完整代码供参考

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)


推荐答案

如果确实必须执行此操作,则需要使用括号:

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

原来的问题是的优先级; vs函数/宏调用,因此其解析如下:

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

您可以验证这是否与您提到的错误完全相同-编译器自然会抱怨,因为您试图在函数的上下文之外使用 c

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.

这篇关于Elixir-同一行上有多个表达式-函数定义中使用do:语法时出现编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆