Proper Tail Recursion vs Iteration
Iteration (in the form of loops) can be implemented
using either proper tail recursion or special syntax
such as while
or for
loops.
Proper tail recursion is more general than special syntax, because tail recursion can be used across multiple functions/methods defined in widely separated parts of a program. Special syntax is almost always limited to the body of a single function or method.
Simple examples of self-tail-recursion can be rewritten as
an equivalent while
or for
loop.
For example,
// Given two non-negative integers, returns their sum. static int sum (int m, int n) { if (m == 0) return n; else return sum (m - 1, n + 1); }
is equivalent to
// Given two non-negative integers, returns their sum. static int sum (int m, int n) { while (m != 0) { m = m - 1; n = n + 1; } return n; }
In current implementations of Java, the while
loop is faster and asymptotically more space efficient.
In a properly tail-recursive implementation of Java, however, those two methods would have the same asymptotic space complexity.