开发者

How do you get a tricky function reference?

开发者 https://www.devze.com 2023-02-23 04:15 出处:网络
How do you get a reference to a function in a module when the module is dynamically specified and you\'ll be passing it to a higher order function?

How do you get a reference to a function in a module when the module is dynamically specified and you'll be passing it to a higher order function?

Ex:

Mod = compare_funs,
lists:sort(fun Mod:compare/开发者_JAVA技巧2, List).

Only, this won't compile. One way would be to wrap a call to the target function in an anonymous fun, but I was wondering if there's a way to get a reference directly.


From the documentation at:

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.

For example, you might do:

-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]
0

精彩评论

暂无评论...
验证码 换一张
取 消