Skip to content

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:

def double (n : Nat) : Nat := n + n

/-- info: 42 -/
#guard_msgs in
#eval double 21

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:

/-- info: Learn.Start.double (n : Nat) : Nat -/
#guard_msgs in
#check double

A first proof

Here is the smallest proof there is:

example : double 21 = 42 := rfl

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

  1. In your scratch file, define triple, which multiplies a number by three, and check with #eval that triple 14 is 42.
  2. Write example : triple 14 = 42 := rfl. Then try example : triple 14 = 41 := rfl and read the error.
Solution
def triple (n : Nat) : Nat := 3 * n

/-- info: 42 -/
#guard_msgs in
#eval triple 14

example : triple 14 = 42 := rfl

The second example fails because triple 14 works out to 42, and rfl can only prove that two things are equal when they are the same.