liveBook · Manning

Console I/O

As explained in Functional Programming in Scala, Second Edition

Console I/O is interaction with a textual console through line-oriented input and output.

Console I/O models line-oriented interaction as a small algebra of effects rather than exposing unrestricted side effects. A Console[A] computation is either ReadLine, yielding Option[String], or PrintLine, yielding Unit. section 13.4.2

A console-only program

Free[Console, A] makes the allowed interaction explicit: print a prompt, read a line, and transform it into an integer with readInt. The program can be composed before anything runs. section 13.4.2

Console itself cannot implement flatMap because ReadLine has no result until interpretation. Free defers composition, while runFree translates each Console operation into a target monad such as Function0 or Par. section 13.4.2

Listing 13.6 Creating our Console type
enum Console[A]:
  case ReadLine extends Console[Option[String]]
  case PrintLine(line: String) extends Console[Unit]
 
  def toPar: Par[A] = this match                             #1
    case ReadLine => Par.lazyUnit(Try(readLine()).toOption)
    case PrintLine(line) => Par.lazyUnit(println(line))
 
  def toThunk: () => A = this match                          #2
    case ReadLine => () => Try(readLine()).toOption
    case PrintLine(line) => () => println(line)

The Console definition and its interpreters show how the same description becomes a thunk or parallel computation. section 13.4.2

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines the algebra, demonstrates interpreters, and explains deferred flatMap through Free, but stops short of full runtime implementation.
Examples
Uses ReadLine, PrintLine, readLn, printLn, readInt, and a prompt-reading Free program.
What it assumes
Assumes familiarity with Free, monads, and higher-kinded types while illustrating why interpretation supplies deferred results.
What you can do after
Build console-only programs and interpret them as thunks or parallel computations.
How it connects
Connects console I/O to algebraic data types, Free monads, interpreters, natural transformations, Function0, and Par.

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.