2010-05-13 278 views
3

在斯卡拉,在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導致所有的素因子進行評估或只有第一個?

回答

8

只有當流實際上是空的:)

否則,它只會看是否流有頭和尾(匹配Stream.cons)並返回false。

+0

這是真的。 'Stream.cons(print(「Hello」),Stream(print(「World!」)))。isEmpty'只會打印出Hello,而不是Hello World!。所以,只有第一個元素將被評估。 – 2010-05-13 13:26:51