 # tail recursion

(algorithmic technique)

Definition: A special form of recursion where the last operation of a function is a recursive call. The recursion may be optimized away by executing the call in the current stack frame and returning its result rather than creating a new stack frame.

Note: Although it may not save a lot of run time, it can save a lot of memory. The following finds the maximum value in a list.

` int max_list(list l, int max_so_far) {     if (null == l) {         return max_so_far;     }      if (max_so_far < head(l)) {         return max_list(tail(l), head(l));     } else {         return max_list(tail(l), max_so_far);     } } `

The return value of the current invocation is just the return value of the recursive call. A compiler could optimize it something like the following so it doesn't allocate new space for l and max_so_far on each invocation or tear down the stack on the returns.

`  int max_list(list l, int max_so_far) {   for (;;) {     if (null == l) {         return max_so_far;     }      if (max_so_far < head(l)) {         max_so_far = head(l);         l = tail(l);     } else {         max_so_far = max_so_far;         l = tail(l);     }   } } `
Now there is no need to allocate new memory for the parameters or get rid of it during the returns, so this will run faster. This code transformation is simple enough to do by hand in this example, but it is much harder for complex recursive data structures, such as trees.

Of course, if a compiler is good enough to find and rewrite tail recursion, it will also collapse the loop test, eliminate the assignment of max_so_far to itself, and hoist the assignment of l after the test giving the following:

`  int max_list(list l, int max_so_far) {   while (null != l) {     if (max_so_far < head(l)) {         max_so_far = head(l);     }     l = tail(l);   }   return max_so_far; } `

Author: PEB