11. State, environments, and transformer order
As a program grows, several effects often occur together. A parser may read configuration, update a position, and report errors. Monad transformers combine these concerns while keeping their types explicit.
A state computation takes an initial state and returns a result and an updated state. A reader computation takes an environment and returns a result. A computation that can fail returns either an error or a result.
def record (amount : Nat) : StateM Nat Nat := do
let old ← get
set (old + amount)
pure old
#eval (record 7).run 10
The result is (10, 17). The value 10 is the initial state, and 17 is the updated state after adding the amount. get and set read and update the state of this computation.
Combine a read-only environment with state
structure Config where
maximum : Nat
abbrev Meter := ReaderT Config (StateM Nat)
def consume (amount : Nat) : Meter Bool := do
let config ← read
let used ← get
if used + amount ≤ config.maximum then
set (used + amount)
pure true
else
pure false
#eval ((consume 4).run { maximum := 10 }).run 3
The reader supplies the configuration, and the state records usage. Pass the environment to the outer reader, then pass the initial state to the resulting computation. The output is (true, 7).
abbrev introduces a name that readily unfolds during elaboration. The abbreviation gives the transformer stack a short name while still letting Lean infer its underlying instances.
Failure and state do not commute
abbrev Rollback := StateT Nat (Except String)
abbrev Preserve := ExceptT String (StateM Nat)
def failRollback : Rollback Unit := do
set 5
throw "stopped"
def failPreserve : Preserve Unit := do
set 5
throw "stopped"
#eval failRollback.run 0
#eval failPreserve.run.run 0
In the first stack, the result has the shape Except String (Unit × Nat). The first stack returns a state only on success. The second result has the shape (Except String Unit) × Nat, so the updated state is available alongside an error.
Here “rollback” describes which pure state is available after failure. Reversing file writes or other external IO effects requires a separate mechanism. Transformer order determines which values and errors the program returns.
Both stacks update the state and then throw an error. Only the second result shape returns the final state alongside an error.
Choose the smallest useful abstraction
Pass explicit arguments when only 1 or 2 functions need configuration. Use a reader when more functions share a read-only environment, or state when passing an evolving value obscures the algorithm.
Use transformers when combining effects makes the failure and state behaviour clearer.
A stack is part of the application’s contract. Before choosing its order, write down what information should remain available after failure and check the expanded result type. Use that type to check whether callers can recover the values they need.
Exercises
- Modify
consumeso that a rejected request returns the unchanged state. Check an example that exceeds the limit. - Predict the result shapes for reader-over-exception and exception-over-reader.
- Explain which state and error arrangement is appropriate when a caller must display how much work occurred before failure.