In Scala, does calling isEmtpy
method on an instance of Stream
class cause the stream to be evaluated completely? My code is like this:
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 }
So, does the call to isEmpty
on the line case x => primeDivisors(x) isEmpty
cause all the prime divisors to be evaluated or only the first one?