liveBook · Manning

Partial type application

As explained in Functional Programming in Scala, Second Edition

Partial type application fixes one or more arguments of a parameterized type constructor while leaving the remaining arguments abstract.

Partial type application fixes one or more arguments of a parameterized type constructor while leaving the remaining arguments abstract. For State[S, A], fixing S produces a one-argument constructor suitable for Monad. section 11.5.2

Partially applying State

A concrete alias fixes the state type: type IntState[A] = State[Int, A]. The same idea can be written anonymously as Monad[[x] =>> State[Int, x]], or more briefly as State[Int, _] with the appropriate compiler option. Generalizing the pattern yields stateMonad[S], one monad instance for every state type. section 11.5.2

given stateMonad[S]: Monad[[x] =>> State[S, x]] with     #1
  def unit[A](a: => A): State[S,A] = State(s => (a, s))
  extension [A](st: State[S, A])
    def flatMap[B](f: A => State[S, B]): State[S, B] =
      State.flatMap(st)(f)

Inspect the generic state monad instance to see the fixed S parameter and the remaining abstract result type. section 11.5.2

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Descends from the type-level analogy to aliases, anonymous type constructors, compiler syntax, and a generic implementation.
Examples
Uses IntState, generic stateMonad[S], and zipWithIndex implemented with State.get and State.set.
What it assumes
Assumes familiarity with State, map, flatMap, and Monad, while making the type-constructor mismatch explicit.
What you can do after
Builds generic Monad instances for partially applied State constructors.
How it connects
Connects State with monads, type constructors, type lambdas, anonymous functions, and for-comprehensions.

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.