Lean examples
Read the source and explanations, then open a file in the editor to run it. These examples use the included core library.
Getting started
- Welcome
Run a program, check a proof, and find your way around leanlab.
- Prove 2 + 2 = 4
Compute an answer, then prove the equality.
- Curry–Howard correspondence
A proposition is a type; a proof is a term of that type.
- Hello, world
Define a function and print its result from main.
- Values & types
Evaluate expressions with #eval and inspect their types with #check.
- Writing functions
Functions take inputs and return values. Application uses spaces, so parentheses group expressions.
Programs
- Fibonacci
Turn the mathematical definition of Fibonacci numbers into a recursive program.
- Lists & pipelines
Build a small data pipeline with immutable lists and higher-order functions.
- Pattern matching
Describe a small set of possibilities and handle each one explicitly.
- Structures
Group named fields into your own data type, then write a function that uses it.
- Handling missing values
Option makes missing values explicit, so the compiler helps you handle both outcomes.
- Factorial
Lean checks that ordinary recursive definitions terminate.
- Parsing with error messages
Use Except and do to return a value or an explanation of failure.
- Arrays and bounds
Build an array and access an element with a checked bound.
- Type classes and instances
Write one function whose behavior depends on the input type.
Proofs
- Your first proof
A theorem is a declaration whose type is a proposition. Lean checks the supplied proof.
- Implication & logic
Use assumptions to construct proofs. An implication is a function from one proof to another.
- Proof by induction
Prove a property for all natural numbers using a base case and a successor case.
- A program with a proof
Write a function, prove a property about it, and execute it in the same file.
- An unfinished proof: sorry
See the warning for an admitted statement, then replace the placeholder.
- Simplify with simp
Simplify expressions with library lemmas and selected definitions.
- have, rw, and calc
Name intermediate facts and justify each step of an equality.
- Reading mathematical notation
Read quantified statements and construct their proofs.
Classic mathematics
- Pythagoras: the square identity
Relate a square-area identity to a² + b² = c², then check an exact right-triangle example.
- Generate Pythagorean triples
Prove Euclid’s identity for arbitrary integer parameters, then generate several Pythagorean triples.
- Arithmetic & geometric means
A nonnegative square is enough to explain why the arithmetic mean dominates the geometric mean.
- The binomial theorem: squares
Expand a square and a cube. Lean’s core grind tactic normalizes polynomial expressions.
- Cayley–Hamilton in 2 × 2
A matrix satisfies its own characteristic polynomial. Unpack that statement into four scalar identities.
- Heron’s formula: a 3–4–5 triangle
Avoid floating-point square roots: verify the squared area with exact natural-number arithmetic.
- A finite geometric series
Prove a familiar summation formula with recursion and induction.
- Add 1 through n
A small recursive function and an induction proof of the triangular-number formula.
- The sum of squares
Repeat the induction pattern with a slightly richer polynomial.
- Cauchy–Schwarz in two dimensions
A famous inequality becomes a nonnegative square after one algebraic identity.
- The factor & remainder identity
Express the factor theorem directly, without importing a polynomial library.
- Cramer’s rule in 2 × 2
Derive the numerators in the formula for solving two simultaneous linear equations.
- The quadratic equation
Discover the algebra behind the quadratic formula, then prove exactly which integers solve x²−5x+6=0.
Number theory
- Euler’s theorem: modulo 10
Every unit modulo 10 raised to the fourth power returns to 1. Exhaust a finite type with a kernel-checked proof.
- Four squares: find a witness
Build a search program, then supply an explicit witness that Lean checks independently.
- Pell’s equation: a next solution
Turn one integer solution into another, and prove the transformation preserves the equation.
- Wilson’s theorem: small primes
Compute (p−1)! modulo p and recognize the residue −1.
- Bézout: a gcd certificate
Negative coefficients let a linear combination of two positive integers equal 1. Supply a certificate Lean can check.
- Euclid’s gcd algorithm
Run an ancient algorithm and reuse its verified properties in your own theorem.
- Perfect numbers: 6 and 28
Compute divisors, sum them, and check the first two perfect numbers.
- Why the digit test for 3 works
Prove the single step behind a familiar school arithmetic trick.
- Using the core math library
Import a core module, reuse a library theorem, and prove a concrete large-number GCD equality.
Counting & logic
- Count subsets with bit strings
Build every binary membership pattern and prove its count by induction.
- Königsberg: count odd vertices
Compute the parity obstruction behind the seven-bridges puzzle.
- Combinations & Pascal’s rule
A recursive program mirrors the two cases in a combinatorial proof.
- Cantor’s diagonal argument
An infinite theorem with a short proof: build a predicate that cannot appear in any proposed complete list.
- The induction principle
State the principle itself as a theorem, with a base case and a step supplied as arguments.
Algebra & fields
- A ring with zero divisors
Addition and multiplication can obey ring laws even when division by a nonzero element is impossible.
- GF(5): a prime field
Prove that arithmetic modulo 5 forms a field by checking every possible input.
- GF(4): build an extension field
Construct a Galois field yourself, then let Lean exhaustively verify its addition, multiplication, and inverses.
Cryptography
- Diffie–Hellman: a shared secret
Run both sides of a key exchange and prove they arrive at the same residue.
- RSA: prove a tiny round trip
Use a finite type to prove a complete round trip for every message in a miniature RSA system.
- Hashing and collisions
Use Lean’s built-in hash and see why a hash match is not proof of equality.
- SHA-256 without extra libraries
Compute SHA-256 digests using the implementation included in this file.
- BLAKE3 without extra libraries
Compute BLAKE3 digests with a self-contained implementation of its compression function and chunk tree.
Advanced Lean
- Efficiency: calculate the proof
Prove a concrete list length by reducing a decision procedure.
- Efficiency: reuse a theorem
Prove the same list length without computing the list.
- Efficiency: tail recursion
Write two equivalent sums and prove the accumulator invariant.