Skip to content

Instantly share code, notes, and snippets.

@sursir
Last active January 2, 2019 10:45
Show Gist options
  • Select an option

  • Save sursir/b12ffd50d6a556cea10a5ea4ea7af880 to your computer and use it in GitHub Desktop.

Select an option

Save sursir/b12ffd50d6a556cea10a5ea4ea7af880 to your computer and use it in GitHub Desktop.
php curry lambda closures functional
<?php
function curry($fn)
{
if (is_callable($fn)) {
$fargc = count((new ReflectionFunction($fn))->getParameters());
return $c = function (...$argv) use (&$c, $fn, $fargc) {
if (count($argv) >= $fargc) {
return $fn(...$argv);
}
return function (...$argv2) use (&$c, $argv) {
return $c(...array_merge($argv, $argv2));
};
};
}
return false;
}
$sum = curry(function ($x, $y, $z) {
echo $x + $y + $z, "\n";
return true;
});
// $sum = curry(function () {
// echo 'xx';
// });
echo memory_get_usage()," ";
echo memory_get_peak_usage()," ";
echo memory_get_usage(true)," ";
echo memory_get_peak_usage(true),"\n";
$sum(1, 2, 3);
$sum(1,2)(3);
$sum(1)(2, 3);
$sum(1, 2, 3, 4, 7);
$sum()()(1,2)()(3);
$sum(1)()()(2, 3);
echo memory_get_usage()," ";
echo memory_get_peak_usage()," ";
echo memory_get_usage(true)," ";
echo memory_get_peak_usage(true),"\n";
function factorial($n, $accumulator = 1) {
    if ($n == 0) {
        return $accumulator;
    }

    return function() use($n, $accumulator) {
        return factorial($n - 1, $accumulator * $n);
    };
}

function trampoline($callback, $params) {
    $result = call_user_func_array($callback, $params);

    while (is_callable($result)) {
        $result = $result();
    }

    return $result;
}

var_dump(trampoline('factorial', array(100)));

引用自 http://n3xtchen.github.io/n3xtchen/2015/04/26/php-functional-programming

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment