recursive arrow functions
Claus Reinke
claus.reinke at talk21.com
Sun Apr 1 13:51:58 PDT 2012
> To get
> recursion at expression level, you can always define your own
> recursion combinator. Something like
>
> // ref(f) produces f(rec(f) modulo some eta-expansions
> let rec = (f)=> (..args)=> f( (..args)=>rec(f)(..args), ..args )
>
> Applying rec to an arrow function would supply the latter with a
> self-reference and
>
> rec( (f,n) => (n>1 ? n*f(n-1) : n) )(6)
>
> would then return 720. This would work even without consensus
> on named arrow functions.
Here is my attempt to translate this to ES5
function rec(f) { return function() {
return f.apply(this,[function(){return rec(f).apply(this,arguments)}]
.concat(Array.prototype.slice.call(arguments))
)
}
}
console.log( rec( function(f,n) { return n>1 ? n*f(n-1) : n } )(6) );
Outputs 720, and shows that all those little syntax simplifications
add up: while the idea is nearly readable from the ES6 version of
the code, the ES5 version obscures it so much that I've got to
think about the encoding as much as about the recursion
combinator itself; also, I'd rate my chances of finding bugs lower
in the ES5 version (apart from not having an ES6 implementation).
Claus
> I would suggest that utilities like 'rec' and my earlier 'getthis'
> (renamed to 'fn') should go into a standard library. To get a feel
> for what other utilities make sense in ES6, partial implementations
> of ES6 need to start supporting the (brand-new) arrow consensus.
More information about the es-discuss
mailing list