Does ES6 Tail Call Optimization Cover Generators?

时光怂恿深爱的人放手 提交于 2019-12-22 04:56:36

问题


Does ES6's support for tail call optimization cover tail calls in generators?

Suppose I have this generator for integers >= 0:

var nums = function* (n) {
    n = n || 0;
    yield n;
    yield* nums(n + 1);
};

Currently, in Chrome and Firefox, it adds a stack level with each recursive call and eventually runs into a "maximum call stack size exceeded" error. Will this still occur once ES6 is fully implemented?

(I know I can write the above generator iteratively and not run into the error. I'm just curious about whether TCO will take care of recursively defined generators.)


回答1:


When a function call is made, according to the section Function call evaluation,

  1. Let tailCall be IsInTailPosition(thisCall)
  2. Return ? EvaluateCall(func, ref, arguments, tailCall)

The call will be evaluated based on the IsInTailPosition's result. And if if we check IsInTailPosition,

  1. If body is the FunctionBody of a GeneratorBody, return false.

So, if the function body is a generator, then Tail Call Optimization will not be done.



来源:https://stackoverflow.com/questions/30135916/does-es6-tail-call-optimization-cover-generators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!