Reputation: 88157
If I'm writing a function that gets passed another function, is there a way to check the arity of the function I'm passed, or pattern match against different arities? I could use is_function/2 to check for specific arities, but that would be an awkward way to get the number.
Upvotes: 19
Views: 3091
Reputation: 818
:erlang.fun_info/1
is good for finding the arity if you have a reference to the function.
If you are trying to figure out what arities a function has, but don't have a reference to it (because the arity is a part of a functions identity) there are two methods.
If you want to know if it supports a specific arity :erlang.function_exported/3
takes the module, function name (sans-arity), and arity:
:erlang.function_exported(IO, :puts, 7) #=> false
:erlang.function_exported(IO, :puts, 2) #=> true
If you want to know all of the arities a function supports you can use the module's __info__
metadata function:
:functions |> IO.__info__ |> Keyword.get_values(:puts) #=> [1,2]
Upvotes: 10
Reputation: 16781
You can use :erlang.fun_info/1
; it returns a bunch of information about a given function, including its arity:
iex> :erlang.fun_info(fn -> :ok end)[:arity]
0
iex> :erlang.fun_info(fn(_, _, _) -> :ok end)[:arity]
3
As the documentation I linked says, this function is mainly intended for debugging purposes but it can be used to determine the arity of a function.
Upvotes: 32