liveBook · Manning

State transition

As explained in Functional Programming in Scala, Second Edition

A state action is a function that consumes an RNG state and returns a generated value together with a successor RNG state.

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

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines the function representation and develops map, map2, sequence, flatMap, and imperative-style composition.
Examples
Uses nonNegativeEven, paired integer-double actions, list sequencing, and a candy-machine simulation.
What it assumes
Assumes an RNG state and functions while teaching explicit state threading through composable functional values.
What you can do after
Build state actions from scratch and combine them with map, map2, sequence, flatMap, and for-comprehensions.
How it connects
Connects RNG, functional programming, referential transparency, State, map, flatMap, and for-comprehensions.

Also explained in

Compare how 7 books explain state transition →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.