A Short Tour of Lean 4
This chapter covers the Lean you need to read the programs in this book. I ran every snippet here with Lean 4.35.0.
Functions
def defines a function. Each parameter has a name and a type. The type after the last colon is the result type.
1 def double (n : Nat) : Nat := n * 2
2
3 def greet (name : String) (greeting : String := "Hello") : String :=
4 s!"{greeting}, {name}!"
Nat is the type of natural numbers: 0, 1, 2, and up, with no size limit. A function call uses spaces, not parentheses and commas. greeting has a default value, so you can leave it out. s!"..." builds a string and inserts the value of each expression in braces.
#eval
#eval runs an expression when Lean checks the file and prints the result. In VS Code you see the result next to the code.
1 #eval double 21 -- 42
2 #eval greet "Lean" -- "Hello, Lean!"
3 #eval greet "Lean" "Goodbye" -- "Goodbye, Lean!"
4 #eval greet "Lean" (greeting := "Hi") -- "Hi, Lean!"
Use #eval the way you use a REPL in other languages. Do not leave #eval lines that call a paid API in a file you edit in VS Code. The editor runs them each time it checks the file.
Lists, arrays, and tuples
1 def nums : List Nat := [1, 2, 3, 4]
2 def arr : Array Float := #[0.5, 1.5]
3
4 #eval nums.map (· * 10) -- [10, 20, 30, 40]
5 #eval nums.map fun n => n * 10 -- [10, 20, 30, 40]
6 #eval nums.foldl (fun acc n => acc + n) 0 -- 10
7 #eval arr[1]! -- 1.500000
8 #eval (3, "three").2 -- "three"
A List is a linked list. An Array gives fast access by index. fun n => n * 10 is an anonymous function, and (· * 10) is a shorter way to write the same function. nums.map f means List.map nums f: Lean looks up map in the namespace of the type of nums.
arr[1]! reads index 1 and stops the program with an error if the index is out of range. A tuple has fields .1 and .2. A triple (a, b, c) is the pair (a, (b, c)), so its third part is .2.2.
String helpers
The standard library has the string functions the later chapters use:
1 #eval "a,b,c".splitOn "," -- ["a", "b", "c"]
2 #eval " x ".trimAscii.toString -- "x"
3 #eval "ab".startsWith "a" -- true
splitOn returns the pieces between each separator. trimAscii returns a slice, so toString copies it. startsWith returns a Bool. The Lightpanda and BM25 chapters use these calls.
Try this: split "one two" on a space and count the pieces.
Structures
A structure is a record with named, typed fields.
1 structure Point where
2 x : Float
3 y : Float
4
5 def origin : Point := { x := 0.0, y := 0.0 }
6
7 def Point.norm (p : Point) : Float := (p.x * p.x + p.y * p.y).sqrt
8
9 #eval ({ x := 3.0, y := 4.0 } : Point).norm -- 5.000000
By naming the function Point.norm, we can call it as p.norm on any Point.
Type classes and instances
A type class names operations that a type may support. ToString has one operation, toString. Square brackets in a signature ask for an instance:
1 structure Money where
2 cents : Nat
3
4 instance : ToString Money where
5 toString m := s!"{m.cents} cents"
6
7 def showTwice [ToString α] (x : α) : String := s!"{x} {x}"
8
9 #eval showTwice (Money.mk 250) -- "250 cents 250 cents"
showTwice works for any type with a ToString instance. Lean searches the instances it knows when it checks the call. deriving can write some instances for you, as Inhabited in the Bayes chapter.
abbrev and dot calls
abbrev gives a type a second name. The two names are the same type, so every function on the original type still works. You can call a function defined in the namespace of the second name with a dot when the argument has that type:
1 abbrev Point2 := Nat × Nat
2
3 def Point2.total (p : Point2) : Nat := p.1 + p.2
4
5 def pairTotal (p : Point2) : Nat := p.total
6
7 #eval pairTotal (3, 4) -- 7
Dot calls need the type of the argument, so name a parameter or give a type ascription. This is how Env.get works in the triple store chapter.
Try this: add Point2.flip and call it on (3, 4).
Coercions
Coe tells Lean how to convert one type to another when the expected type differs. In a later chapter on triple store we use coe to turn a string into a Term. Here are a few simpler examples:
1 structure Celsius where
2 degrees : Float
3
4 instance : Coe Float Celsius where
5 coe d := ⟨d⟩
6
7 def boiling : Celsius := (100.0 : Float)
8
9 #eval boiling.degrees -- 100.000000
Lean inserts coe only when it knows the expected type. The conversion runs at run time, so a bad rule can hide a mistake.
Try this: remove the Coe instance and read the error at boiling.
Inductive types and pattern matching
An inductive type lists every form a value can take. Each form is a constructor, and a constructor can hold data.
1 inductive Shape where
2 | circle (radius : Float)
3 | rect (width height : Float)
4
5 def area : Shape → Float
6 | .circle r => 3.14159 * r * r
7 | .rect w h => w * h
8
9 #eval area (.rect 2.0 3.0) -- 6.000000
area matches on its argument. Lean requires a case for each constructor. If you delete the .rect line, Lean reports Missing cases and names the constructor you forgot.
Try this: add a ToString instance for Shape and print a shape with showTwice from the type class section.
Option and do
Lean has no null value. A function that can fail to produce a result returns an Option: either some value or none.
1 def safeDiv (a b : Nat) : Option Nat :=
2 if b = 0 then none else some (a / b)
3
4 def both (a b c : Nat) : Option Nat := do
5 let x ← safeDiv a b
6 let y ← safeDiv x c
7 return x + y
8
9 #eval both 100 5 2 -- some 30
10 #eval both 100 0 2 -- none
Inside a do block, let x ← e runs e and names its result. If e is none, the whole block returns none and the later lines do not run. The same do syntax works for Except, which holds an error message in place of none, and for IO, which performs input and output.
More monads: Except and StateM
do works for any monad, not only Option. Except holds an error message:
1 def half (n : Nat) : Except String Nat :=
2 if n % 2 = 0 then .ok (n / 2) else .error s!"{n} is odd"
3
4 def halves (xs : List Nat) : Except String (List Nat) := xs.mapM half
5
6 #eval halves [2, 4] -- Except.ok [1, 2]
7 #eval halves [2, 3] -- Except.error "3 is odd"
mapM applies a failing function to every element and stops at the first error. StateM passes a state from step to step:
1 def count : StateM Nat Nat := do
2 let n ← get
3 set (n + 1)
4 return n
5
6 #eval count.run 0 -- (0, 1)
The result is the returned value and the final state. The Autograd chapter uses StateM (Array Node) for its tape.
Try this: write a StateM step that doubles the state and returns the old value.
Loops and local variables
Lean functions are pure: they cannot change a variable defined outside the function. Inside a do block you can still write loops and update local variables declared with let mut.
1 def sumTo (n : Nat) : Nat := Id.run do
2 let mut total := 0
3 for i in [0:n + 1] do
4 total := total + i
5 return total
6
7 #eval sumTo 100 -- 5050
[0:n + 1] is the range from 0 up to but not including n + 1. Id.run runs a do block that needs no effects and returns its value. Callers see sumTo as a pure function.
Typing the symbols
Lean code uses Unicode symbols. In VS Code with the Lean 4 extension, type a backslash and a short name, and the editor replaces it with the symbol.
| Symbol | Type this | Meaning in this book | Plain text form |
|---|---|---|---|
→ |
\to |
function type | -> |
← |
\l |
run a step in a do block |
<- |
× |
\x |
pair type | none |
· |
\. |
the argument of a short function | none |
≥ |
\ge |
greater than or equal | >= |
≠ |
\ne |
not equal | none |
⟨ ⟩ |
\< and \>
|
build a structure from its fields | none |
∅ |
\empty |
an empty collection | {} |
α, ε
|
\a, \e
|
names of type parameters | any name |
Numbers
Lean has several number types, and it never converts between them for you.
1 #eval 7 / 2 -- 3
2 #eval (7 : Rat) / 2 -- (7 : Rat)/2
3 #eval (7 : Float) / 2 -- 3.500000
4 #eval (2 : Int) - 5 -- -3
5 #eval 2 - 5 -- 0
A number literal with no other hint is a Nat. Division on Nat drops the remainder, and subtraction on Nat stops at zero. (7 : Rat) is a type ascription: it tells Lean which type the literal has. Int has negative numbers, Rat has exact fractions, and Float is a 64-bit floating point number. Note, dear reader, that a Type ascription is a programming language construct that allows a developer to explicitly specify the expected type of a sub-expression inline, instructing the compiler to treat or validate that specific expression as having the given type.
To convert, call a function: n.toFloat for a Nat, Float.ofInt i for an Int. You will see these calls in most of the programs.
Sorting and exact fractions
mergeSort takes a comparison function that returns a Bool. It keeps equal elements in their original order:
1 #eval [3.0, 1.0, 2.0].mergeSort (fun a b => a ≥ b) -- [3.000000, 2.000000, 1.000000]
Rat keeps fractions exact, so equality is reliable where Float is not:
1 #eval (1/3 : Rat) + 1/6 -- (1 : Rat)/2
The symbolic math chapter uses Rat for coefficients. Its four checked examples depend on this exactness. 0.1 + 0.2 == 0.3 is false for Float, as it is in most languages.
Try this: compute 1/3 + 1/6 as a Float and compare the printed result with the Rat result.
Bool and Prop
Lean has two kinds of truth. A Bool is a value, true or false, that a program computes. A Prop is a statement that can have a proof, such as 2 + 2 = 4.
a == b returns a Bool. a = b is a Prop. For most types Lean can decide an equation by computing, so you can write either one after if. The programs in this book use both forms. The example lines need the Prop form, because a proof proves a statement.
Proofs
A type in Lean can state a fact, and a value of that type is a proof of the fact. example asks Lean to check a proof without giving it a name. theorem names it.
1 example : double 21 = 42 := rfl
2 example : 2 + 2 = 4 := by decide
3 example : sumTo 100 = 5050 := by native_decide
4
5 theorem double_eq (n : Nat) : double n = n + n := by
6 unfold double
7 omega
rfl proves that two sides are equal when Lean can compute both to the same value. The word by starts a tactic proof. decide evaluates a yes-or-no claim and accepts it if the answer is yes. native_decide does the same with compiled code. It is faster, but you must trust the Lean compiler as well as the small proof checker. omega proves facts about integers and natural numbers that use only addition, comparison, and multiplication by constants.
The first three proofs each check one value. The theorem covers every n.
If a claim is false, the file does not compile. example : 2 + 2 = 5 := by decide gives this error:
1 error: Tactic `decide` proved that the proposition
2 2 + 2 = 5
3 is false
Two programs in this book use native_decide to check their own results at compile time.
Programs
A program that you run has a main function of type IO Unit.
1 def main : IO Unit := do
2 IO.println (greet "world")
IO marks code that has effects: printing, reading files, starting a process. A function whose type does not mention IO cannot perform them.
A helper you will see again
toString prints a Float with six digits after the point. Six of the programs need fewer digits, so each has this helper:
1 def fixed (x : Float) (d : Nat := 4) : String :=
2 let n := (x.abs * (10 ^ d).toFloat).round.toUInt64.toNat
3 let frac := toString (n % 10 ^ d)
4 let pad := "".pushn '0' (d - frac.length)
5 s!"{if x < 0 then "-" else ""}{n / 10 ^ d}.{pad}{frac}"
It scales the number by 10 ^ d, rounds it to a natural number n, and prints n / 10 ^ d, a point, and n % 10 ^ d padded with zeros on the left. Subtraction on Nat stops at zero, so d - frac.length is never negative.
Cheat sheet
| Construct | Where to see it |
|---|---|
[ToString α], instance
|
Bayes, Search |
Coe |
Triple store |
do in Option
|
Triple store |
Std.HashMap |
Summarizer, Vector store |
abbrev, |>.
|
Vector store, Autograd |
Fin, Array.ofFn
|
Hopfield |
Rat, OfNat
|
Symbolic math |
StateM |
Autograd |
IO.Process.output |
Apple, Lightpanda |
Json, Except
|
Ollama, Gemini, SPARQL, Search |
mapM |
SPARQL |
structure |
Search |
native_decide |
Hopfield, Symbolic math |
Use #check when you need the full type of a name. In the Bayes chapter, #check @normalize prints the implicit type parameter that the source does not declare.