Effects as State
Tutorial Video
Text description (accessibility)
This video demonstrates the "Effects as State" functional Rust example. Difficulty level: Expert. Key concepts covered: Functional Programming. The state monad is a functional pattern for threading state through a computation without explicit mutable state. Key difference from OCaml: 1. **Native vs. simulated**: OCaml's effect
Tutorial
The Problem
The state monad is a functional pattern for threading state through a computation without explicit mutable state. The effect-based equivalent provides Get and Put effects that a handler satisfies by threading state. This unifies state management with the effect handler model, enabling stateful computations to be tested with different initial states, logged, and combined with other effects — all without modifying the computation itself.
🎯 Learning Outcomes
Get and Put as algebraic effects satisfied by a state handler&mut passingCode Example
#![allow(clippy::all)]
// Stub — awaiting conversion from OCaml source.Key Differences
ref cell — the program cannot access it directly; Rust's simulation must structure the callbacks carefully to prevent state leakage.&mut State passed through functions is the production idiom; effects are educational/advanced-pattern territory.OCaml Approach
OCaml 5 native state effects:
effect Get : int
effect Put : int -> unit
let with_state initial f =
let state = ref initial in
match_with f () {
effc = fun (type a) (e : a eff) ->
match e with
| Get -> Some (fun k -> continue k !state)
| Put v -> Some (fun k -> state := v; continue k ())
| _ -> None }
The ref is local to the handler — the program itself has no access to mutable state.
Full Source
#![allow(clippy::all)]
// Stub — awaiting conversion from OCaml source.Deep Comparison
OCaml vs Rust: Effect State
Overview
See the example.rs and example.ml files for detailed implementations.
Key Differences
| Aspect | OCaml | Rust |
|---|---|---|
| Type system | Hindley-Milner | Ownership + traits |
| Memory | GC | Zero-cost abstractions |
| Mutability | Explicit ref | mut keyword |
| Error handling | Option/Result | Result<T, E> |
See README.md for detailed comparison.
Exercises
with_pure_state handler that uses an immutable value thread instead of ref.Modify(f: impl Fn(S) -> S) effect that atomically applies a function to the state.Get and Put operation while also managing the state.