15. Object languages: a typed lambda calculus¶
An object language is a language that a QVR module computes over: its terms are values of the module, built, taken apart, compared, normalized, and typed by checked code. This chapter builds the simply typed lambda calculus with a unit type and pairs in five declarations, each of which generates code that would otherwise be written by hand:
- a
syntaxdeclaration gives the terms and types, with binding; - its
equationsorient the computation rules, and the module gains a normalizer; - a
judgmentstates the typing rules, and the host gains a type checker and inferencer; - a
notationlets terms be written as on paper, in quotations; - a family of combinators derives equality, printing, and a translation into the calculus.
The chapter ends with tests of exact normal forms, run by qvr test. This page is itself a
literate module: its qvr blocks, in order, are one
module, so qvr test docs/tutorials/qvr/15-object-languages.qvr.md runs the tests it states.
1. Terms with binding¶
syntax STLC
sorts
Term : object
Type : object
constructors
One : -> Type
Arrow : Type, Type -> Type
Product : Type, Type -> Type
Star : -> Term
Lam : (x : Term).Term -> Term
App : Term, Term -> Term
Let : Term, (x : Term).Term -> Term
Pair : Term, Term -> Term
Fst : Term -> Term
Snd : Term -> Term
equations [strategy=innermost]
beta : App(Lam(x. M[x]), N) ~> M[N]
zeta : Let(N, x. M[x]) ~> M[N]
first : Fst(Pair(A, B)) ~> A
second : Snd(Pair(A, B)) ~> B
assume terminating
The sorts block declares two sorts of trees, terms and types. Each constructor line gives a
constructor's arguments and its result: One is the unit type and Star its one value, Arrow
and Product build function and pair types, and Pair, Fst, and Snd build and project
pairs. An argument written (x : Term).Term is a scope: a term in which a new variable of sort
Term is bound. Lam takes one scope, its body. Let takes a plain term, the value, and then a
scope, the body in which the value is named, so the binding arity is stated per argument and a
let never binds its variable in its own value.
The bound name x is only a display name. Terms are stored with
de Bruijn indices (de Bruijn, 1972), in which
a variable is the number of binders between it and the binder it refers to, so λx. x and
λy. y are one value, and alpha-equivalence
is structural equality. Each object sort is a checked family: STLC.Term has the constructors
above that build terms, plus the variable constructor STLC.Term.var(index), so code builds terms
with constructors and takes them apart with case like any other family's values. From the
declaration alone the module also contains, for each sort, capture-avoiding substitution
(STLC.Term.subst.Term), shifting, an occurs check, equality, an order, a hash, and printing
(Generated term operations).
2. Equations and the normalizer¶
The equations block orients the computation rules of the calculus. beta contracts the
application of an abstraction: the left side App(Lam(x. M[x]), N) matches a Lam whose body
is any term M in which x may occur, applied to any N, and the right side M[N] is that body
with N substituted for x. M[x] is a metavariable applied to the bound variable, a
higher-order pattern in the sense of
Miller (Miller, 1991), so a match is unique when it exists. zeta does the same for let, and
first and second project a pair.
At compile time the rules are checked as a rewriting system
(Baader and Nipkow, 1998): every critical pair,
a term that two rules rewrite in different ways, must rewrite to one normal form, so the rules are
confluent and a term has at most one normal form. Termination is proved by a recursive path order
when one applies. beta admits none, since substituting N for x may make a term larger, and on
untyped terms it does not terminate at all: \((\lambda x.\, x\, x)(\lambda x.\, x\, x)\) rewrites to
itself. Every well-typed term of the calculus has a normal form, though, which is the
strong normalization
theorem of the simply typed calculus, so the module records termination as an
assumption with assume terminating. The assumption is recorded as a law of the theory that is
assumed rather than proved, so the normalizer is meant for well-typed terms, on which it
terminates.
Because the rules pass the check, the module contains a normalizer, STLC.Term.normalize, and an
equality modulo the rules, STLC.Term.equal_modulo. The option strategy=innermost, the
default, contracts the innermost redexes first, so arguments are normal before the application that receives them
is contracted. The first tests state normal forms exactly:
test "an applied identity is its argument" =
expect STLC.Term.normalize(App(Lam(STLC.Term.var(0)), Star)) == Star
test "a projection of a pair is its component" =
expect STLC.Term.normalize(Snd(Pair(Star, Lam(STLC.Term.var(0))))) == Lam(STLC.Term.var(0))
== on two terms is the structural equality the syntax generates, so these expectations compare
the normal form exactly, constructor by constructor.
3. A typing judgment¶
judgment Ty(ctx : Context[Type] in, t : Term in, ty : Type out)
rule variable : lookup(ctx, i, A) |- Ty(ctx, Term.var(i), A)
rule star : |- Ty(ctx, Star, One)
rule abstraction : Ty((ctx, x : A), M[x], B) |- Ty(ctx, Lam(x. M[x]), Arrow(A, B))
rule application : Ty(ctx, F, Arrow(A, B)), Ty(ctx, N, A) |- Ty(ctx, App(F, N), B)
rule binding : Ty(ctx, N, A), Ty((ctx, x : A), M[x], B) |- Ty(ctx, Let(N, x. M[x]), B)
rule pairing : Ty(ctx, M, A), Ty(ctx, N, B) |- Ty(ctx, Pair(M, N), Product(A, B))
rule first : Ty(ctx, M, Product(A, B)) |- Ty(ctx, Fst(M), A)
rule second : Ty(ctx, M, Product(A, B)) |- Ty(ctx, Snd(M), B)
The judgment Ty(ctx, t, ty) says that in the context ctx, which gives a type to each free
variable, the term t has the type ty. Its arguments carry modes: the context and the term
are given (in) and the type is computed (out), so the judgment runs as an inference procedure.
Each rule is an inference rule, premises
before |- and the conclusion after. variable reads a variable's type from the context with
lookup; abstraction checks the body of a Lam in the context extended by the bound variable,
(ctx, x : A); and binding types a let by typing its value first and its body in the extended
context. A type no premise determines, such as the type A of the variable of λx. x, is
left as an unknown, so the judgment infers the most general type.
The judgment runs on the host, as
JudgmentSystem.infer, which
returns the outputs of every derivation of a goal. Load this page as a module with
load, build terms with
make_term and
bound_var, and infer their types in the empty context:
from quivers.dsl import load
from quivers.structural import bound_var, make_term, render_pattern
from quivers.structural.theories.judgments import ContextValue, JudgmentFailure
calculus = load("docs/tutorials/qvr/15-object-languages.qvr.md")
typing = calculus.judgments["Ty"]
empty = ContextValue(entries=())
star = make_term("Star")
identity = make_term("Lam", bound_var(0))
def type_of(term):
((inferred,),) = typing.infer("Ty", empty, term, None)
return render_pattern(inferred, typing.signature)
assert type_of(make_term("App", identity, star)) == "One"
assert type_of(make_term("Pair", star, make_term("App", identity, star))) == "Product(One, One)"
print(type_of(identity))
try:
typing.infer("Ty", empty, make_term("App", star, star), None)
except JudgmentFailure as failure:
print(failure)
The identity's type is Arrow(A, A) for an unknown A, printed with the number the inference
gave it; no rule fixes A, so the derivation leaves it open, which is the most general type of
the identity. Applying ⋆ to ⋆ has no derivation: application asks for ⋆ to have an arrow
type, and the only rule that types ⋆ gives it One. A
JudgmentFailure names the constraint
that the deepest attempt could not satisfy.
4. Notation and quotation¶
Terms written with constructors and indices are hard to read. A notation declares how terms
are written on paper, and a quotation [| ... |] writes a term in that notation:
notation Paper for STLC
lam : "λ" x ". " M => Lam(x. M)
app : M " " N [assoc=left] => App(M, N)
let_ : "let " x " = " A " in " B => Let(A, x. B)
pair : "⟨" A ", " B "⟩" => Pair(A, B)
fst : "π₁ " A => Fst(A)
snd : "π₂ " A => Snd(A)
star : "⋆" => Star
one : "𝟙" => One
arrow : A " → " B [assoc=right] => Arrow(A, B)
product : A " × " B [assoc=left] => Product(A, B)
app > lam
lam = let_
fst > lam
fst = snd
app > fst
product > arrow
open notation Paper
#! The pair with the components of `p` exchanged.
define swap(p : STLC.Term) : STLC.Term !{} =
return [| ⟨π₂ $p, π₁ $p⟩ |]
Each production line is a shape of quoted tokens and holes, then => and the term the shape
stands for. A hole the template uses as a term is an operand, and a hole the template binds, as
x in Lam(x. M), is a binder, so in λx. M the name written for x is bound in M. The
precedence lines form a graph, not a numbered ladder: app > lam makes application bind tighter
than abstraction, so λx. f x reads as λx. (f x). open notation Paper makes the productions
active in the rest of the module.
A quotation elaborates to the constructor tree it spells, with each name resolved to its binder
and stored as an index, so [| λx. λy. x |] is Lam(Lam(STLC.Term.var(1))). Inside a quotation,
$p splices in the value of the program's own p; a splice that a production places under a
binder of its own is shifted past it (with the generated STLC.Term.shift), so the binder never captures the splice's variables. The open notation also
prints: STLC.Term.show writes a term through Paper, naming each bound variable by its
binding depth, as in λx0. λx1. x0. The tests of section 6 use both directions
(Notation and quotation).
5. Combinators, deriving, and a translation¶
Combinatory logic writes functions without bound variables, from three combinators: \(I\,x = x\), \(K\,x\,y = x\), and \(S\,x\,y\,z = x\,z\,(y\,z)\). A family of combinator terms derives three classes:
family Comb : Type deriving (Eq, Show, Quote[STLC.Term via combinators])
constructor S : Comb
constructor K : Comb
constructor I : Comb
constructor Ap : Comb * Comb -> Comb
#! The translation of each combinator into the calculus.
meta define combinators : Morph !{} =
let s = ([| Lam(Lam(Lam(App(App(STLC.Term.var(2), STLC.Term.var(0)), App(STLC.Term.var(1), STLC.Term.var(0)))))) |] : SynValue)
let k = ([| Lam(Lam(STLC.Term.var(1))) |] : SynValue)
let i = ([| Lam(STLC.Term.var(0)) |] : SynValue)
let ap = ([| App(arg0, arg1) |] : SynValue)
return Morph(SeqCons(MorphClause("S", s), SeqCons(MorphClause("K", k), SeqCons(MorphClause("I", i), SeqCons(MorphClause("Ap", ap), SeqNil)))))
Eq derives Comb.eq, structural equality, and Show derives Comb.show, which prints a value
by its constructors. Quote[STLC.Term via combinators] derives Comb.quote : Comb -> STLC.Term
from a signature morphism: one clause per constructor of Comb, giving a term of the calculus
over the constructor's fields, arg0 and arg1 for the two fields of Ap. Since Comb is the
initial algebra of its constructors, the
morphism induces exactly one fold, and the derived
Comb.quote is that fold: it replaces each constructor by its clause, with each recursive field replaced by its own
translation, so Ap(K, I) becomes App of the translations of K and I.
The morphism is computed in the meta phase, while the
module is checked. meta define declares a computation of that phase, and a code quotation
([| ... |] : SynValue) writes a QVR value as the quoted syntax the phase manipulates; a clause
for a constructor that Comb lacks, or a constructor with no clause, is refused when the module
is checked. The clause for S is the term \(\lambda x.\,\lambda y.\,\lambda z.\; x\,z\,(y\,z)\) with
its variables written as indices.
6. Exact tests of normal forms¶
test "S K K normalizes to the identity" =
expect STLC.Term.normalize(Comb.quote(Ap(Ap(S, K), K))) == [| λx. x |]
test "a let and a projection compute" =
expect STLC.Term.normalize([| let f = λx. ⟨x, ⋆⟩ in π₁ (f ⋆) |]) == [| ⋆ |]
expect STLC.Term.normalize(swap([| ⟨⋆, λy. y⟩ |])) == [| ⟨λy. y, ⋆⟩ |]
test "combinators print by constructor and terms by notation" =
expect Comb.show(Ap(Ap(S, K), K)) == "Ap(Ap(S, K), K)"
expect STLC.Term.show(Comb.quote(K)) == "λx0. λx1. x0"
expect Comb.eq(Ap(K, I), Ap(K, I))
The first test is the classical identity \(S\,K\,K = I\): the translation of S K K normalizes,
by beta steps alone, to the translation of I, and the expectation compares the two normal forms
as terms. The second test quotes both sides, so it states the normal forms as they are written on
paper. Run the tests of this page:
ok docs/tutorials/qvr/15-object-languages.qvr.md:93 test 'an applied identity is its argument'
ok docs/tutorials/qvr/15-object-languages.qvr.md:96 test 'a projection of a pair is its component'
ok docs/tutorials/qvr/15-object-languages.qvr.md:260 test 'S K K normalizes to the identity'
ok docs/tutorials/qvr/15-object-languages.qvr.md:263 test 'a let and a projection compute'
ok docs/tutorials/qvr/15-object-languages.qvr.md:267 test 'combinators print by constructor and terms by notation'
5 passed (0 cached), 0 failed, 0 errors, 0 modules failed to load
The calculus in the standard library,
std.syntax.lambda, is this one with constants and
a monad, whose laws its equations orient, and
std.syntax.types gives its typing judgment and the
unification of its types.
Next¶
Chapter 16 composes a categorial grammar from a core rule set, lexicon modules, and an extension, writes code that reads any grammar extending the core, and specializes one chart to several semirings.
Cited sources¶
N. G. de Bruijn. Lambda Calculus Notation with Nameless Dummies, a Tool for Automatic Formula Manipulation, with Application to the Church-Rosser Theorem. Indagationes Mathematicae (Proceedings), 75(5):381–392, 1972. doi:10.1016/1385-7258(72)90034-0.
Dale Miller. A Logic Programming Language with Lambda-Abstraction, Function Variables, and Simple Unification. Journal of Logic and Computation, 1(4):497–536, 1991. doi:10.1093/logcom/1.4.497.
Franz Baader and Tobias Nipkow. Term Rewriting and All That. Cambridge University Press, 1998. doi:10.1017/CBO9781139172752.