In Erlang, how do you invoke a function dynamically?

It is correct that you have to export p and g. You can then use apply/3 to call it.

erlang:apply(sample, p, []).

Only fun-values are usable with the Fun(...) syntax. You are passing in an atom-value. An atom is a 'bad function' as the error message go. You could do something similar to

xyz(p) -> fun p/0;
xyz(g) -> fun g/0.

Then go ahead and call

Fun = xyz(p),
Fun()

-module(sample).
-export([xyz/1, p/0, g/0]).

xyz(Name) -> ?MODULE:Name().

p() -> "you called p".
g() -> "you called g".


1> sample:xyz(p).
"you called p"

Pattern match is the idiom to use:

-module(sample).
-export([xyz/1]).

xyz(p) -> p();
xyz(q) -> g().

p() -> "you called p".
g() -> "you called g".

If you want to be dynamic you can use a gen_event server.

Essentially what this is is a server that holds a state which consists of key/function pair like so:

[{p, #func1},
 {g, #func2},
 {..., ...},
 ...]

You can then essentially bind events to functions. (there is, needless to say, a bit more to it than that.


The easiest way to do is to try exporting p and g along with xyz.

-export([xyz/1, p/0,g/0]).

After exporting the function p and g can be called as follows :

1> sample:xyz(fun sample:p/0).
"you called p"
2> sample:xyz(fun sample:g/0).
"you called g"

Tags:

Erlang