Last active
September 4, 2017 15:06
-
-
Save missingfaktor/a70b8fe1c2fe314017b90663127a485b to your computer and use it in GitHub Desktop.
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
| akar.try-out=> (defn tail-recursive-sum [x running-total] | |
| #_=> (if (zero? x) running-total #(tail-recursive-sum (dec x) (+ running-total x)))) | |
| #'akar.try-out/tail-recursive-sum | |
| akar.try-out=> (alter-var-root #'tail-recursive-sum (fn [cur] (partial trampoline cur))) | |
| #object[clojure.core$partial$fn__4759 0x6188158f "clojure.core$partial$fn__4759@6188158f"] | |
| akar.try-out=> (tail-recursive-sum 10000 0) | |
| StackOverflowError clojure.lang.Util.equiv (Util.java:30) |
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
| scala> import util.control.TailCalls._ | |
| import util.control.TailCalls._ | |
| scala> def tailRecursiveSum(x: Int, running: Int): TailRec[Int] = x match { | |
| | case 0 => done(running) | |
| | case _ => tailcall(tailRecursiveSum(x - 1, x + running)) | |
| | } | |
| tailRecursiveSum: (x: Int, running: Int)util.control.TailCalls.TailRec[Int] | |
| scala> tailRecursiveSum(100000, 0).result | |
| res2: Int = 705082704 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@puredanger Thanks a lot, mate! I figured out what was wrong.
alter-var-rootalso changes the reference totail-recursive-sumin its original definition. :-) Mutability... Still bites me after all these years!