Search code examples
functionerlangarity

Call a function by its name and arity


I'm trying to write a function that calls a function with a specified name and arity:

my_fun(FunctionName, Arity) ->
    %Call FunctionName/Arity 
.

So that calling it like this:

my_fun(foo, 3)

should result in a call to function foo/3.

The problem is, I don't know how to call a function if only its name and arity are specified. The function I'm trying to call is guaranteed to exist in the same module from which I'm trying to call it.

Is it possible to implement this in Erlang, and how?


Solution

  • You can use erlang:apply/3 with the first argument being ?MODULE to refer to the same module, the second one being the name of the function as an atom and the third one being a list containing Arity elements:

    -module(a).
    -compile(export_all).
    
    my_fun(FunctionName, Arity) ->
      apply(?MODULE, FunctionName, lists:seq(1, Arity)).
    
    foo(A, B, C) ->
      io:format("~p ~p ~p~n", [A, B, C]).
    
    bar(A, B) ->
      io:format("~p ~p~n", [A, B]).
    
    main() ->
      my_fun(foo, 3),
      my_fun(bar, 2).
    

    Output:

    1> c(a), a:main().
    1 2 3
    1 2