简体   繁体   English

java中的尾递归

[英]Tail Recursion in java

Is this a good example to show tail recursion? 这是显示尾递归的一个很好的例子吗?

public printName(){
    System.out.println("Smith");
    printName();
}

I'm not intending to do this in real life, but i put this as an example for my exam. 我不打算在现实生活中这样做,但我把它作为我考试的一个例子。 Is this one correct? 这是正确的吗?

No, for two reasons: 不,有两个原因:

  • tail recursion is only valuable when compiler supports it ( tail call optimization ). 尾递归仅在编译器支持它时才有价值( 尾调用优化 )。 In Java it will still end with StackOverflowError 在Java中,它仍将以StackOverflowError结束

  • it would be nice to show some stop condition. 显示一些停止条件会很好。 Your code is equivalent to loop running forever. 您的代码相当于永远循环运行。

Consider almost identical code in Scala, the only difference is that Scala compiler will perform tail call optimization and the loop runs forever: 考虑Scala中几乎相同的代码,唯一的区别是Scala编译器执行尾调用优化并且循环永远运行:

def printName() {
  println("Smith"); 
  printName()
}

A better example of tail recursion would be something like this: 尾递归的一个更好的例子是这样的:

public printName(int level){
    if( level <= 0 )
         return;
    System.out.prntln("Smith");
    printName(--level);
}

This examples includes the important part where the recursion is terminated. 此示例包括终止递归的重要部分。

Besides of this: As other answers already noted: Since Java does not optimize tail-recursion, there is no point in using it in this language. 除此之外:正如其他答案已经指出的那样:由于Java不优化尾递归,因此在这种语言中使用它没有任何意义。 So you basically end up to optimize your algorithm yourself - by making it iterative. 所以你基本上最终会自己优化你的算法 - 通过迭代。 That's the point of tail-recursion: It can be proved, that any tail-recursive algorithm can be transformed into an iterative algorithm. 这就是尾递归的要点:可以证明,任何尾递归算法都可以转换为迭代算法。

我会说这是尾递归的一个例子,因为你在程序的尾部递归:)但我不认为JVM会优化它,这可能是你想要的。

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

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