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

Exercise answers and proof patterns

These are representative solutions. Equivalent total functions and complete proofs are equally valid. Try the exercises first, then compare the structure of your reasoning with the solutions.

Chapters 1–2: first definitions

namespace First

def triple (n : Nat) : Nat := n + n + n
#eval triple 14
example : triple 4 = 12 := by rfl

def first {α : Type} (x _y : α) : α := x

def compose {α β γ : Type} (g : β → γ) (f : α → β) : α → γ :=
  fun x => g (f x)

#eval (3 : Nat) - 5
#eval (3 : Int) - 5

end First

Lean rejects an incorrect expected literal because the sides of the equality reduce to different constructor values. Use Int or another signed model for signed temperatures and Nat for list lengths.

Chapter 3: data and errors

namespace Data

structure Account where
  balance : Nat
  frozen : Bool

def freeze (a : Account) : Account := { a with frozen := true }

def first? {α : Type} : List α → Option α
  | [] => none
  | x :: _ => some x

inductive Error where
  | insufficientFunds
  | frozenAccount
  deriving Repr

def withdraw (a : Account) (amount : Nat) : Except Error Account :=
  if a.frozen then .error .frozenAccount
  else if amount ≤ a.balance then .ok { a with balance := a.balance - amount }
  else .error .insufficientFunds

end Data

The order of checks is observable: a frozen account with insufficient funds returns frozenAccount. Make this policy intentional when several errors apply.

Chapters 4 and 8: recursion and induction

namespace Recursive

def doubleEach : List Nat → List Nat
  | [] => []
  | x :: xs => (x + x) :: doubleEach xs

def doubleMap (xs : List Nat) : List Nat := xs.map (fun x => x + x)

def count {α : Type} : List α → Nat
  | [] => 0
  | _ :: xs => count xs + 1

theorem countLength {α : Type} (xs : List α) : count xs = xs.length := by
  induction xs with
  | nil => rfl
  | cons x xs ih => simp [count, ih]

def sum : List Nat → Nat
  | [] => 0
  | x :: xs => x + sum xs

theorem sumAppend (xs ys : List Nat) : sum (xs ++ ys) = sum xs + sum ys := by
  induction xs with
  | nil => simp [sum]
  | cons x xs ih => simp [sum, ih, Nat.add_assoc]

end Recursive

For an append proof, induct on the argument whose constructors drive append’s recursion. For an accumulator proof, quantify over every accumulator so the induction hypothesis applies after the accumulator changes.

Chapters 5–6: logical structure

namespace Logic

variable {P Q R : Prop}

example : P → Q → P ∧ Q := fun hp hq => ⟨hp, hq⟩
example : P ∧ Q → P := fun h => h.1
example : ¬ P → P → Q := fun hn hp => False.elim (hn hp)

example (hpq : P → Q) (hqr : Q → R) : P → R := by
  intro hp
  exact hqr (hpq hp)

example : P ∧ (Q ∧ R) → (P ∧ Q) ∧ R := by
  intro h
  exact ⟨⟨h.1, h.2.1⟩, h.2.2⟩

example : P ∨ Q → (P → R) → (Q → R) → R := by
  intro h hp hq
  cases h with
  | inl p => exact hp p
  | inr q => exact hq q

end Logic

For quantifier order, every natural number has a larger natural number, but there is no single natural number larger than every natural number. The existential witness in the first statement depends on the universally quantified input.

Chapter 7: equality

namespace Equality

example (b x y : Nat) : (b + x) + y = b + (x + y) :=
  Nat.add_assoc b x y

example (n k : Nat) : n ≤ n + k := by omega

def fallback (x : Option Nat) : Nat := x.getD 7

example (n : Nat) : fallback (some n) = n := by simp [fallback]
example : fallback none = 7 := by simp [fallback]

end Equality

Chapter 9: interfaces

namespace Interfaces

class Label (α : Type) where
  label : α → String

structure UserId where
  value : Nat

instance : Label UserId where
  label user := s!"user-{user.value}"

class HasDefault (α : Type) where
  value : α

def twoDefaults {α : Type} [HasDefault α] : α × α :=
  (HasDefault.value, HasDefault.value)

end Interfaces

An always-true Boolean comparison merely defines an unreliable comparison operation. Turning its result into evidence of equality requires a law connecting that operation to propositional equality.

Chapter 10: effects

namespace Effects

def parse (s : String) : Except String Nat :=
  match s.toNat? with
  | some n => .ok n
  | none => .error "expected a natural number"

def addParsed (a b : String) : Except String Nat := do
  let x ← parse a
  let y ← parse b
  pure (x + y)

def printFile (path : System.FilePath) : IO Unit := do
  let text ← IO.FS.readFile path
  let out ← IO.getStdout
  out.putStr text

end Effects

An ordinary let binds an Except String Nat; the monadic bind extracts a Nat on the success path and propagates failure on the other path.

Chapter 11: transformer semantics

The original consume already leaves the state unchanged on rejection. With a limit of 10, a state of 8, and a request of 4, it returns (false, 8).

In either order, running both the reader and exception layers gives a function from an environment to an error or a result. The APIs and lifting operations differ between the arrangements.

State and exception have different result types depending on their order. One arrangement returns state only on success, and the other returns state on success and failure.

Choose the state-preserving result shape when callers need to inspect progress after failure. This does not reverse or commit external IO effects.

Chapter 12: checked values

namespace Checked

def three : Fin 5 := ⟨3, by decide⟩

def positive? (n : Nat) : Option {n : Nat // 0 < n} :=
  if h : 0 < n then some ⟨n, h⟩ else none

inductive Vec (α : Type) : Nat → Type where
  | nil : Vec α 0
  | cons : α → Vec α n → Vec α (n + 1)

def Vec.toList {α : Type} : Vec α n → List α
  | .nil => []
  | .cons x xs => x :: Vec.toList xs

end Checked

The empty constructor has index 0. The input type of head requires an index of the form n + 1, which excludes the empty constructor.

Chapter 13: withdrawal boundaries

namespace Contracts

def withdraw (b a : Nat) : Option Nat :=
  if a ≤ b then some (b - a) else none

example (b : Nat) : withdraw b 0 = some b := by simp [withdraw]
example (b : Nat) : withdraw b b = some 0 := by simp [withdraw]
example (b a : Nat) : withdraw (b + a) a = some b := by
  have h : a ≤ b + a := by omega
  simp [withdraw, h]

end Contracts

An always-failing operation makes a success-implies-conservation claim vacuously true. A useful contract also establishes when success occurs.

Chapters 14–17: project and verification decisions

import loads the module’s declarations. open changes how Lean resolves unqualified names for declarations that are already available.

For Mathlib, the square identity follows from ring even if the summands are reordered. Use hx.2 to extract the proof of membership in the second set. Search for Set.inter_comm and inspect it in the installed library.

Check these answers in the Mathlib environment described in Chapter 15.

An array summation invariant relates the accumulator to the sum of the processed prefix. Its statement must also track that the current index lies between 0 and the array size. A sorting proof needs ordering and preservation of the full multiset, since equality of sets alone would lose duplicate counts.

The conservation theorem covers Workbook.withdraw over mathematical natural numbers. CLI tests exercise selected parsing, printing, and exit-code paths.

Classical axioms describe the chosen logical foundations. sorryAx marks a missing argument.

Chapter 18: transfer extension

namespace Transfer

def transfer (source destination amount : Nat) : Option (Nat × Nat) :=
  if amount ≤ source then
    some (source - amount, destination + amount)
  else
    none

theorem succeeds (s d a : Nat) (h : a ≤ s) :
    transfer s d a = some (s - a, d + a) := by
  simp [transfer, h]

theorem conserves (s d a s' d' : Nat)
    (h : transfer s d a = some (s', d')) : s' + d' = s + d := by
  unfold transfer at h
  split at h
  · rename_i affordable
    have pair := Option.some.inj h
    have hs : s - a = s' := congrArg Prod.fst pair
    have hd : d + a = d' := congrArg Prod.snd pair
    omega
  · contradiction

end Transfer

This verifies transfer of natural-number units between mathematical balances. Adding persistence, concurrency, or retries would require additional contracts. For example, the database layer would need to guarantee atomic updates to both balances.

For the CLI extension, follow the existing argument parsing and exit-code structure. Test a transfer of 0, exact depletion, insufficient funds, and invalid arguments. State which pure theorems each integration path relies on.