The book 'Functional Programming in Scala' demonstrates an example of pure functional random number generator as below
trait RNG {
def nextInt: (Int, RNG)
}
object RNG {
def simple(seed: Long): RNG = new RNG {
def nextInt = {
val seed2 = (seed*0x5DEECE66DL + 0xBL) &
((1L << 48) - 1)
((seed2 >>> 16).asInstanceOf[Int],
simple(seed2))
}
}
}
The usage will look like
val (randomNumber,nextState) = rng.nextInt
I do get the part that it's a pure function as it returns the next state and leaves it on the API client to use it to call nextInt
the next time it would need a random number but what I did not understand is 'how will the first random number be generated as we must provide seed
at least once.
Should there be another function to lift seed
to get a RNG
? And if so then how do we expect the client of this API to know about it (because in the non-functional implementation user just calls nextInt
and the state is maintained by API)
Can someone give a full example of pure functional random number generator in Scala and perhaps relate it to state Monad in general.