2009-06-03

Tail recursion is preferred when scanning a list left-to-right, and the result does not specify a particular order. If the result must be in the same order as input, then non-tail is easier to implement. If tail-recursion is desired and result must be in the same order as input, then the accumulator, which is constructed by prepending elements from left-to-right, needs to be reversed. Do not use list append, as it is O(n) for each element, which makes the whole function O(n2).

When traversing the whole binary tree, tail recursion is still possible, but we need to use continuation passing style. For example, in post-order traversal, when traversing the left subtree, we pass it a continuation to tell it what to do when that's done (i.e. should traverse the right tree). When traversing the right tree, we pass it a continuation to tell what to do when that's done (i.e. do something with the parent). A continuation is a function closure that is called by the base case of recursion, taking the accumulator (which is the partial result) as the argument. The continuation would perform further computation on the accumulator.