18. Capstone: a checked account CLI
This chapter assembles a complete package. The pure core implements withdrawal and exposes its theorems. The IO boundary parses arguments, calls the core, prints the result, and returns an exit code.
The workbook tests cover properties of the core and selected behaviours of the compiled executable.
Get the complete project
Download the workbook archive, extract it, and enter the examples directory. It contains the following files:
examples/
lean-toolchain
lakefile.toml
lake-manifest.json
Workbook.lean
Workbook/Core.lean
Main.lean
Tests.lean
With Elan installed, build and run:
tar -xzf workbook.tar.gz
cd examples
lake build
lake env lean -DwarningAsError=true Tests.lean
.lake/build/bin/account 100 30
The final command prints 70. Use lake build to compile the native executable and lake env lean Tests.lean to check the proofs.
Configure the package
The toolchain file selects leanprover/lean4:v4.35.0. The Lake configuration defines a library and an executable:
name = "workbook"
version = "0.1.0"
defaultTargets = ["Workbook", "account"]
[[lean_lib]]
name = "Workbook"
[[lean_exe]]
name = "account"
root = "Main"
Workbook.lean imports Workbook.Core. The lean_lib target tells Lake how to build that library. The executable target uses Main.lean as its root and produces the binary account.
Implement and verify the pure core
Theorems cover the pure operation for all natural-number inputs. Native CLI tests exercise selected parsing, output, and exit-code paths.
import Std
namespace Workbook
def withdraw (balance amount : Nat) : Option Nat :=
if amount ≤ balance then some (balance - amount) else none
theorem withdraw_success (balance amount : Nat) (h : amount ≤ balance) :
withdraw balance amount = some (balance - amount) := by
simp [withdraw, h]
theorem withdraw_failure (balance amount : Nat) (h : balance < amount) :
withdraw balance amount = none := by
have hn : ¬ amount ≤ balance := by omega
simp [withdraw, hn]
theorem withdraw_accounts (balance amount result : Nat)
(h : withdraw balance amount = some result) :
result + amount = balance := by
unfold withdraw at h
split at h
· rename_i affordable
have same : balance - amount = result := Option.some.inj h
omega
· contradiction
theorem withdraw_exact (balance amount result : Nat) :
withdraw balance amount = some result ↔
amount ≤ balance ∧ result = balance - amount := by
by_cases h : amount ≤ balance
· simp [withdraw, h, eq_comm]
· simp [withdraw, h]
end Workbook
The public contract, withdraw_exact, states when a withdrawal succeeds and what balance it returns. The derived property withdraw_accounts states that the remaining balance plus the amount withdrawn equals the original balance.
The theorems quantify over all natural-number balances and amounts. Both the implementation and the proofs use the decidable comparison to distinguish affordable withdrawals from excessive ones.
The pure core returns an Option Nat. A caller that stores state should update the balance on some remaining and leave it unchanged on none.
Add the IO boundary
import Workbook
def main (args : List String) : IO UInt32 := do
let out ← IO.getStdout
match args with
| [balanceText, amountText] =>
match balanceText.toNat?, amountText.toNat? with
| some balance, some amount =>
match Workbook.withdraw balance amount with
| some remaining =>
out.putStrLn s!"{remaining}"
pure 0
| none =>
out.putStrLn "insufficient balance"
pure 1
| _, _ =>
out.putStrLn "expected two natural numbers"
pure 2
| _ =>
out.putStrLn "usage: account BALANCE AMOUNT"
pure 2
main accepts a list of argument strings and returns an IO action producing an exit code. The exit codes are 0 for success, 1 for insufficient balance, and 2 for an invalid invocation.
This example writes all messages to standard output. A larger Unix tool would normally send diagnostics to standard error and document that choice.
The CLI uses String.toNat? and accepts amounts as natural numbers. Currency notation, fractional amounts, and locale-specific formats would require a richer parser. A production financial model would define units, rounding, and persistence before extending this boundary.
Verify the integration
import Workbook
open Workbook
example : withdraw 100 30 = some 70 := by decide
example : withdraw 30 30 = some 0 := by decide
example : withdraw 0 0 = some 0 := by decide
example : withdraw 20 30 = none := by decide
example (balance : Nat) : withdraw balance 0 = some balance := by
simp [withdraw]
example (balance : Nat) : withdraw balance balance = some 0 := by
simp [withdraw]
example (balance amount : Nat) : withdraw (balance + amount) amount = some balance := by
have h : amount ≤ balance + amount := by omega
rw [withdraw_success _ _ h]
congr 1
omega
#print axioms withdraw_accounts
#print axioms withdraw_exact
The first examples check concrete core outcomes. The next examples establish generic boundary properties. Axiom inspection reports the dependencies of the central theorems.
Run these native cases as well:
| Invocation arguments | Output | Exit code |
|---|---|---|
100 30 | 70 | 0 |
30 30 | 0 | 0 |
0 0 | 0 | 0 |
20 30 | insufficient balance | 1 |
bad 3 | expected two natural numbers | 2 |
| No arguments | usage: account BALANCE AMOUNT | 2 |
The repository checker runs these 6 cases against the compiled binary to exercise argument parsing, IO, and process exit. The conservation theorem covers the pure operation for all inputs.
Extend the project independently
Add a transfer operation that returns either failure or a pair of updated balances. State and prove that a transfer preserves the combined balance and succeeds when the source has sufficient funds.
Add a command-line mode that accepts the source balance, destination balance, and amount.
Use the library search and debugging workflow to complete the extension independently. After your attempt, compare the contract and proof with the solution in the answer chapter.
You have reached the book’s practical goal when you can make this extension, explain its assumptions, build it, and test its boundaries.