Writing one function to extract the first element of a list of natural numbers and a separate function for a list of strings would be a waste. Taking the element type itself as a parameter solves it once and for all.
Use a new file, OptionsAndLists.lean. Append each section’s Lean code in order and run lean OptionsAndLists.lean after saving. The output from the earlier section will appear again.
1. Implicit Type Parameters {α : Type} and Option α
The function headOr, which extracts the first element, takes both a list and a fallback value (fallback) to return when the list is empty. In contrast, the division function safeDiv does not take a fallback value; to distinguish a valid quotient from an impossible division by 0, its return type is Option Nat, encoding whether a quotient exists at all.
If we write the element type as a capital letter , we can express the type of (where the subscript indicates that it works for any type ) in a single line. In the arrow type , the first input is a list of elements of type , the second input is the type of the fallback value used when the list is empty, and the final is the return type.
Below it, shows that Option A is a sum type made of two branches: the single empty branch none () meaning no value is present, or the branch some a () wrapping an actual value .
In the code, the curly braces in {α : Type} declare that the element type is passed implicitly. Because Lean can infer from the list and fallback arguments at each call site, you do not have to repeat the type name.1 Whenever you need to communicate the absence of a result directly to the caller instead of substituting a default value, use the two-branch Option type: none is the empty branch, and some is the branch carrying a value of type .2
α is the Greek letter alpha. Here it names the element type before we've picked a concrete one. At headOr [10, 20, 30] 0, Lean uses the numeric list and fallback to settle on Nat; the type annotation in ([] : List String) tells Lean to use String even though the list is empty.
The == in if b == 0 compares two natural numbers and produces a Bool, either true or false. safeDiv uses that result to pick a branch. In Part 5, you'll see = in a statement such as b = 0, an equality you can prove.
def headOr {α : Type} (xs : List α) (fallback : α) : α :=
match xs with
| [] => fallback
| x :: _ => x
def safeDiv (a b : Nat) : Option Nat :=
if b == 0 then none else some (a / b)
#eval headOr [10, 20, 30] 0
#eval headOr ([] : List String) "empty"
#eval safeDiv 20 4
#eval safeDiv 20 0Output:
10
"empty"
some 5
noneEach of the four output lines tests one branch. In headOr, the pattern [] matches the empty list, while x :: _ binds the front element (head) to x and ignores the remaining list (tail) with an underscore (_).
Thus the first line, headOr [10, 20, 30] 0, extracts the head element 10 from 10 :: [20, 30], and the second line, headOr ([] : List String) "empty", takes the first arm and returns the fallback "empty". An interesting fact in Lean is that dividing a natural number by zero (20 / 0) is defined to return 0 rather than raising a runtime error!
To distinguish that case from a genuine division like 1 / 2 whose integer quotient happens to be 0, safeDiv returns Option Nat. As a result, the third line safeDiv 20 4 wraps the valid quotient 5 in a box as some 5, while the fourth line safeDiv 20 0 returns none to signal that the divisor was zero.3
Writing safeDiv as a piecewise mathematical function (where the large left brace lists the result for each condition) looks like this. Here the floor brackets denote the integer quotient obtained by dropping any fractional part after dividing by (for example, and ).
Dividing 1 by 2 in the natural numbers yields a quotient of 0, which is a valid result and therefore some 0. When the divisor itself is 0, the result is none, allowing the caller to handle the two cases separately.4
2. Recursive List Functions and Termination Checking
To sum a list, we add its first element to the sum of the remaining elements. Because summing the remainder is the exact same task, the x :: rest branch calls sumList rest recursively. When [] finally arrives, there is nothing left to add, so it returns 0. Counting positive numbers also recurses over the tail, adding 1 only when the current head element is positive.
We can state how the recursion terminates in three lines of math. The double-colon notation (the cons operator) denotes a list whose head element is and whose tail list is , while the vertical bars denote the number of elements (length) in list .
The third line states that the tail is strictly shorter by one element. Lean accepts this recursive definition as terminating because rest is a structural subterm of x :: rest. Our positive-number counter walks the same tail, adding 1 to the count only when the head element is greater than zero.5
def sumList (xs : List Nat) : Nat :=
match xs with
| [] => 0
| x :: rest => x + sumList rest
def countPositive (xs : List Int) : Nat :=
match xs with
| [] => 0
| x :: rest =>
if x > 0 then 1 + countPositive rest
else countPositive rest
#eval sumList [10, 20, 30, 40]
#eval countPositive [-3, 5, 0, 12, -1, 8]Output:
100
3Unfolding the recursive calls traces how both numbers arise. First, sumList [10, 20, 30, 40] expands along its recursive calls to 10 + (20 + (30 + (40 + sumList []))), where the final sumList [] evaluates to 0 and yields 100.
Second, countPositive [-3, 5, 0, 12, -1, 8] checks each element and adds 1 only when x > 0, skipping the negative numbers -3 and -1 as well as 0 (which is not positive) to count only 5, 12, and 8 for a total of 3. What would happen if you replaced x + sumList rest with x + sumList xs?
Because the recursive call would receive the unshortened list xs over and over, Lean’s termination checker rejects this definition. In the original code, passing the one-step shorter tail rest from x :: rest (, structural recursion) lets Lean verify termination automatically.6
Function definitions in Lean are used not only to compute values at run time, but also for **theorem proving**. In Part 5, we will see how evaluating expressions and unfolding definitions power equality proofs.
Footnotes
- Lean Language Reference 4.36.0. Headers and Signatures · Universes. Summarizes inference rules for implicit type parameters
{α : Type}and theType(Type 0) universe. ↩ - Lean Language Reference 4.36.0. Headers and Signatures: Bracketed Parameters · Optional Values. Explains implicit parameters in curly braces and the two constructors of
Option. ↩ - Lean Language Reference 4.36.0. Natural Numbers. Explains subtraction and division rules on natural numbers. ↩
- Lean Language Reference 4.36.0. Natural Numbers: Arithmetic · Optional Values. Contrasts the total function rule
a / 0 = 0inNat.divwith representing a partial function viaOption. ↩ - Lean Language Reference 4.36.0. Linked Lists: Syntax · Recursive Definitions: Structural Recursion. Covers list syntax for empty and head-tail lists and the criteria for structural recursion. ↩
- Lean Language Reference 4.36.0. Recursive Definitions. Summarizes how termination is verified for structurally recursive functions. ↩