Skip to content
Recursion and recur
step 1/5

Reading — step 1 of 5

Learn

~1 min readFlow 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))))

Discussion

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

Sign in to post a comment or reply.

Loading…

Recursion and recur — Clojure Fundamentals