liveBook · Manning

Translate

As explained in Functional Programming in Scala, Second Edition

translate is a book-defined operation that converts a Free program between instruction or execution representations using a natural transformation.

translate converts a Free[F, A] program into Free[G, A] by supplying a polymorphic instruction conversion from F[x] to G[x]. Unlike runFree, it keeps the result inside Free rather than interpreting it into a final effect. section 13.10 section 13.4.2

The operation follows a small sequence:

  • Accept a natural transformation-like function, [x] => F[x] => G[x], so every instruction type is translated without changing its result type. section 13.4.2
  • Use runFree with Free[G, x] as the target effect and suspend each translated G[x] instruction. section 13.10
  • Interpret the resulting Free[G, A] later with an interpreter appropriate to G. section 13.10

Translating console effects

A Free[Console, A] program can translate each Console[x] instruction to a Function0[x] thunk, producing Free[Function0, A]. Calling runTrampoline then executes the translated program. The same Console program can instead translate to Par[x] for a different execution strategy.

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines the type transformation and implementation through runFree, but defers actual execution to a later interpreter.
Examples
Uses Console programs translated to thunks or Par values, then executed with runTrampoline or interpreted through Par.
What it assumes
Assumes Free, runFree, Monad, and polymorphic function types, while motivating why instruction translations must preserve result types.
What you can do after
Apply it via a polymorphic instruction mapping to retarget Free programs without rewriting their sequencing logic.
How it connects
Connects Free monads, runFree, natural transformations, Monad instances, Function0, Par, and interpreters.

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.