Prove which branch runs

Use a hypothesis to decide the condition of an if, for every input.

14 minBeginnerif in a goalsimp [h] on a conditionboth branches
0/8 completed in this course

You wrote clamp in Lean foundations: it returns lo when n < lo, and n otherwise. For concrete numbers, rfl computes which branch runs. For an unknown n, Lean cannot tell, so the proof needs a hypothesis that settles the condition.

After unfold clamp the goal shows the if. Step through the example: simp [h] uses h to decide the condition, picks the branch, and closes the goal.

Without a hypothesis that answers the condition, simp can only rewrite the if into something it cannot finish. It then leaves a goal such as n < lo → lo = n, an implication: “if n < lo, then …”. omega can finish goals of that shape too.

Worked example

def shipping (express : Bool) : Nat :=
  if express then 9 else 4

example (express : Bool) (h : express = false) : shipping express = 4 := by
  unfold shipping
  simp [h]
Step through the proof1 / 3

At the start of the proof on line 4. Everything above ⊢ may be used; the line below it is what must be proved.

express:Bool
h:express = false
⊢shipping express = 4

The hypothesis says which branch runs, for any input that satisfies it. Your exercise does the same with a comparison instead of a Bool.

Takeaway

To prove what a function with an if returns for every input, unfold it and give simp the hypothesis that settles the condition.

Exercise 1 of 3

For every lo and n with n < lo, prove that clamp returns the lower bound.

Suggested steps
  1. Unfold clamp so the if appears
  2. Settle the condition with the hypothesis

These marks only recognize text. Another correct proof may use different steps; Lean checks whether it works.

Exercise.lean
1def clamp (lo n : Nat) : Nat := if n < lo then lo else n
2theorem exercise (lo n : Nat) (h : n < lo) : clamp lo n = lo := by
given
Loading editor…

Where you start. Everything above ⊢ may be assumed; the line below it is what you must prove.

lo n:Nat
h:n < lo
⊢clamp lo n = lo
ReadyLn 1, Col 1Lean 4
Draft saved in this browser
Stuck?
Recall and apply

Knowledge check

Answer without looking back, then check your reasoning.

0of 2
correct
Question 1 of 2What does clamp 5 8 return?
Question 2 of 2Why can rfl not prove clamp lo n = lo for unknown lo and n?