Self-recursion and arrow functions

Jason Orendorff jason.orendorff at gmail.com
Sun Mar 17 04:16:48 PDT 2013


On Sun, Mar 17, 2013 at 2:43 AM, Claus Reinke <claus.reinke at talk21.com>wrote:

> Neither arguments.callee (not available in strict) nor let (clumsy to
> use in expressions) are needed for self-reference
>
>    var rec = (f) => f((...args)=>rec(f)(...args));
>
>    var f = (self)=>(n)=> n>1 ? n*self(n-1) : n;
>
>    [1,2,3,4,5,6].map((n)=>rec(f)(**n));
>

...but then you have a function rec which self-references. Much better to
use the Z combinator:

    f => (x => f(v => x(x)(v)))(x => f(v => x(x)(v)))

which can be conveniently inlined into any expression where it's used:

  js> [1,2,3,4,5,6].map((n)=>(f => (x => f(v => x(x)(v)))(x => f(v =>
x(x)(v))))(self => n => n>1 ? n*self(n-1) : n)(n));
  [1, 2, 6, 24, 120, 720]

Obviously this is much better than arguments.callee.

-j
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130317/776d28f7/attachment.html>


More information about the es-discuss mailing list