如何在Clojure中将惰性序列转换为非惰性 [英] How to convert lazy sequence to non-lazy in Clojure
问题描述
我在 Clojure 中尝试了以下操作,期望返回非惰性序列的类:
I tried the following in Clojure, expecting to have the class of a non-lazy sequence returned:
(.getClass (doall (take 3 (repeatedly rand))))
然而,这仍然返回clojure.lang.LazySeq
.我的猜测是 doall
确实会评估整个序列,但会返回原始序列,因为它对于记忆仍然有用.
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
就是你所需要的.仅仅因为 seq
的类型为 LazySeq
并不意味着它有待处理的评估.惰性 seq
缓存它们的结果,所以你需要做的就是遍历惰性 seq
一次(如 doall
那样)以强制它所有,从而使其非懒惰.seq
不会不强制评估整个集合.
doall
is all you need. Just because the seq
has type LazySeq
doesn't mean it has pending evaluation. Lazy seq
s 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屋!