PHP Exercises: Create a new function that composes multiple functions into a single callable
PHP: Exercise-98 with Solution
Write a PHP program to create a new function that composes multiple functions into a single callable.
Sample Solution:
PHP Code:
<?php
// Licence: https://bit.ly/2CFA5XY
// Function definition for 'compose' that takes a variable number of functions as parameters
function compose(...$functions)
{
// Use 'array_reduce' to iterate through the functions and create a composition
return array_reduce(
$functions,
function ($carry, $function) {
// Return a new function that applies the current function to the result of the previous function
return function ($x) use ($carry, $function) {
return $function($carry($x));
};
},
// The initial function that simply returns the input
function ($x) {
return $x;
}
);
}
// Create a composition of two functions: add 2 and multiply by 4
$compose = compose(
// add 2
function ($x) {
return $x + 2;
},
// multiply by 4
function ($x) {
return $x * 4;
}
);
// Call the composed function with an argument and display the result using 'print_r'
print_r($compose(2));
// Display a newline
echo("\n");
// Call the composed function with another argument and display the result using 'print_r'
print_r($compose(3));
?>
Sample Output:
16 20
Flowchart:
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous:Write a PHP program to decapitalize the first letter of the string and then adds it with rest of the string.
Next: Write a PHP program to memoize a given function results in memory.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics