Skip to content

Instantly share code, notes, and snippets.

@tafsiri
Created July 26, 2011 04:24
Show Gist options
  • Save tafsiri/1105974 to your computer and use it in GitHub Desktop.
Save tafsiri/1105974 to your computer and use it in GitHub Desktop.
;standard stack consuming fib
(defn fib [n]
(cond
(= 0 n) 0
(= 1 n) 1
:else (+ (fib (- n 1)) (fib (- n 2)))))
;tail recursive fib using loop-recur
;loop-recur allow you to rebind variables each
;pass through. According to the docs it is the only non stack-consuming
;looping method in closure.
(defn fib-tail [n]
(loop [num n, a1 0, a2 1]
(if (= 0 num) a1
(recur (- num 1), a2, (+ a1 a2)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment