Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

10. Effects, monads, and IO

A pure function describes a value determined by its inputs. An IO α value describes an action that can interact with its environment and produce an α when executed. Reading a line has type IO String, which makes the effect explicit.

Start with failure propagation

def parseNat (s : String) : Except String Nat :=
  match s.toNat? with
  | some n => .ok n
  | none => .error s!"not a natural number: {s}"

def parsePair (left right : String) : Except String (Nat × Nat) := do
  let a ← parseNat left
  let b ← parseNat right
  pure (a, b)

#eval parsePair "12" "7"
#eval parsePair "bad" "7"

The arrow in let a ← ... sequences a computation and binds its successful result. If the first parse fails, the second step is skipped and the error propagates. The form let a := ... binds the computation itself without sequencing it.

The monad interface centres on pure and bind. The first puts an ordinary value into the computation context, and the second uses one computation’s result to choose the next. The do notation combines these operations with syntax for conditionals, loops, and local mutable variables.

Sequencing propagates absence in Option and errors in Except. It runs successive actions in IO. In each case, the next step can depend on the previous result.

Functor and Applicative

A failed parse skips later computations. The same do notation follows the sequencing rules of the chosen monad.

Functor.map transforms a result inside a context. Applicative applies a function produced by one computation to an argument produced by another, where the choice of argument computation is independent of the function result. Monad adds value-dependent sequencing.

#eval (fun n => n + 1) <$> (some 8)
#eval Prod.mk <$> (some 8) <*> (some "units")

The first expression produces some 9. The second combines 2 available values into an optional pair. To read these operators, check the types of map and applicative application.

Monad laws describe the expected behaviour of pure and bind. Prove the relevant laws separately when reasoning about a custom instance.

A small IO action

def greet : IO Unit := do
  let out ← IO.getStdout
  out.putStrLn "Enter an account name:"
  let input ← IO.getStdin
  let name ← input.getLine
  out.putStrLn s!"Account: {name.trimAscii.toString}"

The Unit result indicates that the action is useful for its effect. Run it through an executable’s main, #eval, or another IO action that is itself executed.

Exceptions in IO represent operational failures such as missing files. Handle expected failures at a boundary using try and catch, then decide whether to return a typed application error, report a message, or terminate. Keep domain failure distinct from a failed system operation.

Local mutation and iteration

def arrayTotal (values : Array Nat) : Nat := Id.run do
  let mut result := 0
  for value in values do
    result := result + value
  return result

example : arrayTotal #[4, 7, 9] = 20 := by decide

Id.run lets you write a pure computation using imperative syntax. Mutation stays local to the computation. Use iteration when it makes the algorithm clearer and keep a simple recursive specification for proofs.

Exercises

  1. Parse 2 natural numbers and return their sum in Except String.
  2. Write an IO action that reads a file and prints its contents. Let the path be an explicit argument.
  3. Explain why let n := parseNat s binds a value of a different type from the value bound by let n ← parseNat s inside the appropriate do block.