12/14/12

Tail Call

In computer science, a tail call is a subroutine call that happens inside another procedure as its final action; it may produce a return value which is then immediately returned by the calling procedure. The call site is then said to be in tail position, i.e. at the end of the calling procedure. If any call that a subroutine performs, such that it might eventually lead to this same subroutine being called again down the call chain, is in tail position, such a subroutine is said to be tail-recursive. This is a special case of recursion.

Tail calls are significant because they can be implemented without adding a new stack frame to the call stack. Most of the frame of the current procedure is not needed any more, and it can be replaced by the frame of the tail call, modified as appropriate (similar to overlay for processes, but for function calls). The program can then jump to the called subroutine. Producing such code instead of a standard call sequence is called tail call elimination, or tail call optimization.

For example, with Tail Call Optimization, following:

call factorial (3)
 call fact (3 1)
  call fact (2 3)
   call fact (1 6)
    call fact (0 6)
    return 6
   return 6
  return 6
 return 6
return 6

might be optimized into the more efficient variant, in terms of both space and time:

call factorial (3)
 call fact (3 1)
 replace arguments with (2 3), jump to "fact"
 replace arguments with (1 6), jump to "fact"
 replace arguments with (0 6), jump to "fact"
 return 6
return 6

No comments:

Post a Comment