7. Equality, rewriting, and simplification
If a = b, you can substitute b for a in a property or expression. Lean can establish some equalities by computational reduction. Other equalities require a theorem or a separate argument.
Rewrite with a named fact
example (a b : Nat) (h : a = b) : a + 3 = b + 3 := by
rw [h]
example (a b : Nat) (h : a = b) : b + 3 = a + 3 := by
rw [← h]
rw [h] rewrites from left to right, and rw [← h] rewrites from right to left. Use rw [h] at hother to rewrite a hypothesis. Choose the direction that gives the next proof step the form it needs.
rfl closes equalities whose sides reduce to the same expression. rw applies a specific equality. simp repeatedly applies simplification rules and reductions towards a normal form.
Use simp with a visible scope
def credit (balance amount : Nat) : Nat := balance + amount
example (balance : Nat) : credit balance 0 = balance := by
simp [credit]
example (n : Nat) : (if n = n then 8 else 9) = 8 := by
simp
simp [credit] asks the simplifier to unfold credit, and simp [h] adds the local hypothesis h as a rule. Even with an explicit list, simp can use lemmas from the default simp set.
Temporarily replace simp with simp? to see a suggested simp only [...] invocation using the lemmas needed for that call. Use the suggestion when you want to keep the lemma dependencies explicit.
Reserve @[simp] for lemmas whose left-to-right direction gives a canonical simplification across proofs. Use simp [h] or an explicit lemma list for a local shortcut, since competing global rewrites can make proof behaviour difficult to predict.
Present a chain with calc
example (a b c : Nat) : (a + b) + c = a + (c + b) := by
calc
(a + b) + c = a + (b + c) := Nat.add_assoc a b c
_ = a + (c + b) := by rw [Nat.add_comm b c]
calc organises a chain of equalities or compatible relations. Each line has its own justification. A calc proof lets readers follow an algebraic argument through its intermediate expressions.
Arithmetic automation has a domain
example (balance amount : Nat) (h : amount ≤ balance) :
balance - amount + amount = balance := by
omega
omega handles Presburger-style arithmetic over natural numbers and integers, including linear relationships and truncated subtraction. Use it for goals about bounds and natural-number account units.
General variable-by-variable multiplication is outside that fragment. Mathlib supplies other tools such as ring for polynomial identities and linarith for suitable linear arithmetic over ordered rings and fields.
Choose automation after identifying the mathematical theory of the goal. If a solver fails, first check whether it supports the operations in the goal.
Exercises
- Prove that 2 deposits can be combined:
(b + x) + y = b + (x + y). - Prove
n ≤ n + kwithomega. - Define a wrapper around
Option.getDand prove how it behaves onsome xandnoneusingsimpwith the wrapper definition.