Scala Language Streams Using a Stream to Generate a Random Sequence


Example

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]
  } else {
    ("%.3f : A random number" format random) #:: genRandom
  }
}

lazy val randos = genRandom  // getRandom is lazily evaluated as randos is iterated through

for {
  x <- randos
} println(x) // The number of times this prints is effectively randomized.

Note the #:: construct, which lazily recurses: because it is prepending the current random number to a stream, it does not evaluate the remainder of the stream until it is iterated through.