Skip to content

Instantly share code, notes, and snippets.

@FLamparski
Created December 15, 2015 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FLamparski/d72d1ce2bdb72c7f6da7 to your computer and use it in GitHub Desktop.
Save FLamparski/d72d1ce2bdb72c7f6da7 to your computer and use it in GitHub Desktop.
A semi-workable implementation of functional composition in PHP.
<?php
/*
This function takes in a bunch of callables (closures, functions, strings naming functions, etc.)
and returns a function such that compose(f, g)(x) <=> f(g(x)). In other words, the return function
will take exactly one argument, and call the functions supplied to compose right to left
on that argument.
*/
function compose() {
$functions = func_get_args();
return (function() use ($functions) {
$intermediate = func_get_arg(0);
for ($i = (count($functions) - 1); $i >= 0; $i--) {
$fn = $functions[$i];
$intermediate = $fn($intermediate);
}
return $intermediate;
});
}
// Proof of concept.
function f($x) { return $x * $x; }
function g($x) { return 2 * $x + 4; }
$fg = compose('f', 'g');
echo f(g(5)) . " " . $fg(5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment