Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get a tricky function reference?

Tags:

erlang

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/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.

like image 749
mwt Avatar asked Nov 29 '25 16:11

mwt


1 Answers

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]
like image 73
Roberto Aloi Avatar answered Dec 02 '25 02:12

Roberto Aloi