Last active
March 2, 2016 09:01
-
-
Save davidkaste/c9d2e5b150b21352110f to your computer and use it in GitHub Desktop.
Some examples of how to get the 15 first fibonacci numbers in Clojure
This file contains hidden or 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
; Classic recursion | |
(defn fibo [n] | |
(if (or (= n 0) (= n 1)) | |
n | |
(+ (fibo (dec n)) (fibo (- n 2))))) | |
(map fibo (range 15)) | |
; Tail-call recursion | |
(defn fibo2 [n] | |
(loop [cnt n fst 0 scd 1] | |
(if (zero? cnt) | |
fst | |
(recur (dec cnt) scd (+ fst scd))))) | |
(map fibo2 (range 15)) | |
; Lazy sequence | |
(defn fibo3 [fst scd] | |
(lazy-seq (cons fst (fibo3 scd (+ fst scd))))) | |
(take 15 (fibo3 0 1)) | |
; Haskell's zipWith inspired oneliner solution | |
(def fibo4 (lazy-cat [0 1] (map + fibo4 (rest fibo4)))) | |
(take 15 fibo4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment