Created
April 27, 2017 10:26
-
-
Save meszaros-lajos-gyorgy/6d34399ebde9d3d0a3cc27da407e8ce9 to your computer and use it in GitHub Desktop.
Curry for php functions
This file contains 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($func, $params = []){ | |
return function() use ($func, $params){ | |
$reflection = new ReflectionFunction($func); | |
$neededArgNum = count($reflection->getParameters()); | |
$args = array_merge($params, func_get_args()); | |
$argNum = count($args); | |
if($argNum >= $neededArgNum){ | |
return call_user_func_array($func, $args); | |
}else{ | |
return curry($func, $args); | |
} | |
}; | |
}; | |
$add = curry(function($a, $b){ | |
return $a + $b; | |
}); | |
$inc = $add(1); | |
header('Content-Type:text/plain'); | |
echo $inc(12).PHP_EOL; // should be 13 | |
echo $add(20, 30).PHP_EOL; // should be 50 | |
echo $add(4)(7).PHP_EOL; // should be 11 | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment