////// A pseudo-random number generator, as a value.////// Randomness is deliberately *data* rather than an effect. A generator is threaded through/// `step` like any other part of the world, which means a simulation that uses randomness is/// still a pure function of its inputs. Replaying a recorded input script from the same seed/// therefore produces a bit-identical result, with no handler to install and no shared/// generator to reason about across threads.////// This is a 64-bit linear congruential generator using the multiplier and increment from/// Knuth's MMIX. It is not cryptographic and is not meant to be.///pubenumRngwithEq, ToString {case Rng(Int64)}mod Rng {defmultiplier(): Int64 = 6364136223846793005i64defincrement(): Int64 = 1442695040888963407i64////// Creates a generator from `seed`.////// The state is advanced once so that adjacent seeds do not produce correlated first/// values, which is the usual failure mode of a bare LCG.///pubdeffromSeed(seed: Int64): Rng = advance(Rng.Rng(seed))/// Advances the state by one step. Int64 arithmetic wraps, which is what an LCG wants.defadvance(r: Rng): Rng = matchr {case Rng.Rng(state) => Rng.Rng(state*multiplier() +increment()) }////// Returns the next 64-bit value and the advanced generator.///pubdefnextInt64(r: Rng): (Int64, Rng) = {letnext = advance(r);matchnext {case Rng.Rng(state) => (state, next) } }////// Returns a non-negative 64-bit value and the advanced generator.////// Negatives are folded rather than negated, because negating `Int64.minValue` would/// overflow back to itself.///pubdefnextNonNegative(r: Rng): (Int64, Rng) = {let (value, next) = nextInt64(r);letfolded = if (value<0i64) -(value+1i64) elsevalue; (folded, next) }////// Returns a value in `0 ..< bound` and the advanced generator.////// A `bound` of zero or less yields `0`, so callers never have to guard.///pubdefnextInt32Below(bound: Int32, r: Rng): (Int32, Rng) =if (bound<=0) (0, advance(r))else {let (value, next) = nextNonNegative(r);letscaled = Int64.remainder(value, Int32.toInt64(bound));// `scaled` is already in 0 ..< bound, so it always fits in an Int32. Crash rather// than substitute a zero: a silent zero here would look like a working generator// that had quietly stopped being random.matchInt64.tryToInt32(scaled) {case Some(fits) => (fits, next)case None => unreachable!() } }////// Returns `true` with probability `1 / oneIn`, and the advanced generator.///pubdefchance(oneIn: Int32, r: Rng): (Bool, Rng) = {let (value, next) = nextInt32Below(oneIn, r); (value==0, next) }}