Created
February 15, 2016 02:14
-
-
Save sirbrillig/9aba93d5419b743fdec8 to your computer and use it in GitHub Desktop.
A compose function for PHP
This file contains hidden or 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
<? | |
class FunctionalFuncs { | |
public static function compose() { | |
$function_reducer = function ( $result, $func ) { | |
return [ call_user_func_array( $func, $result ) ]; | |
}; | |
$callbacks = func_get_args(); | |
return function() use ( $callbacks, $function_reducer ) { | |
$arguments = func_get_args(); | |
return array_reduce( $callbacks, $function_reducer, $arguments )[0]; | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is not a real "composition" per se.
According to Mathematics (and many languages are following those naming conventions), composition needs to be processed from the right to the left.
f · g · h => f(g(h(...)))
This example, despite the fact it's technically valid, should better be renamed into:
Pipe
.Pipe is usually a kind of "composition" applied from left to right and is sometimes better suited.
On my side, I definitely prefer using
Pipe
because processing stuff from left to right is definitely more readable.However, if you want to use
Composition
, you'll have to reverse the array of provided functions and process it like aPipe
.Examples: