samedi 13 juin 2020

Functional Random in Scala using Java Random

I am writing a functional random value with State monad of cats library (as described here). I'd like to reuse java.util.Random instead of writing nextInt, nextBytes, nextBoolean again, so I am writing something like that:

import cats.data.State

object Random {

  case class Seed(value: Long) {
    def next() = Seed(value * 6364136223846793005L + 1442695040888963407L)
  }

  type Random[T] = State[Seed, T]

  private val javaRandom: Random[java.util.Random] = 
    State(seed => (seed.next(), new java.util.Random(seed.value)))

  val randomLong: Random[Long] = javaRandom.map(_.nextLong())

  val randomInt: Random[Long] = javaRandom.map(_.nextInt())

  ... // randomBoolean, randomBytes, randomFloat, etc.
}

Does it make sense to use java.util.Random ?
Would it be better implement nextLong, nextInt and others manually instead of using java.util.Random ?




Aucun commentaire:

Enregistrer un commentaire