Contents    Page-10    Prev    Next    Page+10    Index   

Tail Recursive Processing of List

A function is tail recursive if it either

Tail recursion often involves the use of an extra function with extra variables as parameters.

public static int length (Cons lst) {
  return lengthb(lst, 0); }

public static int lengthb (Cons lst, int answer) {
  if ( lst == null )
     return answer;
   else return lengthb(rest(lst), answer + 1); }

(defun length (lst)
  (lengthb lst 0))         ; init extra variable

(defun lengthb (lst answer)
  (if (null lst)           ; test for base case
      answer               ; answer for base case
      (lengthb (rest lst)  ; recursive call
               (+ answer 1)) ) )   ; update answer