Chapter 4
Typed λ-terms and unification problems
Chapter 2 and Chapter 3 did logic programming over first-order terms. Chapter 3 added universal quantifiers and implications to goals (fohh), and with them eigenvariables: constants made up during the search that no logic variable created earlier may capture. Chapter 4 of the book Dale Miller and Gopalan Nadathur. Programming with Higher-Order Logic. Cambridge University Press, Cambridge, 2012 keeps the logic and changes the terms. First-order terms give way to simply typed λ-terms. This chapter studies those terms on their own and leaves the higher-order logic built on them to Chapter 5 [MN p. 96].
The change has three consequences, and each of them touches a different part of a miniKanren:
- What equality means. Two terms are equal when they are λ-convertible (α, β, η), not only when they are identical. This affects the term representation and the unifier.
- What a logic variable may be bound to. A unification problem becomes a quantified formula. Its prefix mixes ∀ and ∃, and the order of the quantifiers decides which symbols a variable may use. This affects the state, which has to track scope.
- How hard unification is. There may be several, infinitely many, or no most general unifiers, and the problem is undecidable. This affects the search: unification has to become a stream of answers.
The chapter follows the book’s order. Section 4.1, Section 4.2 and Section 4.3 cover the calculus. Section 4.4, Section 4.5, Section 4.6 and Section 4.7 recast unification as quantified equalities. Section 4.8 fixes the vocabulary that Chapter 7 uses for the unification procedure, and Section 4.9 proves undecidability.
4.1Syntax and types of λ-terms#
Typed λ-terms are built from typed constants and variables with two operations. The first is
application, written as juxtaposition and associating to the left, exactly as for first-order terms.
The second is abstraction, which is new: from an expression in which a variable
may occur free, it forms the function [MN p. 97]. In λProlog this is written
(x:A)\ T. The type annotation can be dropped (x\ T), and the type is then inferred.
Parsing. The body of an abstraction extends as far to the right as possible. So application binds tighter than abstraction, and abstraction associates to the right [MN p. 97]:
| mathematical | λProlog concrete syntax |
|---|---|
f\x\ f (f (f x)) | |
x\ f (g y\ h x y) x | |
x\y\ x |
A backslash cannot occur inside an identifier, so no spaces are needed around it.
Definition 4.1 (Types and terms). Types are generated from primitive types (sorts such as , and the type of propositions), type variables , type constructors such as , and the arrow , which associates to the right. Terms are
(The book introduces the grammar in prose [MN p. 97–99]. This compact form is ours.)
Typing. The judgement (in the book, with a double turnstile) says that has type when gives the types of the constants and those of the variables. It is defined by the rules of Figure 4.1 [MN p. 98]:
Proviso : is not declared as a type or kind in or . Proviso : and differ only in the names of bound variables. means that is a substitution instance of , so a polymorphic constant is instantiated afresh at every use [MN p. 97]. Compared with the first-order rules of Chapter 2, the restrictions on the types in and are gone: a constant may have any type, including a functional type that ends in . There is one new rule, for abstraction. And there are no special rules for the quantifiers, because the quantifiers have become ordinary constants (see below) [MN p. 97–98].
Definition 4.2 (Well-formed, closed, simply typed [MN p. 98]). A term is a well-formed λ-term over if is derivable for some and . It is closed if this holds with empty, and open otherwise. It is simply typed if neither its type nor the types of its subterms contain type variables.
When every bound variable carries its annotation, the type of a well-formed term is unique up to renaming of type variables. When annotations are omitted, type inference gives each bound variable a fresh type variable and refines it “in as minimal a way as possible”. The type found this way is again unique up to renaming, the principal type [MN p. 98–99]. The unification theory of Chapter 7 is stated for simply typed terms.
Example 4.3 (A typing derivation). The Church numeral f\x\ f (f x) has type . Write
:
Read the derivation bottom up. Each abstraction rule moves one binder into the context. The application rule app then checks against a functional type twice, and the leaves are instances of the variable rule (the two leaves above are left implicit). Because the derivation ends with an empty context, the term is closed. No constant was used, so this derivation works for every , including one with no constant of type , a case that matters in Section 4.3.1 and Section 4.6.
4.1.1Formulas are terms of type o#
A formula is a well-formed term of type . The connectives are constants such as . The quantifiers become constants too [MN p. 99]:
and abbreviates , written when the type of
matters. A quantified formula is typed with the ordinary rules. From
the abstraction rule gives , the instance
of the constant gives the rest, and so .
For example, applying pi at type (list int -> o) -> o to an abstraction of type
list int -> o [MN p. 99]:
y\ append (1::2::nil) y X.
pi y\ append (1::2::nil) y X.Since signatures are no longer restricted, logical symbols may now appear inside the arguments of non-logical ones [MN p. 99–100]:
type foreach (A -> o) -> list A -> o.
foreach (x\ x > 5, x < 9) (3::10::6::8::nil).Here the conjunction , sits inside an argument of foreach. Higher-order programming
(Chapter 5) rests on this possibility. One more fact matters a lot later. The logic has a
single binder, λ-abstraction: ∀, ∃ and every object-level binder (Chapter 6) are encoded
with it [MN p. 100].
Kanren angle (terms are data, goals are procedures). In (aux kanren micro) a goal is a Scheme procedure from a state to a stream of states. A procedure is opaque to
the unifier: it cannot be walked, compared or reified. So a formula on which one wants to
unify, for example to solve for a predicate variable, has to be represented as
data, such as a record for or for pi applied to an abstraction, and then
interpreted by a meta-level relation. This is the design of Chapter 5 and Chapter 9. For
foreach with a ground Scheme predicate, ordinary higher-order Scheme is enough. Note also that
the term language now needs a representation of λ itself, which Scheme closures cannot provide:
Section 4.3 and Section 4.4 use de Bruijn terms 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, 34(5):381–392, 1972 (lists in the first, records in the second), and Chapter 11
discusses the options.
4.2λ-conversion: the equality of the logic#
An abstraction is meant to denote a function, and an application of an abstraction is meant to denote the result of the function. The conversion rules make this intended meaning part of the equality. They rely on substitution, which must not capture variables.
Definition 4.4 (Free for; substitution [MN p. 100]). is free for in if no free occurrence of in lies in the scope of an abstraction that binds a free variable of . If is free for in and both have the same type, is with every free occurrence of replaced by .
For example, is free for in , but is not: substituting it would put its free under the binder . Ignoring the proviso is logically unsound, for the same reason as with quantified formulas in Chapter 3.
Definition 4.5 (The rules of λ-conversion [MN p. 100–101]). The following rewrites may be applied to any subterm:
| rule | redex contractum | proviso |
|---|---|---|
| α-rewriting | free for in , not free in | |
| β-contraction | free for in (lifted below) | |
| η-contraction | not free in |
The converses are β-expansion and η-expansion. α-conversion is the reflexive, symmetric, transitive closure of α-rewriting. β-reduction is the reflexive, transitive closure of α-conversion together with β-contraction, and β-conversion is its symmetric, transitive closure. η-reduction and η-conversion are defined in the same way. λ-conversion is the transitive closure of α-, β- and η-conversion.
λ-conversion is an equivalence and a congruence, and it is the equality of higher-order logic [MN p. 101]. Two consequences stand out. First, terms related by λ-conversion cannot be told apart in the logic. Second, no specification can determine the name of a bound variable, because that name can always be changed by α-conversion without changing the term. Chapter 6 builds λ-tree syntax on this second fact.
Example 4.6 (Four equal terms [MN p. 101]).
x\y\ f (g x) y
X\Y\ f (g X) Y
x\ f (g x)
x\y\ f ((u\v\v) (2 + 3) (g x)) yThe first two terms are α-convertible. The third is the first after an η-contraction:
A β-contraction of the fourth gives
x\y\ f ((v\v) (g x)) yand a second one gives back the first. Note that (2 + 3) disappears entirely, because does
not occur in the body v\v.
Pitfall (capital letters are not always logic variables). In X\Y\ f (g X) Y the tokens X and Y are bound names, not logic variables. In
λProlog only free capitalised tokens are logic variables. A Scheme reader of λProlog code has to
look at where a name is bound before deciding what it is.
Liberalised substitution. From now on is defined even when is not free for in . First α-rename to some in which is free for , then substitute. The result depends on the renaming only up to α, so modulo equality it is well defined. β-contraction then becomes with no proviso [MN p. 101]. This is ordinary capture-avoiding substitution.
Tutorial (capture-avoiding β, by hand). Contract . The argument has a free . A naive textual replacement would give , where the outer has been captured and now refers to the bound variable. This is a different function. Liberalised substitution first renames the binder, , and then substitutes:
With de Bruijn indices (Section 4.3) the renaming becomes index arithmetic: the argument is shifted by one when it goes under a binder.
4.3Normal forms and the power of β#
A β-redex is a term . An η-redex is a term with not free in . A term with no β-redexes is in β-normal form. If it has no η-redexes either, it is in λ-normal form (also called βη-normal form) [MN p. 101–102].
Theorem 4.7 (Normal forms [MN p. 102]). Every term of the typed language has a λ-normal form, unique up to α-conversion. It is written . It can be computed by contracting β-redexes until none is left and then contracting η-redexes.
Corollary 4.8 (Decidable equality [MN p. 102]). Two terms of the same type are λ-convertible if and only if their λ-normal forms are α-equivalent.
Remark 4.9 (Background the book does not spell out). The book states Theorem 4.7 as “well known”. In the literature it rests on two classical properties of the simply typed λ-calculus. Strong normalisation says that every reduction sequence terminates, which gives existence. The Church–Rosser property (confluence) says that diverging reductions can be joined again, which gives uniqueness. The algorithm also relies on a standard fact the book uses without proof: η-contracting a β-normal term creates no new β-redex, so doing η after β is enough.
Pitfall (equality is intensional). Logical equivalences do not affect term equality. With , the term is not equal to [MN p. 102]. Types are inhabited by expressions, not by sets. A syntactic unifier gets this right automatically. A unifier that knew about commutativity of would be wrong.
4.3.1Computing with β: Church numerals#
The rule can copy many times or throw it away. Even when and are both normal, the result need not be, because may sit in head position [MN p. 102]. So normalisation is a model of computation. Let the sort have no constants. Then the closed λ-normal forms of type are exactly the Church numerals [MN p. 102]. Arithmetic is then definable [MN p. 103]:
λProlog prints λ-normal forms, so it can run these functionsThe ambient signature has the
sort i. [MN p. 103]:
?- N = ((n\m\f\x\ n (m f) x) ((f:i -> i)\x\ f (f x)) (f\x\ f (f x))).
N = f\x\ f (f (f (f x)))
?-The book adds that the functions definable this way are “limited to the polynomial ones” [MN p. 103].The phrasing is informal. The precise class, a result outside the book due to Schwichtenberg and Statman, is the extended polynomials, which also allow a test for zero.
Blow-up. Define the size of a term as its number of applications. Normalising can increase the size enormously. The book’s series [MN p. 104] is
(g\e\ e) (e\f\ e (e f)) (f\x\ f (f x)).
(g\e\ g e) (e\f\ e (e f)) (f\x\ f (f x)).
(g\e\ g (g e)) (e\f\ e (e f)) (f\x\ f (f x)).
(g\e\ g (g (g e))) (e\f\ e (e f)) (f\x\ f (f x)).with x : i, f : i -> i, e : (i -> i) -> i -> i and
g : ((i -> i) -> i -> i) -> (i -> i) -> i -> i. The g\e\ parts are Church numerals one type
level up. g\e\ g (g e) has a fourth-order type. The -th term has size , and its
normal forms are the numerals 2, 4, 16 and 256 [MN p. 104].
Remark 4.10 (An erratum in the size formula). The book says the -th normal form has size with twos
[MN p. 104]. The term e\f\ e (e f) squares a numeral, and the outer numeral applies it times to
. So the normal form is , of size : 2, 4, 16,
256, 65536. This matches the book’s own “256” for the fourth term. A right-nested tower with
four twos is 65536, though, so the printed formula is right only if the tower is read
left-nested, . The run below confirms the numbers. The point of the passage is
unaffected: sizes can explode (Statman Richard Statman. The typed -calculus is not elementary recursive. Theoretical Computer Science, 9:73–81, 1979 showed that λ-conversion is not elementary
recursive, as the book’s notes cite [MN p. 116]).
Kanren angle (de Bruijn terms and a β-normaliser in plain Scheme). With de Bruijn indices 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, 34(5):381–392, 1972 a bound variable is the number of binders between its
occurrence and its binder. α-equivalent terms are then the same data structure, and
capture-avoidance turns into the index arithmetic of shift. The following illustration is plain
Scheme, not a proposed API (the design is in Chapter 11). It converts named terms to de Bruijn
form and computes β-normal forms (file norm-core.scm):
;; A tiny β-normaliser: de Bruijn inside, names outside.
;; Input: (λ (x y ...) body), applications (f a b ...), symbols.
(define (->db t env) ; named term -> de Bruijn
(cond
((symbol? t) (let ((i (index-of t env))) (if i i t)))
((eq? (car t) 'λ)
(let loop ((xs (cadr t)) (env env))
(if (null? xs)
(->db (caddr t) env)
(list 'lam (loop (cdr xs) (cons (car xs) env))))))
(else
(let loop ((f (->db (car t) env)) (as (cdr t)))
(if (null? as)
f
(loop (list 'app f (->db (car as) env)) (cdr as)))))))
(define (index-of x l)
(let loop ((l l) (i 0))
(cond ((null? l) #f)
((eq? (car l) x) i)
(else (loop (cdr l) (+ i 1))))))
(define (shift d c t) ; add d to the indices >= c
(cond ((integer? t) (if (>= t c) (+ t d) t))
((symbol? t) t)
((eq? (car t) 'lam) (list 'lam (shift d (+ c 1) (cadr t))))
(else (list 'app (shift d c (cadr t)) (shift d c (caddr t))))))
(define (subst t j s) ; t[s/j], capture-free
(cond ((integer? t) (if (= t j) s t))
((symbol? t) t)
((eq? (car t) 'lam)
(list 'lam (subst (cadr t) (+ j 1) (shift 1 0 s))))
(else (list 'app (subst (cadr t) j s) (subst (caddr t) j s)))))
(define (beta body arg) (shift -1 0 (subst body 0 (shift 1 0 arg))))
(define (nf t) ; β-normal form
(cond ((or (integer? t) (symbol? t)) t)
((eq? (car t) 'lam) (list 'lam (nf (cadr t))))
(else (let ((f (nf (cadr t))))
(if (and (pair? f) (eq? (car f) 'lam))
(nf (beta (cadr f) (caddr t)))
(list 'app f (nf (caddr t))))))))
(define (size t) ; number of applications
(cond ((not (pair? t)) 0)
((eq? (car t) 'lam) (size (cadr t)))
(else (+ 1 (size (cadr t)) (size (caddr t))))))
(define (church t) ; λf λx f^n x -> n, else #f
(and (pair? t) (eq? (car t) 'lam)
(pair? (cadr t)) (eq? (car (cadr t)) 'lam)
(let loop ((b (cadr (cadr t))) (n 0))
(cond ((eqv? b 0) n)
((and (pair? b) (eq? (car b) 'app) (eqv? (cadr b) 1))
(loop (caddr b) (+ n 1)))
(else #f)))))
(define (run t) (church (nf (->db t '()))))Running Church arithmetic and the blow-up series (file church.scm):
(include "norm-core.scm")
(define two '(λ (f x) (f (f x))))
(define three '(λ (f x) (f (f (f x)))))
(define (show . xs) (display xs) (newline))
(show 'succ-3 (run `((λ (n f x) (f (n f x))) ,three)))
(show 'add-2-3 (run `((λ (n m f x) (n f (m f x))) ,two ,three)))
(show 'mul-2-2 (run `((λ (n m f x) (n (m f) x)) ,two ,two)))
(define (series n) ; (g\e\ g^n e) (e\f\ e (e f)) (f\x\ f (f x))
`((λ (g e) ,(let loop ((k n)) (if (= k 0) 'e `(g ,(loop (- k 1))))))
(λ (e f) (e (e f)))
,two))
(do ((n 0 (+ n 1))) ((> n 4))
(let* ((t (->db (series n) '())) (v (nf t)))
(show 'n n 'size (size t) 'nf-size (size v) 'numeral (church v))))(succ-3 4)
(add-2-3 5)
(mul-2-2 4)
(n 0 size 6 nf-size 2 numeral 2)
(n 1 size 7 nf-size 4 numeral 4)
(n 2 size 8 nf-size 16 numeral 16)
(n 3 size 9 nf-size 256 numeral 256)
(n 4 size 10 nf-size 65536 numeral 65536)The input sizes are , as the book says, and the normal-form sizes are , as
Remark 4.10 says. For the unifier, the useful lesson is that a de Bruijn λ-term
built from Scheme records or lists is already handled by (aux kanren micro)’s structural =° up to α.
What =° cannot do is β: binding a logic variable that sits in head position creates a redex, so
some walk-and-normalise step has to be added (Definition 12.3).
Why logic programs do not explode. The book gives three reasons [MN p. 104–105]. (1) Integers and data structures are built-in or made from non-logical constructors, not Church-encoded. (2) Bound variables usually have primitive (order-0) types. If every bound variable in a term has a primitive type and are λ-normal, then is λ-normal: it may contain many copies of , but there are no new redexes. (3) In the sublanguage (Chapter 6), β is restricted to -contraction , which only renames, and normalisation then shrinks terms.
Remark 4.11 (Order of a type). The book uses “-th order” without giving a formula. The usual definition, consistent with all
its uses, is for primitive and
. Checks: the type
is called second-order [MN p. 102], and the type of
g\e\ g (g e) fourth-order [MN p. 104]. A unification problem whose variables have order at most
2 is called third-order [MN p. 116].
4.4Unification problems as quantified equalities#
Section 1.5 of the book (Chapter 1) defined a unification problem as a multiset and related it to the formula , with the ’s the constants and the ’s the logic variables [MN p. 105]. Following Miller Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991; and Dale Miller. Unification under a mixed prefix. Journal of Symbolic Computation, 14(4):321–358, 1992, the book now makes the formula the official presentation and allows any quantifier prefix.
Definition 4.12 (Generalised unification problem [MN p. 105]). A unification problem is a formula
with and λ-terms of the same type. The bound variables may have types of any order.
Why mix the quantifiers? The book gives two reasons [MN p. 106], each with a query that fails.
First, fohh proof search creates mixed prefixes. A pi in a goal introduces an
eigenvariable after the logic variables already present:
?- pi y\ X = y.
no
?-The problem is . It fails because no instance of X may contain the
eigenvariable that stands for .
Second, binders in terms behave like inner universal quantifiers.
?- (y\ X) = (y\ y).
no
?-The problem is . The equation
is logically equivalent to , so this is again , and it
fails for the same reason: no instance of X may contain a variable bound by an abstraction
inside whose body X occurs [MN p. 106].
Tutorial (reading a quantifier prefix). Every problem in this chapter can be read with one rule.
An existential variable may be instantiated only with a term built from symbols quantified to its left (together with fresh logic variables when one is content with a unifier rather than a solution, Section 4.6).
Here is where each quantifier of a λProlog problem comes from.
- Constants of the signature are outermost universals. They are to the left of everything, so every logic variable may use them.
- Free variables of the query (
X) are existentials. - A
piin a goal adds a universal at that point, to the right of the logic variables that already exist. Variables created later, for example by backchaining inside the scope of thepi, sit to its right and may use it (Chapter 3). - A λ inside an equation is an innermost universal around that equation.
Four readings follow, with :
| problem | what the ∃ may use | verdict |
|---|---|---|
| solved by | ||
| nothing that mentions | no solution | |
| and | four solutions | |
| only | one solution |
The last two rows are worked out in Section 4.7. The same mechanism explains the
second failing query. In (y\ X) = (y\ y) the logic variable X was created
outside the binder, so it is to the left of the inner . It may be instantiated with
anything except a term that mentions that .
From ∀∃ to ∀∃∀. In fohc the natural class is ∀∃ problems: constants first, then logic variables. With λ-terms the natural class is ∀∃∀ [MN p. 106]. The outer ∀’s are the constants. The inner ∀’s come from the binders of the equations: an equation at type is replaced by around an equation at type , and those quantifiers are moved out over the whole conjunction.
Example 4.13 (Turning λ-equations into a ∀∃∀ prefix [MN p. 106–107]). Let and , and consider
where . The transformation has three steps.
Make the constants explicit: .
Replace each λ-equation by a quantified one:
Prenex (one possibility):
Moving quantifiers to the prefix can introduce dependencies that are not really part of the problem: and now both scope over the whole conjunction, although each was attached to one equation. The book calls these “logically harmless” and assumes prenex form from now on [MN p. 107].
The example only illustrates the transformation. By a short check of ours (the book does not discuss it), it has no solution. The first equation forces . But a closed over is or , so is or , never .
Kanren angle (miniKanren has only ∃, and binders leak). fresh° is an existential, and there is no universal. The second failing query shows what this
costs once binders are present. Encode (y\ X) = (y\ y) with de Bruijn records (illustrative
records, file scope.scm):
(import (aux kanren micro) (aux base) (aux stream))
;; de Bruijn records: α-equivalent terms are equal data
(define-record lam body)
(define-record dbi n)
(define (show x) (display x) (newline))
;; λx.λy.x and λu.λv.u are the same record tree
(show (°->list #f (fresh° (q) (=° (make-lam (make-lam (make-dbi 1)))
(make-lam (make-lam (make-dbi 1))))
(=° q 'equal))))
;; ?- (y\ X) = (y\ y). λProlog answers no; plain =° answers yes
(show (°->list #f (fresh° (q) (=° (make-lam q) (make-lam (make-dbi 0))))))
;; ∃x[x = x]: the answer is a unifier, not a closed witness
(show (°->list #f (fresh° (q) (=° q q))))((λ () (quote equal)))
((λ () (make-record-instance (quote dbi) 0)))
((λ (α) α))The first line is what we want: α for free. The second is a wrong yes. q is bound to a
dangling index, which is exactly the forbidden capture of the inner . (The third line is
discussed in Section 4.6.) For the prefix discipline, a miniKanren therefore needs
(i) eigenvariables, that is, fresh constants that are never bound, and (ii) a scope check on
every binding: a variable may not receive a symbol quantified to its right. In (aux kanren micro) the monotone
vars-count index already records the order in which things are created, which is almost the
prefix order. The open question is how a variable inherits the restriction of the variable it is
bound to. λProlog implementations answer it with universe levels
Gopalan Nadathur, Bharat Jayaraman, and Keehang Kwon. Scoping constructs in logic programming: implementation problems and their solution. Journal of Logic Programming, 25(2):119–161, 1995; and Cvetan Dunchev, Ferruccio Guidi, Claudio Sacerdoti Coen, and Enrico Tassi. ELPI: fast, embeddable, Prolog interpreter. In Logic for Programming, Artificial Intelligence, and Reasoning (LPAR-20), volume 9450 of LNCS, pages 460–468. Springer, 2015, and Chapter 11 spells out the proposal.
4.5Simplifying prefixes: raising#
A prefix can alternate as often as it likes. Raising is the tool that brings every prefix to the ∀∃∀ shape, or even to ∃∀. It moves an existential to the left of a universal and pays for it by making the existential’s type higher-order.
Proposition 4.14 (Raising [MN p. 107]). Let , and . Then
Proof (the book’s argument). () A proof of the left formula replaces by a new constant and by a term , which may contain . Prove the right formula with and . Note that is not free in , as the order requires. () A proof of the right formula replaces by some and by a new , and cannot be free in . Prove the left formula with and . □
Applied repeatedly, raising moves every existential to the left of the universals before it. As a rule, for a block of universals:
The “cost” is that the type of the existential is raised by the types of the universals it crosses [MN p. 108].
Tutorial (raising, step by step). Step 0: a problem whose answer depends on order. Let and be constants, and compare
By the reading rule, in may use and solves it. In may not use , and no term without equals , so has no solution.
Step 1: raise . Move across . The new variable replaces by :
Now comes first and may not mention . But it is applied to , so it gets back as an argument. The solution is , and the check is . Translating back with the proof of Proposition 4.14 gives , the solution of Step 0. cannot be raised, because its existential is already on the left. The difference between the two problems is now visible in the syntax: is applied to in one, and stands alone in the other.
Step 2: raise over constants as well (∃∀ form). Constants are outer universals, so one can also raise across them. Take with . Raising across gives , with replaced by :
may not use . It must be with each , so there are four solutions. Mapped back by , they are the four solutions of the original problem, which Section 4.7 lists. For instance, gives .
What to remember. Raising is an exact logical equivalence. It replaces “may use the
universals to my left” by “is a closed function applied to those universals”. A logic variable
under binders, X inside y\ ..., can always be read as a raised variable applied to the bound
variables, (H y). When the arguments are distinct bound variables, as in , the
application is a higher-order pattern (Chapter 6 and Chapter 7), and pattern problems
have most general unifiers. In Step 2 the argument is repeated, , which is not a pattern,
and indeed there is no most general solution.
Skolemization, the dual. Skolemizing an assumption with and gives , where is a new Skolem constant. For a goal the roles swap: becomes , that is, [MN p. 108]. The two techniques are dual in two senses. Skolemization moves an ∃ to a smaller scope and introduces a new constant of raised type. Raising moves a ∀ to a smaller scope and introduces a new existential variable of raised type. Logically they differ: “relating unifiers for Skolemized unification problems to original, un-Skolemized unification problems is problematic, especially when unification involves variables of higher-order type” [MN p. 108]. Raising, in contrast, is an equivalence (Proposition 4.14), which is why the book uses it to normalise prefixes.
Pitfall (raising creates higher-order variables). Raising a first-order problem gives a higher-order one: in Step 1, became . A first-order miniKanren with ∀-goals cannot implement scope by raising unless it also has λ-terms and β. Prenexing (Example 4.13) has a related cost: it may add spurious dependencies. These are logically harmless, but a scope-tracking implementation becomes less permissive than it needs to be.
Kanren angle (raising versus levels). Raising is how the book explains logic variables under pi and λ. Implementations usually
do not raise up front. Nadathur, Jayaraman and Kwon tag each variable and constant with a universe index
Gopalan Nadathur, Bharat Jayaraman, and Keehang Kwon. Scoping constructs in logic programming: implementation problems and their solution. Journal of Logic Programming, 25(2):119–161, 1995. A binding is allowed only if the term’s constants have tags no larger
than the variable’s, and the tags of the term’s variables are lowered to match. ELPI uses the same
levels Cvetan Dunchev, Ferruccio Guidi, Claudio Sacerdoti Coen, and Enrico Tassi. ELPI: fast, embeddable, Prolog interpreter. In Logic for Programming, Artificial Intelligence, and Reasoning (LPAR-20), volume 9450 of LNCS, pages 460–468. Springer, 2015. Nadathur and Linnell Gopalan Nadathur and Natalie Linnell. Practical higher-order pattern unification with on-the-fly raising. In ICLP 2005: 21st International Logic Programming Conference, volume 3668 of LNCS, pages 371–386, Sitges, Spain, 2006. Springer show how to erase
the prefix and raise on the fly, only over the universals that actually occur. For (aux kanren micro),
the choice is between raising, which needs only terms (λ, application, β) but makes every existential
higher-order, and levels, which need a new per-variable piece of state and keep variables first-order.
The two must agree on the examples of this chapter. Chapter 11 makes the choice.
4.6Unifiers, solutions and empty types#
Once a problem is a formula, solving it should mean proving it. The connection is subtler than it looks. The higher-order version of ∃R [MN p. 108–109] is
The witness must be closed, because its context is empty. Proving with therefore needs a closed term of type , and whether one exists depends on . In the same way, with has the most general unifier in the sense of the book’s Section 1.5 (Chapter 1). The formula, however, is provable only if some closed term of type exists [MN p. 109].
Definition 4.15 (Legitimate substitution, unifier, solution [MN p. 109]). Consider the ∀∃∀ problem
and let be a substitution for .
- is legitimate if no occurs free in any .
- A legitimate is a unifier if and are λ-convertible for every .
- A unifier is a solution if the only free variables in the terms are among .
A problem can have a unifier and no solution. It is a solution that makes the quantified formula provable.
In the book’s Section 1.5 (Chapter 1) “solution” and “unifier” meant the same thing. They have to be separated now because, unlike first-order classical logic, higher-order intuitionistic logic does not assume that every type is inhabited. The Church numerals show why this matters. They are the closed terms of type only if has no closed term , since otherwise would be a further, non-numeral inhabitant [MN p. 109–110].
Example 4.16 (Unifier but no solution). Let contain only , so is empty. The problem has the unifier with a fresh logic variable. It has no solution, because there is no closed term of type . Add a constant and becomes a solution.
Kanren angle (miniKanren answers are unifiers). The third answer of scope.scm above, ((λ (α) α)) for , is a
unifier in the sense of Definition 4.15. The reified α is a fresh logic
variable, not a closed witness. This is also λProlog’s practice: answers may contain variables, and
leftover flex–flex constraints (Section 4.8). An untyped miniKanren cannot see empty types
at all. Obtaining solutions would need an explicit generator of closed inhabitants of a type
over a signature, itself a proof-search relation. Section 4.9 shows that the gap
between unifiers and solutions is exactly where undecidability lives.
4.7Example problems and their solutions#
These examples [MN p. 110–111] are the core intuition pump of the chapter. Each one shows a way in which higher-order unification differs from the first-order kind.
4.7.1Quantifier order changes the answers#
Let be a constructor of .
- has four solutions: .
- has the unique solution .
Walk-through. is closed, so with built from , and whatever may use. The β-normal form of is , and it must be . So is where each either is or becomes under the substitution, that is, . In the first problem is to the left of , so both choices are allowed for each position: . In the second, may not mention , only remains, and there is one solution. (Section 4.5 reached the same count of four by raising.)
Kanren angle (a first-order simulation of both prefixes). In this example is applied to a single argument and its body is first-order, so the problem can be
simulated in today’s (aux kanren micro). Represent ’s body as a first-order term in which x stands for the
bound variable, and relate a body to its instance with a relation inst°. The
universal is the symbol a. The ∃F∀a prefix, “ may not mention ”, is then the
constraint (absent° 'a body). This is an illustration, not general higher-order unification (file
order.scm):
(import (aux kanren micro) (aux base) (aux stream))
;; F = λx.body, body a first-order term over g, a and x = (dbi 0)
(define-record dbi n)
(set-record-printer! dbi (λ (r port) (display "x" port)))
(define x (make-dbi 0))
(define (show x) (display x) (newline))
;; (inst° body arg out): out = body[arg/x], the normal form of (F arg)
(define-relation (inst° body arg out)
(cond°
((=° body x) (=° out arg))
((symbol° body) (=° out body))
((null° body) (null° out))
((fresh° (h t h* t*)
(=° body (cons h t)) (=° out (cons h* t*))
(inst° h arg h*) (inst° t arg t*)))))
;; ∀a ∃F [(F a) = (g a a)]: F's body may mention the constant a
(show (°->list/ground
(fresh° (body) (inst° body 'a '(g a a)))))
;; ∃F ∀a [(F a) = (g a a)]: a comes after F, F's body must avoid it
(show (°->list/ground
(fresh° (body) (absent° 'a body) (inst° body 'a '(g a a)))))((g x x) (g a x) (g x a) (g a a))
((g x x))These are the book’s four answers and its one answer. Two points carry over to the real design. First,
the scope check is a constraint on what a variable may contain, like absent°, and it is
attached at the moment the variable is created. Second, a relation that runs substitution
backwards (inst° with out known) is what imitation and projection do in Huet’s
procedure (Chapter 7): each a in the output is either imitated or projected from the
argument.
4.7.2Words over a two-letter alphabet#
Let the only constructors with target be . Then has no closed terms, and the closed terms of type are words: is the empty word , is “u”, and is “uvu”. Function composition is concatenation [MN p. 110]. Three problems, all with :
- has four solutions, the four ways of splitting uvu: . Replacing the right-hand side by any other closed term asks for all ways of splitting that word.
- has the only solution . The left-hand side is a pattern that checks whether a word starts and ends with u.
- is the word equation . Its solutions are infinitely many: , that is, for every . They are closed and pairwise distinct, so none is an instance of another: there is no most general solution.
Kanren angle (words are lists, composition is append). Because is empty, a closed term of type is a word, and in this one case
higher-order unification becomes ordinary relational list programming (file words.scm):
(import (aux kanren micro) (aux base) (aux stream))
;; closed terms of type i -> i over u, v : i -> i are words,
;; and composition is concatenation
(define-relation (append° r s rs)
(cond°
((null° r) (=° s rs))
((fresh° (a d c) (cons° a d r) (cons° a c rs) (append° d s c)))))
(define (show x) (display x) (newline))
;; ∃F ∃G [(λw F (G w)) = (λw u (v (u w)))]
(show (μkanren-run (q -1 #t)
(fresh° (F G) (append° F G '(u v u)) (=° q (list F G)))))
;; ∃F [(λw u (F (u w))) = (λw u (v (v (u w))))]
(show (μkanren-run (q -1 #t)
(fresh° (uF) (append° '(u) q uF) (append° uF '(u) '(u v v u)))))
;; ∃F [(λw u (F w)) = (λw (F (u w)))]: five of infinitely many
(show (μkanren-run (q 5 #t)
(fresh° (W) (append° '(u) q W) (append° q '(u) W))))((() (u v u)) ((u) (v u)) ((u v) (u)) ((u v u) ()))
((v v))
(() (u) (u u) (u u u) (u u u u))The third query shows the right attitude toward problems without an mgu. A miniKanren does not need
a single answer: it returns a stream of them, and take° (here μkanren-run with
) cuts the stream. This is the shape a general higher-order unifier in (aux kanren micro) must have
(Section 4.9).
4.7.3Weak functionality#
Let have at least the constants . Then has no solution. The first equation is solved only by : cannot produce by projecting its argument , so it must be the constant function. That fails the second equation [MN p. 110–111]. A function that maps and exists as a set-theoretic object, but it is not expressible by these λ-terms, which have no case analysis on constants. The book calls this “a relatively weak notion of functionality”.
Pitfall (what a first-order intuition gets wrong).
- Quantifier order is semantic: and give four answers and one answer.
- There may be several incomparable solutions (four splittings of uvu), or
infinitely many with no mgu (u·F = F·u). A unifier returning one substitution, as
μkanren-state-unifydoes, cannot express this. - λ-terms are not arbitrary functions: no case analysis, so is unsolvable.
4.8Vocabulary for a unification procedure#
Chapter 7 presents Huet’s procedure Gérard Huet. A unification algorithm for typed -calculus. Theoretical Computer Science, 1:27–57, 1975. The book prepares it with some vocabulary and a few structural observations [MN p. 111–113].
Definition 4.17 (Binder, head, arguments, body [MN p. 111]). Every β-normal term has the shape
where is a constant or a variable and every is β-normal. is the binder, the head, the arguments, and the body.
Definition 4.18 (βη-long normal form [MN p. 111]). A term is in βη-long normal form if it has the shape above, every is βη-long, and the body has a non-functional type. For simply typed terms, that means a primitive type. Every β-normal form can be η-expanded into an equal βη-long form.
Example 4.19 (η-expanding to long form [MN p. 111]). Let . The term is β-normal but not long, since its body has functional type. One η-expansion gives with . This is still not long, because the argument has a non-primitive type. Expanding gives with , which is βη-long. Note that deciding when to stop requires knowing the types.
Definition 4.20 (Rigid and flexible [MN p. 111–113]). In a problem over β-normal terms, an occurrence is rigid if is ∀-bound in the prefix (constants included) or belongs to the binder . It is flexible if is ∃-bound in the prefix. Equations are rigid–rigid, rigid–flexible, flexible–rigid or flexible–flexible, and a problem is flexible–flexible if all of its equations are.
The names are meant to suggest what substitution can do. Substitution never changes the head of a rigid term: every instance has a β-normal form with the same head. It can change the head of a flexible term [MN p. 112].
Observation 1: rigid heads must agree. By α and η, two rigid terms of the same type can be given the same binder: and . Since neither head can change, a unifier can exist only if and are the same symbol [MN p. 112]. With logic variables and constants, none of the following has a unifier:
The first one, written precisely, is
Note that in the second and third problems one of the heads is a bound variable, which counts as rigid.
Observation 2: substitution cannot create captured occurrences. If a binder variable has no free occurrence in the body of a β-normal form, it has none in any instance either, because substitution avoids capture. So
has no unifier [MN p. 112–113]. Every instance of the left side has head . No instance of the right side can contain the bound : may be instantiated with a term containing a free , but that is a different .
Observation 3: flexible terms are limited only in their use of the binder. A flexible term can become almost any term of its type, except in how it uses the binder variables. For instance, can become any with not free in : take , which throws its argument away. Some instances also contain , such as , obtained with and . But no instance contains [MN p. 113], because is passed to neither nor , and by Observation 2 substitution cannot introduce it.
Observation 4: a flex–flex pair. Unify with . Instances of the first ignore , and instances of the second ignore , so a common instance is with neither variable free in . The “most general” unifier, derived in Chapter 7, is and , with a new variable [MN p. 113]. (Pattern unification calls this step pruning, Chapter 7.)
Tutorial (classifying heads in practice). Take the prefix and three occurrences:
| term | head | status |
|---|---|---|
| , ∀-bound | rigid: every instance starts with | |
| , in the binder | rigid: every instance starts with the bound | |
| , ∃-bound | flexible: makes the head |
A rigid–rigid equation either fails immediately or decomposes into equations between arguments (Chapter 7). A flex–rigid equation is where the search branches (imitate the rigid head, or project an argument). A flex–flex equation always has a unifier, as in Observation 4, so Huet’s procedure postpones it (Chapter 7). It need not have a solution, as Section 4.9 shows.
Kanren angle (what the vocabulary means for the unifier). (aux kanren micro)’s =° already performs “rigid–rigid”: two records or pairs with different
constructors fail at once, and the same constructor decomposes slot-wise. A de Bruijn representation
whose application node exposes head and arguments, as in Definition 4.17, makes Observation 1
a constructor clash. Bound-variable heads (dbi records) are rigid automatically. Everything about
flexible heads is new: the unifier must recognise a logic variable in head position, normalise
after binding it, and either solve the equation deterministically (patterns, Chapter 6) or
branch and delay it. Delayed flex–flex equations need a store in the state, next to the disequality
store, and Chapter 11 proposes one.
4.9Undecidability#
Derivability from fohc programs is already undecidable, and so is unifiability of typed λ-terms modulo λ-conversion [MN p. 113]. The book proves the second fact by two reductions. It also stresses that the specifications of later chapters produce “much tamer” problems.
4.9.1The Post correspondence problem#
Definition 4.21 (PCP [MN p. 114]). Given and two lists and of words over , decide whether there is a non-empty sequence with such that . This problem is undecidable.
Encode a word as , as in Section 4.7.2. Concatenation is then . Take a sort with no constructors, and introduce by universal quantifiers [MN p. 114]:
with . For the lists and [MN p. 114]:
$$ \begin{aligned} \exists F,\exists G,\forall u,\forall v, [,&(F,(\lambda w,u,(v,w)),u)=(F,u,(\lambda w,v,(u,w)))\
\end{aligned} $$
where has the second-order type .
Tutorial (why the encoding is correct). Read the prefix. and come before , so they may not mention or . They can only rearrange their arguments. has no constructors, so a closed must be with built only from . The only possible shape is with [MN p. 114].
Read off the index sequence. normalises to the word , and the right side to . So the first equation says exactly that solves the PCP, except in the degenerate case , where both sides are .
Exclude . The second equation says that starts with , which forces . In the other direction, a PCP solution gives a unification solution directly [MN p. 114–115]. The argument extends to unifiers and to types with constructors [MN p. 115].
Check the instance. For / , the sequence
works: . This suggests
and . may not mention
and has to obtain it from its argument. The book does not print this solution. The normaliser of
Section 4.3, with as free symbols, confirms both equations, and also the Diophantine
gadget of the next subsection (file checks.scm):
(include "norm-core.scm")
(define (same? s t) (equal? (nf (->db s '())) (nf (->db t '()))))
(define (show . xs) (display xs) (newline))
;; PCP instance uv,u / u,vu; u and v are free symbols
(define F '(λ (x1 x2 w) (x1 (x2 w))))
(define G '(λ (y w) (y w)))
(show 'pcp (same? `(,F (λ (w) (u (v w))) u) `(,F u (λ (w) (v (u w)))))
(same? `(,F u u) `(λ (w) (u (,G u w)))))
;; gadget for x = 1: λf λx N f (N f x) = λf λx N f (f x)
(define (numeral n)
`(λ (f x) ,(let loop ((k n)) (if (= k 0) 'x `(f ,(loop (- k 1)))))))
(define (gadget N)
(same? `(λ (f x) (,N f (,N f x))) `(λ (f x) (,N f (f x)))))
(show 'numerals-0..3 (map (lambda (n) (gadget (numeral n))) '(0 1 2 3)))
(show 'λf.λx.U (gadget '(λ (f x) U)))(pcp #t #t)
(numerals-0..3 (#f #t #f #f))
(λf.λx.U #t)Historically, Huet Gérard Huet. The undecidability of unification in third order logic. Information and Control, 22:257–267, 1973 gave the PCP reduction, which shows that third-order unification is undecidable [MN p. 116].
4.9.2Hilbert’s tenth problem#
Hilbert’s tenth problem asks for an algorithm that decides whether a system of Diophantine equations (variables, numerals, , over ) has a solution. No such algorithm exists [MN p. 115]. It is enough to treat equations of the forms , and . Take a sort without constructors, so that the closed terms of are exactly the Church numerals , and give every existential this type. Then [MN p. 115]:
- The flex–flex problem has the unique solution . With the sides are and , so .
- The flex–flex problem has the solution iff , and for some .
- The flex–flex problem has the solution iff , and .
Remark 4.22 (An erratum in the addition gadget). The book prints the left side of item 2 as [MN p. 115]. This parses as , which is ill-typed, since is applied to . The intended term is the addition combinator of Section 4.3.1, , and that is the term shown above.
Theorem 4.23 ([MN p. 116]). A system of such equations becomes a flex–flex problem with one existential variable per -variable and one equation per equation. The problem has a solution iff the system has a solution in . The variables have order at most 2, so the problem is third-order, and the construction extends to arbitrary Diophantine equations. Hence it is undecidable whether a third-order flex–flex problem has a solution.
Unifiers versus solutions, once more. The encoding always has a unifier: pick a new variable and set every existential to . Both sides of every gadget then normalise to . This term is not closed, so it is not a solution [MN p. 116]. The run above confirms both facts for gadget 1. Among only works, and works too. So the undecidable question concerns solutions. Asking only for unifiers, a flex–flex problem is trivially unifiable, and this is why Huet’s procedure can leave flex–flex pairs for last. In the bibliographic notes [MN p. 116–117] the book credits this reduction to Miller Dale Miller. Unification under a mixed prefix. Journal of Symbolic Computation, 14(4):321–358, 1992. It differs from Goldfarb’s Warren Goldfarb. The undecidability of the second-order unification problem. Theoretical Computer Science, 13:225–230, 1981, which already shows that second-order unification, for unifiers, is undecidable.
Kanren angle (undecidability and the search). Since unification is undecidable, no complete procedure terminates on every input. A complete
higher-order unifier is a semi-decision procedure: a search, some of whose branches never
finish. In a miniKanren this is a familiar situation. Such a unifier would be a goal that produces a
stream of unifiers. Huet’s branching steps would become disjunctions, and (aux kanren micro)’s interleaving
orª would explore them fairly, which a depth-first exploration does not. Flex–flex pairs, which always
have unifiers, would be left in a constraint store and reified with the answer, which then is a unifier and
not necessarily a solution. The proposal keeps only the deterministic part: pattern problems are solved by
one =°, and non-patterns, flex–flex pairs included, wait in a store and are reported
(Section 12.3.7). Huet’s branching is left to an optional search over that store, which needs
types (Section 14.5.4).
Remark 4.24 (Polymorphism). All the formal results of the book’s chapter concern simply typed terms. Type variables are
allowed for convenience, for instance one declaration for pi, but unification does not
instantiate type variables: they behave like sorts, so the simply typed results still apply
[MN p. 117].
4.10Summary#
- Terms are simply typed λ-terms (Figure 4.1). Formulas are terms of type , the quantifiers are constants applied to abstractions, and λ is the only binder.
- The equality of the logic is λ-conversion (α, β, η). Bound names are unobservable, substitution avoids capture, and equality ignores logical equivalences.
- Every term has a λ-normal form, unique up to α, so equality is decidable. β is powerful (Church numerals) and normal forms can be huge ( in the book’s series, see the erratum). Practical programs avoid this through built-in data, order-0 binders and .
- A unification problem is a quantified formula .
An existential may use only what is quantified to its left.
piand λ both introduce universals, which is whypi y\ X = yand(y\ X) = (y\ y)fail. - Raising () is an exact equivalence that brings any prefix to ∀∃∀ or ∃∀, at the cost of higher-order types. Skolemization is its dual but does not preserve unifiers well.
- A unifier may leave free variables, while a solution uses only the outer universals. Only solutions give proofs, and empty types make the difference real. miniKanren answers are unifiers.
- Higher-order unification has several, infinitely many, or no solutions, and no mgu in general. Quantifier order changes the count (4 versus 1), and λ-terms cannot do case analysis.
- Vocabulary for Chapter 7: binder, head, arguments, body; βη-long form; rigid and flexible terms; rigid heads must agree; vacuous binders stay vacuous; flex–flex pairs always have unifiers.
- Unifiability is undecidable (PCP, third order), and so is the existence of solutions of third-order flex–flex problems (Hilbert’s tenth problem). Hence a miniKanren higher-order unifier must be a goal producing a fair stream of unifiers, with flex–flex pairs postponed.