如何递归地在ES6中编写箭头函数? [英] How do I write an arrow function in ES6 recursively?

查看:147
本文介绍了如何递归地在ES6中编写箭头函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ES6中的箭头函数没有参数属性,因此 arguments.callee 将无法正常工作即使只是使用匿名函数,也不能在严格模式下工作。



箭头函数不能被命名,因此命名的功能表达式技巧无法使用。 >

所以...如何编写递归箭头函数?这是一个箭头函数,它根据某些条件递归调用自身,等等?

解决方案

编写递归函数没有命名它是一个与计算机科学本身一样古老的问题(实际上,由于λ -calculus早于计算机科学),因为在λ -calculus中,所有的功能都是匿名的,但是你仍然需要递归。



解决方案是使用固定点组合器,通常是Y组合器。这看起来像这样:

 (y =&$ 
y(
givenFact =>
n =>
n< 2?1:n * givenFact(n-1)
)(5)
)(le =>
(f =
f(f)
)(f =>
le(x =>(f(f))(x))

);

这将递归地计算 5 的阶乘



注意:代码基于以下原因: Y Combinator与JavaScript的。所有的信用都应该是原作者。我主要只是协调一致(这是你所说的重构旧代码的ES / Harmony的新功能)。


Arrow functions in ES6 do not have an arguments property and therefore arguments.callee will not work and would anyway not work in strict mode even if just an anonymous function was being used.

Arrow functions cannot be named, so the named functional expression trick can not be used.

So... How does one write a recursive arrow function? That is an arrow function that recursively calls itself based on certain conditions and so on of-course?

解决方案

Writing a recursive function without naming it is a problem that is as old as computer science itself (even older, actually, since λ-calculus predates computer science), since in λ-calculus all functions are anonymous, and yet you still need recursion.

The solution is to use a fixpoint combinator, usually the Y combinator. This looks something like this:

(y => 
  y(
    givenFact => 
      n => 
        n < 2 ? 1 : n * givenFact(n-1)
  )(5)
)(le => 
  (f => 
    f(f)
  )(f => 
    le(x => (f(f))(x))
  )
);

This will compute the factorial of 5 recursively.

Note: the code is heavily based on this: The Y Combinator explained with JavaScript. All credit should go to the original author. I mostly just "harmonized" (is that what you call refactoring old code with new features from ES/Harmony?) it.

这篇关于如何递归地在ES6中编写箭头函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆