简体   繁体   English

Java中的尾部/前向递归

[英]Tail/forward recursion in Java

I dont understand why this is forward recursion: 我不明白为什么这是前向递归:

int count(int x) {
    if(x<=0) return 0;
    return 1 + count(x - 1);
}

It's a question on a practice exam, and the answer is that its forward recursion. 这是一个关于练习考试的问题,答案是它的前向递归。 Why is this the case? 为什么会这样? How could I distinguish between the two? 我怎么能区分这两者?

You're doing an addition after calling yourself. 在给自己打电话之后,你正在做一个补充。 Tail recursion means absolutely nothing can be after 尾递归意味着绝对没有什么可以追随

If you understand the implementation, it's clear why. 如果您了解实施,那么很明显为什么。

Say we call count for the first time from main , which is at program counter 0xAAA . 假设我们第一次从main调用count ,这是在程序计数器 0xAAA It then does most of its method. 然后它完成了大部分方法。 We'll say the recursive call to count is at 0xBBB for this stack frame. 我们将说这个堆栈帧的递归调用计数为0xBBB If you're using tail recursion, when calling itself, it can set the return address as 0xAAA (just go straight to the code that called me). 如果您正在使用尾递归,则在调用自身时,它可以将返回地址设置为0xAAA (直接转到调用我的代码)。 If it's doing anything after, it must set the return address as 0xBBC (the address of the addition). 如果之后正在执行任何操作 ,则必须将返回地址设置为0xBBC (添加的地址)。 Because it doesn't need stack frames to store return addresses, it's also much easier to transform the recursion to iteration. 因为它不需要堆栈帧来存储返回地址,所以将递归转换为迭代也更容易。 When count calls itself, it can just jump to the beginning of the method. count调用自身时,它可以跳转到方法的开头。

The solution (to the trivial example) is to build up the result in another parameter: 解决方案(对于简单的例子)是在另一个参数中建立结果:

int count(int x, int res) {
  if(x<=0) return res;
  return count(x - 1, res + 1);
}

Note we do nothing after. 注意我们之后什么都不做。

Did you look at this SO question, tail vs forward recursion ? 您是否看过这个问题,尾部与前向递归

Matthew has the answer,and the long form would be that: 马修有答案,长篇大论就是:

int count(int x) {
  if(x<=0) return 0;
  return 1 + count(x - 1);
}  

can be written as (and is expanded as something like): 可以写成(并扩展为类似):

int count(int x) {
    if(x<=0) return 0;
    int tmp_result = count(x - 1);
    return 1 + tmp_result; // e.g. recursion is not last
}

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

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