Monday, October 24, 2011

Clojure recursion and recur

I'm still trying to find good explanations of this stuff but for now, trial and error provides results.
(defn loopthru1 [n]
  (if-not (empty? n) (do
       (println (first n))
       (loopthru1 (rest n))
  ))
)
(loopthru1 [1 2 3 4 5 6])

(def pack
  [ { :name "Bichon Frise"
      :description (list "small" "white" "even-tempered")}
    { :name "Australian Shepherd"
      :description (list "medium" "mottled" "even-tempered")}
  ])
(loopthru1 pack)
loopthru 1 (above) explicitly calls itself whereas loopthru2 (below) uses recur.
(defn loopthru2 [n]
  (if-not (empty? n)
    (do (println (first n))
     (recur (rest n)))))
(loopthru2 [1 2 3 4 5 6])

(defn loopthru3 [n]
  (when (seq n)
    (println (first n))
    (recur (rest n))))
(loopthru3 [1 2 3 4 5 6])