在斯卡拉,在Stream
类的实例上调用isEmtpy
方法是否会导致流被完全评估?我的代码是这样的:Stream中的isEmpty方法是否评估整个Stream?
import Stream.cons
private val odds: Stream[Int] = cons(3, odds.map(_ + 2))
private val primes: Stream[Int] = cons(2, odds filter isPrime)
private def isPrime(n: Int): Boolean = n match {
case 1 => false
case 2 => true
case 3 => true
case 5 => true
case 7 => true
case x if n % 3 == 0 => false
case x if n % 5 == 0 => false
case x if n % 7 == 0 => false
case x if (x + 1) % 6 == 0 || (x - 1) % 6 == 0 => true
case x => primeDivisors(x) isEmpty
}
import Math.{sqrt, ceil}
private def primeDivisors(n: Int) =
primes takeWhile { _ <= ceil(sqrt(n))} filter {n % _ == 0 }
那么,这是否调用isEmpty
就行case x => primeDivisors(x) isEmpty
导致所有的素因子进行评估或只有第一个?
这是真的。 'Stream.cons(print(“Hello”),Stream(print(“World!”)))。isEmpty'只会打印出Hello,而不是Hello World!。所以,只有第一个元素将被评估。 – 2010-05-13 13:26:51