简体   繁体   中英

Is a method that has a method call in one if its parameters called tail recursive?

I am studying tail recursion and I am not sure I am getting the definition right.

I saw this post's best answer (link) and am wondering if the method sum(int x, int num) is considered tail-recursive in the following example:

public class tailrecusiontest {

    private static int total;

    private static int add(int num)
    {
        total+=num;
        return total;
    }

    public static int sum(int x, int num) //THIS METHOD TAIL-RECURSIVE?
    {
        if(num == 0)
        {
            return x;
        }

        return sum(add(num), num-1);
    }


    public static void main(String[] args) {
        System.out.print("" + sum(0,4));
    }
}

Ie: What is stopping me to create an object and have call a method ( add(int num) in my example) that will handle the data, give back an output and, by definition , call it the method tail-recursive ?

I am asking this question because an assignment is asking me if I can make a method "tail-recursive", and wonder how far the definition of tail-recursion extends.

This means that I can create any method and pass in the values then call it tail-recursive

Your method meets the definition of tail recursion, but Java itself does not have the tail recursion optimization. That means that you will still have a N-sized stack and return through it 1 by 1.

In simplistic terms, tail recursion is a type of recursion where the recursive call is the final instruction in the function.

Based on that simple definition, your sample code is tail recursive because the recursive call is the last instruction.

That said, this question feels like a duplicate since you're essentially asking what tail recursion is and several posts on SO have done justice to that. For further reading on tail recursion see 'What is tail recursion' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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