Skip to content

Instantly share code, notes, and snippets.

@scribu
Created March 16, 2013 01:54
Show Gist options
  • Save scribu/5174562 to your computer and use it in GitHub Desktop.
Save scribu/5174562 to your computer and use it in GitHub Desktop.
A few utilities for functional programming in PHP.
<?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 );
};
}
@scribu
Copy link
Author

scribu commented Mar 16, 2013

Example usage:

$d = [ [1, 2, 3], ['a', 'b', 'c', 'd'] ];

var_dump( array_map( fn_partial( 'implode', ' - ' ), $d ) );

var_dump( array_map( fn_compose( 'strlen', fn_partial( 'implode', '' ) ), $d ) );

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