liveBook · Manning

ST action

As explained in Functional Programming in Scala, Second Edition

An ST action is a value representing a computation in the ST monad that may access or mutate state when run with its state-thread token.

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

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains action representation, state-token typing, safe execution, and reference leakage checks through Scala types.
Examples
Demonstrates allocating, swapping, incrementing, and reading two integer STRef cells.
What you can do after
Build it from scratch using STRef operations, compose the actions, and run only actions whose results do not expose local state.
How it connects
Connects ST actions to the ST monad, STRef, STArray, mutable state, and referential transparency.

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.