Saturday, September 29, 2007

Building Things with high order functions...

One thing that always surprise me, is code that extensively uses high order function or let's call that "functions that returns functions" (may be known also as "closure")...
What can I, myself, do with such things ?
After a little time reading and thinking, and reading and reading, I designed a really simple usage of all of this. I'll create some helper functions to build xml tags...

-module(tags).
-export([tags/1]).

tags(Elem) ->
fun(X) ->
"<" ++ Elem ++ ">" ++ X ++ "</" ++ Elem ++ ">"
end.


Let me explain:
  • Elem will be the enclosing tag
  • X is the parameter the function will receive at call time

The module in action:

1> c(tags).
{ok,tags}
2> Div = tags:tags("div").
#Fun<tags.0.28130594>
3> Div("html text").
"<div>html text</div>"
4>

'tags:tags' returns a function that will create div tags...

Now you're able to build a list of functions that will create valid output, without knowing the real syntax. You can see 'tags:tags' as a function that abstract the final notation of an element of your choice.

For example, building a 'title' tags is done by :

Title = tags:tags("title").

Building a list of functions for your language can be done like this:

lists:map(fun tags:tags/1, ["title", "div", "p", "ul", "li", "script"]).

No comments:

Sticky