liveBook · Manning

Set

As explained in Functional Programming in Scala, Second Edition

set is a State constructor that replaces the current state with a supplied state and returns Unit.

set constructs a State action from a new state. When run, the action ignores the incoming state, replaces it with the supplied state, and returns Unit rather than a meaningful value. section 6.6

Together with get, set provides the primitive operations needed to express state changes with for-comprehensions and flatMap. Mutable data and side effects become immutable state transitions. section 6.6

Implementing modify

A general modify operation reads the current state with get, applies a function, writes the result with set, and yields (). section 6.6

def set[S](s: S): State[S, Unit] = _ => ((), s)

The implementation makes the operational behavior explicit: discard the incoming state, return Unit, and install the supplied state. section 6.6

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines the State action operationally, including discarded input, replacement state, and Unit output.
Examples
Uses the set implementation and a modify definition composed from get and set.
What it assumes
Uses State actions, for-comprehensions, map, and flatMap before introducing state-reading and state-writing primitives.
What you can do after
Build purely functional stateful programs by composing explicit state transitions.
How it connects
Connects State with get, modify, map, flatMap, immutable data structures, and state machines.

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.