2013-05-18 78 views
3

我有一個關於Erlang函數的問題。看到代碼在Erlang的外殼:關於Erlang函數,特別是函數的標識符

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<erl_eval.20.111823515>?這些神奇數字是什麼意思?


有在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. 

我也不能趕上這一段的意思,可以請你解釋一下嗎?

回答

6

不要在匿名函數的名稱中讀取太多含義。您可以放心地從中獲得它們是創建它們的模塊的名稱。你可以嘗試在模塊中計算funs來找到哪一個,但我不會打擾。

這就是說,這是爲什麼兩個funs有同名的原因。輸入到shell中的表達式不會被編譯,而是由模塊erl_eval中的解釋器進行評估。這個模塊有一個用於解釋每個元素的樂趣的樂趣。所以erl_eval有一個樂趣,樂隊1,#Fun<erl_eval.20.111823515>。哈克,但它的作品。

2

考慮相同的功能的模塊(讓不認爲殼的現在)

-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(模塊中每個函數的增量),返回地址等構建的,如ERTS Manual中所定義。這解釋了手冊中提到的段落。雖然不是很有用,但函數編號在調試過程中非常方便,因爲跟蹤中的-test/0-fun-1-會告訴您,test/0函數中的匿名函數1是錯誤的來源。

對於在shell中定義的函數,使用rvirding解釋的erl_eval模塊。函數對象聲明的結果是返回erl_eval。所以總是返回相同的價值。