Is isEmpty method in Stream evaluate the whole stream?

In Scala, does a method invoke an isEmtpyinstance of a class Streamso that the stream is fully evaluated? My code is as follows:

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 a call isEmptyin a string cause case x => primeDivisors(x) isEmptyall simple divisors, or just the first?

+3
source share
2 answers

Only if the stream is actually empty :)

Otherwise, it will simply see if the stream has a head and tail (matches Stream.cons) and returns false.

+8
source

Looking at the source:

https://lampsvn.epfl.ch/trac/scala/browser/scala/trunk/src///library/scala/collection/immutable/Stream.scala#L550

, Stream.Cons, , false. , Stream.cons factory - , , , :

Stream.cons(print("Hello"), Stream(print(" World!")))

, "Hello".

+2

Source: https://habr.com/ru/post/1745247/


All Articles