Created
January 31, 2020 19:17
-
-
Save cystbear/42623a5ee19ecbfb045b4dba03b1b3e2 to your computer and use it in GitHub Desktop.
My PHP Currying implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function curry(\Closure $f) { | |
$rf = new \ReflectionFunction($f); | |
$arity = $rf->getNumberOfParameters(); | |
function acc($f, $arity, $args=[]) { | |
return function(...$acc) use($f, $arity, $args) { | |
$acc = array_merge($args, $acc); | |
return (count($acc) >= $arity) ? $f(...$acc) : acc($f, $arity, $acc); | |
}; | |
}; | |
return acc($f, $arity); | |
}; | |
// ================================================== | |
$sum_func = function($a,$b,$c) { | |
return $a+$b+$c; | |
}; | |
$cur = curry($sum_func); | |
var_dump($cur(1,2,3)); | |
var_dump($cur(1,2)(3)); | |
var_dump($cur(1)(2)(3)); | |
var_dump($cur()(1)()(2)()(3)); | |
var_dump($cur()()()()(1)()(2)()(3,4,5)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment