Squirrel

The programming language
Welcome to Squirrel Sign in | Join | Help
in Search

What counts as tail recursion?

Last post 06-16-2008, 8:17 AM by Zutty. 2 replies.
Sort Posts: Previous Next
  •  05-30-2008, 9:22 AM 2549

    What counts as tail recursion?

    Hi all,

    I am trying to build some tail recursive functions, but I must admit that I am unfamiliar with the concepts behind it. I have read some guides about tail recursion, but the Squirrel documentation is pretty sparse and I'm still not really certain how strictly I must meet the criteria. How will I know if Squirrel is treating my function as tail recursive or just as regular recursion?

    The code is here...
    function BinaryHeap::BubbleDown(index) {
        if(index * 2 >= this.data.len()) {
            return;
        }
       
        local left  = index * 2;
        local right = index * 2 + 1;
        local smallest = left;
       
        if(right < (this.data.len() - 1) && this.data[left] > this.data[right]) {
            smallest = right;
        }
       
        if(this.data[smallest] < this.data[index]) {
            this.Swap(index, smallest);
            this.BubbleDown(smallest);
        }
    }

    function BinaryHeap::BubbleUp(index) {
        if(index < 1) {
            return;
        }
       
        local parnt  = index / 2;
       
        if(this.data[index] < this.data[parnt]) {
            this.Swap(parnt, index);
            this.BubbleUp(parnt);
        }
    }

    Can you tell what it's for? Wink [;)]

    The calls for recursion come at the end of the function as required, but they are inside a conditional block (which goes against a guide I read about tail recursion) AND not in a return statement (which goes against the Squirrel documentation). Does this still count?

    Any thoughts? Thanks in advance Smile [:)]
  •  06-08-2008, 1:29 PM 2562 in reply to 2549

    Re: What counts as tail recursion?

    tail recursion kicks in only if the call is the expression in a return statement:

    return myfunction(a,b,c);

    this code is always a tail recursion, there aren't any other case.

    if you don't care about the return value of your function, you still have to call it like this to make the tail recursion happend.

    also if the function is a C++ native function it will never be invoked as a tail call.

    I hope this helps

    Alberto

  •  06-16-2008, 8:17 AM 2568 in reply to 2562

    Re: What counts as tail recursion?

    Thanks very much for the reply.
View as RSS news feed in XML
Powered by Community Server, by Telligent Systems