简体   繁体   English

这是尾巴吗? (JavaScript)

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

Supose you have a recursive function like: 假设您有一个递归函数,例如:

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

Is the child.add() a tail call? child.add()是尾叫吗? If not can it be written so it is? 如果不能,可以这样写吗?

Yes, it is a tail call: 是的,这是一个尾声:

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

Yet nothing here is tail-recursive, because it's not a direct recursive call. 但是这里没有什么是尾递归的,因为它不是直接的递归调用。

Also this.children.forEach(…) is a tail call within the add method. 另外, this.children.forEach(…)add方法中的尾部调用。

However, the invocation of the callback within the native forEach method is probably not tail-call optimised (and all but the last one cannot be anyway). 但是,本机forEach方法中的回调调用可能未进行尾调用优化(无论如何,除最后一个以外的所有调用都不能进行优化)。 You can force it by rewriting your function to 您可以通过重写函数来强制执行以下操作:

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

Notice that none of these tail calls will be optimised if you don't also return their results. 请注意,如果您也不return它们的结果,则这些尾调用都不会被优化。

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

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