How to get the name of a function?

at runtime, you could throw an exception and check the top of the stacktrace.

foo() ->
    catch throw(away),
    [{Module, Fun, Arity} | _] = erlang:get_stacktrace(),
    io:format("I am ~p:~p/~p!~n",[Module, Fun, Arity]).

Use the macro ?FUNCTION_NAME to get the name of the current function as an atom, and ?FUNCTION_ARITY to get the arity as an integer.

Example:

-module(test).

-export([a_function/2]).

a_function(_Foo, _Bar) ->
    io:write("I am ~p/~p!",[?FUNCTION_NAME, ?FUNCTION_ARITY]).
1> c(test).
{ok,test}
2> test:a_function(a, b).
I am a_function/2!

This was implemented in EEP-0045.

For Erlang Versions 18 and Older

In older Erlang versions, there's no simple way to get the current function name at compile time. You can however retrieve it at runtime:

{current_function, {M, F, A}} = process_info(self(), current_function)

Where A is the arity (number of arguments), not the actual arguments. The first argument to process_info/2 is a process ID which can be either the current process (self()) or an other process. For example:

1> process_info(self(), current_function).
{current_function,{erl_eval,do_apply,5}}

Note however, that while this would be functionally equivalent to the ?FUNCTION_NAME macro, it's much slower because it is evaluated in runtime.

Tags:

Erlang