[erlang-questions] more flexible code generation

Ulf Wiger ulf@REDACTED
Sun Dec 16 12:39:28 CET 2012


I made a little addition to my parse_trans library, in parse_trans_codegen:

The 'original' method for generating code for a function was e.g.:

g(Name, V) ->
    codegen:gen_function(
      Name,
      fun(L) ->
              member({'$var',V}, L)
      end).

Where the {'$var', V} notation is a way to insert a reference to a variable, rather than using the variable itself. 

To illustrate, let's first create a little pretty-printer fun:

1> PP = fun(F) -> io:fwrite("~s~n", [erl_pp:form(F)]) end.
#Fun<erl_eval.6.82930912>


2> PP(ex_codegen:g(foo,17)).
foo(L) ->
    member(17, L).

There are a few other, similar, functions, but in some cases, this is still too restrictive. A few days ago, I added support for specifying a more dynamic pattern:

k(L) ->
    codegen:gen_function(
      lcf,
      [fun({'$var',X}) ->
               {'$var',Y}
       end || {X, Y}  <- L]).

The list comprehension results in a list of clauses based on data resolved at run-time. For example:

3> PP(ex_codegen:k([ {"a", {1,2,3}}, {"b", {4,5,6}} ])).
lcf("a") ->
    {1,2,3};
lcf("b") ->
    {4,5,6}.

https://github.com/uwiger/parse_trans/blob/master/doc/parse_trans_codegen.md

Feedback is welcome.

BR,
Ulf W

Ulf Wiger, Co-founder & Developer Advocate, Feuerlabs Inc.
http://feuerlabs.com






More information about the erlang-questions mailing list