Skip to content

Commit

Permalink
Merge pull request #1191 from mpilquist/topic/random
Browse files Browse the repository at this point in the history
Added Stream.random and Stream.randomSeeded
  • Loading branch information
pchlupacek committed Jul 27, 2018
2 parents 7c458a1 + 0411d34 commit 6fc5277
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
12 changes: 12 additions & 0 deletions core/jvm/src/test/scala/fs2/StreamSpec.scala
Expand Up @@ -463,6 +463,18 @@ class StreamSpec extends Fs2Spec with Inside {
}
}

"random" in {
val x = runLog(Stream.random[IO].take(100))
val y = runLog(Stream.random[IO].take(100))
x should not be y
}

"randomSeeded" in {
val x = Stream.randomSeeded(1L).take(100).toList
val y = Stream.randomSeeded(1L).take(100).toList
x shouldBe y
}

"regression #1089" in {
(Stream.chunk(Chunk.bytes(Array.fill(2000)(1.toByte))) ++ Stream.eval(
IO.async[Byte](_ => ())))
Expand Down
20 changes: 20 additions & 0 deletions core/shared/src/main/scala/fs2/Stream.scala
Expand Up @@ -2447,6 +2447,26 @@ object Stream {
def raiseError[F[x] >: Pure[x], O](e: Throwable): Stream[F, O] =
fromFreeC(Algebra.raiseError(e))

/**
* Creates a random stream of integers using a random seed.
*/
def random[F[_]](implicit F: Sync[F]): Stream[F, Int] =
Stream.eval(F.delay(new scala.util.Random())).flatMap { r =>
def loop: Stream[F, Int] = Stream.emit(r.nextInt) ++ loop
loop
}

/**
* Creates a random stream of integers using the supplied seed.
* Returns a pure stream, as the psuedo random number generator is
* deterministic based on the supplied seed.
*/
def randomSeeded[F[x] >: Pure[x]](seed: Long): Stream[F, Int] = Stream.suspend {
val r = new scala.util.Random(seed)
def loop: Stream[F, Int] = Stream.emit(r.nextInt) ++ loop
loop
}

/**
* Lazily produce the range `[start, stopExclusive)`. If you want to produce
* the sequence in one chunk, instead of lazily, use
Expand Down

0 comments on commit 6fc5277

Please sign in to comment.