This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

View file

@ -0,0 +1,2 @@
(defn fibs []
(map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))

View file

@ -0,0 +1 @@
(nth (fibs) 5)

View file

@ -0,0 +1,6 @@
(defn fibs []
(map first ;; throw away the "metadata" (see below) to view just the fib numbers
(iterate ;; create an infinite sequence of [prev, curr] pairs
(fn [[a b]] ;; to produce the next pair, call this function on the current pair
[b (+ a b)]) ;; new prev is old curr, new curr is sum of both previous numbers
[0 1]))) ;; recursive base case: prev 0, curr 1

View file

@ -0,0 +1 @@
(def fib (lazy-cat [0 1] (map + fib (rest fib))))

View file

@ -0,0 +1,2 @@
user> (take 10 fib)
(0 1 1 2 3 5 8 13 21 34)

View file

@ -0,0 +1,18 @@
;; max is which fib number you'd like computed (0th, 1st, 2nd, etc.)
;; n is which fib number you're on for this call (0th, 1st, 2nd, etc.)
;; j is the nth fib number (ex. when n = 5, j = 5)
;; i is the nth - 1 fib number
(defn- fib-iter
[max n i j]
(if (= n max)
j
(recur max
(inc n)
j
(+ i j))))
(defn fib
[max]
(if (< max 2)
max
(fib-iter max 1 0N 1N)))