Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this code does not throw StackOverflow exception

Tags:

jvm

clojure

In clojure v1.6.0, this code just runs forever and consumes 100% of one core:

(defn average [x y] (/ (+ x y) 2))

(defn improve [guess x]
  (average guess (/ x guess)))

(defn sqrt-iter [guess x]
  (sqrt-iter (improve guess x) x))

(sqrt-iter 1 4)

I'd expect it to throw a StackOverflowError immediately, but it doesn't.

Any explanation why it happens?

like image 412
zerkms Avatar asked Nov 16 '14 06:11

zerkms


1 Answers

Because 1 is a long. The code starts computing extremely long rationals, and slows to a crawl after a few iterations. If you run it with 1.0 and 4 it blows the stack very quickly after a few thousand calls (may vary depending on your jvm parameters).

like image 148
Diego Basch Avatar answered Sep 20 '22 12:09

Diego Basch