Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 542
Snowman Avatar asked Dec 17 '22 20:12

Snowman


2 Answers

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. It then does most of its method. We'll say the recursive call to count is at 0xBBB for this stack frame. 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). If it's doing anything after, it must set the return address as 0xBBC (the address of the addition). 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.

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.

like image 189
Matthew Flaschen Avatar answered Jan 04 '23 15:01

Matthew Flaschen


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
}
like image 41
extraneon Avatar answered Jan 04 '23 16:01

extraneon