Skip to content

Instantly share code, notes, and snippets.

@psfblair
Created August 28, 2010 18:56
Show Gist options
  • Select an option

  • Save psfblair/555456 to your computer and use it in GitHub Desktop.

Select an option

Save psfblair/555456 to your computer and use it in GitHub Desktop.
; Here's one using the standard fibonacci sequence to get the nth fibonacci number
; The nth fibonacci is the sum of the n-1 and the n-2 fibonacci, unless n is < 2 in which case it is 1
(defn fibs [x]
(defn inner-fib [x one-back two-back]
(case x
0 two-back
1 one-back
(recur (dec x) (+ one-back two-back) one-back)
)
)
(inner-fib x 1 0)
)
; We are really building the sequence up from the bottom, but using the number of recursive calls to
; track how many times we iterate. First the base cases:
; (fibonaccis 0) -> (inner-fib 0 1 0) -> 0
; (fibonaccis 1) -> (inner-fib 1 1 0) -> 1
; Now our accumulators keep incrementing the two preceding fibonaccis, while the first parameter decrements.
; When the first parameter hits one, then the first accumulator is our answer:
; (fibonaccis 2) -> (inner-fib 2 1 0) -> (inner-fib 1 1 1) -> 1
; (fibonaccis 3) -> (inner-fib 3 1 0) -> (inner-fib 2 1 1) -> (inner-fib 1 2 1) -> 2
; (fibonaccis 4) -> (inner-fib 4 1 0) -> (inner-fib 3 1 1) -> (inner-fib 2 2 1) -> (inner-fib 1 3 2) -> 3
(apply + (filter even? (take-while #(< % 4000000)
(for [nth (iterate inc 0)] (fibs nth)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment