A function is tail recursive if it either returns an answer directly, or the answer is exactly the result of a recursive call. Tail recursion often involves the use of an auxiliary function with extra variables as parameters.
(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
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); }
Contents    Page-10    Prev    Next    Page+10    Index