繁体   English   中英

这是尾巴吗? (JavaScript)

[英]Is this a tail call? (Javascript)

假设您有一个递归函数,例如:

Blah.prototype.add = function(n) {
    this.total += n;
    this.children.forEach(function(child) {
        child.add(n);
    });
};

child.add()是尾叫吗? 如果不能,可以这样写吗?

是的,这是一个尾声:

function(child) {
    child.add(n);
// ^ tail
}

但是这里没有什么是尾递归的,因为它不是直接的递归调用。

另外, this.children.forEach(…)add方法中的尾部调用。

但是,本机forEach方法中的回调调用可能未进行尾调用优化(无论如何,除最后一个以外的所有调用都不能进行优化)。 您可以通过重写函数来强制执行以下操作:

Blah.prototype.add = function(n) {
    "use strict";
    this.total += n;
    let l = this.children.length;
    if (!l--)
        return;
    for (let i=0; i<l; i++)
        this.children[i].add(n);
    this.children[i].add(n); // tail-recursion
};

请注意,如果您也不return它们的结果,则这些尾调用都不会被优化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM