| Copyright | © Frank Jung 2025 |
|---|---|
| License | GPL-3 |
| Safe Haskell | Safe-Inferred |
| Language | Haskell2010 |
MySum
Description
This is a simple example of using the ST Monad for stateful summation of a
list.
The ST monad in Haskell allows you to perform mutable (stateful) computations
in a safe, local way. It stands for "State Thread" and is defined in
Control.Monad.ST (ST).
Key Points
- Local Mutability
- You can create and modify mutable variables (
STRefs) inside theSTmonad. - Safety
- Changes made in the
STmonad are not visible outside; the mutation is encapsulated. - Pure Interface
- When you run an
STcomputation (usingrunST), you get a pure result, and the mutable state cannot escape.
Example usage
Computes the sum of a list using the mySum function:
let total = mySum [1, 2, 3, 4, 5]