Scala的理解力何时会变得懒惰? [英] When are scala's for-comprehensions lazy?
问题描述
在Python中,我可以执行以下操作:
In Python, I can do something like this:
lazy = ((i,j) for i in range(0,10000) for j in range(0,10000))
sum((1 for i in lazy))
需要一段时间,但是内存使用量是恒定的.
It will take a while, but the memory use is constant.
scala中的相同构造:
The same construct in scala:
(for(i<-0 to 10000; j<-i+1 to 10000) yield (i,j)).count((a:(Int,Int)) => true)
过一会儿,我得到一个java.lang.OutOfMemoryError
,即使应该懒惰地对其求值.
After a while, I get a java.lang.OutOfMemoryError
, even though it should be evaluated lazily.
推荐答案
Scala的理解力并没有天生地懒惰.它是语法糖*,不会改变您两个范围的组合会急切的事实.
Nothing's inherently lazy about Scala's for-comprehension; it's syntactic sugar* which won't change the fact that the combination of your two ranges will be eager.
如果您使用范围的惰性view
,则理解的结果也将是惰性的:
If you work with lazy view
s of your ranges, the result of the comprehension will be lazy too:
scala> for(i<-(0 to 10000).view; j<-(i+1 to 10000).view) yield (i,j)
res0: scala.collection.SeqView[(Int, Int),Seq[_]] = SeqViewN(...)
scala> res0.count((a: (Int, Int)) => true)
res1: Int = 50005000
这里的惰性与理解力无关,但是因为在某些类型的容器上调用flatMap
或map
(请参见下文)时,您会在相同类型的容器中返回结果.因此,理解力只会保留您所放内容的惰性(或缺乏).
The laziness here is nothing to do with the for-comprehension, but because when flatMap
or map
(see below) are called on some type of container, you get back a result in the same type of container. So, the for-comprehension will just preserve the laziness (or lack of) of whatever you put in.
*用于类似的内容:
(0 to 10000).flatMap(i => (i+1 to 10000).map(j => (i, j)))
这篇关于Scala的理解力何时会变得懒惰?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!