Created
March 16, 2013 01:54
-
-
Save scribu/5174562 to your computer and use it in GitHub Desktop.
A few utilities for functional programming in PHP.
This file contains 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
<?php | |
/** | |
* Returns a callable which is the composition of all the arguments, | |
* which should be callable themselves. | |
*/ | |
function fn_compose( $fn ) { | |
$funcs = func_get_args(); | |
$last = array_pop( $funcs ); | |
return function() use( $last, $funcs ) { | |
$args = func_get_args(); | |
$r = call_user_func_array( $last, $args ); | |
foreach ( array_reverse( $funcs ) as $fn ) { | |
$r = $fn( $r ); | |
} | |
return $r; | |
}; | |
} | |
/** | |
* Returns a callable with the arguments partially applied. | |
*/ | |
function fn_partial( $fn ) { | |
$args = array_slice( func_get_args(), 1 ); | |
return function() use ( $fn, $args ) { | |
$final_args = array_merge( $args, func_get_args() ); | |
return call_user_func_array( $fn, $final_args ); | |
}; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: