template programing in erlang

Vincent Adam Burns discoloda@REDACTED
Tue Aug 11 21:23:38 CEST 2009


I have been writing a little rfc2234 parser for a SMTP server and client in
erlang, it doesn't parse the format directly but uses erlang functions to
describe a form. I ended up with with format of programming:

character(Character) ->
    fun(<<X, Rest/binary>>) when X == Character -> {<<X>>, Rest};
        (_) -> false
    end.

space(Bin) ->
    (character(16#20))(Bin).

And it came to my attention how slow this might be: I have to reduce
character, create a function from scratch, and then reduce that function. So
I decided that I could write a parse_transform that finds a list of function
factories (such as character) and reduces it into expressions that call it,
automatically inserting the arguments into the fun body. so the above
example becomes after running the parse_transform:

space(Bin) ->
    fun(<<X, Rest/binary>>) when X == 16#20 -> {<<X>>, Rest};
        (_) -> false
    end(Bin).

And then after reading some of the AST some more, I found I could replace
the clauses of the function entirely so now space looks like this:

space(<<X, Rest/binary>>) when X == 16#20 -> {<<X>>, Rest};
space(_) -> false.

And now I had a special little thing going on; Template programming in
Erlang. I could make functions that take many parameters, and inject
parameters directly into the code. Another good thing about the code is the
ability to run without the parse_transform module.

Here is the source <http://www.3spire.com/optimizer.erl> for the beginning
of a AST optimizer that includes this functionality.
blog post<http://discoloda.blogspot.com/2009/08/template-programming-in-erlang.html>
--
--- You know you've achieved perfection in design, not when you have nothing
more to add, but when you have nothing more to take away.


More information about the erlang-questions mailing list