1.8. The Calculus of Constructions
The simply typed lambda calculus rigidly separates two worlds: that of terms
(proofs) and that of types (propositions). Types cannot depend on terms, and
terms cannot depend on types. This separation accounts for the simplicity of
the STLC, but also for its logical limitation: the STLC corresponds only to
propositional logic. Predicate logic, studied in the previous chapter,
requires quantifiers,
\forall x : A.\; P(x) \qquad \exists x : A.\; P(x)
and these have no natural representation in the STLC: the proposition P(x)
depends on the term x.
To go further, we need a system able to express three new forms of dependency:
-
polymorphism — terms that depend on types, such as the polymorphic identity, which takes a type
\alphaand returns the identity on\alpha; -
dependent types — types that depend on terms, such as the type of vectors of length
n, or the propositionP(x); -
type operators — types that depend on types, such as the constructor
\mathrm{List}, which maps a type\alphato the type of lists of\alpha.
The Calculus of Constructions (CoC), proposed by Thierry Coquand and Gérard Huet in 1988, incorporates all of these forms of dependency into a single coherent system in which terms and types belong to the same syntactic category. The CoC is the theoretical foundation of proof assistants such as Coq (whose name pays homage to the calculus) and Lean. In this chapter:
-
we place the CoC within the hierarchy of pure type systems (the Barendregt cube);
-
we present the typing rules of the CoC and the notion of definitional equality via beta-delta reduction;
-
we show how the logical connectives and the quantifiers can be encoded in the CoC, in the style of Church;
-
we describe the Haskell implementation (folder
haskell/src/CoC) of a type checker and of a REPL with tactics for the interactive construction of proofs.
1.8.1. The Barendregt cube
Henk Barendregt arranged eight type systems in a cube, according to the forms
of dependency they allow. At the origin vertex sits the STLC, \lambda{\to},
in which only terms depend on terms (ordinary functions). Each of the cube's
three axes adds a new form of dependency:
|
System |
Added dependency |
Example |
|---|---|---|
|
|
terms depending on types (polymorphism) |
|
|
|
types depending on types (type operators) |
|
|
|
types depending on terms (dependent types) |
|
The system \lambda 2 is Girard and Reynolds's System F; \lambda P
corresponds to the system LF, used as a logical framework. Combinations of
the axes yield the remaining vertices — for instance,
\lambda\omega = \lambda 2 + \lambda\underline{\omega} is System
F_\omega. The vertex opposite the STLC, which combines all three extensions,
is the Calculus of Constructions, \lambda C.
1.8.2. Pure type systems
The eight systems of the cube can be described uniformly as pure type
systems (PTS). A PTS is specified by a triple
(\mathcal{S}, \mathcal{A}, \mathcal{R}):
-
\mathcal{S}is a set of sorts — the "types of types"; -
\mathcal{A}is a set of axioms of the forms_1 : s_2, which determine the type of each sort; -
\mathcal{R}is a set of rules(s_1, s_2, s_3)stating which\Pitypes may be formed: if the domain has sorts_1and the codomain has sorts_2, the resulting\Pitype has sorts_3. Whens_3 = s_2, we abbreviate the rule as(s_1, s_2).
For the Calculus of Constructions:
\mathcal{S} = \{*, \square\} \qquad \mathcal{A} = \{* : \square\} \qquad \mathcal{R} = \{(*, *),\; (*, \square),\; (\square, *),\; (\square, \square)\}
The sort * is the sort of propositions (or of "small types"): A : *
means that A is a type/proposition. The sort \square is the sort of
types of types (called kinds); for example, * : \square and
* \to * : \square. The inhabitants of \square are therefore the kinds,
and \square itself has no type.
Each rule in \mathcal{R} enables one form of dependency:
|
Rule |
Meaning |
Example |
|---|---|---|
|
|
functions between terms |
|
|
|
polymorphism |
|
|
|
types depending on terms |
|
|
|
type operators |
|
The systems of the cube differ only in the set \mathcal{R}, all of them
containing (*, *): \lambda{\to} has only (*,*); \lambda 2 adds
(\square, *); \lambda\underline{\omega} adds (\square,\square);
\lambda P adds (*, \square); and \lambda C has all four.
1.8.3. Syntax
In the CoC, terms and types belong to the same syntactic category:
t, A, B \;::=\; s \;\mid\; x \;\mid\; t\;t \;\mid\; \lambda x{:}A.\, t \;\mid\; \Pi x{:}A.\, B
where s \in \{*, \square\} is a sort, x is a variable, t\;t is an
application, \lambda x{:}A.\,t is an abstraction and \Pi x{:}A.\,B is the
dependent product: the type of functions that take an x : A and return a
result of type B, where B may mention x. Under the logical reading,
\Pi x{:}A.\,B is the universal quantifier \forall x{:}A.\,B.
The usual function type is a special case. When x \notin \mathsf{fv}(B), the
result does not depend on the argument, and we write
A \to B \;\stackrel{\text{def}}{=}\; \Pi\_{:}A.\, B
From the logical point of view, implication is a "universal quantifier over
proofs of A" whose proofs are not used in the conclusion.
Some examples of terms and their types:
|
Term |
Type |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
The second example is the polymorphic identity (a term depending on a type);
the third shows that the type of the polymorphic identity is itself a
proposition of sort * — this feature, impredicativity, is what will make
the Church encodings below possible; the last one is a type operator.
1.8.4. Type system
1.8.4.1. Contexts
A context \Gamma is a list of declarations, which may be hypotheses or
definitions:
\Gamma \;::=\; \emptyset \;\mid\; \Gamma,\, x : A \;\mid\; \Gamma,\, x := t : A
The declaration x : A says that x has type A (a hypothesis); the
declaration x := t : A says that x is defined as t, with type
A. Definitions enable delta-reduction, which replaces a name with its
definition. Proof assistants rely heavily on definitions: in Lean, every def
adds such a declaration to the global environment.
1.8.4.2. Typing rules
The judgement \Gamma \vdash t : A is defined by the following rules. The
first ones deal with sorts and variables:
\frac{}{\Gamma \vdash * : \square}\;\text{(Ax)} \qquad \frac{(x : A) \in \Gamma}{\Gamma \vdash x : A}\;\text{(Var)} \qquad \frac{(x := t : A) \in \Gamma}{\Gamma \vdash x : A}\;\text{(Def)}
Rule (Ax) is the single axiom of \mathcal{A}. Rule (Def) gives a defined
name its declared type; the reduction x \longrightarrow_\delta t will be
part of definitional equality.
The formation of dependent products is governed by the rules of
\mathcal{R}:
\frac{\Gamma \vdash A : s_1 \qquad \Gamma,\, x : A \vdash B : s_2 \qquad (s_1, s_2) \in \mathcal{R}}{\Gamma \vdash \Pi x{:}A.\, B : s_2}\;\text{(Pi)}
For example, to type \Pi\alpha{:}*.\,\alpha \to \alpha, we have
* : \square and, under \alpha : *, \alpha \to \alpha : *; rule
(\square, *) lets us conclude that the product has sort *.
Abstraction and application generalize the rules of the STLC:
\frac{\Gamma \vdash \Pi x{:}A.\, B : s \qquad \Gamma,\, x : A \vdash t : B}{\Gamma \vdash \lambda x{:}A.\, t : \Pi x{:}A.\, B}\;\text{(Lam)} \qquad \frac{\Gamma \vdash f : \Pi x{:}A.\, B \qquad \Gamma \vdash a : A}{\Gamma \vdash f\; a : B[x := a]}\;\text{(App)}
The first premise of (Lam) ensures that the type of the abstraction is well
formed. In (App), the type of the result is obtained by substituting the
argument into the codomain: if f : \Pi n{:}\mathbb{N}.\,\mathrm{Vec}\;n,
then f\;3 : \mathrm{Vec}\;3. Logically, (App) is universal elimination: from
\forall x{:}A.\,B and a : A, we obtain B[x := a].
Finally, the conversion rule allows the type of a term to be replaced by any
definitionally equal type:
\frac{\Gamma \vdash t : A \qquad \Gamma \vdash B : s \qquad A =_{\beta\delta} B}{\Gamma \vdash t : B}\;\text{(Conv)}
This rule is indispensable when types contain computation: if
t : (\lambda\alpha{:}*.\,\alpha \to \alpha)\;\beta, we want to be able to
use t as an element of \beta \to \beta.
For simplicity, the rules above omit the well-formedness conditions on contexts
(each type declared in \Gamma must have a sort, and the variables must be
distinct), which are part of the full presentation.
1.8.4.3. An example derivation
Let us look at the derivation of
\vdash \lambda\alpha{:}*.\,\lambda x{:}\alpha.\,x : \Pi\alpha{:}*.\,\alpha \to \alpha.
Writing \Gamma = \alpha : * and \Delta = \alpha : *,\, x : \alpha, the
central part is the typing of the body:
\frac{\dfrac{\Gamma \vdash \alpha \to \alpha : * \qquad \dfrac{(x : \alpha) \in \Delta}{\Delta \vdash x : \alpha}\;\text{(Var)}}{\Gamma \vdash \lambda x{:}\alpha.\,x : \alpha \to \alpha}\;\text{(Lam)} \qquad \vdash \Pi\alpha{:}*.\,\alpha \to \alpha : *}{\vdash \lambda\alpha{:}*.\,\lambda x{:}\alpha.\,x : \Pi\alpha{:}*.\,\alpha \to \alpha}\;\text{(Lam)}
where the well-formedness premises for the types are obtained by (Pi):
\frac{\dfrac{}{\vdash * : \square}\;\text{(Ax)} \qquad \dfrac{\Gamma \vdash \alpha : * \qquad \Gamma, \_ : \alpha \vdash \alpha : *}{\Gamma \vdash \alpha \to \alpha : *}\;\text{(Pi)}\,(*,*)}{\vdash \Pi\alpha{:}*.\,\alpha \to \alpha : *}\;\text{(Pi)}\,(\square,*)
1.8.5. Reduction and definitional equality
The CoC has two forms of reduction. Beta-reduction is the familiar
application of a function to its argument; delta-reduction unfolds
definitions from the context:
(\lambda x{:}A.\, t)\; a \;\longrightarrow_\beta\; t[x := a] \qquad\qquad x \;\longrightarrow_\delta\; t \quad\text{when}\quad (x := t : A) \in \Gamma
Definitional equality =_{\beta\delta} is the reflexive, symmetric and
transitive closure of \longrightarrow_{\beta\delta} (also closed under all
term constructors). Thanks to the properties of the CoC discussed below
(confluence and strong normalization), checking A =_{\beta\delta} B is
decidable: it suffices to reduce both terms to normal form and test whether
the results are alpha-equivalent.
In practice, full normalization is often unnecessary. Frequently it is enough
to know the outermost constructor of a term — for instance, to check whether
the type of a function really is a \Pi. For this we use the weak head
normal form (WHNF), in which only the "head" of the term is reduced. Terms in
WHNF are characterized by the rules:
\frac{}{s \;\text{in WHNF}} \qquad \frac{}{x \;\text{in WHNF}} \qquad \frac{}{\lambda x{:}A.\,t \;\text{in WHNF}} \qquad \frac{}{\Pi x{:}A.\,B \;\text{in WHNF}} \qquad \frac{f \;\text{in WHNF}\quad f \neq \lambda}{f\;a \;\text{in WHNF}}
(with x a variable that has no definition in the context). Note that there is
no reduction under \lambda and \Pi, nor in the arguments of an
application. The full normal form is obtained by reducing to WHNF and then
recursively normalizing the subterms, including under binders.
In Lean, definitional equality is visible in proofs by rfl: the checker
accepts the proof if both sides are definitionally equal, using beta, delta
and other reductions:
namespace Ch07
def twice (α : Type) (f : α → α) (x : α) : α := f (f x)
-- delta (unfolding twice) followed by beta
example : twice Nat (· + 1) 0 = 2 := rfl
-- conversion: (fun α => α → α) Nat reduces to Nat → Nat
def Endo : Type → Type := fun α => α → α
def succE : Endo Nat := fun n => n + 1
example : succE 1 = 2 := rfl
1.8.6. Church encodings
In the STLC, each logical connective required new syntactic constructs: pairs
for \wedge, injections and \mathbf{case} for \vee, \mathbf{unit}
and \mathbf{absurd} for \top and \bot. In the CoC this is not
necessary: the connectives can be encoded as \Pi types, without extending
the syntax. The idea is the same as that of the Church encodings of the untyped
lambda calculus: a proposition is characterized by the way it can be used.
The essential ingredient is the impredicativity of *: a type such as
\Pi c{:}*.\,\ldots quantifies over all propositions — including itself —
and is nevertheless a proposition of sort *.
1.8.6.1. Truth and falsity
Truth is the proposition that "implies anything it itself implies":
\top \;\stackrel{\text{def}}{=}\; \Pi\alpha{:}*.\, \alpha \to \alpha
whose only inhabitant (up to definitional equality) is the polymorphic
identity, \mathbf{tt} = \lambda\alpha{:}*.\, \lambda x{:}\alpha.\, x.
Falsity is the proposition that implies every proposition:
\bot \;\stackrel{\text{def}}{=}\; \Pi\alpha{:}*.\, \alpha
If we had a proof f : \bot, then f\;A : A for any A — this is the
principle of ex falso quodlibet,
\mathbf{exFalso} = \lambda f{:}\bot.\,\lambda\alpha{:}*.\,f\;\alpha \;:\; \bot \to \Pi\alpha{:}*.\, \alpha
Negation is defined, as usual, by \neg A \stackrel{\text{def}}{=} A \to \bot.
1.8.6.2. Conjunction and disjunction
A proof of A \wedge B is something that allows us to conclude any c from
a function that uses a proof of A and a proof of B:
A \wedge B \;\stackrel{\text{def}}{=}\; \Pi c{:}*.\, (A \to B \to c) \to c
The introduction takes both proofs and hands them to the continuation; the
eliminations choose c appropriately:
\begin{array}{lcl}
\mathbf{and\_intro} & = & \lambda c{:}*.\,\lambda f{:}A \to B \to c.\; f\; t_A\; t_B \\
\mathbf{fst} & = & \lambda p{:}A \wedge B.\; p\;A\;(\lambda a{:}A.\,\lambda b{:}B.\, a) \\
\mathbf{snd} & = & \lambda p{:}A \wedge B.\; p\;B\;(\lambda a{:}A.\,\lambda b{:}B.\, b)
\end{array}
Similarly, a proof of A \vee B allows us to conclude any c, provided we
know how to handle both cases:
A \vee B \;\stackrel{\text{def}}{=}\; \Pi c{:}*.\, (A \to c) \to (B \to c) \to c
with injections \lambda c\, f_l\, f_r.\; f_l\; t_A and
\lambda c\, f_l\, f_r.\; f_r\; t_B. Elimination (case analysis) is simply
application: given p : A \vee B, we have p\;C\;g\;h : C whenever
g : A \to C and h : B \to C.
1.8.6.3. Quantifiers
The universal quantifier needs no encoding at all: it is the \Pi type
itself:
\forall x{:}A.\, P(x) \;\stackrel{\text{def}}{=}\; \Pi x{:}A.\, P(x)
The existential is encoded in a way analogous to disjunction — a disjunction
"indexed" by x : A:
\exists x{:}A.\, P(x) \;\stackrel{\text{def}}{=}\; \Pi c{:}*.\, (\Pi x{:}A.\, P(x) \to c) \to c
A proof of \exists x{:}A.\,P(x) allows us to conclude any c that follows
from P(x) for an arbitrary x — exactly the existential elimination rule
of natural deduction, with the eigenvariable condition expressed by the
\Pi x. The introduction with witness a and proof p_a : P(a) is
\lambda c\, k.\; k\; a\; p_a.
1.8.6.4. Summary of the encodings
|
Connective |
Encoding in the CoC |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1.8.6.5. Encodings in Lean
Lean's sort Prop is impredicative, just like the * of the CoC: a ∀ over
all propositions is still a proposition. Compare this with Type, which is
predicative — quantifying over Type produces something in Type 1:
#check (∀ α : Prop, α → α)
#check (∀ α : Type, α → α)
We can therefore transcribe the Church encodings directly:
def CTrue : Prop := ∀ α : Prop, α → α
def CFalse : Prop := ∀ α : Prop, α
def CAnd (A B : Prop) : Prop := ∀ c : Prop, (A → B → c) → c
def COr (A B : Prop) : Prop :=
∀ c : Prop, (A → c) → (B → c) → c
def CEx {α : Type} (P : α → Prop) : Prop :=
∀ c : Prop, (∀ x, P x → c) → c
theorem tt : CTrue := fun _ x => x
theorem exFalso : CFalse → ∀ α : Prop, α := fun f α => f α
theorem and_intro {A B : Prop} (a : A) (b : B) : CAnd A B :=
fun _ f => f a b
theorem and_fst {A B : Prop} (p : CAnd A B) : A :=
p A (fun a _ => a)
theorem and_snd {A B : Prop} (p : CAnd A B) : B :=
p B (fun _ b => b)
theorem or_inl {A B : Prop} (a : A) : COr A B :=
fun _ fl _ => fl a
theorem or_inr {A B : Prop} (b : B) : COr A B :=
fun _ _ fr => fr b
theorem ex_intro {α : Type} {P : α → Prop} (a : α)
(h : P a) : CEx P :=
fun _ k => k a h
The encodings are equivalent to Lean's inductive connectives. For example, for conjunction and the existential:
theorem cand_iff (A B : Prop) : CAnd A B ↔ A ∧ B :=
⟨fun p => ⟨and_fst p, and_snd p⟩,
fun ⟨a, b⟩ => and_intro a b⟩
theorem cex_iff {α : Type} (P : α → Prop) :
CEx P ↔ ∃ x, P x :=
⟨fun h => h _ (fun x hx => ⟨x, hx⟩),
fun ⟨x, hx⟩ => ex_intro x hx⟩
-- commutativity of the encoded conjunction
example (A B : Prop) : CAnd A B → CAnd B A :=
fun p => and_intro (and_snd p) (and_fst p)
Note that, in the proof of cex_iff, the left-to-right direction
instantiates c with the proposition ∃ x, P x itself: this is only
possible because c ranges over all propositions. This is impredicativity in
action. Although the encodings suffice from a logical point of view, they have
limitations (for instance, the induction principle for the encoded natural
numbers cannot be derived). That is why Coq and Lean extend the CoC with
inductive types, yielding the Calculus of Inductive Constructions.
1.8.7. Properties of the CoC
The CoC enjoys the following fundamental metatheoretical properties:
-
Confluence (the Church-Rosser theorem): if
t \twoheadrightarrow_\beta t_1andt \twoheadrightarrow_\beta t_2, there existst'such thatt_1 \twoheadrightarrow_\beta t'andt_2 \twoheadrightarrow_\beta t'. In particular, the normal form of a term, when it exists, is unique. -
Strong normalization: every well-typed term of the CoC has a normal form, and every reduction sequence starting from it terminates — there are no infinite computations. As a consequence, the CoC is not Turing-complete, but it is sufficient for constructive mathematics.
-
Logical consistency:
\botis not inhabited in the empty context, that is,\Pi\alpha{:}*.\,\alphacannot be proved without hypotheses. This follows from normalization: a closed normal-form inhabitant of\Pi\alpha{:}*.\,\alphawould have the form\lambda\alpha{:}*.\,twitht : \alphain normal form in the context\alpha : *, and there is no sucht. -
Decidability of type checking: given
\Gammaandt, it is decidable whether there existsAsuch that\Gamma \vdash t : A. The algorithm is syntax-directed (inferring types bottom-up) and its termination depends on strong normalization, since rule (Conv) requires comparing types by normalization.
1.8.8. Implementation in Haskell
The folder haskell/src/CoC contains a type checker for the CoC and a REPL
(run with cabal run coc) with a tactic proof mode. Its modules closely follow
the theoretical presentation.
1.8.8.1. Syntax
The type Term mirrors the unified grammar, with an extra constructor for type
annotations (t : A). The context is an association list whose entries are
hypotheses (HasType) or definitions (HasDef):
data Sort = Star | Box data Term = Sort Sort | Var String | App Term Term | Lam String Term Term -- λx:A. t | Pi String Term Term -- Πx:A. B | Ann Term Term -- (t : A) data CtxEntry = HasType Term -- x : A | HasDef Term Term -- x := t : A type Ctx = [(String, CtxEntry)]
1.8.8.2. Substitution and alpha-equivalence
Unlike the implementations of the previous chapters, the CoC type checker works
directly with names. The substitution subst x s t, which computes
t[x := s], avoids capture by renaming the binder when it occurs free in
s. The function freshFor generates a new name by appending primes:
subst :: String -> Term -> Term -> Term
subst x s t = go t
where
fvs = freeVars s
go (Var y) | y == x = s
| otherwise = Var y
go (Lam y a b)
| y == x = Lam y (go a) b -- x is shadowed
| y `Set.member` fvs =
let y' = freshFor (fvs `Set.union` freeVars b
`Set.union` Set.singleton x) y
in Lam y' (go a) (go (subst y (Var y') b))
| otherwise = Lam y (go a) (go b)
-- analogous cases for Pi, App, Ann and Sort
Alpha-equivalence traverses both terms simultaneously, associating with each bound variable the depth of its binder. Two bound variables are equal if they were bound at the same depth; two free variables, if they have the same name — a way of comparing "De Bruijn style" without converting the terms:
alphaEq :: Term -> Term -> Bool
alphaEq = go [] []
where
go e1 e2 (Var x) (Var y) =
case (lookup x e1, lookup y e2) of
(Just d1, Just d2) -> d1 == d2
(Nothing, Nothing) -> x == y
_ -> False
go e1 e2 (Lam x a1 b1) (Lam y a2 b2) =
let d = length e1
in go e1 e2 a1 a2 && go ((x,d):e1) ((y,d):e2) b1 b2
-- ...
1.8.8.3. Reduction
The module CoC.Reduce implements WHNF, normal form and definitional
equality. In whnf, a variable with a definition in the context is unfolded
(delta) and an application whose head reduces to a \lambda is contracted
(beta); all other terms are already in WHNF:
whnf :: Ctx -> Term -> Term
whnf ctx (Var x) =
case lookupDef x ctx of
Just t -> whnf ctx t -- delta
Nothing -> Var x
whnf ctx (App f a) =
case whnf ctx f of
Lam x _ body -> whnf ctx (subst x a body) -- beta
f' -> App f' a
whnf ctx (Ann t _) = whnf ctx t
whnf _ t = t -- Sort, Lam, Pi
nf :: Ctx -> Term -> Term
nf ctx t =
case whnf ctx t of
App f a -> App (nf ctx f) (nf ctx a)
Lam x ty b -> Lam x (nf ctx ty) (nf (extendCtx x ty ctx) b)
Pi x ty b -> Pi x (nf ctx ty) (nf (extendCtx x ty ctx) b)
t' -> t'
betaEq :: Ctx -> Term -> Term -> Bool
betaEq ctx s t = alphaEq (nf ctx s) (nf ctx t)
The function nf follows the description of the full normal form exactly: WHNF
followed by recursive normalization of the subterms. Definitional equality
betaEq compares normal forms modulo alpha-equivalence.
1.8.8.4. Type checker
The type checker (CoC.Check) consists of three mutually recursive functions:
infer infers the type of a term; check verifies that a term has an expected
type up to definitional equality — this is where rule (Conv) is
implemented —; and inferSort infers the type of a term and requires it to be
a sort.
infer :: Ctx -> Term -> Either String Term
infer _ (Sort Star) = Right (Sort Box) -- (Ax)
infer _ (Sort Box) = Left "□ has no type"
infer ctx (Var x) = -- (Var)/(Def)
case lookupType x ctx of
Just ty -> Right ty
Nothing -> Left $ "Variable not in scope: " ++ x
infer ctx (App f a) = do -- (App)
fTy <- infer ctx f
case whnf ctx fTy of
Pi x dom cod -> do
check ctx a dom
return (subst x a cod)
other -> Left "Expected a function type"
infer ctx (Lam x a body) = do -- (Lam)
_ <- inferSort ctx a
b <- infer (extendCtx x a ctx) body
return (Pi x a b)
infer ctx (Pi x a b) = do -- (Pi)
s1 <- inferSort ctx a
s2 <- inferSort (extendCtx x a ctx) b
if validRule s1 s2 then return (Sort s2)
else Left "Invalid PTS rule"
check :: Ctx -> Term -> Term -> Either String ()
check ctx t expected = do -- (Conv)
actual <- infer ctx t
if betaEq ctx actual expected then Right ()
else Left "Type mismatch"
inferSort :: Ctx -> Term -> Either String Sort
inferSort ctx ty = do
k <- infer ctx ty
case whnf ctx k of
Sort s -> Right s
_ -> Left "Expected a sort"
A few details deserve attention. In the application case, the type of the
function is put in WHNF before checking whether it is a \Pi: the type may
be, for example, a defined name (such as True) or an application of a type
operator, and it must be reduced to expose the \Pi. Since the CoC admits all
four rules of \mathcal{R}, the function validRule simply returns True
for any pair of sorts; to obtain other vertices of the cube it would suffice to
restrict it (for instance, accepting only (Star, Star) would yield the STLC).
Finally, the (Lam) case is an algorithmic version of the rule: instead of
requiring the whole \Pi to be well formed, it checks that the domain is a
type and infers the type of the body.
1.8.8.5. Preloaded encodings
The module CoC.Encode defines the Church encodings as Haskell functions that
build terms, together with a set of definitions (builtins) loaded into the
REPL's initial context, such as True, False, tt, exFalso,
and_intro, and_fst, and_snd, or_inl and or_inr. For example:
-- A ∧ B ≡ Πc:*. (A → B → c) → c
andTy :: Term -> Term -> Term
andTy a b =
Pi "c" (Sort Star)
(arr (arr a (arr b (Var "c"))) (Var "c"))
-- ∃x:A. B ≡ Πc:*. (Πx:A. B → c) → c
existsTy :: String -> Term -> Term -> Term
existsTy x a b =
Pi "c" (Sort Star)
(arr (Pi x a (arr b (Var "c"))) (Var "c"))
where arr a b = Pi "_" a b builds the non-dependent function type.
1.8.8.6. REPL and tactics
The REPL accepts commands to define names (:def), check types (:check),
normalize terms (:eval) and reduce to WHNF (:whnf):
coc> \(a:*)(x:a). x λa. λx. x : Πa:*. a → a coc> :def id := \(a:*)(x:a). x id : Πa:*. a → a coc> :eval id * (\(x:*). x) Value: λx. x Type: * → *
The proof mode reuses the architecture from the previous chapter: a proof state
is a list of goals, each with its local context and the type to be inhabited,
together with a function assemble that builds the final term; all tactics are
built with the refine combinator. The difference is that types may now
contain computation, so the tactics must reduce the goal (with whnf) and
compare types with betaEq instead of syntactic equality. The tactic intro,
for instance, accepts any goal whose WHNF is a \Pi and replaces the bound
variable in the codomain with the chosen name:
introTactic :: String -> ProofState -> Either String ProofState
introTactic x = refine $ \g ->
case whnf (cocCtx g) (goalTy g) of
Pi binder dom cod ->
let cod' = subst binder (Var x) cod
ctx' = extendCtx x dom (cocCtx g)
newGoal = g { cocCtx = ctx', goalTy = cod' }
in Right ([newGoal], \[t] -> Lam x dom t)
other -> Left "intro: goal is not a Π-type"
Since the connectives are encoded, tactics such as split, left, right and
exists must recognize the shape of the encoding in the goal. The tactic
split, for example, uses matchAnd to check whether the goal has the form
\Pi c{:}*.\,(A \to B \to c) \to c, opens the goals A and B and builds
the term \lambda c{:}*.\,\lambda f{:}A \to B \to c.\,f\;h_A\;h_B:
splitTactic = refine $ \g ->
case matchAnd (cocCtx g) (goalTy g) of
Nothing -> Left "split: goal does not look like A ∧ B"
Just (a, b) ->
let comb [ha, hb] =
Lam "c" (Sort Star)
(Lam "f" (Pi "_" a (Pi "_" b (Var "c")))
(App (App (Var "f") ha) hb))
in Right ([g { goalTy = a }, g { goalTy = b }], comb)
Similarly, exists t recognizes the encoding of the existential, replaces the
goal \exists x{:}A.\,B with B[x := t] and builds
\lambda c.\,\lambda k.\,k\;t\;h. The table below summarizes the available
tactics:
|
Tactic |
Description |
|---|---|
|
|
introduces the outermost |
|
|
introduces a binder |
|
|
applies |
|
|
closes the goal with the term |
|
|
closes the goal with a definitionally equal hypothesis |
|
|
proves |
|
|
proves |
|
|
proves |
|
|
unfolds the definition of |
|
|
closes a goal |
|
|
closes any goal using |
A proof session for \forall a\, b{:}*.\; a \wedge b \to a, with the
conjunction written out explicitly via its encoding, illustrates the use of
introType, intro and apply:
coc> proof ∀(a:*)∀(b:*). (∀(c:*).(a->b->c)->c) -> a coc[1]> introType a coc[1]> introType b coc[1]> intro h coc[1]> apply h coc[2]> intro ha coc[1]> intro hb coc[1]> assumption coc[0]> :qed Proof complete!
After the introductions, the goal is a and the hypothesis is
h : \Pi c{:}*.\,(a \to b \to c) \to c. The idea behind apply h is to use
the hypothesis with the conclusion c instantiated to the goal a itself,
leaving us to prove a \to b \to a, which is done by introducing ha and
hb and using assumption. The term built is essentially
\lambda a\,b\,h.\,h\;a\;(\lambda ha\,hb.\,ha), that is, the and_fst of the
encodings. (To achieve this, apply decomposes the type of h with the
function unfoldPi, which walks through the sequence of \Pis in WHNF
collecting the argument types and the conclusion, and compares the conclusion
with the goal using betaEq.)
The same proof in Lean, over the encoded conjunction CAnd:
example : ∀ a b : Prop, CAnd a b → a := ⊢ ∀ (a b : Prop), CAnd a b → a
intro a a:Propb:Prop⊢ CAnd a b → a a:Propb:Proph:CAnd a b⊢ a
a:Propb:Proph:CAnd a b⊢ a → b → a
intro ha a:Propb:Proph:CAnd a bha:aa✝:b⊢ a
All goals completed! 🐙
end Ch07
1.8.9. Exercises
-
For each system of the Barendregt cube, give its set of rules
\mathcal{R}and an example of a term typable in it but not in the system immediately below. -
Build the complete derivation of
\vdash \lambda\alpha{:}*.\,\lambda\beta{:}*.\,\lambda x{:}\alpha.\,\lambda y{:}\beta.\,x : \Pi\alpha{:}*.\,\Pi\beta{:}*.\,\alpha \to \beta \to \alpha, indicating which rule of\mathcal{R}is used in each application of (Pi). -
Show that
\lambda\alpha{:}*.\,\Pi\beta{:}*.\,\alpha \to \beta : * \to *and explain why this term is not typable in\lambda 2. -
Reduce to WHNF and to normal form the term
(\lambda f{:}* \to *.\,\lambda\alpha{:}*.\,f\;(f\;\alpha))\;(\lambda\beta{:}*.\,\beta \to \beta). -
Write, using the Church encoding of the CoC, terms for proofs of: (a)
A \wedge B \to B \wedge A; (b)A \vee B \to B \vee A; (c)(\exists x{:}A.\,P\;x) \to \neg\,\Pi x{:}A.\,\neg P\;x. Check your answers in the Haskell REPL and in Lean, with the definitionsCAnd,COrandCEx. -
Prove in Lean that
COr A B ↔ A ∨ Band thatCFalse ↔ False. -
Define in Lean the impredicative encoding of Leibniz equality,
LEq a b := ∀ P : α → Prop, P a → P b, and prove that it is reflexive, symmetric and transitive. -
Modify the function
validRuleof the Haskell implementation to obtain System F (\lambda 2). Which of the definitions inbuiltinsremain typable? -
Implement in the Haskell REPL a tactic
destruct h h1 h2that, given a hypothesish : A \wedge B(encoded), produces the hypothesesh_1 : Aandh_2 : B. -
Explain why the consistency of the CoC depends on strong normalization. What would happen if we added the axiom
\square : \square(or, equivalently,* : *)? Look up Girard's paradox.