liveBook · Manning

State monad

As explained in Functional Programming in Scala, Second Edition

A state monad represents a stateful computation as a function from an input state to a result paired with an output state.

A state monad represents a stateful computation as a function from an input state to a result paired with an output state. Its primitive operations read state with get and replace it with set; unit and flatMap compose these computations. section 11.5.2

Numbering a list

zipWithIndex threads an Int state through a list: each iteration gets the current number, sets the next number, and yields the element paired with its index. Running the composite action from 0 produces the numbered list.

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines unit, flatMap, get, and set, then demonstrates state threading; exercises defer laws and combinator behavior.
Examples
Uses zipWithIndex to number list elements by incrementing an Int state through a for-comprehension.
What it assumes
Assumes monadic operations and Scala type constructors, while motivating partial application through State-specific implementations.
What you can do after
Build it from scratch by implementing State, unit, flatMap, get, set, and state-threading programs.
How it connects
Connects State to monads, type lambdas, for-comprehensions, map, sequence, replicateM, get, and set.

Also explained in

Compare how 2 books explain state monad →

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.