Tail Recursive List Design Pattern
public int fn (Cons lst) {
return fnb(lst, answerinit); }
public static int fnb (Cons lst, answer) {
if ( lst == null )
return answer;
else return fnb(rest(lst),
someCombinationOf(
answer,
somethingAbout(first(lst))));}
(defun fn (lst) (fnb lst answerinit))
(defun fnb (lst answer)
(if (null lst) ; test for base case
answer ; answer for base case
(fnb (rest lst)
(some-combination-of
answer
(something-about (first lst)))) ) )
A smart compiler can detect a tail-recursive function and compile it so that it is iterative and uses O(1) stack space.