liveBook · Manning

Get

As explained in Functional Programming in Scala, Second Edition

get is a State constructor that returns the current state as its result without changing the state.

get is a State constructor that reads the incoming state and returns it as both the action’s result and its unchanged next state. Its implementation is simply s => (s, s). section 6.6

Combined with set, map, and flatMap, get restores an imperative style without mutable data or side effects. A stateful program can read a value, bind it in a for-comprehension, and continue with the same state unless another action changes it. section 6.6

Reading state inside modify

def modify[S](f: S => S): State[S, Unit] = for s <- get _ <- set(f(s)) yield () Here get supplies the current state to f; set installs the transformed state. section 6.6

def get[S]: State[S, S] = s => (s, s)

Inspect the minimal implementation: get passes the incoming state through unchanged while returning it as the result. section 6.6

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines get and gives its complete implementation, then connects it to modify and State composition.
Examples
Uses random-number generation, a modify constructor, and the implementation s => (s, s).
What it assumes
Assumes State, map, and flatMap while demonstrating state reading from first principles.
What you can do after
Builds a State action that reads the current state without changing it.
How it connects
Connects get with State, set, modify, map, flatMap, for-comprehensions, and immutable data structures.

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.