philipbohun.com

Glojure by Example: Recursion

recur repeats a function or a loop without growing the stack. This factorial multiplies an accumulator on the way down.

(defn factorial [n]
  (loop [i n
         acc 1]
    (if (<= i 1)
      acc
      (recur (dec i) (* acc i)))))

(println (factorial 5))

A function can also call itself by name. That uses a stack frame per call, which is fine for a short collection and the wrong tool for a long one.

(defn length [coll]
  (if (empty? coll)
    0
    (inc (length (rest coll)))))

(println (length [:a :b :c]))

5! is 120. The vector has three elements.

$ glj recursion.glj
120
3

Next example: Strings and Characters.