Clojure:懒惰的魔法 [英] Clojure: lazy magic

查看:142
本文介绍了Clojure:懒惰的魔法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几乎两个相同的程序生成无限延迟随机数。
第一个不会崩溃。第二个崩溃与OutOfMemoryError异常。为什么?

 ;返回无限延迟随机数序列
(defn inf-rand [](lazy-seq cons(rand)(inf-rand))))

;从不返回。烧毁CPU,但不会崩溃,永远生活。但是下面的崩溃很快: p>

 ;返回无限延迟随机数序列
(lny-seq (inf r rand)))
(def r1(inf-rand))

;崩溃与OutOfMemoryError
(last r1)


解决方案

我相信这是一个坚持头脑的例子。



通过在第二个例子中使用引用r1,你可以稍后说出(第一个r1)



在第一种情况下,Clojure可以确定以前的成员不会做任何事情的无限序列,所以他们可以处置,不消耗记忆。



我仍然是一个Clojure初学者自己,任何评论或更正我的理解或术语大大赞赏。


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)

解决方案

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.

这篇关于Clojure:懒惰的魔法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆