[erlang-questions] Convert atom and arity into fun

Jeroen Koops <>
Fri Sep 5 12:54:55 CEST 2008


I needed this as a quick way to invoke all exported functions from a
module whose names start with 'test_' - a miniature unit-test
framework if you will. Each function returns either true, if the test
succeeds, or {false, Reason} if it fails.

The following function gives a list of all exported functions starting
with 'test_' and arity 0:

tests() ->
        lists:filter(fun({Name, Arity}) ->
                        Arity =:= 0 andalso lists:prefix("test_",
atom_to_list(Name))
                     end, module_info(exports)).

Next, using apply/3 as suggested by Gleb, they're all invoked and the
results formatted by:

 [ case apply(?MODULE, X, []) of true -> {X, ok}; {false, Why} -> {X,
error, Why} end || {X,0} <- tests() ].

Works like a charm (until test-functions start throwing unexpected
exceptions, but I'll get to that when it actually happens)!





On Fri, Sep 5, 2008 at 12:45 PM, Richard Carlsson <> wrote:
> Jeroen Koops wrote:
>> Given a function's name as an atom and an arity (for instance as
>> returned by module_info(exports)), how can I convert this into a fun
>> that I can invoke?
>
> There is currently no immediate way of doing this. If you just want
> to call the function, you can use M:F(...) or apply(M,F,[...]). If
> you need a fun, to pass it somewhere, you can wrap such a call in a
> new fun, like this: F = fun (...) -> M:F(...) end.
>
>    /Richard
>



More information about the erlang-questions mailing list