Sunday, May 06, 2007

More erlang awesomenes

This weekend I started playing with erlang again, and erlang started impressing me again.

I just declared a lexically scoped anonymous function and sent it to a different node. I then executed it on that node and it worked as expected.

For those who are not familiar, an anonymous function is a function that exists, but that is not associated with a function name in a global table of functions. It only exists by a variable reference that can and will go away at some point.

Lexical scoping is when you use a variable in an anonymous function that exists in the current scope where the function is created. That is the only copy of the variable that will be used in the execution of the anonymous function, even in the case that another variable of the same name is seen near the anonymous function later.

Creating the lexically scoped anonymous function and sending it to the other host:

(nomad@nomad)43> Var = 4.
(nomad@nomad)44> Fn = fun(X) -> Var * X end.
(nomad@nomad)45> global:send(slim_proc,Fn).

Receiving the anonymous function into the variable Fn and executing it using map and executing it directly:

(slim@slim)28> receive Fn -> Fn end.
(slim@slim)29> L = [1,3,4].
(slim@slim)30> lists:map(Fn,L).
(slim@slim)31> Fn(3).

Remember: these are on two different machines executing in a clustered erlang environment.

Is this not awesome?

No comments: