1

如果我调用 test(),它不起作用。有人可以解释一下吗?

-module(anony).

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

test1() -> "hello".

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

3 回答 3

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,但是除非您有要传入的其他值等,否则没有理由这样做。

于 2010-07-16T10:16:03.843 回答
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]).
于 2010-07-16T16:22:42.753 回答
2

首先,C变量根本没有被使用,其次你应该test1用 a包装fun/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]).
于 2010-07-16T09:08:32.107 回答