What is tail recursion?

前端 未结 28 3582
一个人的身影
一个人的身影 2020-11-21 05:03

Whilst starting to learn lisp, I\'ve come across the term tail-recursive. What does it mean exactly?

28条回答
  •  感动是毒
    2020-11-21 05:16

    Here is a quick code snippet comparing two functions. The first is traditional recursion for finding the factorial of a given number. The second uses tail recursion.

    Very simple and intuitive to understand.

    An easy way to tell if a recursive function is a tail recursive is if it returns a concrete value in the base case. Meaning that it doesn't return 1 or true or anything like that. It will more than likely return some variant of one of the method parameters.

    Another way is to tell is if the recursive call is free of any addition, arithmetic, modification, etc... Meaning its nothing but a pure recursive call.

    public static int factorial(int mynumber) {
        if (mynumber == 1) {
            return 1;
        } else {            
            return mynumber * factorial(--mynumber);
        }
    }
    
    public static int tail_factorial(int mynumber, int sofar) {
        if (mynumber == 1) {
            return sofar;
        } else {
            return tail_factorial(--mynumber, sofar * mynumber);
        }
    }
    

提交回复
热议问题