这是尾巴吗? (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);
});
};
是 child.add()
a尾叫?如果不是这样可以写的呢?
Is the child.add()
a tail call? 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.
此外 this.children.forEach(...)
是一个尾调用添加
方法。
Also this.children.forEach(…)
is a tail call within the add
method.
但是,在本机 forEach <中调用回调/ code>方法可能不是尾部调用优化的(除了最后一个之外的所有方法都不能)。您可以通过将您的函数重写为
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). 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.
这篇关于这是尾巴吗? (JavaScript)的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!