PHP program to create a new function that composes multiple functions into a single callable.
<?php
//Licence: https://bit.ly/2CFA5XY
function compose(...$functions)
{
return array_reduce(
$functions,
function ($carry, $function) {
return function ($x) use ($carry, $function) {
return $function($carry($x));
};
},
function ($x) {
return $x;
}
);
}
$compose = compose(
// add 2
function ($x) {
return $x + 2;
},
// multiply 4
function ($x) {
return $x * 4;
}
);
print_r($compose(2));
echo("\n");
print_r($compose(3));
?>
Output:
16
20
