Skip to content
Lesson 7 of 10

Step 1 of 5 · Reading · ~1 min

Learn

Flow and Recursion

Clojure has loops, but idiomatic Clojure uses recursion. The JVM doesn't optimize tail calls, so Clojure provides recur — an explicit jump to the function start that doesn't grow the stack.

Plain recursion (limited by stack):

(defn factorial [n]
  (if (<= n 1)
    1
    (* n (factorial (- n 1)))))

Tail-recursive with recur (constant stack):

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

loop establishes recur targets. recur can only appear in tail position — if you put it elsewhere, the compiler errors.

For small problems prefer reduce:

(defn factorial [n] (reduce * (range 1 (inc n))))
Up nextThe Sequence AbstractionSequences, Strings, Destructuring

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…