[erlang-questions] Construct a function refrence from variables

Andreas Hillqvist andreas.hillqvist@REDACTED
Thu Oct 25 16:17:03 CEST 2007


In your case when the number of arguments is known, just pass the name
of the module and call it with:

     1> Mod = io.
     io
     2> Mod:format("test~n").

This is how call backs for gen_server is called.
But it requires that the receiver knows the name of the function.

But using this principle you can pass a the modules nme as an atom, or
a both module and functions name as a tuple:

     do(Fun) when is_function(Fun) ->
         Data = "FooBar",
         Fun(Data);
     do(Module) when is_atom(Module) ->
         Data = "FooBar",
         Module:format(Data);
     do({Module, Function}) ->
         Data = "FooBar",
         Module:Function(Data).


Or you can make this into a fun:

     1> Mod = io.
     io
     2>Fun = fun(Data) -> Mod:format(Data) end.


But fun's are slower then the Module:Function(Data) call.


Regards
Andreas Hillqvist

________________________________

From: William FINK
Sent: den 25 oktober 2007 13:28
To: TrapExit
Subject: [erlang-questions] Construct a function refrence from variables

If I need a function reference, I use this syntax:

> Fun = fun io:format/1.
#Fun<io.format.1>

> Fun("test~n").
test
ok

Now, I want to construct my function reference from a module name:

> Mod = io.
io
1> Fun2 = Mod:format/1.
** 1: illegal expression **

The problem is that I need to call a function from an unknown module quite a lot
Calling apply each time will be slower than using a function reference.

How can I construct a function reference from variables ?

_________________
William FINK



More information about the erlang-questions mailing list