Saturday, May 17, 2008

inline lambda with out a wrapper function

So here is my implementation to allow for inline lambda functions:

This is built on top of my fn (anonymous function which is written to defun directory), fnx (function with one variable called x) and sfnx (single command which should be returned with one variable passed in called x).

The only thing I had to add was a GLOBAL variable called $_ which is an array (I initially called it $L but I like how $_ feels more like a piece of syntax than a variable name). In fn when it gets the name via md5 it then sets $_[$name] = $name; so that you may use it as follows:

echo $_[sfnx('$x')]('hello world');

You can use this how ever you would normally use a function (nested, in function calls etc.)

I mean "with out a wrapper function" because this could be accomplished with a function like: inline($args,$body,$arg1..$argn) which would create the anonymous function and call it with arg1..$argn and return the value.

echo inline('$x','return $x;','hello world');

As you can see it's doable but I guess I like the "feel" of the first one.

I should mention I was inspired by Peter Goodmans i/o reader blog post on a similar tip here: Hacking variable composition - another approach to php lambdas

No comments: