[erlang-questions] Function Reference to Code Tree

Aggelos Giantsios aggelgian@REDACTED
Wed Jan 23 03:15:13 CET 2013

On Tue, Jan 22, 2013 at 7:21 PM, Tyron Zerafa <tyron.zerafa@REDACTED>wrote:

> F = fun(X,Y) -> X+Y end,
> In the above statement, F is just a function reference. Can I get the
> syntax, code tree or anything else from this variable? All I need is to
> extract the syntax out of a function reference. Any ideas how I can achieve
> this?
> The following convert a fun string into an actual fun. I need something
> the other way round, any ideas ??

Although I am not sure, I believe that such information may be impossible
to retrieve from the bytecode of a compiled module.
Having said that, I think that the important question is whether you have
access to
a) the source code of the module or
b) a compiled version of the module with debug_info.
In both cases you can generate the Abstract Syntax Tree and then extract
the desired expression that corresponds to the body of the lambda function.

However, if what you want is something more like the result of
erlang:fun_info/1, things may be somewhat tricky.
Consider the following example:

 1> X = 42. 42 2> F = fun(Y) -> X + Y end. #Fun<erl_eval.6.31705386> 3>
proplists:get_value(env, erlang:fun_info(F)). [[{'X',42}],
{value,#Fun<shell.7.20862592>}, {eval,#Fun<shell.24.20862592>}, [{clause,1,
[{var,1,'Y'}], [], [{op,1,'+',{var,1,'X'},{var,1,'Y'}}]}]]

The value associated with the key env of the returned proplist also
contains the environment (namely X = 42) in which the function must be
This information is not stated explicitly in the AST so if you want it
you'll have to parse the expression and locate the variables of the outer

Here's an example of the resulting AST of a lambda function
Erlang Code: bar(X) -> F = fun(Y) -> X + Y end, F(42). AST of F {'fun',5,
{clauses,[{clause,5, [{var,5,'Y'}], [],

I hope I gave you some ideas!!

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20130123/a7ea16c5/attachment.htm>

More information about the erlang-questions mailing list