STRef wraps a private mutable cell while exposing only ST actions for allocation, reading, and writing. The cell remains local to an ST computation, allowing mutation without exposing observable effects. section 14.2.2 section 14.5
Use STRef through three scoped operations:
- Allocate with STRef.apply, which returns an ST[S, STRef[S, A]] action rather than a naked reference. section 14.2.2
- Read through read: ST[S, A] and write through write(a): ST[S, Unit]; both methods return actions instead of performing effects immediately. section 14.2.2
- Keep the phantom-like S parameter aligned across the action and reference; this token authorizes access without representing the cell's value. section 14.2.2
Swapping two local cells
A computation allocates two Int cells, reads their values, writes them back in swapped-and-incremented form, and yields the resulting pair. Running the polymorphic ST program produces (3, 2), while attempting to return the STRef itself is rejected because it would escape the local scope.
