如何将惰性序列转换为非惰性在Clojure [英] How to convert lazy sequence to non-lazy in Clojure

查看:124
本文介绍了如何将惰性序列转换为非惰性在Clojure的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 (。getClass (doall(take 3(repeated rand))))

c> clojure.lang.LazySeq 。我的猜测是 doall 会评估整个序列,但返回原始序列,因为它仍然对记忆有用。



解决方案

doall 强>是你需要的。只是因为seq有类型LazySeq并不意味着它有待评估。 Lazy seqs缓存他们的结果,所以你需要做的是走懒惰seq一次(doall),以强制它,所以,使它非惰性。 seq不强制对整个收藏集进行评估。


I tried the following in Clojure, expecting to have the class of a non-lazy sequence returned:

(.getClass (doall (take 3 (repeatedly rand))))

However, this still returns clojure.lang.LazySeq. My guess is that doall does evaluate the entire sequence, but returns the original sequence as it's still useful for memoization.

So what is the idiomatic means of creating a non-lazy sequence from a lazy one?

解决方案

doall is all you need. Just because the seq has type LazySeq doesn't mean it has pending evaluation. Lazy seqs cache their results, so all you need to do is walk the lazy seq once (as doall does) in order to force it all, and thus render it non-lazy. seq does not force the entire collection to be evaluated.

这篇关于如何将惰性序列转换为非惰性在Clojure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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