Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

erlang

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.

like image 525
AJed Avatar asked Apr 06 '12 19:04

AJed


People also ask

What is fun in Erlang?

Funs are used to define anonymous functions in Erlang.

What is function clause?

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 .

How do I return a value from Erlang?

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.

What is export in Erlang?

-export(Functions).Specifies which of the functions, defined within the module, that are visible from outside the module.


2 Answers

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}
like image 110
Odobenus Rosmarus Avatar answered Nov 24 '22 01:11

Odobenus Rosmarus


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.
like image 33
Tamas Toth Avatar answered Nov 23 '22 23:11

Tamas Toth