Write a PHP program to curry a function to take arguments in multiple calls
<?php //Licence: https://bit.ly/2CFA5XY function curry($function) { $accumulator = function ($arguments) use ($function, &$accumulator) { return function (...$args) use ($function, $arguments, $accumulator) { $arguments = array_merge($arguments, $args); $reflection = new ReflectionFunction($function); $totalArguments = $reflection->getNumberOfRequiredParameters(); if ($totalArguments <= count($arguments)) { return $function(...$arguments); } return $accumulator($arguments); }; }; return $accumulator([]); } $curriedAdd = curry( function ($a, $b) { return $a + $b; } ); $add10 = $curriedAdd(10); var_dump($add10(15)); // 25 ?>
Sample Output:
int(25)
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Sample Output:
need an explanation for this answer? contact us directly to get an explanation for this answer