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.
monadkind of · A monad is a functional abstraction that encapsulates computational context and provides operations for composing computations while preserving that context.
state-passingimplements · State-passing is a technique in which state is supplied as a function argument and the resulting computation returns updated state.
runStateused by · runState is a Haskell state-monad function that executes a stateful computation from an initial state and returns its result together with the final state.
monad stackpart of · A monad stack is a nested composition of monads or monad transformers that combines multiple computational effects behind one monadic interface.
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.