Skip to content

Instantly share code, notes, and snippets.

@tapichu
Created February 21, 2012 22:16
Show Gist options
  • Save tapichu/1879392 to your computer and use it in GitHub Desktop.
Save tapichu/1879392 to your computer and use it in GitHub Desktop.
Fibonacci with Clojure
; Credit: Programming Clojure http://pragprog.com/book/shcloj/programming-clojure
; Fibonacci infinite sequence
(defn lazy-seq-fibo
([]
(concat [0 1] (lazy-seq-fibo 0N 1N)))
([a b]
(let [n (+ a b)]
(lazy-seq
(cons n (lazy-seq-fibo b n))))))
(take 10 (lazy-seq-fibo))
(nth (lazy-seq-fibo) 10000)
; Reusing existing sequence library functions
; (take 5 (iterate (fn [[a b]] [b (+ a b)]) [0N 1N])) -> ([0 1] [1 1] [1 2] [2 3] [3 5])
(defn fibo []
(map first (iterate (fn [[a b]] [b (+ a b)]) [0N 1N])))
(take 10 (fibo))
(nth (fibo) 10000)
; All fibos (never ends):
(fibo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment