liveBook · Manning

ST

As explained in Functional Programming in Scala, Second Edition

ST is a book-defined monadic abstraction for in-place mutable state whose underlying state-manipulating function cannot be directly invoked outside its scope.

ST is a monadic abstraction for local, in-place mutation. It uses a state token of type S to authorize operations on mutable data tagged with the same scope, while preventing mutable references from escaping that scope. section 14.2.1

Unlike State[S, A], which passes an immutable-looking state value from one action to the next, ST represents mutation through a token. Its underlying state-manipulating function remains unavailable for direct invocation outside the permitted scope. section 14.2.1

The abstraction provides:

  • STRef for allocating, reading, and writing a mutable cell. section 14.5
  • STArray for local mutable-array access and updates. section 14.5

Quicksort with local mutation

A functional quicksort can use STArray for the array and STRef for the partition index. Reads, swaps, and writes become composed ST actions, while the mutation remains unobservable outside the operation. section 14.2.1

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines the token model and combinators, then applies STRef, STArray, and STMap without detailing the complete scope-running mechanism.
Examples
Demonstrates quicksort, array partitioning, map filling, mutable maps, and recycled file-I/O buffers.
What it assumes
Assumes familiarity with State[S, A] as a state-transforming function and introduces typed scoping as the new constraint.
What you can do after
Build local mutable algorithms by composing ST actions around cells, arrays, and maps while preserving scope boundaries.
How it connects
Connects ST to the State monad, STRef, STArray, mutable maps, quicksort, and typed effect tracking.

Related concepts

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.