Created
December 15, 2015 13:40
-
-
Save FLamparski/d72d1ce2bdb72c7f6da7 to your computer and use it in GitHub Desktop.
A semi-workable implementation of functional composition 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 | |
/* | |
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