Skip to content

Instantly share code, notes, and snippets.

@adaburrows
Created April 26, 2011 06:24
Show Gist options
  • Save adaburrows/941874 to your computer and use it in GitHub Desktop.
Save adaburrows/941874 to your computer and use it in GitHub Desktop.
Composing functions in PHP
<?php
/**
* Just trying out more functional programming in PHP
* This gist provides some basic utility functions for:
* + Working with functions
* + Working with arrays
*/
// This function allows creating a new function from two functions passed into it
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));
};
}
// Convenience wrapper for mapping
function map(&$data, &$f) {
return array_map($f, $data);
}
// Convenience wrapper for filtering arrays
function filter(&$data, &$f) {
return array_filter($data, $f);
}
// Convenience wrapper for reducing arrays
function fold(&$data, &$f) {
return array_reduce($data, $f);
}
// f(x) = (1/2)*x
$f = function($x) {
return (0.5*$x);
};
// g(x) = x^2
$g = function($x) {
return ($x*$x);
};
// h = f . g
$h = compose($f, $g);
// Get a range of values
$X = range(0, 10);
// Print the application of $h of $X
print_r(map($X, $h));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment