Stage 01 · Step 3 of 50
Make a function.
01The idea
A recipe takes ingredients and produces something. A function takes an input and returns an output.
Naming the recipe lets you use it again.
02In maths
The function double sends a natural number n to 2n.
Picture it
Swipe sideways to see the whole picture.
n is the slot where the input goes, so double 7 runs the recipe with 7 in the slot. To check double 7 = 14, rfl opens the machine, works out 2 * 7, and sees 14 on both sides.03In Lean
This code comes directly from the file checked by Lean.
def double (n : Nat) : Nat := 2 * n
#eval double 7
example : double 7 = 14 := by
rfl
A definition gives a name to an expression. A parameter names an input while we describe the function.
The parentheses declare the input and its type. The next type describes the output. The expression after := supplies the definition.
Applying a function means giving it an argument. The evaluation command applies double to one specific number.
The final claim records the result as an equality. Lean opens the definition of double to check it.
04Step by step
Choose a line to see Lean’s recorded goal state after that line.
⊢ double 7 = 14
After line 5: example : double 7 = 14 := by
⊢ double 7 = 14
After line 6: rfl
no goals
05Lean says
14 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.
#eval doubel 7
Unknown identifier `doubel`
The function name is misspelled or has not been defined.
The fix: Define the function first, then use its exact spelling.
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 triple so it returns three times its input.
Show a hint
Use the input named n in your expression.
One more hint
Multiply n by three.
- A little stretch
Define addThenDouble: add one to the input, then double the result.
Show a hint
The addition must happen first.
One more hint
Multiply the parenthesized sum by two.
def triple (n : Nat) : Nat := sorry
def addThenDouble (n : Nat) : Nat := sorry
Compare with the checked solutions
There are often several valid proofs. These solutions were compiled with the same pinned Lean version.
def triple (n : Nat) : Nat := 3 * n
#eval triple 4
def addThenDouble (n : Nat) : Nat := 2 * (n + 1)
#eval addThenDouble 4
12 10
08A quick check
09New words & tools
Take your time. Progress is yours to mark.