Does isEmpty method in Stream evaluate the whole Stream?
Posted
by abhin4v
on Stack Overflow
See other posts from Stack Overflow
or by abhin4v
Published on 2010-05-13T09:38:22Z
Indexed on
2010/05/14
8:04 UTC
Read the original article
Hit count: 350
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?
© Stack Overflow or respective owner