Clojure: lazy magic

社会主义新天地 提交于 2019-12-21 07:36:06

问题


Almost 2 identical programs to generate infinite lazy seqs of randoms. The first doesn't crash. The second crash with OutOfMemoryError exception. Why?

;Return infinite lazy sequence of random numbers    
(defn inf-rand[] (lazy-seq (cons (rand) (inf-rand))))    

;Never returns. Burns the CPU but won't crash and lives forever.    
(last (inf-rand))

But the following crash pretty quickly:

;Return infinite lazy sequence of random numbers    
(defn inf-rand[] (lazy-seq (cons (rand) (inf-rand))))    
(def r1 (inf-rand))

;Crash with "OutOfMemoryError"
 (last r1)

回答1:


I believe this is an example of "holding onto the head".

By making the reference r1 in the second example you open up the possibility of later saying something like (first r1) so you will end up storing the members of your lazy-seq as they are reified.

In the first case Clojure can determine that nothing will ever be done with earlier members of the infinite sequence so they can be disposed of and not consume memory.

I am still very much a Clojure beginner myself, any comments or corrections to my understanding or terminology greatly appreciated.



来源:https://stackoverflow.com/questions/1756563/clojure-lazy-magic

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