2010-07-16 69 views
1

如果我打电话测试(),它不起作用。有人可以解释这一点吗?Erlang - Anonymouos函数

-module(anony). 

-export([test/0, test1/0]). 

test1() -> "hello". 

test() -> 
    C = fun(F) -> Val = F(), io:format("~p ", [Val]) end, 
    lists:foreach(debug, [test1]). 
+1

你应该指明了预期的结果。虽然我想你想要它打印“你好”,对吧? – gleber 2010-07-16 10:16:49

回答

2

首先,C变量尚未完全使用,和第二应包住test1fun/end

-module(anony). 

-export([test/0, test1/0]). 

test1() -> "hello". 

test() -> 
    C = fun(F) -> Val = F(), io:format("~p ", [Val]) end, 
    lists:foreach(C, [fun() -> test1() end]). 
+1

你的'fun() - > test1 end'根本不会调用'test1',它只是返回原子'test1'。 – cthulahoops 2010-07-16 10:16:47

+0

@cthulahoops谢谢,你说得对(+1) – 2010-07-16 10:23:13

7

test1自身是一个简单的原子,而不是参考本地功能。要创建对函数的引用,请使用下面的Fun Function/Arity。

-module(anony). 

-export([test/0, test1/0]). 

test1() -> "hello". 

test() -> 
    C = fun(F) -> Val = F(), io:format("~p ", [Val]) end, 
    lists:foreach(C, [fun test1/0]). 

你也可以构造一个匿名函数调用test1这样的:fun() -> test1() end,但没有理由给,除非你有你想传递的或类似的附加价值。

3

另外两个答案确实回答了这个问题。我只想添加到他们。

我希望你能够传递一个原子并用这个名字调用函数。这对于本地功能来说是不可能的。尽管导出的函数是非常可能的。

所以,你可以这样做(我唯一的变化是增加“模块:”和改变“调试”,以“C”):

-module(anony). 

-export([test/0, test1/0]). 

test1() -> "hello". 

test() -> 
    C = fun(F) -> Val = ?MODULE:F(), io:format("~p ", [Val]) end, 
    lists:foreach(C, [test1]). 
+0

一个有趣的选择。我想知道它在性能方面与其他答案(使用fun test1/0作出明确的函数引用)相比如何。 – 2010-07-19 17:17:45

+0

由于“外部”函数调用,我的解决方案会慢一点。另一方面他们解决了两个不同的问题。 – 2010-07-20 10:34:42