Module 1
Lean as a programming language
- Evaluate expressions with #eval and inspect types with #check.
- Define functions with def.
- Recursion and pattern matching (match).
- Inductive types and structures.
The playground runs the latest Lean in your browser. Locally, the file is Exercises/Programming.lean and you check it with lake exe check Programming.
Guide
Read: Functional Programming in Lean, chapter 1 ("Getting to Know Lean").
Key ideas:
#evalevaluates an expression and#checkshows its type.defdefines functions. Types are written after:.- Pattern matching with
|andmatch. - Recursion: Lean must check that it terminates, and it can when the recursive
call uses a "smaller" argument (
ninstead ofn + 1,xsinstead ofx :: xs). inductivedefines new types andstructuredefines records with fields.
Exercises: length, reverse and Tree.size.
Hint: for reverse, the ++ operator appends two lists.
Extra challenge: implement Tree.insert for a binary search tree and
Tree.toList, which traverses it in order.
Exercises
Solve them in the file, not here: the playground or VS Code shows the goal at each step. Tick an exercise once lake exe check marks it ✅ (or it compiles without sorry in the playground).
1length
/-- Returns the length of a list. -/
def length {α : Type} : List α → Nat
| _ => sorry3 tests check your definition when you run lake exe check Programming.
2reverse
/-- Reverses a list. -/
def reverse {α : Type} : List α → List α
| _ => sorry4 tests check your definition when you run lake exe check Programming.
3Tree.size
def Tree.size : Tree → Nat
| _ => sorry3 tests check your definition when you run lake exe check Programming.