Why do no javascript engines support tail call optimization?

烈酒焚心 提交于 2019-12-04 03:58:39

问题


I recently learned about tail call optimization in Haskell. I've learned from the following posts that this is not a feature of javascript:

  • Tail Recursion optimization for JavaScript?
  • Are any Javascript engines tail call optimized?

Is there something inherent to javascript's design that makes tail call optimization especially difficult? Why is this a main feature of a language like haskell, but is only now being discussed as a feature of certain javascript engines?


回答1:


Tail call optimisation is supported in JavaScript. No browsers implement it yet but it's coming as the specification (ES2015) is finalized and all environments will have to implement it. Transpilers like BabelJS that translate new JavaScript to old JavaScript already support it and you can use it today.

The translation Babel makes is pretty simple:

function tcoMe(x){
    if(x === 0) return x;
    return tcoMe(x-1)
}

Is converted to:

function tcoMe(_x) {
    var _again = true;

    _function: while (_again) {
        var x = _x;
        _again = false;

        if (x === 0) return x;
        _x = x - 1;
        _again = true;
        continue _function;
    }
}

That is - to a while loop.

As for why it's only newly supported, there wasn't a big need from the community to do so sooner since it's an imperative language with loops so for the vast majority of cases you can write this optimization yourself (unlike in MLs where this is required, as Bergi pointed out).



来源:https://stackoverflow.com/questions/31273281/why-do-no-javascript-engines-support-tail-call-optimization

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