问题
In ERLANG: Assume we have a function f() that takes F1 as inputs where F1 is a function. Is there a way to know the number of input parameters of F1.
I feel somehow there IS a solution, but I am not sure. for instance:
-module(high).
-compile(export_all).
f1() -> 1.
f2(X) -> X.
f3(X, Y) -> {X,Y}.
run(F) -> io:format("F ~p ~n", [F]).
So, is there any way for function run/1 to know information about the passed function [mainly the number of input parameters of the passed function].
Note: Please be informed that this is a theoretical question. Note: is the code of apply(fun,[arguments]) available in open-source .. this may hep me I guess.
回答1:
erlang:fun_info(Fun,arity).
For example
F = fun(A,B) -> A+B end.
#Fun<erl_eval.12.111823515>
3> erlang:fun_info(F,arity).
{arity,2}
回答2:
You can use module_info/1 to get info about your module.
module_info/1The call
module_info(Key), whereKeyis an atom, returns a single piece of information about the module.The following values are allowed for
Key:...
exportsReturns a list of {Name,Arity} tuples with all exported functions in the module.
functionsReturns a list of {Name,Arity} tuples with all functions in the module.
http://erlang.org/doc/reference_manual/modules.html
run(F) -> find_value(F,module_info(exports)).
find_value(Key, List) ->
case lists:keyfind(Key, 1, List) of
{Key, Result} -> {Key,Result};
false -> io:format("There is no function called ~w.~n", [Key])
end.
来源:https://stackoverflow.com/questions/10048001/knowing-the-number-of-parameters-of-a-passed-function-erlang