Currying with PHP 5.3

In my recent adventure of exploring the new anonymous functions of PHP 5.3, I started experimenting with currying.

Here is my implementation:

function curry(){
    $args = func_get_args();
    $func = array_shift($args);
    $want_array = array_shift($args);
    return function() use ($func,$args,$want_array) {
        return $want_array === TRUE
            ? $func(array_merge(func_get_args(),$args))
            : call_user_func_array($func,array_merge(func_get_args(),$args)); 
    };
}


curry( callback $function, boolean $want_array[, mixed $parameter [, mixed $… ]] )
I had an earlier version using Reflection, but it proved to be slower.

To understand the usage of these function, lets work with a few examples. We’ll start off with this simple function:

$sum = function($a,$b) { return $a + $b; };

This function has two simple parameters, returning the sum of them.

Now, lets say new functionality must be added to where you always add 10 to the result. In this case, we would typically add another function for this (keeping the original in order to not break existing functionality):

$sum10 = function($a,$b) { return $a + $b + 10; };

Now, to avoid the bloat of the extra function we use the php curry function:

$sum10 = curry($sum,FALSE,10);

The $sum10 function in use:

echo $sum10(5); // prints 15

Now, lets use an example where the function has just an array as the paramter:

$sum = function($nums) { return array_sum($nums); };

This is where the second param comes into play: $want_array.
If the $want_array is TRUE, then the callback will be called with just one parameter…. the array.

So, using the new $sum function:

$addtwenty = curry($sum,TRUE,20);
echo $addtwenty(5); // prints 25

~ by ityndall on October 26, 2010.

2 Responses to “Currying with PHP 5.3”

  1. This is such a great resource that you are providing and you give it away for free. I enjoy seeing websites that understand the value of providing a prime resource for free. I truly loved reading your post. Thanks!

  2. What a great resource!

Leave a Reply