Stage 02 · Step 9 of 50

Swap equal things.

Core Lean5 minutesLean 4.36.0

01The idea

If two labels name the same box, you can swap the labels. Rewriting replaces an expression using a proved equality.

Tacto · Your guide for this idea
Tacto pointing

The surrounding expression keeps its meaning.

02In maths

If a = b, then a + 1 = b + 1.

Picture it

rw swaps a piece for an equal pieceTop: the claim a + 1 = b + 1 is drawn as a row of tiles. The hypothesis h : a = b says the tile a may be swapped for the tile b. After the swap the row reads b + 1 = b + 1, and both sides are now identical, so rw finishes the proof by itself. Bottom: the goal state with a b : Nat and h : a = b above the line and a + 1 = b + 1 to prove. The tactic rw [h] leads straight to no goals.h : a = bBEFOREa+1=b+1swap a → bAFTERb+1=b+1both sides identical, so rw closes itIN LEANa b : Nath : a = b⊢ a + 1 = b + 1rw [h]no goals

Swipe sideways to see the whole picture.

The hypothesis h : a = b is a swap card: wherever you see a, you may put b. rw [h] makes that swap in the goal, turning the left side into b + 1. Now both sides are exactly the same, so rw finishes the proof on its own.

03In Lean

This code comes directly from the file checked by Lean.

E09.leanTry it live (opens official Lean editor)
example (a b : Nat) (h : a = b) : a + 1 = b + 1 := by
  rw [h]

A hypothesis is information available in the current proof. Here the hypothesis named h states an equality.

The tactic rw means rewrite. Square brackets hold the names of equalities to use.

A left arrow before an equality name reverses its direction. Type ← with \l.

04Step by step

Choose a line to see Lean’s recorded goal state after that line.

After line 1
a b : Nat
h : a = b
⊢ a + 1 = b + 1
After line 1: example (a b : Nat) (h : a = b) : a + 1 = b + 1 := by
a b : Nat
h : a = b
⊢ a + 1 = b + 1
After line 2: rw [h]
no goals

05Lean says

Captured from Lean 4.36.0
no goals

A goal is what remains to prove. The symbol ⊢ points to it. Meet the turnstile.

07Your turn

sorry is a placeholder for unfinished work. Replace it as you solve each task. A finished proof has no placeholders.

  1. Warm-up

    Rewrite the goal using the supplied equality between a and b.

  2. A little stretch

    Connect a to c using the two supplied equalities.

Exercises/E09.leanTry it live (opens official Lean editor)
example (a b : Nat) (h : a = b) : a * 2 = b * 2 := by
  sorry

example (a b c : Nat) (h₁ : a = b) (h₂ : b = c) : a = c := by
  sorry

08A quick check

1. What can justify a rewrite?

Read the answer and explanation

A proved equality or supported equivalence. Rewriting uses a fact Lean has checked.

2. What happens if the chosen pattern is absent?

Read the answer and explanation

The rewrite fails. The diagnostic tells you the expected occurrence was not found.

One more idea in your toolkit.

Take your time. Progress is yours to mark.