Can all recursive functions be re-written as tail-recursions?

aerain picture aerain · Jul 30, 2012 · Viewed 9.3k times · Source

Possible Duplicate:
Are there problems that cannot be written using tail recursion?

From my understanding, tail recursion is an optimization you can use when a recursive call does not need information from the recursive calls that it will spam.

Is it possible then to implement all recursive functions using tail-recursion? What about something like DFS, where you need the innermost child to return before the parent can?

Answer

andrew cooke picture andrew cooke · Aug 2, 2012

It depends on exactly what you are asking.

If you want to keep all functions as functions (no mutable state) with the same signatures, then no. The most obvious example is the quicksort, where both calls can't be tail calls.

If you can modify the function in various ways, then yes. Sometimes a local modification is sufficient - often you can add an "accumulator" that builds some expression that is returned, although, if the result involves non-commutative operations, then you need to be careful (for example, when naively constructing linked lists, the order is reversed) or you can add a stack.

Alternatively, you can do a global modification of the entire program, in which each function takes as an extra argument the function that contains future actions. This is the continuation passing that Pete is talking about.

if you are working by hand then the local modification is often fairly easy. but if you're doing automated rewriting (in a compiler for example) then it's simpler to take the global approach (it requires less "smarts").