懒惰的scala中的理解评估

GTD*_*Dev 3 functional-programming scala immutability lazy-evaluation for-comprehension

我是scala和大多数函数式语言的新手,我现在正试图计算一个数字.我写了代码:

lazy val factors = for(int <- 2 until  math.ceil(math.sqrt(number)).toInt if number%int == 0) yield int
Run Code Online (Sandbox Code Playgroud)

我想知道如果我宣布scala val是懒惰的,那么当我打电话时它不会评估整个理解factors.head吗?

mis*_*tor 10

你的factors变量是懒惰的; 的for理解是没有的.当您factors第一次访问时,您的for理解将得到充分评估.

在Scala中,for理解仅仅是糖flatMap,mapwithFilter方法调用.因此,如果您的支持数据结构是严格的(例如Range- 您正在使用的),您的for理解也将是严格的.如果数据结构是懒惰的(如Stream),那么将是for理解.

观察差异:

scala> val number = 50
number: Int = 50

scala> lazy val factors = for(int <- 2 until  math.ceil(math.sqrt(number)).toInt if number%int == 0) yield int
factors: scala.collection.immutable.IndexedSeq[Int] = <lazy>

scala> factors.head
res5: Int = 2

scala> factors
res6: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 5)

scala> lazy val factors = for(int <- Stream.range(2, math.ceil(math.sqrt(number)).toInt - 1) if number%int == 0) yield int
factors: scala.collection.immutable.Stream[Int] = <lazy>

scala> factors.head
res7: Int = 2

scala> factors
res8: scala.collection.immutable.Stream[Int] = Stream(2, ?)
Run Code Online (Sandbox Code Playgroud)