Stage 01 · Step 5 of 50
Make a decision.
01The idea
A signpost sends you one way or another. A conditional chooses between two results.
A Boolean test supplies the yes-or-no answer.
02In maths
A natural number is even exactly when its remainder after division by two is zero.
Picture it
Swipe sideways to see the whole picture.
isEven is a signpost: it divides by 2, checks whether the remainder is 0, and answers true or false. An if … then … else is the fork in the trail: true takes the then path, false takes the else path. So if isEven 7 then "even" else "odd" ends at "odd".03In Lean
This code comes directly from the file checked by Lean.
def isEven (n : Nat) : Bool := n % 2 == 0
#eval isEven 12
#eval if isEven 7 then "even" else "odd"
example : isEven 12 = true := by
rfl
A Boolean is a value of type Bool. A conditional selects its then branch when the condition is true.
The percent symbol computes a remainder. The double equals sign is a Boolean equality test in this example.
A Boolean value and a proposition play different roles in Lean. Next, we will move from computing answers to proving statements.
The final claim records what the decision returns. Lean computes the remainder and checks that the Boolean result is true.
04Step by step
Choose a line to see Lean’s recorded goal state after that line.
⊢ isEven 12 = true
After line 6: example : isEven 12 = true := by
⊢ isEven 12 = true
After line 7: rfl
no goals
05Lean says
true "odd" no goals
A goal is what remains to prove. The symbol ⊢ points to it. Meet the turnstile.
06A common slip
Lean is telling us something useful here.
def badEven (n : Nat) : Bool := n
Type mismatch n has type Nat but is expected to have type Bool
The body returns a natural number where a Boolean is required.
The fix: Use the Boolean remainder comparison shown in the worked example.
07Your turn
sorry is a placeholder for unfinished work. Replace it as you solve each task. A finished proof has no placeholders.
- Warm-up
Define isOdd using the remainder after division by two.
Show a hint
An odd natural number has remainder one.
One more hint
Use the Boolean equality test, with two equals signs.
- A little stretch
Define numberLabel to return the text even or odd.
Show a hint
Choose between two strings using a conditional.
One more hint
Test whether the remainder after division by two is zero.
def isOdd (n : Nat) : Bool := sorry
def numberLabel (n : Nat) : String := sorry
Compare with the checked solutions
There are often several valid proofs. These solutions were compiled with the same pinned Lean version.
def isOdd (n : Nat) : Bool := n % 2 == 1
#eval isOdd 7
def numberLabel (n : Nat) : String := if n % 2 == 0 then "even" else "odd"
#eval numberLabel 8
true "even"
08A quick check
09New words & tools
Take your time. Progress is yours to mark.