Tutorial by Examples

genRandom creates a stream of random numbers that has a one in four chance of terminating each time it's called. def genRandom: Stream[String] = { val random = scala.util.Random.nextFloat() println(s"Random value is: $random") if (random < 0.25) { Stream.empty[String] ...
Streams can be built that reference themselves and thus become infinitely recursive. // factorial val fact: Stream[BigInt] = 1 #:: fact.zipWithIndex.map{case (p,x)=>p*(x+1)} fact.take(10) // (1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880) fact(24) // 620448401733239439360000 // the ...
// Generate stream that references itself in its evaluation lazy val primes: Stream[Int] = 2 #:: Stream.from(3, 2) .filter { i => primes.takeWhile(p => p * p <= i).forall(i % _ != 0) } .takeWhile(_ > 0) // prevent overflowing // Get list of 10 primes assert(primes.take(...

Page 1 of 1