Contents    Page-10    Prev    Next    Page+10    Index   

Recursive List Design Pattern

(defun fn (lst)
  (if (null lst)       ; test for base case
      baseanswer       ; answer for base case
         (something-about (first lst))
         (fn (rest lst))) ) )  ; recursive call

public int fn (Cons lst) {
  if ( lst == null )
     return baseanswer;
   else return someCombinationOf(
                  fn(rest(lst))); }

The recursive version is often short and elegant, but it has a potential pitfall: it requires O(n) stack space on the function call stack. Many languages do not provide enough stack space for 1000 calls, but a linked list with 1000 elements is not unusual.