Clojure Programming/Examples/API Examples/Recursion Tools

loop

edit

See recur

recur

edit
; compute the factorial of 5, establishes two 'variables' cnt and acc
; cnt is decremented every call until it reaches 0
; acc stores the result of multiplying each value cnt took
(loop [cnt 5,
       acc 1]
  (if (zero? cnt)
    acc
    (recur (dec cnt) (* acc cnt))))

lazy-cons

edit
(defn fib-seq []
  ((fn rfib [a b] 
       (lazy-cons a (rfib b (+ a b)))) 
    0 1))
 
user> (take 20 (fib-seq))
(0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181)