w3resource

PHP Exercises: Curry a function to take arguments in multiple calls

PHP: Exercise-100 with Solution

Write a PHP program to curry a function to take arguments in multiple calls.

Sample Solution:

PHP Code:

<?php
// Licence: https://bit.ly/2CFA5XY

// Function definition for 'curry' that takes a function as a parameter
function curry($function)
{
    // Define an accumulator function using a closure
    $accumulator = function ($arguments) use ($function, &$accumulator) {
        // Return a closure that takes a variable number of arguments
        return function (...$args) use ($function, $arguments, $accumulator) {
            // Merge the accumulated arguments with the new arguments
            $arguments = array_merge($arguments, $args);

            // Use Reflection to get information about the original function
            $reflection = new ReflectionFunction($function);

            // Get the total number of required parameters for the original function
            $totalArguments = $reflection->getNumberOfRequiredParameters();

            // Check if the accumulated arguments meet the total required parameters
            if ($totalArguments <= count($arguments)) {
                // If true, call the original function with the accumulated arguments
                return $function(...$arguments);
            }

            // If not enough arguments, continue accumulating by calling the accumulator recursively
            return $accumulator($arguments);
        };
    };

    // Return the initial accumulator with an empty array of arguments
    return $accumulator([]);
}

// Create a curried version of the 'add' function using 'curry'
$curriedAdd = curry(
    function ($a, $b) {
        return $a + $b;
    }
);

// Partially apply the curried function with one argument (10)
$add10 = $curriedAdd(10);

// Call the partially applied function with another argument (15) and display the result using 'var_dump'
var_dump($add10(15)); // 25
  
?>

Sample Output:

int(25)

Flowchart:

Flowchart: Curry a function to take arguments in multiple calls.

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous:Write a PHP program to memoize a given function results in memory.
Next: Write a PHP program to call a given function only once.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.