Why special function apply(Mod, Func, Args).

Mickael Remond <>
Fri Feb 7 14:40:14 CET 2003


* Suresh S <> [2003-02-07 13:06:54 +0000]:

> Hi,
> 
> In erlang Course there is a special function described
> i.e apply(Mod, Func, Args) at
> http://www.erlang.org/course/course.html 
> 
> Special Function :
> 
> apply(Mod, Func, Args)
> 
> 1> apply( lists1,min_max,[[4,1,7,3,9,10]]).
>     {1, 10}
> 
> but this will solve the problem  
> 
> 2> lists1:min_max([4,1,7,3,9,10]).
>     {1, 10}		
> 
> i really do not understand why the special function 
> apply(Mod, Func, Args).

With apply, you can generate dynamic function calls depending on variables or
result of functions:

  apply(getModule(Params...), getFunction(Params...), [Param1, Param2]).

With the other syntax, you can only use variable name and not function calls:

1> Mod=io.
io
2> Function=format.
format
3> Mod:Function("~p~n", ["Hello"]).                                      
"Hello"

The apply syntax can be used to easily generate plug-ins, based on call-back
mechanism (If you do that, be carefull with security aspects: You are
dynamcally building code that is executed with the privilege of the user that
launched the program). 

For example, as long as you can provide a module / function name in a config
file for example and that you respect the function signature, you can
dynamically change a given function call. 

-- 
Mickaël Rémond



More information about the erlang-questions mailing list