What is tail recursion?

前端 未结 28 3662
一个人的身影
一个人的身影 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:23

    In Java, here's a possible tail recursive implementation of the Fibonacci function:

    public int tailRecursive(final int n) {
        if (n <= 2)
            return 1;
        return tailRecursiveAux(n, 1, 1);
    }
    
    private int tailRecursiveAux(int n, int iter, int acc) {
        if (iter == n)
            return acc;
        return tailRecursiveAux(n, ++iter, acc + iter);
    }
    

    Contrast this with the standard recursive implementation:

    public int recursive(final int n) {
        if (n <= 2)
            return 1;
        return recursive(n - 1) + recursive(n - 2);
    }
    

提交回复
热议问题