Contents    Page-10    Prev    Next    Page+10    Index   

Recursive List Design Pattern


(defn fn [lst]
  (if (empty? lst)       ; test for base case
      baseanswer       ; answer for base case
      (some-combination-of
         (something-about (first lst))
         (fn (rest lst))) ) )  ; recursive call

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.