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

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

问题描述

ES6 中的箭头函数没有 arguments 属性,因此 arguments.callee 将不起作用,并且无论如何都不会在严格模式下运行,即使只是一个匿名函数正在使用中.

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?

推荐答案

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

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.

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

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))
  )
);

这将递归计算5的阶乘.

注意:代码主要基于以下内容:Y Combinator 用 Ja​​vaScript 解释.所有的功劳都应该归原作者所有.我大多只是协调"(这就是你所说的用 ES/Harmony 的新功能重构旧代码?)它.

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天全站免登陆