【问题标题】:About Erlang function, especially the function's identifier关于 Erlang 函数,尤其是函数的标识符
【发布时间】:2013-05-13 15:27:24
【问题描述】:

我有一个关于 Erlang 函数的问题。查看 Erlang shell 中的代码:

1> F1 = fun() -> timer:sleep(1000) end.
#Fun<erl_eval.20.111823515>
2> F2 = fun() -> io:format("hello world~n", []) end.
#Fun<erl_eval.20.111823515>

F1F2 是不同的,但为什么它们都有一个标识符 #Fun&lt;erl_eval.20.111823515&gt;?这些神奇的数字是什么意思?


ERTS Manual中有一段话,说:

When interpreting the data for a process, it is helpful to know that anonymous
function objects (funs) are given a name constructed from the name of the
function in which they are created, and a number (starting with 0) indicating
the number of that fun within that function.

我也看不懂这一段的意思,能解释一下吗?

【问题讨论】:

    标签: erlang


    【解决方案1】:

    不要对匿名函数的名称解读太多含义。您可以安全地从中得到的只是创建它们的模块的名称。您可以尝试在模块中计算乐趣以找出哪个,但我不会打扰。

    话虽如此,这两个游戏名称相同是有原因的。在 shell 中输入的表达式不会被编译,而是由模块 erl_eval 中的解释器评估。这个模块有一个有趣的解释每个arity的乐趣。所以erl_eval 有一个有趣的 arity 1 的乐趣,#Fun&lt;erl_eval.20.111823515&gt;。哈克,但它有效。

    【讨论】:

      【解决方案2】:

      考虑一个模块中的相同功能(暂时不要考虑 shell)

      -module(fun_test).
      -export([test/0]).
      
      test() ->
          F1 = fun() -> timer:sleep(1000) end,
          F2 = fun() -> io:format("hello world~n", []) end,
          {F1,F2}.
      

      输出如下

      1> fun_test:test().
      {#Fun<fun_test.0.78536365>,#Fun<fun_test.1.78536365>}
      

      在上面的示例中,匿名函数对象 F1 和 F2 的名称是使用模块 fun_test 的名称、唯一标识符 0 和 1(模块中每个函数的增量)、返回地址等在 @987654321 中定义的@。这解释了手册中提到的段落。虽然不是很有用,但函数编号在调试期间很方便,因为跟踪中的 -test/0-fun-1- 会告诉您 test/0 函数中的匿名函数 1 是错误的根源。

      对于 shell 中定义的函数,请使用 rvirding 解释的 erl_eval 模块。函数对象声明的结果是该参数的 erl_eval 的返回。所以总是为那个arity返回相同的值。

      【讨论】:

        猜你喜欢
        • 2011-07-21
        • 1970-01-01
        • 2014-03-11
        • 1970-01-01
        • 1970-01-01
        • 2016-08-25
        • 2021-03-20
        • 1970-01-01
        • 2013-08-19
        相关资源
        最近更新 更多