Tail Recursion
Overview of Tail Recursion
Tail Recursion is simply a special form of recursion, in which the recursive call is at the end of the function. This allows for improved efficiency as the final value to be computed is returned without any further calculation when the recursion function terminates.
Factorial without Tail Recursion in C++
First a version without tail recursion will be shown in C++. This version requires that the function has to compute a new value to return to it’s caller after the function it called returned a value.
if ( n <= 1 ) return n;
return n * fact(n-1);
}
Factorial with Tail Recursion in C++
Below is the factorial function with tail recursion. Can you tell the difference from the one posted above? The function below doesn’t need to do any more computations when the function it called returns (considering its not the last function that was called). It simply returns the value without any further calculation.
Usually, if it can be done using tail recursion, the function can be iteratively solved as well.
return fact_h(n, 1);
}
int fact_h(int n, int res) {
if ( n <= 1 ) return res;
return fact_h(n-1, n*res);
}
Tail Recursion in a functional language
In C++, if you can write a tail recursive function most likely you can right an iterative version. In a functional language where iteration isn’t possible, tail recursion allows for greater efficiency in such functions.
Recursive function in ML without tail recursion
Below is a factorial function in ML. This version does not implement tail recursion.
| fact x = x * fact (x-1);
Implementing Tail Recursion in ML
The function below, does implement tail recursion. If you notice, this function does not require to do any computations after the function has returned as the function in the previous version.
| facth x n = facth (x-1) (n*x);
fun fact 1 = 1
| fact x = facth x 1;
Overview of Tail Recursion
So why is this faster? Well, first of all, it means you are uses the stack less, thus increasing efficiency. If you can implement tail recursion in a programming language such as C++, there must be an iterative version of the function. On the other hand if you are creating functions in a logic or functional programming language, try using tail recursion. On large projects you’ll notice a great improvement in runtime.


