1.6. The Simply Typed Lambda Calculus and the Curry-Howard Isomorphism

In the previous chapter we saw that the untyped lambda calculus is Turing-complete, but also that it admits "meaningless" terms. Any term can be applied to any argument — there is no distinction between functions, numbers and booleans — and there are terms whose evaluation never terminates, such as (\lambda x.\; x\; x)\; (\lambda x.\; x\; x) \;\longrightarrow\; (\lambda x.\; x\; x)\; (\lambda x.\; x\; x) \;\longrightarrow\; \cdots

The simply typed lambda calculus (STLC) introduces a type system that rejects ill-formed terms. The price is a loss of expressiveness; the gain is a strong guarantee: every well-typed term terminates. The STLC is the basis of the type systems of functional languages such as Haskell and OCaml, but its importance for this course lies elsewhere: it is, at the same time, a programming language and a proof system for intuitionistic propositional logic. This coincidence is the Curry-Howard isomorphism, the principle on which proof assistants such as Lean and Coq are built.

In this chapter:

  • we present the syntax and the type system of the STLC;

  • we state the Curry-Howard isomorphism, establishing the correspondence between types and formulas and between terms and proofs;

  • we relate the rules of natural deduction to the typing rules of the STLC;

  • we present the strong normalization property, with a sketch of its proof via reducibility;

  • we discuss the Haskell implementation (folder haskell/src/Typed) of a type checker and of a small system for building terms with tactics.

1.6.1. Syntax

1.6.1.1. Types

The types of the STLC are generated by the grammar: \begin{array}{lcl} A, B & ::= & P \;\mid\; \top \;\mid\; \bot \;\mid\; A \to B \\ & \mid & A \times B \;\mid\; A + B \end{array} Here, P, Q, R, \ldots are type variables (which, under the logical reading, will be propositional variables); \top is the unit type, with a single inhabitant; \bot is the void type, with no inhabitants; A \to B is the type of functions from A to B; A \times B is the product type, whose elements are ordered pairs; and A + B is the sum type, the disjoint union of A and B. The constructor \to associates to the right: A \to B \to C \;=\; A \to (B \to C) This convention fits currying: a function of two arguments takes an A and returns a function expecting a B.

1.6.1.2. Terms

The terms of the STLC extend those of the untyped lambda calculus with type annotations on parameters and with constructs for the unit, product, sum and empty types: \begin{array}{lcl} t & ::= & x \;\mid\; \lambda x{:}A.\, t \;\mid\; t\;t\\ & \mid & \mathbf{unit}\\ & \mid & (t, t) \;\mid\; \mathbf{fst}\;t \;\mid\; \mathbf{snd}\;t\\ & \mid & \mathbf{inl}\;t \;\mid\; \mathbf{inr}\;t \\ & \mid & \mathbf{case}\;t\;\mathbf{of}\;(\mathbf{inl}\;x \Rightarrow t \mid \mathbf{inr}\;y \Rightarrow t)\\ & \mid & \mathbf{absurd}\;t \end{array} The first three forms are the familiar ones: variable, abstraction (now with the parameter's type A made explicit) and application. The term \mathbf{unit} is the only inhabitant of \top. Pairs (t_1, t_2) build elements of products, which are consumed by the projections \mathbf{fst} and \mathbf{snd}. The injections \mathbf{inl} and \mathbf{inr} build elements of sums, which are consumed by case analysis \mathbf{case}. Finally, \mathbf{absurd}\;t eliminates a term t : \bot: since \bot has no inhabitants, such a t can only exist under contradictory hypotheses, and in that case we may produce a value of any type.

Notice the recurring pattern: for each type there are introduction constructs (which build values: \lambda, pairs, injections, \mathbf{unit}) and elimination constructs (which use values: application, projections, \mathbf{case}, \mathbf{absurd}). This is exactly the pattern of natural deduction, as we shall see.

1.6.2. Type system

A context \Gamma is a sequence of variable declarations: \Gamma \;::=\; \emptyset \;\mid\; \Gamma,\, x : A The judgement \Gamma \vdash t : A asserts that, under the hypotheses \Gamma, the term t has type A. It is defined by the following rules.

1.6.2.1. Variables, functions and application

\frac{}{\Gamma,\, x : A \vdash x : A}\;\text{(Var)} \qquad \frac{\Gamma,\, x : A \vdash t : B}{\Gamma \vdash \lambda x{:}A.\, t : A \to B}\;\text{(Abs)} \frac{\Gamma \vdash t_1 : A \to B \qquad \Gamma \vdash t_2 : A}{\Gamma \vdash t_1\;t_2 : B}\;\text{(App)}

Rule (Var) says that a variable has the type with which it was declared (we assume the variables in the context are distinct, and that the declaration may appear in any position). (Abs) says that, to type a function, we type its body assuming that the parameter has the annotated type. (App) requires the type of the argument to match the domain of the function.

1.6.2.2. Unit and products

\frac{}{\Gamma \vdash \mathbf{unit} : \top}\;(\top\text{-I}) \qquad \frac{\Gamma \vdash t_1 : A \qquad \Gamma \vdash t_2 : B}{\Gamma \vdash (t_1, t_2) : A \times B}\;(\times\text{-I}) \frac{\Gamma \vdash t : A \times B}{\Gamma \vdash \mathbf{fst}\;t : A}\;(\times\text{-E}_1) \qquad \frac{\Gamma \vdash t : A \times B}{\Gamma \vdash \mathbf{snd}\;t : B}\;(\times\text{-E}_2)

1.6.2.3. Sums and the empty type

\frac{\Gamma \vdash t : A}{\Gamma \vdash \mathbf{inl}\;t : A + B}\;(+\text{-I}_1) \qquad \frac{\Gamma \vdash t : B}{\Gamma \vdash \mathbf{inr}\;t : A + B}\;(+\text{-I}_2) \frac{\Gamma \vdash t : A + B \qquad \Gamma, x{:}A \vdash t_1 : C \qquad \Gamma, y{:}B \vdash t_2 : C}{\Gamma \vdash \mathbf{case}\;t\;\mathbf{of}\;(\mathbf{inl}\;x \Rightarrow t_1 \mid \mathbf{inr}\;y \Rightarrow t_2) : C}\;(+\text{-E}) \frac{\Gamma \vdash t : \bot}{\Gamma \vdash \mathbf{absurd}\;t : C}\;(\bot\text{-E})

In rule (+\text{-E}), each branch is typed with an additional hypothesis: x : A in the left branch, y : B in the right one; both branches must have the same type C, which is the type of the \mathbf{case}. Observe that in rules (+\text{-I}_1) and (+\text{-I}_2) the type B (respectively A) is not determined by the term, and the same happens with C in (\bot\text{-E}). For this reason, in an implementation these terms carry a type annotation, as we will see in the Haskell implementation.

1.6.2.4. Example derivations

The derivation of \vdash \lambda x{:}A.\, x : A \to A uses (Var) followed by (Abs): \frac{\dfrac{}{x : A \vdash x : A}\;\text{(Var)}}{\vdash \lambda x{:}A.\, x : A \to A}\;\text{(Abs)}

To project the first component of a hypothesis of product type: \frac{\dfrac{}{h : A \times B \vdash h : A \times B}\;\text{(Var)}}{h : A \times B \vdash \mathbf{fst}\;h : A}\;(\times\text{-E}_1)

A larger example: function composition. Let \Gamma = f : A \to B,\, g : B \to C,\, x : A. Then: \frac{\dfrac{\dfrac{\dfrac{\Gamma \vdash g : B \to C \qquad \dfrac{\Gamma \vdash f : A \to B \qquad \Gamma \vdash x : A}{\Gamma \vdash f\;x : B}\;\text{(App)}}{\Gamma \vdash g\;(f\;x) : C}\;\text{(App)}}{f : A \to B,\, g : B \to C \vdash \lambda x{:}A.\,g\;(f\;x) : A \to C}\;\text{(Abs)}}{f : A \to B \vdash \lambda g{:}B \to C.\,\lambda x{:}A.\,g\;(f\;x) : (B \to C) \to A \to C}\;\text{(Abs)}}{\vdash \lambda f{:}A \to B.\,\lambda g{:}B \to C.\,\lambda x{:}A.\,g\;(f\;x) : (A \to B) \to (B \to C) \to A \to C}\;\text{(Abs)} (the leaves \Gamma \vdash g : B \to C, \Gamma \vdash f : A \to B and \Gamma \vdash x : A are instances of (Var)).

A term such as \Omega is not typable: to type x\;x we would need x to have both a type A \to B and the type A, that is, A = A \to B, which is impossible for finite types.

1.6.3. The Curry-Howard isomorphism

In 1934, Haskell Curry observed that the axioms of combinatory logic corresponded to the types of the basic combinators: the combinator K = \lambda x.\,\lambda y.\,x has type A \to B \to A, which is precisely an axiom of Hilbert-style propositional logic. In 1969, William Howard extended this observation to the typed lambda calculus and Gentzen's natural deduction. The result, now called the Curry-Howard isomorphism, states that there is a one-to-one, structure-preserving correspondence between

  • logical formulas and types;

  • proofs and terms.

This is not a superficial analogy but a structural identity. Some immediate consequences:

  • checking a type is the same as checking a proof;

  • constructing a term of a type is the same as constructing a proof of the corresponding formula;

  • reducing terms corresponds to normalizing proofs, that is, eliminating "detours" in proofs.

This is exactly how Lean works: a proposition is a type (of sort Prop), and a proof is a term of that type. When we write theorem t : P, Lean checks that the term provided has type P.

1.6.4. Natural deduction and the STLC

Natural deduction, proposed by Gentzen, formalizes logical reasoning through introduction and elimination rules for each connective. We present the rules of intuitionistic propositional logic in sequent notation, \Gamma \vdash A, where \Gamma is a set of hypotheses, and compare them with the rules of the STLC. It suffices to erase the terms from a typing rule to obtain the corresponding logical rule.

The hypothesis rule corresponds to (Var), implication introduction to (Abs) and its elimination (modus ponens) to (App): \frac{}{\Gamma,\, A \vdash A}\;\text{(Hyp)} \qquad \frac{\Gamma,\, A \vdash B}{\Gamma \vdash A \to B}\;(\to\text{-I}) \qquad \frac{\Gamma \vdash A \to B \qquad \Gamma \vdash A}{\Gamma \vdash B}\;(\to\text{-E})

The rules for conjunction correspond to the rules for products — proving A \wedge B means providing a pair of proofs: \frac{\Gamma \vdash A \qquad \Gamma \vdash B}{\Gamma \vdash A \wedge B}\;(\wedge\text{-I}) \qquad \frac{\Gamma \vdash A \wedge B}{\Gamma \vdash A}\;(\wedge\text{-E}_1) \qquad \frac{\Gamma \vdash A \wedge B}{\Gamma \vdash B}\;(\wedge\text{-E}_2)

The rules for disjunction correspond to those for sums — a proof of A \vee B is a proof of A or a proof of B, together with the information of which one was provided; using a disjunction means reasoning by cases: \frac{\Gamma \vdash A}{\Gamma \vdash A \vee B}\;(\vee\text{-I}_1) \qquad \frac{\Gamma \vdash B}{\Gamma \vdash A \vee B}\;(\vee\text{-I}_2) \qquad \frac{\Gamma \vdash A \vee B \qquad \Gamma, A \vdash C \qquad \Gamma, B \vdash C}{\Gamma \vdash C}\;(\vee\text{-E})

Finally, truth and falsity correspond to \mathbf{unit} and \mathbf{absurd}: \frac{}{\Gamma \vdash \top}\;(\top\text{-I}) \qquad \frac{\Gamma \vdash \bot}{\Gamma \vdash A}\;(\bot\text{-E})

Negation is not primitive: \neg A is an abbreviation for A \to \bot.

1.6.4.1. Summary of the correspondence

Propositional logic

STLC

Formula A

Type A

Proof of A

Term t : A

Propositional variable

Type variable

\top

Unit type

\bot

Void type

A \to B

Function type A \to B

A \wedge B

Product type A \times B

A \vee B

Sum type A + B

At the level of rules:

Logical rule

Term constructor

Hypothesis

Variable x

\to-I

Abstraction \lambda x{:}A.\,t

\to-E

Application t_1\;t_2

\top-I

\mathbf{unit}

\wedge-I

Pair (t_1, t_2)

\wedge-E

\mathbf{fst}, \mathbf{snd}

\vee-I

\mathbf{inl}, \mathbf{inr}

\vee-E

\mathbf{case}\;\cdots\;\mathbf{of}

\bot-E

\mathbf{absurd}

1.6.4.2. Examples

Every intuitionistic tautology is inhabited by a closed term. For example:

  • A \to A is inhabited by \lambda x{:}A.\,x;

  • A \wedge B \to B \wedge A is inhabited by \lambda p{:}A \times B.\;(\mathbf{snd}\;p,\;\mathbf{fst}\;p);

  • (A \to B) \to (B \to C) \to A \to C is inhabited by \lambda f{:}A{\to}B.\;\lambda g{:}B{\to}C.\;\lambda x{:}A.\;g\;(f\;x);

  • \bot \to A (ex falso quodlibet) is inhabited by \lambda x{:}\bot.\;\mathbf{absurd}\;x.

In Lean, these very same terms are proofs of the corresponding propositions. The pair is written ⟨_, _⟩, the projections .1 and .2, the injections Or.inl and Or.inr, case analysis Or.elim and absurdity False.elim:

namespace Ch05 variable (A B C : Prop) example : A → A := fun x => x example : A ∧ B → B ∧ A := fun p => ⟨p.2, p.1⟩ example : (A → B) → (B → C) → A → C := fun f g x => g (f x) example : False → A := fun x => False.elim x example : A ∨ B → B ∨ A := fun h => Or.elim h (fun a => Or.inr a) (fun b => Or.inl b) example : (A ∨ B → C) → (A → C) ∧ (B → C) := fun h => ⟨fun a => h (Or.inl a), fun b => h (Or.inr b)⟩

The same correspondence holds for data types: replacing Prop with Type, ∧ with × and ∨ with ⊕, the same terms are programs:

def swap {α β : Type} : α × β → β × α := fun p => (p.2, p.1) def swapSum {α β : Type} : α ⊕ β → β ⊕ α | .inl a => .inr a | .inr b => .inl b ("one", 1)#eval swap (1, "one")
("one", 1)

1.6.4.3. Uninhabited propositions

The isomorphism also holds "in the negative direction": if a formula is not provable in intuitionistic propositional logic, then the corresponding type has no closed, well-typed inhabitants. For instance, A \vee B \to A is not provable, and there is no closed term t such that \vdash t : A + B \to A — intuitively, if we receive an \mathbf{inr}\;b, there is no way to produce an A.

More interesting is the case of the law of excluded middle, A \vee \neg A. It is a classical tautology, but it is not inhabited in the pure STLC: an inhabitant would have to decide, with no information whatsoever about A, whether to return a proof of A or a refutation of A. This is what distinguishes intuitionistic logic from classical logic. To obtain classical logic one must extend the calculus, for instance with control operators (continuations). In Lean, excluded middle is available as the axiom Classical.em, which is not definable from the constructive rules.

1.6.5. Strong normalization

In a reduction system, a term t is strongly normalizing (SN) if every reduction sequence starting from t terminates. This is stronger than having a normal form: (\lambda x.\,y)\;\Omega has normal form y, but it also admits an infinite reduction sequence (always reducing inside \Omega), so it is not strongly normalizing.

The reduction rules of the STLC comprise beta-reduction and the rules that eliminate "introductions followed by eliminations": \begin{array}{lcl} (\lambda x{:}A.\,t)\;u & \longrightarrow & [x \mapsto u]\,t \\ \mathbf{fst}\;(t_1, t_2) & \longrightarrow & t_1 \\ \mathbf{snd}\;(t_1, t_2) & \longrightarrow & t_2 \\ \mathbf{case}\;(\mathbf{inl}\;t)\;\mathbf{of}\;(\mathbf{inl}\;x \Rightarrow t_1 \mid \mathbf{inr}\;y \Rightarrow t_2) & \longrightarrow & [x \mapsto t]\,t_1 \\ \mathbf{case}\;(\mathbf{inr}\;t)\;\mathbf{of}\;(\mathbf{inl}\;x \Rightarrow t_1 \mid \mathbf{inr}\;y \Rightarrow t_2) & \longrightarrow & [y \mapsto t]\,t_2 \end{array} each of which may be applied at any position in the term.

Theorem (strong normalization of the STLC). If \Gamma \vdash t : A, then t is strongly normalizing.

As a corollary, the STLC cannot express functions that loop: we give up expressiveness (the STLC is not Turing-complete) in exchange for a guarantee of termination. From the logical point of view this is essential: a proof system in which a "proof term" could fail to terminate would allow us to prove anything (an infinite loop would have every type, including \bot).

Via Curry-Howard, strong normalization means that every proof in intuitionistic propositional logic can be normalized into a proof without "detours": a detour is the introduction of a connective immediately followed by its elimination, such as proving A \wedge B by (\wedge\text{-I}) only to extract A right away by (\wedge\text{-E}_1). Eliminating the detour is exactly the step \mathbf{fst}\;(t_1, t_2) \longrightarrow t_1. This result is the computational analogue of Gentzen's cut-elimination theorem for the sequent calculus.

1.6.5.1. Proof sketch: reducibility

The naive attempt to prove the theorem by induction on the typing derivation fails in the application case: knowing that t_1 and t_2 are SN does not guarantee that t_1\;t_2 is SN — \Omega itself is the application of two terms in normal form! The induction hypothesis is too weak. The solution, due to Tait (1967), is the method of logical relations, or reducibility: we define, by recursion on the type, a predicate stronger than SN.

For each type A, we define the set \mathrm{RED}_A of reducible terms of type A (we restrict ourselves to \to and \times for simplicity): \begin{array}{lcl} \mathrm{RED}_P & = & \{ t \mid t \text{ is SN} \} \\ \mathrm{RED}_{A \to B} & = & \{ t \mid \forall u \in \mathrm{RED}_A,\; t\;u \in \mathrm{RED}_B \} \\ \mathrm{RED}_{A \times B} & = & \{ t \mid \mathbf{fst}\;t \in \mathrm{RED}_A \text{ and } \mathbf{snd}\;t \in \mathrm{RED}_B \} \end{array} The idea is that, for functions, being reducible means "mapping reducible arguments to reducible results" — precisely the property that was missing in the application case. The proof proceeds in two steps.

Step 1 (candidate properties). By induction on the type A, one shows that every \mathrm{RED}_A satisfies:

  • (CR1) if t \in \mathrm{RED}_A, then t is SN;

  • (CR2) if t \in \mathrm{RED}_A and t \longrightarrow t', then t' \in \mathrm{RED}_A;

  • (CR3) if t is neutral (not an introduction, such as \lambda or a pair) and every t' with t \longrightarrow t' is in \mathrm{RED}_A, then t \in \mathrm{RED}_A.

In particular, by (CR3), every variable is in \mathrm{RED}_A (a variable is neutral and does not reduce).

Step 2 (adequacy lemma). By induction on the derivation, one shows: if x_1 : A_1, \ldots, x_n : A_n \vdash t : A and u_i \in \mathrm{RED}_{A_i} for each i, then [x_1 \mapsto u_1, \ldots, x_n \mapsto u_n]\,t \in \mathrm{RED}_A. The crucial case is abstraction: to show that \lambda x{:}A.\,t (with the substitution applied) is in \mathrm{RED}_{A \to B}, we take u \in \mathrm{RED}_A and use (CR3) to analyse all possible reductions of (\lambda x{:}A.\,t)\;u, by induction on the maximal length of the reductions of t and u (finite by (CR1)). The application case, which was the problem before, is now immediate from the very definition of \mathrm{RED}_{A \to B}.

Conclusion. Taking u_i = x_i (variables are reducible), the adequacy lemma gives t \in \mathrm{RED}_A, and by (CR1) t is SN.

Handling sums and \bot requires a more careful definition of \mathrm{RED}_{A+B} (and additional commuting reductions), but the structure of the proof is the same. Girard's book Proofs and Types presents the complete proof.

1.6.6. Implementation in Haskell

The folder haskell/src/Typed contains a REPL for the STLC (run with cabal run typed) that type-checks terms, evaluates them and offers a tactic proof mode. We now discuss its main components.

1.6.6.1. Types and terms

Types are represented directly by the grammar; the comments highlight the logical reading of each constructor:

data Ty
  = TyVar  String   -- propositional variable P, Q, ...
  | TyUnit          -- ⊤  (unit)
  | TyVoid          -- ⊥  (void)
  | TyArr  Ty Ty    -- A → B
  | TyProd Ty Ty    -- A ∧ B  (product)
  | TySum  Ty Ty    -- A ∨ B  (sum)
  deriving (Eq, Show)

In terms, the injections and absurd carry a type annotation since, as we observed, their types are not determined by the subterm alone:

data Term
  = Var     String
  | Lam     String Ty Term       -- λx:A. t
  | App     Term   Term
  | TmUnit                       -- unit
  | TmPair  Term Term            -- (t, u)
  | TmFst   Term                 -- fst t
  | TmSnd   Term                 -- snd t
  | TmInl   Term Ty              -- inl t as A+B
  | TmInr   Term Ty              -- inr t as A+B
  | TmCase  Term String Term String Term
  | TmAbsurd Term Ty             -- absurd t as C

1.6.6.2. Type checker

The type checker (Typed.Typechecker) is a function that infers the type of a term in a context, represented as an association list. Each equation corresponds to a typing rule, read "bottom-up": to type the conclusion, we recursively type the premises. Errors are reported in the Either String monad.

typecheck :: TyCtx -> Term -> Either String Ty
typecheck ctx (Var x) =
  case lookup x ctx of
    Just ty -> Right ty
    Nothing -> Left $ "Unbound variable: " ++ x
typecheck ctx (Lam x ty body) = do
  bodyTy <- typecheck ((x, ty) : ctx) body
  return (TyArr ty bodyTy)
typecheck ctx (App t1 t2) = do
  ty1 <- typecheck ctx t1
  ty2 <- typecheck ctx t2
  case ty1 of
    TyArr a b | ty2 == a -> Right b
    TyArr a _ -> Left $ "type mismatch: expected "
                     ++ renderTy a ++ " got " ++ renderTy ty2
    _ -> Left $ "not a function type: " ++ renderTy ty1

The (Var) case is a context lookup; (Abs) extends the context with the parameter (at the front of the list, so that lookup finds the innermost declaration); (App) checks that the type of the argument equals the domain of the function. Products follow the same pattern:

typecheck ctx (TmPair t1 t2) = do
  a <- typecheck ctx t1
  b <- typecheck ctx t2
  return (TyProd a b)
typecheck ctx (TmFst t) = do
  ty <- typecheck ctx t
  case ty of
    TyProd a _ -> Right a
    _ -> Left $ "fst: not a product: " ++ renderTy ty

For sums, the annotation supplies the full type A + B, and the checker verifies that the subterm has the type of the correct component. In \mathbf{case}, each branch is checked in an extended context and the types of the branches must agree; in \mathbf{absurd}, a term of type \bot is required and the annotated type is returned:

typecheck ctx (TmInl t annot) =
  case annot of
    TySum a _ -> do
      ta <- typecheck ctx t
      if ta == a then Right annot
      else Left "inl: type mismatch"
    _ -> Left "inl: annotation must be a sum type"
typecheck ctx (TmCase t x t1 y t2) = do
  tty <- typecheck ctx t
  case tty of
    TySum a b -> do
      c1 <- typecheck ((x, a) : ctx) t1
      c2 <- typecheck ((y, b) : ctx) t2
      if c1 == c2 then Right c1
      else Left "case: branch type mismatch"
    _ -> Left "case: scrutinee must have a sum type"
typecheck ctx (TmAbsurd t c) = do
  ty <- typecheck ctx t
  case ty of
    TyVoid -> Right c
    _      -> Left "absurd: term must have type ⊥"

Since the STLC is simple, the same type checker can be written in Lean in a few lines. Below is a fragment with functions and products, using Option instead of Either:

inductive Ty where | base : String → Ty | arr : Ty → Ty → Ty | prod : Ty → Ty → Ty deriving DecidableEq, Repr inductive Tm where | var : String → Tm | lam : String → Ty → Tm → Tm | app : Tm → Tm → Tm | pair : Tm → Tm → Tm | fst : Tm → Tm | snd : Tm → Tm def infer (Γ : List (String × Ty)) : Tm → Option Ty | .var x => Γ.lookup x | .lam x a t => do let b ← infer ((x, a) :: Γ) t pure (.arr a b) | .app t u => do let .arr a b ← infer Γ t | none let a' ← infer Γ u if a = a' then pure b else none | .pair t u => do pure (.prod (← infer Γ t) (← infer Γ u)) | .fst t => do let .prod a _ ← infer Γ t | none pure a | .snd t => do let .prod _ b ← infer Γ t | none pure b -- λp:A×B. (snd p, fst p) def swapTm : Tm := .lam "p" (.prod (.base "A") (.base "B")) (.pair (.snd (.var "p")) (.fst (.var "p"))) some (Ch05.Ty.arr (Ch05.Ty.prod (Ch05.Ty.base "A") (Ch05.Ty.base "B")) (Ch05.Ty.prod (Ch05.Ty.base "B") (Ch05.Ty.base "A")))#eval infer [] swapTm -- λx:A. x x (ill-typed) none#eval infer [] (.lam "x" (.base "A") (.app (.var "x") (.var "x")))
some (Ch05.Ty.arr
  (Ch05.Ty.prod (Ch05.Ty.base "A") (Ch05.Ty.base "B"))
  (Ch05.Ty.prod (Ch05.Ty.base "B") (Ch05.Ty.base "A")))
none

1.6.6.3. The tactic system

Besides checking hand-written terms, the REPL lets us build terms interactively using tactics, in the style of proof assistants such as Lean and Coq. The central idea is that a proof in progress is a term with "holes": each hole is a goal, consisting of the available hypotheses and the type to be inhabited.

data Goal = Goal
  { hyps   :: [(String, Ty)]  -- available hypotheses
  , goalTy :: Ty              -- type / formula to prove
  }

data ProofState = ProofState
  { goals    :: [Goal]
  , assemble :: [Term] -> Term  -- assembles the final term
  }

The field assemble is a function that, given one term for each open goal, assembles the complete term. At the start of a proof there is a single goal and assemble is the identity; when no goals remain, assemble [] returns the final term.

All tactics are built with the refine combinator. A tactic is described by a function that receives the first goal and returns a list of new goals together with a function (comb) that builds the term for the current goal from the terms for the new goals. The combinator then replaces the first goal with the new ones and composes the assembly functions:

refine :: (Goal -> Either String ([Goal], [Term] -> Term))
       -> ProofState -> Either String ProofState
refine f (ProofState (g:gs) asm) =
  case f g of
    Left err -> Left err
    Right (newGoals, comb) ->
      Right $ ProofState
        { goals = newGoals ++ gs
        , assemble = \ts ->
            let (here, rest) = splitAt (length newGoals) ts
            in  asm (comb here : rest)
        }

The tactic intro x corresponds to rule (Abs) read bottom-up: if the goal is A \to B, it adds the hypothesis x : A and the new goal becomes B; the term built is \lambda x{:}A.\,t, where t is the proof of the new goal:

introTactic :: String -> ProofState -> Either String ProofState
introTactic x = refine $ \g ->
  case goalTy g of
    TyArr a b ->
      let newGoal = g { hyps   = (x, a) : hyps g
                      , goalTy = b }
      in  Right ([newGoal], \[t] -> Lam x a t)
    _ -> Left "intro: goal is not an implication"

The tactic apply h corresponds to repeated uses of (App): if h : A_1 \to \cdots \to A_n \to B and the goal is B, it opens the goals A_1, \ldots, A_n and builds the term h\;t_1\;\cdots\;t_n. The auxiliary function unfoldArr splits the type of h into its arguments and its conclusion:

applyTactic :: String -> ProofState -> Either String ProofState
applyTactic h = refine $ \g ->
  case lookup h (hyps g) of
    Nothing -> Left $ "apply: " ++ h ++ " not in context"
    Just ty ->
      let (args, ret) = unfoldArr ty
      in  if ret == goalTy g
          then Right ( map (\a -> g { goalTy = a }) args
                     , \ts -> foldl App (Var h) ts )
          else Left "apply: conclusion does not match goal"

The remaining tactics follow the same scheme, each corresponding to a typing rule:

  • intro x: goal A \to B; adds x : A and the goal becomes B (rule Abs);

  • assumption: closes the goal with a hypothesis of the same type (Var);

  • exact t: closes the goal with the term t, which is checked;

  • apply h: applies h : A_1 \to \cdots \to B to the goal B (App);

  • split: goal A \wedge B; opens the goals A and B (\times-I);

  • left and right: goal A \vee B; picks one of the branches (+-I);

  • cases h x y: case analysis on h : A \vee B (+-E);

  • trivial: closes a goal \top (\top-I);

  • absurd h: closes any goal using h : \bot (\bot-E);

  • destruct h h1 h2: decomposes h : A \wedge B into the hypotheses h_1 : A and h_2 : B (\times-E).

Let us look at a proof session for the transitivity of implication. The number in parentheses in the prompt indicates how many goals remain open:

proof (P -> Q) -> (Q -> R) -> P -> R
tactic(1)> intro hpq
tactic(1)> intro hqr
tactic(1)> intro hp
tactic(1)> apply hqr
tactic(1)> apply hpq
tactic(1)> assumption
tactic(0)> :qed
Proof complete!
  Term:  λhpq:P→Q hqr:Q→R hp:P. hqr (hpq hp)
  Type:  (P → Q) → (Q → R) → P → R
  DB:    λ:P→Q. λ:Q→R. λ:P. 1 (2 0)
  Value: λa:P→Q b:Q→R c:P. b (a c)

After the three introductions, the goal is R with hypotheses hpq : P \to Q, hqr : Q \to R and hp : P. The tactic apply hqr replaces the goal with Q; apply hpq replaces it with P; and assumption closes it with hp. The assembled term is exactly the function composition we derived by hand earlier. A second example uses split and destruct:

proof (P * Q) -> (Q * P)
  intro h
  split
  -- subgoal 1: Q
  destruct h h1 h2
  assumption
  -- subgoal 2: P
  destruct h h1 h2
  assumption
  :qed
Proof complete!
  Term:  λh:P×Q. (snd h, fst h)
  Type:  P × Q → Q × P

(The displayed term is simplified: in the implementation, destruct introduces the hypotheses h_1 and h_2 by means of an application (\lambda h_1.\,\lambda h_2.\,t)\;(\mathbf{fst}\;h)\;(\mathbf{snd}\;h), which normalization reduces to the pair above.)

The same proofs in Lean, in tactic mode, use tactics with the same names and the same meaning. The #print command shows the term built by the tactics:

theorem trans (P Q R : Prop) : (P → Q) → (Q → R) → P → R := P:PropQ:PropR:Prop⊢ (P → Q) → (Q → R) → P → R intro hpq P:PropQ:PropR:Prophpq:P → Qhqr:Q → R⊢ P → R P:PropQ:PropR:Prophpq:P → Qhqr:Q → Rhp:P⊢ R P:PropQ:PropR:Prophpq:P → Qhqr:Q → Rhp:P⊢ Q P:PropQ:PropR:Prophpq:P → Qhqr:Q → Rhp:P⊢ P All goals completed! 🐙 theorem Ch05.trans : ∀ (P Q R : Prop), (P → Q) → (Q → R) → P → R := fun P Q R hpq hqr hp => hqr (hpq hp)#print trans
theorem Ch05.trans : ∀ (P Q R : Prop), (P → Q) → (Q → R) → P → R :=
fun P Q R hpq hqr hp => hqr (hpq hp)
example (P Q : Prop) : P ∧ Q → Q ∧ P := A:PropB:PropC:PropP:PropQ:Prop⊢ P ∧ Q → Q ∧ P A:PropB:PropC:PropP:PropQ:Proph:P ∧ Q⊢ Q ∧ P A:PropB:PropC:PropP:PropQ:Proph1:Ph2:Q⊢ Q ∧ P A:PropB:PropC:PropP:PropQ:Proph1:Ph2:Q⊢ QA:PropB:PropC:PropP:PropQ:Proph1:Ph2:Q⊢ P A:PropB:PropC:PropP:PropQ:Proph1:Ph2:Q⊢ Q All goals completed! 🐙 A:PropB:PropC:PropP:PropQ:Proph1:Ph2:Q⊢ P All goals completed! 🐙 example (P Q R : Prop) : (P ∨ Q) → (P → R) → (Q → R) → R := A:PropB:PropC:PropP:PropQ:PropR:Prop⊢ P ∨ Q → (P → R) → (Q → R) → R intro h A:PropB:PropC:PropP:PropQ:PropR:Proph:P ∨ Qhp:P → R⊢ (Q → R) → R A:PropB:PropC:PropP:PropQ:PropR:Proph:P ∨ Qhp:P → Rhq:Q → R⊢ R cases h with A:PropB:PropC:PropP:PropQ:PropR:Prophp:P → Rhq:Q → Rp:P⊢ R All goals completed! 🐙 A:PropB:PropC:PropP:PropQ:PropR:Prophp:P → Rhq:Q → Rq:Q⊢ R All goals completed! 🐙 end Ch05

1.6.7. Conclusion

The simply typed lambda calculus is, at the same time, a functional programming language with guaranteed termination and a proof system for intuitionistic propositional logic. The Curry-Howard isomorphism establishes that types correspond to formulas, terms to proofs and reduction to proof normalization. Strong normalization, proved by Tait's reducibility method, guarantees that every well-typed program terminates. Finally, construction by tactics mirrors the way modern proof assistants operate: each tactic incrementally builds a well-typed term. In the next chapter we will review predicate logic, whose quantifiers will demand a type system more expressive than the STLC.

1.6.8. Exercises

  1. Build complete typing derivations for \vdash \lambda p{:}A \times B.\;(\mathbf{snd}\;p, \mathbf{fst}\;p) : A \times B \to B \times A and for \vdash \lambda x{:}\bot.\,\mathbf{absurd}\;x : \bot \to A.

  2. Find closed STLC terms with the types below and write the corresponding proofs in Lean: (a) A \to B \to A; (b) (A \to B \to C) \to (A \to B) \to A \to C; (c) (A + B \to C) \to (A \to C) \times (B \to C); (d) A \times (B + C) \to (A \times B) + (A \times C).

  3. Show that \neg\neg(A \vee \neg A) is inhabited, that is, find a term of type ((A + (A \to \bot)) \to \bot) \to \bot. Why does this not contradict the fact that A \vee \neg A is not inhabited?

  4. Explain why there is no closed term of type ((A \to B) \to A) \to A (Peirce's law) in the STLC. Prove it in Lean using Classical.em.

  5. Extend this chapter's Lean type checker with the types \top, \bot and A + B and the corresponding terms (with annotations where necessary).

  6. Write the sequence of Haskell REPL tactics that proves (P + Q) \to (Q + P), and the resulting term.

  7. Consider the reduction rule \mathbf{fst}\;(t_1, t_2) \longrightarrow t_1. Draw the natural deduction derivation corresponding to the term \mathbf{fst}\;(a, b) and the derivation after the reduction. Which "detour" was eliminated?

  8. In the sketch of the strong normalization proof, explain where the naive proof (induction on the derivation, with hypothesis "t is SN") fails and why the definition of \mathrm{RED}_{A \to B} solves the problem.

  9. Implement in Haskell the tactic exfalso, which replaces any goal C with the goal \bot, using the refine combinator.