Skip to content

Instantly share code, notes, and snippets.

@cystbear
Created November 8, 2015 01:01
Show Gist options
  • Save cystbear/1b5ef77d0d7e9ebf7e43 to your computer and use it in GitHub Desktop.
Save cystbear/1b5ef77d0d7e9ebf7e43 to your computer and use it in GitHub Desktop.
My Function Composition implementation via PHP
<?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));
@mcfedr
Copy link

mcfedr commented Nov 8, 2015

Doesn't the use of array_pop mean you can only use the resulting composed function once?

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