Skip to content

Instantly share code, notes, and snippets.

@pauloricardokoch
Last active April 29, 2016 21:49
Show Gist options
  • Save pauloricardokoch/4a42014977d744dae4e20ff4737a65b1 to your computer and use it in GitHub Desktop.
Save pauloricardokoch/4a42014977d744dae4e20ff4737a65b1 to your computer and use it in GitHub Desktop.
Functions to currying and compose functions with PHP.
<?php
// This function allows creating a new function from two functions passed into it
//e.g.:
//php > $explode = curry_left("explode", ",");
//php > $toUpper = curry_left("strtoupper");
//php > $map = curry_left("array_map", $toUpper);
//php > $compose = compose($map, $explode);
//php > print_r($compose("paulo,ricardo,koch"));
//Array
//(
// [0] => PAULO
// [1] => RICARDO
// [2] => KOCH
//)
function compose(&$f, &$g)
{
// Return the composed function
return function() use ($f, $g) {
// Get the arguments passed into the new function
$x = func_get_args();
// Call the function to be composed with the arguments
// and pass the result into the first function.
return $f(call_user_func_array($g, $x));
};
}
<?php
//This function allows creating a new function that needs the last parameter of other function
//e.g.:
//php > $func = curry_left("explode", ",");
//php > print_r( $func("paulo,koch"));
//Array
//(
// [0] => paulo
// [1] => koch
//)
function curry_left($callable)
{
$outer_arguments = func_get_args();
array_shift($outer_arguments);
return function() use ($callable, $outer_arguments) {
return call_user_func_array($callable, array_merge($outer_arguments, func_get_args()));
};
}
<?php
//This function allows creating a new function that needs the first parameter of other function
//e.g.:
//php > $func = curry_right("strpos", ",");
//php > print_r( $func("paulo,koch") );
//5
function curry_right($callable)
{
$outer_arguments = func_get_args();
array_shift($outer_arguments);
return function() use ($callable, $outer_arguments) {
return call_user_func_array($callable, array_merge(func_get_args(), $outer_arguments));
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment