Skip to content

Instantly share code, notes, and snippets.

@sirbrillig
Created February 15, 2016 02:14
Show Gist options
  • Save sirbrillig/9aba93d5419b743fdec8 to your computer and use it in GitHub Desktop.
Save sirbrillig/9aba93d5419b743fdec8 to your computer and use it in GitHub Desktop.
A compose function for PHP
<?
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];
};
}
}
@drupol
Copy link

drupol commented Oct 6, 2020

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 a Pipe.

Examples:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment