ES6尾部调用优化是否涵盖生成器? [英] Does ES6 Tail Call Optimization Cover Generators?

查看:94
本文介绍了ES6尾部调用优化是否涵盖生成器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ES6对尾部调用优化的支持是否涵盖了生成器中的尾部调用?

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

假设我有这个生成器,用于> = 0的整数:

Suppose I have this generator for integers >= 0:

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

当前,在Chrome和Firefox中,它为每个递归调用添加了堆栈级别,并最终遇到超出最大调用堆栈大小"错误.完全实施ES6后,这种情况还会发生吗?

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?

(我知道我可以迭代地编写上述生成器,而不会遇到错误.我很好奇TCO是否会处理递归定义的生成器.)

(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.)

推荐答案

进行函数调用时,根据函数调用评估

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

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

将基于IsInTailPosition的结果评估呼叫.如果我们检查 IsInTailPosition

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

  1. 如果body是 GeneratorBody FunctionBody ,则返回 false .
  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.

这篇关于ES6尾部调用优化是否涵盖生成器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆