2.9. Programming with Dependent Types
In the previous chapters, the correctness of a program was established in two steps: first we wrote the function, then we proved theorems about it. Dependent types allow an alternative approach, in which part of the specification is built into the type of the program. In that case, the type checker itself guarantees that the specification is satisfied, and a program that violated it would simply not be accepted.
We have already met a few examples of this idea: the function headPre, which
requires a proof that the list is nonempty, and the type Vec α n of vectors
of fixed length. In this chapter we explore the topic systematically. We begin
with subtypes, which let us attach a property to the result of a function;
we then move on to length-indexed lists and safe indices, which make it
impossible to access a nonexistent position; and we finish with
heterogeneous lists, whose type records the type of each element.
namespace Ch16
2.9.1. Subtypes and the safe predecessor
The predecessor of a natural number is not defined for zero. In Lean's
library, the convention is that 0 - 1 = 0, but this convention hides a
potential bug: if we compute the predecessor of 0 by mistake, the program
keeps running with a meaningless value. We will look at three versions of the
predecessor, each with a more precise specification in its type.
2.9.1.1. Preconditions as arguments
The first version requires, as an additional argument, a proof that n > 0.
The caller must supply this proof; the function cannot be called with
n = 0, since there is no proof of 0 > 0.
def pred1 (n : ℕ) (_ : n > 0) : ℕ := n - 1
#eval pred1 5 (⊢ 5 > 0 All goals completed! 🐙)
The proof by omega is computed at compile time. At run time, proofs are
erased: they take up no memory and consume no time, because they belong to
Prop, and Lean guarantees that no computation can depend on the content of
a proof.
2.9.1.2. Postconditions with subtypes
The version pred1 guarantees that the function is only called when it makes
sense, but it says nothing about the result. To express a postcondition, we
use a subtype. The type {m : ℕ // P m} (notation for Subtype P) has as
its elements the pairs formed by a natural number m and a proof of P m.
The two components are accessed with .val and .property, and an element is
built with the anonymous pair notation ⟨m, proof⟩.
def pred2 (n : ℕ) (h : n > 0) : {m : ℕ // n = m + 1} :=
⟨n - 1, n:ℕh:n > 0⊢ n = n - 1 + 1 All goals completed! 🐙⟩
The type of pred2 is a complete specification: the result is an m such
that n = m + 1, that is, the predecessor of n. When building the result,
we must prove that n = (n - 1) + 1, which requires the hypothesis h —
without it, the equation would be false for n = 0.
#eval (pred2 8 (⊢ 8 > 0 All goals completed! 🐙)).val
example : (pred2 5 (⊢ 5 > 0 All goals completed! 🐙)).val = 4 := rfl
2.9.1.3. Pattern matching and impossible cases
The third version is defined by pattern matching. In the case succ k, the
result is k, and the proof of succ k = succ k is rfl. In the case 0,
the hypothesis h : 0 > 0 is contradictory, and we can leave that case with
absurd, which builds a value of any type from a proposition and its
negation.
def pred3 : (n : ℕ) → n > 0 → {m : ℕ // n = Nat.succ m}
| Nat.succ k, _ => ⟨k, rfl⟩
| 0, h => absurd h (h:0 > 0⊢ ¬0 > 0 All goals completed! 🐙)
#eval (pred3 7 (⊢ 7 > 0 All goals completed! 🐙)).val
The .property component of the result provides the proof of the
postcondition, which can be used in other proofs:
example (h : 10 > 0) : 10 = Nat.succ (pred3 10 h).val :=
(pred3 10 h).property
2.9.2. Length-indexed lists
The type IList A n of lists of elements of A with length n is an
inductive family indexed by the natural numbers, identical to the type Vec
from the chapter on functional programming:
inductive IList (A : Type) : ℕ → Type where
| inil : IList A 0
| icons {n : ℕ} : A → IList A n → IList A (n + 1)
def test1 : IList ℕ 3 :=
.icons 1 (.icons 2 (.icons 3 .inil))
The length is part of the type, so the expression .icons 1 .inil does not
have type IList ℕ 2: the type checker rejects the definition.
2.9.2.1. Total head and tail
The functions ihead and itail require a list of length n + 1. Since the
index of the constructor inil is 0, and 0 does not unify with n + 1,
Lean knows that the inil case is impossible and does not require us to
handle it. We obtain total functions, with no Option, no default value and
no explicit precondition.
def ihead {A : Type} {n : ℕ} : IList A (n + 1) → A
| .icons x _ => x
def itail {A : Type} {n : ℕ} : IList A (n + 1) → IList A n
| .icons _ xs => xs
#eval ihead test1
Trying to apply ihead to the empty list is a type error, detected at
compile time:
#eval ihead (IList.inil : IList ℕ 0)
2.9.2.2. Concatenation and definitional equality
Concatenating a list of length m with one of length n yields a list of
length m + n. When defining it, we run into a subtle difficulty. In the
inil case, the resulting list is ys, of type IList A n, but the expected
type is IList A (0 + n). Although 0 + n = n is a theorem, it is not a
definitional equality: addition of natural numbers is defined by recursion
on the second argument, so 0 + n does not reduce to n when n is a
variable. Something similar happens in the icons case. In the definition
used in class, we resolve these mismatches by rewriting the type of the goal
with rw:
def iapp {A : Type} :
∀ {m n : ℕ}, IList A m → IList A n → IList A (m + n)
A:Typen:ℕys:IList A n⊢ IList A (0 + n) A:Typen:ℕys:IList A n⊢ IList A (0 + n)
A:Typen:ℕys:IList A n⊢ IList A n
All goals completed! 🐙
A:Typem:ℕn:ℕx:Axs:IList A mys:IList A n⊢ IList A (m + 1 + n) A:Typem:ℕn:ℕx:Axs:IList A mys:IList A n⊢ IList A (m + 1 + n)
have h : m + n + 1 = m + 1 + n := A:Typem:ℕn:ℕx:Axs:IList A mys:IList A n⊢ IList A (m + 1 + n) All goals completed! 🐙
A:Typem:ℕn:ℕx:Axs:IList A mys:IList A nh:m + n + 1 = m + 1 + n⊢ IList A (m + n + 1)
All goals completed! 🐙
This definition works, but the rw steps insert type casts into the
resulting term, which makes it harder to prove properties of iapp. An
alternative is to choose the index of the result so that the required
equalities are definitional. If the result type is IList A (n + m), with the
left list of length m, then in the inil case the index is n + 0, which
reduces to n, and in the icons case it is n + (m + 1), which reduces to
(n + m) + 1. No rewriting is needed:
def iapp' {A : Type} :
∀ {m n : ℕ}, IList A m → IList A n → IList A (n + m)
| _, _, .inil, ys => ys
| _, _, .icons x xs, ys => .icons x (iapp' xs ys)
This phenomenon is characteristic of programming with dependent types: the choice of definitions (here, the order of the arguments of addition) directly affects how much proof work is required.
2.9.2.3. Converting to and from lists
The functions inject and eject convert ordinary lists into indexed lists
and back. Note that the type of inject depends on the value of the input
list:
def inject {A : Type} : (l : List A) → IList A l.length
| [] => .inil
| x :: xs => .icons x (inject xs)
def eject {A : Type} {n : ℕ} : IList A n → List A
| .inil => []
| .icons x xs => x :: eject xs
#eval eject (iapp' (.icons 1 (.icons 2 .inil))
(.icons 3 .inil))
Ejecting an injected list gives back the original list, by a simple
induction. With the definition iapp', it is also easy to prove that eject
turns the concatenation of indexed lists into the concatenation of ordinary
lists: induction on xs goes through without difficulty because there are no
casts in the way.
theorem eject_inject {A : Type} (l : List A) :
eject (inject l) = l := A:Typel:List A⊢ eject (inject l) = l
induction l with
A:Type⊢ eject (inject []) = [] All goals completed! 🐙
A:Typex:Axs:List Aih:eject (inject xs) = xs⊢ eject (inject (x :: xs)) = x :: xs All goals completed! 🐙
theorem eject_iapp' {A : Type} {m n : ℕ}
(xs : IList A m) (ys : IList A n) :
eject (iapp' xs ys) = eject xs ++ eject ys := A:Typem:ℕn:ℕxs:IList A mys:IList A n⊢ eject (iapp' xs ys) = eject xs ++ eject ys
induction xs with
A:Typem:ℕn:ℕys:IList A n⊢ eject (iapp' IList.inil ys) = eject IList.inil ++ eject ys All goals completed! 🐙
A:Typem:ℕn:ℕys:IList A nn_1:ℕx:Axs:IList A n_1ih:eject (iapp' xs ys) = eject xs ++ eject ys⊢ eject (iapp' (IList.icons x xs) ys) = eject (IList.icons x xs) ++ eject ys All goals completed! 🐙
theorem length_eject {A : Type} {n : ℕ} (xs : IList A n) :
(eject xs).length = n := A:Typen:ℕxs:IList A n⊢ (eject xs).length = n
induction xs with
A:Typen:ℕ⊢ (eject IList.inil).length = 0 All goals completed! 🐙
A:Typen:ℕn_1:ℕx:Axs:IList A n_1ih:(eject xs).length = n_1⊢ (eject (IList.icons x xs)).length = n_1 + 1 All goals completed! 🐙
2.9.3. Safe indices
Accessing the i-th position of a list is another partial operation: the
index may be out of bounds. With indexed lists, we can require the index to
belong to a type that contains only valid indices. The type Idx n has
exactly n elements, representing the positions 0, 1, …, n - 1:
inductive Idx : ℕ → Type where
| zero {n : ℕ} : Idx (n + 1)
| succ {n : ℕ} : Idx n → Idx (n + 1)
In particular, Idx 0 is empty: there are no valid indices into an empty
list. (Lean's library offers an equivalent type, Fin n, defined as a
subtype: {i : ℕ // i < n}.) The access function only needs to handle
nonempty lists, since there is no index for the empty list:
def iget {A : Type} : ∀ {n : ℕ}, IList A n → Idx n → A
| _, .icons x _, .zero => x
| _, .icons _ xs, .succ i => iget xs i
def list123 : IList ℕ 3 :=
.icons 10 (.icons 20 (.icons 30 .inil))
#eval iget list123 (.succ (.succ .zero))
Trying to access the fourth position of a three-element list is, once again,
a type error: the term .succ (.succ (.succ .zero)) has type Idx (k + 4)
for some k, which cannot be equal to Idx 3.
2.9.4. Heterogeneous lists
An ordinary list contains elements of a single type. A heterogeneous list
may contain elements of different types, and its type records the type of
each position. The idea is to index the list by a list of "codes"
ts : List α, together with a function B : α → Type that interprets each
code as a type. The element at position i has type B t, where t is the
i-th code.
universe u v
inductive HList {α : Type u} (B : α → Type v) :
List α → Type (max u v) where
| hnil : HList B []
| hcons {t : α} {ts : List α} :
B t → HList B ts → HList B (t :: ts)
The type HList lives in the universe max u v, since it contains elements
of types B t : Type v and is indexed by lists of elements of α : Type u.
2.9.4.1. Example: database records
A typical application is the representation of records (rows) of a table, whose schema describes the type of each column. The codes are the column types, and the interpretation function maps them to Lean types:
inductive BaseType where
| TNat | TBool | TString
deriving Repr
@[reducible]
def denoteBase : BaseType → Type
| .TNat => ℕ
| .TBool => Bool
| .TString => String
def schema : List BaseType :=
[.TNat, .TBool, .TString, .TNat]
def record : HList denoteBase schema :=
.hcons 42 (.hcons true (.hcons "Lean" (.hcons 12 .hnil)))
The @[reducible] attribute lets Lean unfold denoteBase during type
checking, so that denoteBase .TNat is recognized as ℕ and the literal
42 is accepted in the first position. A record such as .hcons true .hnil
would not have type HList denoteBase [.TNat].
2.9.4.2. Operations on heterogeneous lists
Head, tail and concatenation have types that describe the result precisely.
In concatenation, the schemas are concatenated with ++; here there is no
definitional equality problem, since [] ++ ss reduces to ss and
(t :: ts) ++ ss reduces to t :: (ts ++ ss).
def hhd {α : Type u} {B : α → Type v} {t : α}
{ts : List α} :
HList B (t :: ts) → B t
| .hcons x _ => x
def htl {α : Type u} {B : α → Type v} {t : α}
{ts : List α} :
HList B (t :: ts) → HList B ts
| .hcons _ xs => xs
def happ {α : Type u} {B : α → Type v} :
∀ {ts ss : List α},
HList B ts → HList B ss → HList B (ts ++ ss)
| [], _, .hnil, ys => ys
| _ :: _, _, .hcons x xs, ys => .hcons x (happ xs ys)
#eval hhd (htl record)
2.9.4.3. Access by membership
To access an arbitrary position of a heterogeneous list, a numeric index is
not enough: the type of the result depends on the position. Instead we use a
membership proof HMember t ts, which indicates at which position of ts
the code t occurs. It is analogous to the predicate Mem from the chapter
on inductive predicates, but it lives in Type, so that we can pattern match
on it when computing.
inductive HMember {α : Type u} (t : α) :
List α → Type u where
| head {ts : List α} : HMember t (t :: ts)
| tail {s : α} {ts : List α} :
HMember t ts → HMember t (s :: ts)
def hget {α : Type u} {B : α → Type v} {t : α} :
∀ {ts : List α}, HList B ts → HMember t ts → B t
| _ :: _, .hcons x _, .head => x
| _ :: _, .hcons _ xs, .tail m => hget xs m
The type of hget states that, if t occurs in ts, then accessing the
list at the corresponding position yields a value of type B t. The type of
the result is computed from the index:
#eval hget record (.tail (.tail .head))
Accessing the fourth position of the concatenation of record with a second
record, we obtain the first element of the latter:
def record2 : HList denoteBase [.TNat] :=
.hcons 100 .hnil
#eval hget (happ record record2)
(.tail (.tail (.tail (.tail .head))))
2.9.4.4. A recursive variant
Type families can also be defined by recursion rather than by induction: a
type can be computed by a function. The variant FHList defines a
heterogeneous list as a sequence of nested pairs, terminated by Unit; the
membership type FHMember is a sum (a computational disjunction) that says
whether the code is in the head or in the tail.
@[reducible]
def FHList {α : Type} (B : α → Type) : List α → Type
| [] => Unit
| t :: ts => B t × FHList B ts
@[reducible]
def FHMember {α : Type} (t : α) : List α → Type
| [] => Empty
| s :: ts => Sum (PLift (s = t)) (FHMember t ts)
def fhget {α : Type} {B : α → Type} {t : α} :
∀ {ts : List α}, FHList B ts → FHMember t ts → B t
| [], _, idx => Empty.elim idx
| _ :: _, fls, Sum.inl ⟨rfl⟩ => fls.1
| _ :: _, fls, Sum.inr idx => fhget fls.2 idx
With this representation, the record from the previous example is simply a
nested tuple. The [] case of fhget uses Empty.elim: since
FHMember t [] is the empty type, there is no index to handle. In the case
Sum.inl ⟨rfl⟩, matching on rfl unifies the code at the head with t, so
that fls.1 has the correct type B t.
def recordF : FHList denoteBase schema :=
(42, (true, ("Lean", (12, ()))))
#eval fhget recordF (.inr (.inl ⟨rfl⟩))
The two representations have complementary advantages. The inductive version
is easier to manipulate by pattern matching and induction; the recursive
version reuses existing types (products, sums, Unit, Empty) and lets Lean
compute the type of a record by simple evaluation.
end Ch16
2.9.5. Exercises
-
Define a function
imap : (A → B) → IList A n → IList B nand prove thateject (imap f xs) = List.map f (eject xs). -
Define
izip : IList A n → IList B n → IList (A × B) n. Compare it with the functionzipon ordinary lists: how many cases are needed? -
Define the reversal of indexed lists,
irev : IList A n → IList A n. You will need an auxiliary function with an accumulator, and some care with the order of the arguments of addition in the index. -
Define a function
toNat : Idx n → ℕand prove thattoNat i < nfor everyi : Idx n. Then define a functionIdx n → Fin n. -
Define a version of
natDivwhose result type is the subtype{qr : ℕ × ℕ // d * qr.1 + qr.2 = n ∧ qr.2 < d}assuming
d > 0as a precondition. -
Prove that
eject (iapp xs ys) = eject xs ++ eject ysfor the versioniappdefined withrw. What difficulties arise? Hint: first prove a lemma aboutejectapplied to a term of the formh ▸ xs. -
Define a function
hmapthat applies, at each position of anHList B ts, a function∀ t, B t → C t, producing anHList C ts.