Knowing the number of parameters of a passed function (erlang)

时光怂恿深爱的人放手 提交于 2020-06-25 10:13:50

问题


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/1

The call module_info(Key), where Key is an atom, returns a single piece of information about the module.

The following values are allowed for Key:

...

exports Returns a list of {Name,Arity} tuples with all exported functions in the module.

functions Returns 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!