Fibonacci Numbers

Posted on May 5, 2024

How would we generate the fibonacci sequnce in clojure?

There are several ways. We could do this with recursion or some type of iterative approach. The recursive solution will not be the most efficient. It will eventually crash on large numbers.

Recursive

(defn simplefib [n]
 (case n
   0 0
   1 1
   (+ (simplefib (- n 1)) (simplefib (- n 2)))
 )
)

(simplefib 10)
; 55

Iterative

(defn fib-add [[a b]]
  [b (+ a b)]
)

(def fib-seq
  (map last (iterate fib-add [0 1]))
)

(take 10 fib-seq)
; => (1 1 2 3 5 8 13 21 34 55)