简体   繁体   English

switch语句是否递归递归?

[英]Are switch statements tail recursive?

I use switch statements now and again. 我不时地使用switch语句。 Every so often I find myself wanting to use return statements inside of my functions. 我经常发现自己想在函数中使用return语句。 I was wondering if switch statements written this way were still tail-call optimized. 我想知道以这种方式编写的switch语句是否仍然是尾调用优化的。

function misc(x) {
    switch(true){
        case x > 1:
            return misc(x-1);
            break;
        default:
            return;
    }
}

What would need to be changed to make case x > 1 tail call optimized. 需要更改以使case x > 1尾部调用优化的情况。 Is it possible to do with a switch statement or would I have to use something else like an if statement? 是否可以使用switch语句或者我是否必须使用if语句之类的其他内容?

Note: I am aware that tail-call optimization isn't supported in JavaScript across most major browsers. 注意:我知道大多数主流浏览器的JavaScript都不支持尾调用优化。 I'm mostly just wondering if the above code is even compatible with tail-call optimization regardless if the current browser supports it or not. 我主要想知道上述代码是否与尾部调用优化兼容,无论当前浏览器是否支持它。

The requirement for tail call optimisation in ES6 only depends on weather the function call is in the tail position - that is, weather the function is the last thing executed before returning. ES6中尾部调用优化的要求仅取决于函数调用处于尾部位置的天气 - 也就是说,函数是返回之前执行的最后一件事。

In your case: 在你的情况下:

return misc(x-1);

puts misc() in the tail position. misc()置于尾部位置。 Therefore it can be tail-call optimised. 因此它可以进行尾调用优化。

The case where that can't happen is if you were to do something like this: 不可能发生的情况是你要做这样的事情:

return 1 + misc(x-1);

That's because it will be equivalent to: 那是因为它等同于:

var tmp = misc(x-1);
tmp = 1 + tmp;
return tmp;

Which means that misc() would not be in the tail position. 这意味着misc()不会处于尾部位置。

So it doesn't matter if the return is in an if or while or switch , as long as the function is in the tail position it can be tail-call optimised. 因此,如果returnifwhileswitch中并不重要,只要函数处于尾部位置,它就可以进行尾调用优化。

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

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