简体   繁体   English

Scala / C ++:Tail递归函数而不是输入循环

[英]Scala/C++: Tail Recursive function instead of input loop

Since I got into Scala I started writing functions using tail recursion, and learned that C++ compilers also support it, and even optimize tail recursive functions. 自从我进入Scala后,我开始使用尾递归编写函数,并了解到C ++编译器也支持它,甚至优化尾递归函数。 Now I'm curious as to how reliable that optimization is, and is it okay to use it for things such as my main loop or command prompt? 现在我很好奇优化的可靠性,并且可以将它用于我的主循环或命令提示符之类的东西吗?

Traditionally I've written command prompts like this: 传统上我写了这样的命令提示:

bool running = true;
string input;
while(running_){
  input = getInput();
  executeCommand(input);
  if(input == "quit") running_ = false;
}

Now would it be a bad thing to replace this with a tail recursive function like this? 现在用这样的尾递归函数替换它会是一件坏事吗?

string input = "nothing";
void parseInput(){
  if(input != "nothing") executeCommand(input);

  getline(cin, input);
  if(input != "quit") parseInput();
}

TCO (tail-call optimization) is applied with different level of reliability by different compilers. TCO(尾调用优化)由不同的编译器应用于不同级别的可靠性。 In your particular case you make it even harder for compiler by not returning immediately after the call inside the branch. 在您的特定情况下,您通过在分支内的调用之后不立即返回来使编译器更难。 Compiler will have to take an extra step to make sure there is no code which will be executed after the call is done. 编译器必须采取额外步骤,以确保在调用完成后没有代码将被执行。

To make sure TCO did happen you have to rely on your best friend. 为了确保TCO确实发生,你必须依靠你最好的朋友。 Your best friend here is asm output. 你最好的朋友是asm输出。

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

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