Created
January 9, 2013 14:29
-
-
Save cgag/4493547 to your computer and use it in GitHub Desktop.
Clojure recur example
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
(defn naive-sum [n] | |
(if (= n 0) | |
0 | |
(+ n (naive-sum (dec n))))) | |
(defn recur-sum [n] | |
(loop [acc 0 | |
cnt n] | |
(if (= cnt 0) | |
acc | |
(recur (+ acc cnt) (dec cnt))))) | |
recur.core=> (naive-sum 1000000) | |
#<StackOverflowError java.lang.StackOverflowError> | |
recur.core=> (recur-sum 1000000) | |
500000500000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment