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.
Funs are used to define anonymous functions in Erlang.
A function declaration is a sequence of function clauses separated by semicolons, and terminated by period (.). A function clause consists of a clause head and a clause body, separated by -> . A clause head consists of the function name, an argument list, and an optional guard sequence beginning with the keyword when .
In Erlang the last expression in your function is returned, in your case that would be the result of io:format which is ok . To return Cmd you can simply make it the last expression in your function: function_test() -> Cmd = os:cmd("ls"), io:format("The result of ls is:~p~n", [Cmd]), Cmd.
-export(Functions).Specifies which of the functions, defined within the module, that are visible from outside the module.
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}
You can use module_info/1
to get info about your module.
module_info/1
The call
module_info(Key)
, whereKey
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With