在斯卡拉,在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