Your first Lean file¶
Make a scratch file anywhere in the repository, say Scratch.lean in the top
folder, and open it in VS Code. (Don't commit it.)
Asking Lean things¶
#eval asks Lean to work out an expression and show the result. Type
#eval 2 + 3 into the file and put the cursor on the line. The infoview
shows 5. Lines starting with # are commands to Lean, not part
of a program: they are how you ask questions while you work.
In this course's files, every #eval is written like this instead:
/-- info: 5 -/
#guard_msgs in
#eval 2 + 3
/-- info: "Snap!" -/
#guard_msgs in
#eval "Snap" ++ "!"
/-- info: true -/
#guard_msgs in
#eval 10 > 3
The comment /-- info: 5 -/ says what Lean should print, and #guard_msgs in
makes Lean check it: if the expression ever printed something else, the file
would fail to build. That is how this site makes sure every result it shows
is true. In your own scratch file, plain #eval is fine.
Definitions¶
def gives a name to a value or a function:
Read def double (n : Nat) : Nat := n + n as: double takes n, a natural
number, and gives back a natural number, namely n + n. Everything after
:= is the body. There is no return and no braces: a Lean function is one
expression.
Nat is the type of natural numbers: 0, 1, 2 and so on, with no upper limit.
Every value in Lean has a type, and #check shows it:
A first proof¶
Here is the smallest proof there is:
example states something without naming it: here, that double 21 = 42.
After := comes the proof, and rfl (for reflexivity) is the proof that
something equals itself. Lean accepts it because, once it works out
double 21, both sides are the same number.
Change 42 to 43 and watch the infoview: Lean refuses, with an error. That
is the whole game of proving, in miniature: you state something, and Lean
only accepts it if you give it a proof it can check.
Exercises¶
- In your scratch file, define
triple, which multiplies a number by three, and check with#evalthattriple 14is42. - Write
example : triple 14 = 42 := rfl. Then tryexample : triple 14 = 41 := rfland read the error.