liveBook · Manning

STRef

As explained in Functional Programming in Scala, Second Edition

STRef is a book-defined mutable-reference wrapper whose operations produce ST actions for reading or writing a cell.

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.

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains private storage, action-returning operations, authorization through S, and the type-level prevention of escaping references.
Examples
Uses a two-cell swap and an in-place partition algorithm with an STRef index.
What it assumes
Assumes ST actions and for-comprehension composition while teaching why polymorphic S prevents mutable references from escaping.
What you can do after
Build it from scratch by wrapping a private cell and returning ST actions for construction, reads, and writes.
How it connects
Connects STRef to the ST monad, local effects, mutable state, referential transparency, and STArray.

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.