Contents    Page-10    Prev    Next    Page+10    Index   

Tail Recursive List Design Pattern


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

(defn fn [lst]  (fnb lst answerinit))

A smart compiler can detect a tail-recursive function and compile it so that it is iterative and uses O(1) stack space; this is called tail-call optimization. Unfortunately, Java and thus Clojure are not this smart.