[erlang-questions] Variable bindings

Steve Vinoski vinoski@REDACTED
Sat Jan 26 19:45:37 CET 2013


On Sat, Jan 26, 2013 at 9:32 AM, Tyron Zerafa <tyron.zerafa@REDACTED>wrote:

> Does there exist any particular function which would give me all variable
> bindings (including their values) at that point. For instance, something
> similar to get_all_bindings (example below) should result in [{X=3},{Y=4}]
> when called with X=2.
>
> my_fun(X) ->
>     Y = X+1,
>      get_all_bindings().
>

I don't think anything like that exists, but here's a parse transform that
might work for you:

https://gist.github.com/4643721

The parse transform looks for a call to get_all_bindings/1 in each function
body and replaces its argument with a list of variable names and their
bindings used in the function up to that point. The argument to
get_all_bindings can be anything because the parse transform replaces it.
Example:

-module(foo).
-export([my_fun/1]).
-compile([{parse_transform,get_all_bindings}]).

-record(rec, {f1, f2, f3}).

my_fun(X) ->
    Y = X+1,
    Z = [a,b,c,d,e,{X,Y}],
    #rec{f1=F1, f2=F2, f3=F3} = #rec{f1=42, f2=[X,Y], f3=Z},
    get_all_bindings([]),
    Q = 32,
    Q.

get_all_bindings(Bindings) ->
    io:format("~p~n", [Bindings]).

The code produced for my_fun/1 by the parse transform looks like this:

my_fun(X) ->
    Y = X + 1,
    Z = [a, b, c, d, e, {X, Y}],
    #rec{f1 = F1, f2 = F2, f3 = F3} = #rec{f1 = 42,
                                           f2 = [X, Y], f3 = Z},
    get_all_bindings([{'Z', Z}, {'Y', Y}, {'X', X},
                      {'F3', F3}, {'F2', F2}, {'F1', F1}]),
    Q = 32,
    Q.

Note that Q isn't included in the list because it occurs after the call to
get_all_bindings/1.

--steve
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20130126/3ce97599/attachment.htm>


More information about the erlang-questions mailing list