Prove which branch runs

Unfold a function and use a hypothesis to simplify its condition.

15 minBeginnerhypothesesif then elseunfoldsimp
0/14 completed in this course

In the previous lesson the checks called your definitions on concrete inputs such as triple 4, and each call computed to a value. A theorem about arbitrary inputs cannot be settled that way. With lo and n unknown, Lean cannot tell which branch of if n < lo then lo else n runs.

if c then a else b returns a when the condition c holds and b otherwise, and both branches must have the same type. clamp lo n returns the lower bound lo when n is below it, and n otherwise: clamp 5 8 is 8 and clamp 5 2 is 5.

The statement below has a hypothesis, (h : n < lo). It is an assumption the theorem is allowed to use: the claim only has to hold for inputs where n < lo is true, and h is the name you use to refer to that fact. The next course is about working with hypotheses; here you only hand one to a tactic.

Two tactics do the work. unfold clamp replaces the call by the body of the definition, so the if appears in the goal. simp is Lean’s simplifier: it rewrites the goal with many known facts until it is closed or can go no further, and simp [h] lets it use h as well. Knowing n < lo, it picks the first branch and closes the equality.

This two-step shape, unfolding the definition and then simplifying with what you know, comes back in almost every later course.

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]

The hypothesis identifies the branch for an arbitrary input. Your exercise proves the other branch of a different function, using the same two-step method.

Takeaway

To prove a branch of a function for arbitrary inputs, unfold its definition and use a hypothesis to simplify the condition.

Exercise 1 of 3

For arbitrary lo and n, use h : n < lo to prove that clamp returns the lower bound.

Suggested steps
  1. Expose the body of clamp
  2. Use the hypothesis to select the true branch

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 3
correct
Question 1 of 3What does clamp 5 8 return?
Question 2 of 3In theorem t (n : Nat) (h : n < 3) : …, what is h?
Question 3 of 3Why can Lean not settle clamp lo n = lo by computation alone?