Files
functional-programming-snake/scala/src/Random.scala
T
2026-10-29 00:07:27 +01:00

35 lines
1.3 KiB
Scala

package snake
/**
* A `Random[A]` is a plain function from a seed to a pair: `seed => (value, nextSeed)`.
* Seeds and values are unsigned 32-bit integers held in a `Long` (0 until 2^32).
* Nothing is hidden or mutated: the caller carries the seed.
*/
final case class Random[A](run: Long => (A, Long)):
/** Transform the value this Random produces; the seed threading is unchanged. */
def map[B](f: A => B): Random[B] = ???
/** Run this Random, feed its value to `f` to pick the next Random, and run that with the seed this one left behind. */
def flatMap[B](f: A => Random[B]): Random[B] = ???
object Random:
/** A Random that always gives `a` and leaves the seed untouched. */
def pure[A](a: A): Random[A] = ???
/**
* The generator (mulberry32). Do the arithmetic in `Int`: `*` wraps around like 32-bit multiplication
* and `>>>` is an unsigned shift. With `s = seed.toInt + 0x6D2B79F5`:
* {{{
* t = (s ^ (s >>> 15)) * (s | 1)
* t = t ^ (t + (t ^ (t >>> 7)) * (t | 61))
* value = t ^ (t >>> 14)
* }}}
* Both `value` and the new seed `s` are returned as unsigned values: `x.toLong & 0xFFFFFFFFL`.
*/
lazy val nextUint32: Random[Long] = ???
/** A Random giving a number in `[0, n)`: the `nextUint32` value modulo `n`. */
def intBelow(n: Int): Random[Int] = ???