Tuesday, August 24, 2010

transmogrified function composition

Using the transmogrifier something like function composition such as:


(define (compose . fs)
(if (null? fs) (lambda (x) x)
(lambda (x) ((car fs) ((apply compose (cdr fs)) x)))))


Becomes possible like:

$compose = [$funcs |
empty($funcs) ? [$_] :
[car($funcs)($compose(cdr($funcs))($_))]];


Which becomes:

$compose = function($funcs) use(&$compose) {
return empty($funcs) ? function($x) { return $x; } :
function($_ = false) use(&$funcs, &$compose) {
return apply(car($funcs), array(apply($compose(cdr($funcs)), array($_))));};};


I am not doing an exact copy here because I am not using ". rest" args as I would probably call this function like:


echo $compose({square negate cube})(500);
//shorter than
echo $compose('square', 'negate', 'cube')(500);


I think the above illustrates that really php IS capable of these sorts of things it's just that in it's incredibly gnarly. With a few syntax tweaks (square bracket closures w/ lexical scope, squiggly bracket arrays w/ barewords as strings, ability to use return value as function) - it's almost livable.

No comments: