Created
November 8, 2015 01:01
-
-
Save cystbear/1b5ef77d0d7e9ebf7e43 to your computer and use it in GitHub Desktop.
My Function Composition implementation via PHP
This file contains hidden or 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 | |
function compose(/* funs to compose */) { | |
$fl = func_get_args(); | |
return function($x) use($fl) { | |
$val = $x; | |
while (null !== $f = array_pop($fl)) { | |
$val = $f($val); | |
}; | |
return $val; | |
}; | |
} | |
// ====================================================== | |
$up = function($s) {return strtoupper($s);}; | |
$y = function($s) {return $s.'!';}; | |
$reverse = function($a) {return array_reverse($a);}; | |
$head = function($a) {$v=array_values($a); return array_shift($v);}; | |
$data = array('jumpkick', 'roundhouse', 'uppercut'); | |
//$c1 = compose($y, $up, $head, $reverse); | |
$c1 = compose(compose($y, 'strtoupper'), compose($head, 'array_reverse')); | |
$c2 = compose(compose($y, 'strtoupper', $head), 'array_reverse'); | |
$c3 = compose($y, 'strtoupper', $head, compose('array_reverse')); | |
$c4 = compose(compose($y), compose('strtoupper'), compose($head), compose('array_reverse')); | |
var_dump($c1($data)); | |
var_dump($c2($data)); | |
var_dump($c3($data)); | |
var_dump($c4($data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Doesn't the use of array_pop mean you can only use the resulting composed function once?