An ST action is a value representing a computation in the ST monad. Running it with a state-thread token may allocate, read, or mutate private state, while returning an ordinary result when that state remains unobservable. section 14.2.2 section 14.2.3
ST actions preserve locality through several linked design choices:
- STRef operations return actions rather than exposing direct reads or writes. section 14.2.2
- The state-thread type tags both an action and the references it creates, preventing references from crossing action boundaries. section 14.2.2 section 14.2.3
- A polymorphic action of type [s] => () => ST[s, A] can be run when its result does not expose s-dependent state. section 14.2.3
Swapping two local cells
A computation allocates two integer cells, reads their values, writes each value into the other cell after adding one, and returns (3, 2). ST.run executes the polymorphic action while discarding its private state. section 14.2.2 section 14.2.3
final class STRef[S, A] private (private var cell: A):
def read: ST[S,A] = ST(cell)
def write(a: => A): ST[S, Unit] = ST.lift[S, Unit]:
s =>
cell = a
((), s)
object STRef:
def apply[S, A](a: A): ST[S, STRef[S, A]] =
ST(new STRef[S, A](a))
The compact STRef definition shows how reading and writing become ST actions while the mutable cell remains private. section 14.2.2
