A state transition is a function of type RNG => (A, RNG): it consumes an RNG state, produces a value, and returns the successor state. The Rand[A] alias treats this function as a reusable state action rather than an immediate random value. section 6.4
State transitions make state propagation explicit while allowing actions to compose:
- unit returns a constant while passing the RNG state through unchanged. section 6.4
- map transforms an action's result without modifying the successor state. section 6.4
- map2 combines two actions, while sequence combines a list of actions into one action. section 6.4.1
- flatMap and for-comprehensions express successive state-dependent actions in an imperative-looking, side-effect-free style. section 6.6
Deriving a non-negative even value
Define nonNegativeEven by mapping nonNegativeInt with i => i - (i % 2). The transformation changes the generated value while preserving the state produced by nonNegativeInt. section 6.4
def map[A, B](s: Rand[A])(f: A => B): Rand[B] =
rng =>
val (a, rng2) = s(rng)
(f(a), rng2)
Inspect the map implementation to see state consumption, result transformation, and successor-state preservation in one function. section 6.4






