当动态指定模块并将其传递给更高阶的函数时,如何获取对模块中函数的引用?
例如:
Mod = compare_funs,
lists:sort(fun Mod:compare/2, List).
只是,这不会编译。一种方法是将对目标函数的调用包装在匿名函数中,但我想知道是否有一种方法可以直接获取引用。
最佳答案
来自以下位置的文档:
http://www.erlang.org/doc/programming_examples/funs.html#id59209
We can also refer to a function defined in a different module with the following syntax:
F = {Module, FunctionName}
In this case, the function must be exported from the module in question.
例如,您可能会这样做:
-module(test).
-export([compare/2, test/2]).
compare(X, Y) when X > Y ->
true;
compare(X, Y) ->
false.
test(Mod, List) ->
lists:sort({Mod, compare}, List).
1> test:test(test, [1,3,2]).
[3,2,1]
关于erlang - 如何获得棘手的函数引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5575176/