// m04 random: a tiny "state monad" for randomness. A Random is a function seed -> [A, nextSeed], // so every draw is a pure function and the seed is passed along explicitly instead of hidden. /** mulberry32: a small, fast generator. `imul` is 32-bit integer multiplication (plain `*` would lose bits). */ export const nextUint32 = (seed) => { const s = (seed + 0x6D2B79F5) >>> 0 // `>>> 0` keeps numbers unsigned 32-bit const t1 = Math.imul(s ^ (s >>> 15), s | 1) const t2 = t1 ^ (t1 + Math.imul(t1 ^ (t1 >>> 7), t1 | 61)) return [(t2 ^ (t2 >>> 14)) >>> 0, s] } /** A Random that always gives `a` and leaves the seed untouched. */ export const pure = (a) => (seed) => [a, seed] /** Transform the value a Random produces; the seed threading is unchanged. */ export const map = (r, f) => (seed) => { const [a, next] = r(seed) return [f(a), next] } /** Run `r`, let `f` pick the next Random from its value, and run that with the seed `r` left behind. */ export const flatMap = (r, f) => (seed) => { const [a, next] = r(seed) return f(a)(next) } /** A Random giving a number in `[0, n)`. */ export const intBelow = (n) => map(nextUint32, (v) => v % n) /** Run a Random from a seed: `[value, nextSeed]`. */ export const run = (r, seed) => r(seed)