Created
February 21, 2012 22:16
-
-
Save tapichu/1879392 to your computer and use it in GitHub Desktop.
Fibonacci with Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; 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