Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Php

Idiom #37 Currying

Transform a function that takes multiple arguments into a function for which some of the arguments are preset.

function curry($f, ...$argsCurried)
{
    return function (...$args) use ($f, $argsCurried) {
        $finalArgs = array_merge($argsCurried, $args);
        return call_user_func_array($f, $finalArgs);
    };
}

function add($n1, $n2)
{
    return $n1 + $n2;
}

$addFive = curry('add', 5);

echo $addFive(2), PHP_EOL;
echo $addFive(-5), PHP_EOL;

curry returns an anonymous function or closure (http://php.net/manual/en/functions.anonymous.php).
function curry($f, ...$argsCurried)
{
    return function (...$args) use ($f, $argsCurried) {
        return $f(...$argsCurried, ...$args);
    };
}

function add($n1, $n2)
{
    return $n1 + $n2;
}

$addFive = curry('add', 5);

echo $addFive(2), PHP_EOL;
echo $addFive(-5), PHP_EOL;
(def add5 (partial + 5))

New implementation...
< >
Adrian