May 26 2009

Anonymous (Lambda) Functions in PHP.

I’ve recently been playing with anonymous (lambda) functions in javascript and I was thinking that it would be great if I could do the same thing in php, which is what I spend most of my time with. Turns out that you can. It’s not as clean and pretty as with javascript but it’s still a lambda function and functional programmers are better…aren’t they?

First the spec :
string create_function ( string $args , string $code )

So here’s a little example of something completely useless that can be done using anonymous functions in PHP :

$first_arg = 100;
$some_function = create_function(‘$first_arg’,’return $first_arg/5;’);

function process($arg,$func)
{
    while($func($arg)>5)
    {
        $arg–;
    }
    return $arg;
}

echo process($first_arg,$some_function);

So we get 25 echoed to the screen. A bunch of better examples can be found at the php website. If you’re willing to read…

Nothing really special but It’s still cool that can pass functions into another PHP function just like a regular variable.


Share

May 24 2009

Recursive, Anonymous, and Simple functions in Javascript

Functions are objects. This makes recursion short and sweet in javascript using anonymous functions.
In your html, php, or asp file try this out.

<input type=’button’ id=’myButton’ value=”5″>

<script type=’text/javascript’>
var myButton = document.getElementById(“myButton”);
var i=myButton.value;

myButton.onclick = function() {
if(i==0)
{
alert(“DONE”);
myButton.value = i;
return i;
}
alert(i);
return arguments.callee(–i);
};

</script>

I attached the anonymous function onto the onclick event for the button that was created right above the javascript. When that button is clicked the anonymous function will call itself and decrement ‘i’ until it is zero. When ‘i’ becomes zero the value of the button is set to 0 and the function returns. Nice and simple.

The only possible confusing thing here is the arguments.callee line. Remember I said that functions are objects? The arguments.callee actually calls itself. We need this because we don’t have a handle for the anonymous function. The arguments object is a local variable that all functions have. It can be used like an array to access the values passed to the function. It also holds ‘callee’, ‘caller’, and ‘length’. Since the callee is the function itself then caller is obviously the function that called it and length is the number of arguments passed to the function.

Share