Why this code does not throw StackOverflow exception

若如初见. 提交于 2019-12-23 09:19:53

问题


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?


回答1:


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).



来源:https://stackoverflow.com/questions/26954404/why-this-code-does-not-throw-stackoverflow-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!