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:

  1. 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.
  2. 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.
  3. 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 tt in which a variable x:αx{:}\alpha may occur free, it forms the function λ(x:α) t\lambda(x{:}\alpha)\,t [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)))\lambda f\,\lambda x\,(f\,(f\,(f\,x)))f\x\ f (f (f x))
λx (f (g λy (h x y)) x)\lambda x\,(f\,(g\,\lambda y\,(h\,x\,y))\,x)x\ f (g y\ h x y) x
λx λy x\lambda x\,\lambda y\,xx\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 𝗂\mathsf{i}, and the type 𝗈\mathsf{o} of propositions), type variables AA, type constructors such as 𝗅𝗂𝗌𝗍 A\mathsf{list}\,A, and the arrow τ1→τ2\tau_1\to\tau_2, which associates to the right. Terms are

t  ::=  c  ∣  x  ∣  (t  t)  ∣  λ(x:τ) t. t \;::=\; c \;\mid\; x \;\mid\; (t\;t) \;\mid\; \lambda(x{:}\tau)\,t .

(The book introduces the grammar in prose [MN p. 97–99]. This compact form is ours.)

Typing. The judgement Σ;Γ⊩t:τ\Sigma;\Gamma\Vdash t:\tau (in the book, with a double turnstile) says that tt has type τ\tau when Σ\Sigma gives the types of the constants and Γ\Gamma those of the variables. It is defined by the rules of Figure 4.1 [MN p. 98]:

c:σ∈Στ◃σΣ;Γ⊩c:τx:τ∈ΓΣ;Γ⊩x:τΣ;Γ⊩g:τ1→τ2Σ;Γ⊩t:τ1Σ;Γ⊩(g  t):τ2 \dfrac{c:\sigma\in\Sigma \qquad \tau\triangleleft\sigma}{\Sigma;\Gamma\Vdash c:\tau} \qquad\qquad \dfrac{x:\tau\in\Gamma}{\Sigma;\Gamma\Vdash x:\tau} \qquad\qquad \dfrac{\Sigma;\Gamma\Vdash g:\tau_1\to\tau_2 \qquad \Sigma;\Gamma\Vdash t:\tau_1}{\Sigma;\Gamma\Vdash (g\;t):\tau_2} Σ;Γ,x:τ⊩t:σΣ;Γ⊩λ(x:τ) t:τ→σ  (†)Σ;Γ⊩B:τΣ;Γ⊩C:τ  (‡) \dfrac{\Sigma;\Gamma,x:\tau\Vdash t:\sigma}{\Sigma;\Gamma\Vdash \lambda(x{:}\tau)\,t:\tau\to\sigma}\;(\dagger) \qquad\qquad \dfrac{\Sigma;\Gamma\Vdash B:\tau}{\Sigma;\Gamma\Vdash C:\tau}\;(\ddagger)

Proviso (†)(\dagger): xx is not declared as a type or kind in Σ\Sigma or Γ\Gamma. Proviso (‡)(\ddagger): BB and CC differ only in the names of bound variables. τ◃σ\tau\triangleleft\sigma means that τ\tau is a substitution instance of σ\sigma, 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 Σ\Sigma and Γ\Gamma are gone: a constant may have any type, including a functional type that ends in 𝗈\mathsf{o}. 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 tt is a well-formed λ-term over Σ\Sigma if Σ;Γ⊩t:τ\Sigma;\Gamma\Vdash t:\tau is derivable for some Γ\Gamma and τ\tau. It is closed if this holds with Γ\Gamma 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 (𝗂→𝗂)→𝗂→𝗂(\mathsf{i}\to\mathsf{i})\to\mathsf{i}\to\mathsf{i}. Write Γ=f:𝗂→𝗂, x:𝗂\Gamma=f{:}\mathsf{i}\to\mathsf{i},\,x{:}\mathsf{i}:

f:𝗂→𝗂∈ΓΣ;Γ⊩f:𝗂→𝗂Σ;Γ⊩f:𝗂→𝗂Σ;Γ⊩x:𝗂Σ;Γ⊩f x:𝗂  APPΣ;Γ⊩f (f x):𝗂  APPΣ;f:𝗂→𝗂⊩λx f (f x):𝗂→𝗂  (†)Σ;∅⊩λf λx f (f x):(𝗂→𝗂)→𝗂→𝗂  (†) \dfrac{ \dfrac{ \dfrac{ \dfrac{f:\mathsf{i}\to\mathsf{i}\in\Gamma}{\Sigma;\Gamma\Vdash f:\mathsf{i}\to\mathsf{i}} \qquad \dfrac{\Sigma;\Gamma\Vdash f:\mathsf{i}\to\mathsf{i} \qquad \Sigma;\Gamma\Vdash x:\mathsf{i}}{\Sigma;\Gamma\Vdash f\,x:\mathsf{i}}\;\text{\small APP} }{\Sigma;\Gamma\Vdash f\,(f\,x):\mathsf{i}}\;\text{\small APP} }{\Sigma;f{:}\mathsf{i}\to\mathsf{i}\Vdash \lambda x\,f\,(f\,x):\mathsf{i}\to\mathsf{i}}\;(\dagger) }{\Sigma;\emptyset\Vdash \lambda f\,\lambda x\,f\,(f\,x):(\mathsf{i}\to\mathsf{i})\to\mathsf{i}\to\mathsf{i}}\;(\dagger)

Read the derivation bottom up. Each abstraction rule (†)(\dagger) moves one binder into the context. The application rule app then checks ff against a functional type twice, and the leaves are instances of the variable rule (the two leaves above f xf\,x 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 Σ\Sigma, including one with no constant of type 𝗂\mathsf{i}, 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 𝗈\mathsf{o}. The connectives are constants such as ∧:𝗈→𝗈→𝗈\wedge:\mathsf{o}\to\mathsf{o}\to\mathsf{o}. The quantifiers become constants too [MN p. 99]:

∀:(A→𝗈)→𝗈,∃:(A→𝗈)→𝗈(concretely pi and sigma), \forall : (A\to\mathsf{o})\to\mathsf{o}, \qquad \exists : (A\to\mathsf{o})\to\mathsf{o} \qquad\text{(concretely \texttt{pi} and \texttt{sigma})},

and ∀x B\forall x\,B abbreviates ∀(λx B)\forall(\lambda x\,B), written ∀τx B\forall_\tau x\,B when the type of xx matters. A quantified formula is typed with the ordinary rules. From Σ;Γ,x:σ⊩B:𝗈\Sigma;\Gamma,x{:}\sigma\Vdash B:\mathsf{o} the abstraction rule gives λx B:σ→𝗈\lambda x\,B:\sigma\to\mathsf{o}, the instance ∀:(σ→𝗈)→𝗈\forall:(\sigma\to\mathsf{o})\to\mathsf{o} of the constant gives the rest, and so ∀(λx B):𝗈\forall(\lambda x\,B):\mathsf{o}. 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 ∧\wedge 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]). tt is free for xx in ss if no free occurrence of xx in ss lies in the scope of an abstraction that binds a free variable of tt. If tt is free for xx in ss and both have the same type, s[t/x]s[t/x] is ss with every free occurrence of xx replaced by tt.

For example, (f x)(f\,x) is free for uu in λw (g u w)\lambda w\,(g\,u\,w), but (f w)(f\,w) is not: substituting it would put its free ww under the binder λw\lambda w. 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:

ruleredex ⇒\Rightarrow contractumproviso
α-rewritingλx s  ⇒  λy s[y/x]\lambda x\,s\;\Rightarrow\;\lambda y\,s[y/x]yy free for xx in ss, yy not free in ss
β-contraction(λx s) t  ⇒  s[t/x](\lambda x\,s)\,t\;\Rightarrow\;s[t/x]tt free for xx in ss (lifted below)
η-contractionλx (s x)  ⇒  s\lambda x\,(s\,x)\;\Rightarrow\;sxx not free in ss

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)) y

The first two terms are α-convertible. The third is the first after an η-contraction:

λy (f (g x) y)  ⇒  f (g x). \lambda y\,(f\,(g\,x)\,y)\;\Rightarrow\;f\,(g\,x).

A β-contraction of the fourth gives

x\y\ f ((v\v) (g x)) y

and a second one gives back the first. Note that (2 + 3) disappears entirely, because uu 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 s[t/x]s[t/x] is defined even when tt is not free for xx in ss. First α-rename ss to some s′s' in which tt is free for xx, then substitute. The result depends on the renaming only up to α, so modulo equality it is well defined. β-contraction then becomes (λx s) t⇒s[t/x](\lambda x\,s)\,t\Rightarrow s[t/x] with no proviso [MN p. 101]. This is ordinary capture-avoiding substitution.

Tutorial (capture-avoiding β, by hand). Contract (λu λw (g u w)) (f w)(\lambda u\,\lambda w\,(g\,u\,w))\,(f\,w). The argument has a free ww. A naive textual replacement would give λw (g (f w) w)\lambda w\,(g\,(f\,w)\,w), where the outer ww has been captured and now refers to the bound variable. This is a different function. Liberalised substitution first renames the binder, λu λw′ (g u w′)\lambda u\,\lambda w'\,(g\,u\,w'), and then substitutes:

(λu λw (g u w)) (f w)  ⇒  λw′ (g (f w) w′). (\lambda u\,\lambda w\,(g\,u\,w))\,(f\,w)\;\Rightarrow\;\lambda w'\,(g\,(f\,w)\,w').

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 (λx s) t(\lambda x\,s)\,t. An η-redex is a term λx (t x)\lambda x\,(t\,x) with xx not free in tt. 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 λnorm(s)\lambda\mathrm{norm}(s). 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 p,q:𝗂→𝗈p,q:\mathsf{i}\to\mathsf{o}, the term λx (p x)∧(q x)\lambda x\,(p\,x)\wedge(q\,x) is not equal to λx (q x)∧(p x)\lambda x\,(q\,x)\wedge(p\,x) [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 ∧\wedge would be wrong.

4.3.1Computing with β: Church numerals

The rule (λx s) t⇒s[t/x](\lambda x\,s)\,t\Rightarrow s[t/x] can copy tt many times or throw it away. Even when ss and tt are both normal, the result need not be, because xx may sit in head position [MN p. 102]. So normalisation is a model of computation. Let the sort 𝗂\mathsf{i} have no constants. Then the closed λ-normal forms of type (𝗂→𝗂)→𝗂→𝗂(\mathsf{i}\to\mathsf{i})\to\mathsf{i}\to\mathsf{i} are exactly the Church numerals ⌜n⌝=λf λx (fn x)\ulcorner n\urcorner=\lambda f\,\lambda x\,(f^n\,x) [MN p. 102]. Arithmetic is then definable [MN p. 103]:

succ=λn λf λx f (n f x),add=λn λm λf λx n f (m f x),mul=λn λm λf λx n (m f) x. \begin{gathered} \mathit{succ}=\lambda n\,\lambda f\,\lambda x\,f\,(n\,f\,x),\\ \mathit{add}=\lambda n\,\lambda m\,\lambda f\,\lambda x\,n\,f\,(m\,f\,x),\\ \mathit{mul}=\lambda n\,\lambda m\,\lambda f\,\lambda x\,n\,(m\,f)\,x . \end{gathered}

λ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 (n+1)(n{+}1)-th term has size n+6n+6, 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 (n+1)(n{+}1)-th normal form has size 22⋅⋅22^{2^{\cdot^{\cdot^{2}}}} with n+1n+1 twos [MN p. 104]. The term e\f\ e (e f) squares a numeral, and the outer numeral applies it nn times to ⌜2⌝\ulcorner 2\urcorner. So the normal form is ⌜22n⌝\ulcorner 2^{2^n}\urcorner, of size 22n2^{2^n}: 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, ((22)2)⋯((2^2)^2)^{\cdots}. The run below confirms the numbers. The point of the passage is unaffected: sizes can explode (Statman Richard Statman. The typed λ\lambda-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 n+6n+6, as the book says, and the normal-form sizes are 22n2^{2^n}, 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 s,ts,t are λ-normal, then s[t/x]s[t/x] is λ-normal: it may contain many copies of tt, but there are no new redexes. (3) In the sublanguage LλL_\lambda (Chapter 6), β is restricted to β0\beta_0-contraction (λx s) x⇒s(\lambda x\,s)\,x\Rightarrow s, which only renames, and normalisation then shrinks terms.

Remark 4.11 (Order of a type). The book uses “nn-th order” without giving a formula. The usual definition, consistent with all its uses, is ord(τ)=0\mathrm{ord}(\tau)=0 for primitive τ\tau and ord(τ1→τ2)=max⁡(ord(τ1)+1,ord(τ2))\mathrm{ord}(\tau_1\to\tau_2)=\max(\mathrm{ord}(\tau_1)+1,\mathrm{ord}(\tau_2)). Checks: the type (𝗂→𝗂)→𝗂→𝗂(\mathsf{i}\to\mathsf{i})\to\mathsf{i}\to\mathsf{i} 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 {t1=s1,…,tp=sp}\{t_1=s_1,\dots,t_p=s_p\} and related it to the formula ∀y1…∀ym ∃x1…∃xn [t1=s1∧⋯∧tp=sp]\forall y_1\dots\forall y_m\,\exists x_1\dots\exists x_n\,[t_1=s_1\wedge\dots\wedge t_p=s_p], with the yy’s the constants and the xx’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

Q1x1…Qnxn [ t1=s1∧⋯∧tm=sm ](n,m≥0, Qi∈{∀,∃}), Q_1x_1\dots Q_nx_n\,[\,t_1=s_1\wedge\dots\wedge t_m=s_m\,]\qquad(n,m\ge 0,\ Q_i\in\{\forall,\exists\}),

with tjt_j and sjs_j λ-terms of the same type. The bound variables xix_i 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 ∃x ∀y [x=y]\exists x\,\forall y\,[x=y]. It fails because no instance of X may contain the eigenvariable that stands for yy.

Second, binders in terms behave like inner universal quantifiers.

?- (y\ X) = (y\ y).
no
?-

The problem is ∃x [(λy x)=(λy y)]\exists x\,[(\lambda y\,x)=(\lambda y\,y)]. The equation (λy t)=(λy s)(\lambda y\,t)=(\lambda y\,s) is logically equivalent to ∀y [t=s]\forall y\,[t=s], so this is again ∃x ∀y [x=y]\exists x\,\forall y\,[x=y], 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 pi in 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 the pi, 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 g:𝗂→𝗂→𝗂g:\mathsf{i}\to\mathsf{i}\to\mathsf{i}:

problemwhat the ∃ may useverdict
∀y ∃x [x=y]\forall y\,\exists x\,[x=y]yysolved by x:=yx:=y
∃x ∀y [x=y]\exists x\,\forall y\,[x=y]nothing that mentions yyno solution
∀a ∃F [(F a)=(g a a)]\forall a\,\exists F\,[(F\,a)=(g\,a\,a)]gg and aafour solutions
∃F ∀a [(F a)=(g a a)]\exists F\,\forall a\,[(F\,a)=(g\,a\,a)]gg onlyone 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 ∀y\forall y. It may be instantiated with anything except a term that mentions that yy.

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 τ→σ\tau\to\sigma is replaced by ∀(w:τ)\forall(w{:}\tau) around an equation at type σ\sigma, and those quantifiers are moved out over the whole conjunction.

Example 4.13 (Turning λ-equations into a ∀∃∀ prefix [MN p. 106–107]). Let f:𝗂→𝗂f:\mathsf{i}\to\mathsf{i} and a:𝗂a:\mathsf{i}, and consider

∃G ∃H [(λw f a)=(λw f (G w))  ∧  (λw f w)=(λw H (H w))], \exists G\,\exists H\,[(\lambda w\,f\,a)=(\lambda w\,f\,(G\,w))\;\wedge\;(\lambda w\,f\,w)=(\lambda w\,H\,(H\,w))],

where G,H:𝗂→𝗂G,H:\mathsf{i}\to\mathsf{i}. The transformation has three steps.

  1. Make the constants explicit: ∀f ∀a ∃G ∃H [… ]\forall f\,\forall a\,\exists G\,\exists H\,[\dots].

  2. Replace each λ-equation by a quantified one:

    ∀f ∀a ∃G ∃H [∀w [(f a)=(f (G w))]∧∀w [(f w)=(H (H w))]]. \forall f\,\forall a\,\exists G\,\exists H\,[\forall w\,[(f\,a)=(f\,(G\,w))]\wedge\forall w\,[(f\,w)=(H\,(H\,w))]].
  3. Prenex (one possibility):

    ∀f ∀a ∃G ∃H ∀w ∀w′ [(f a)=(f (G w))∧(f w′)=(H (H w′))]. \forall f\,\forall a\,\exists G\,\exists H\,\forall w\,\forall w'\,[(f\,a)=(f\,(G\,w))\wedge(f\,w')=(H\,(H\,w'))].

Moving quantifiers to the prefix can introduce dependencies that are not really part of the problem: ∀w\forall w and ∀w′\forall w' 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 G=λw aG=\lambda w\,a. But a closed HH over f,af,a is λz fkz\lambda z\,f^k z or λz fka\lambda z\,f^k a, so H (H w′)H\,(H\,w') is f2kw′f^{2k}w' or fkaf^k a, never f w′f\,w'.

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 ∀y\forall y. (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, λ\lambdaProlog 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 x:τx:\tau, y:σy:\sigma and h:σ→τh:\sigma\to\tau. Then

∀y ∃x Gis provable iff∃h ∀y G[(h y)/x]. \forall y\,\exists x\,G\quad\text{is provable iff}\quad\exists h\,\forall y\,G[(h\,y)/x].

Proof (the book’s argument). (⇒\Rightarrow) A proof of the left formula replaces yy by a new constant cc and xx by a term tt, which may contain cc. Prove the right formula with h:=λc th:=\lambda c\,t and y:=cy:=c. Note that cc is not free in λc t\lambda c\,t, as the order ∃h ∀y\exists h\,\forall y requires. (⇐\Leftarrow) A proof of the right formula replaces hh by some ss and yy by a new cc, and cc cannot be free in ss. Prove the left formula with y:=cy:=c and x:=(s c)x:=(s\,c). □

Applied repeatedly, raising moves every existential to the left of the universals before it. As a rule, for a block of universals:

∀y1:σ1…∀yk:σk  ∃x:τ  G⇝  ∃h:σ1→⋯→σk→τ  ∀y1…∀yk  G[(h y1…yk)/x]. \begin{aligned} &\forall y_1{:}\sigma_1\dots\forall y_k{:}\sigma_k\;\exists x{:}\tau\;G\\ \rightsquigarrow\;& \exists h{:}\sigma_1\to\dots\to\sigma_k\to\tau\;\forall y_1\dots\forall y_k\;G[(h\,y_1\dots y_k)/x]. \end{aligned}

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 g:𝗂→𝗂→𝗂g:\mathsf{i}\to\mathsf{i}\to\mathsf{i} and a:𝗂a:\mathsf{i} be constants, and compare

(P1)  ∀w ∃z [z=g a w]and(P2)  ∃z ∀w [z=g a w]. (\mathrm{P}_1)\;\forall w\,\exists z\,[z=g\,a\,w] \qquad\text{and}\qquad (\mathrm{P}_2)\;\exists z\,\forall w\,[z=g\,a\,w].

By the reading rule, in P1\mathrm{P}_1 zz may use ww and z:=g a wz:=g\,a\,w solves it. In P2\mathrm{P}_2 zz may not use ww, and no term without ww equals g a wg\,a\,w, so P2\mathrm{P}_2 has no solution.

Step 1: raise P1\mathrm{P}_1. Move ∃z\exists z across ∀w\forall w. The new variable h:𝗂→𝗂h:\mathsf{i}\to\mathsf{i} replaces zz by (h w)(h\,w):

∃h ∀w [h w=g a w]. \exists h\,\forall w\,[h\,w=g\,a\,w].

Now hh comes first and may not mention ww. But it is applied to ww, so it gets ww back as an argument. The solution is h:=λc g a ch:=\lambda c\,g\,a\,c, and the check is (λc g a c) w→βg a w(\lambda c\,g\,a\,c)\,w\to_\beta g\,a\,w. Translating back with the proof of Proposition 4.14 gives z:=h w=g a wz:=h\,w=g\,a\,w, the solution of Step 0. P2\mathrm{P}_2 cannot be raised, because its existential is already on the left. The difference between the two problems is now visible in the syntax: hh is applied to ww in one, and zz 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 ∀a ∃F [(F a)=(g a a)]\forall a\,\exists F\,[(F\,a)=(g\,a\,a)] with F:𝗂→𝗂F:\mathsf{i}\to\mathsf{i}. Raising FF across ∀a\forall a gives F′:𝗂→𝗂→𝗂F':\mathsf{i}\to\mathsf{i}\to\mathsf{i}, with FF replaced by (F′ a)(F'\,a):

∃F′ ∀a [(F′ a a)=(g a a)]. \exists F'\,\forall a\,[(F'\,a\,a)=(g\,a\,a)].

F′F' may not use aa. It must be λy λx (g s1 s2)\lambda y\,\lambda x\,(g\,s_1\,s_2) with each si∈{x,y}s_i\in\{x,y\}, so there are four solutions. Mapped back by F:=F′ aF:=F'\,a, they are the four solutions of the original problem, which Section 4.7 lists. For instance, F′=λy λx g y xF'=\lambda y\,\lambda x\,g\,y\,x gives F=λx g a xF=\lambda x\,g\,a\,x.

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 h wh\,w, the application is a higher-order pattern (Chapter 6 and Chapter 7), and pattern problems have most general unifiers. In Step 2 the argument aa is repeated, F′ a aF'\,a\,a, which is not a pattern, and indeed there is no most general solution.

Skolemization, the dual. Skolemizing an assumption ∀x ∃y D\forall x\,\exists y\,D with x:σx:\sigma and y:τy:\tau gives ∀x D[(f x)/y]\forall x\,D[(f\,x)/y], where f:σ→τf:\sigma\to\tau is a new Skolem constant. For a goal the roles swap: ∃x ∀y G\exists x\,\forall y\,G becomes ∃x G[(f x)/y]\exists x\,G[(f\,x)/y], that is, ∀f ∃x G[(f x)/y]\forall f\,\exists x\,G[(f\,x)/y] [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, z:𝗂z:\mathsf{i} became h:𝗂→𝗂h:\mathsf{i}\to\mathsf{i}. 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, λ\lambdaProlog 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

Σ;𝒫⟶B[t/x]Σ;∅⊩t:τΣ;𝒫⟶∃τx B  ∃R \dfrac{\Sigma; \mathcal{P} \longrightarrow B[t/x] \qquad \Sigma;\emptyset\Vdash t:\tau}{\Sigma; \mathcal{P} \longrightarrow \exists_\tau x\,B}\;\exists\text{\small R}

The witness tt must be closed, because its context is empty. Proving ∃x [x=x]\exists x\,[x=x] with x:𝗂x:\mathsf{i} therefore needs a closed term of type 𝗂\mathsf{i}, and whether one exists depends on Σ\Sigma. In the same way, ∃x ∃y ∃z [x=(f y)∧y=(f z)]\exists x\,\exists y\,\exists z\,[x=(f\,y)\wedge y=(f\,z)] with f:𝗂→𝗂f:\mathsf{i}\to\mathsf{i} has the most general unifier {⟨X,f (f Z)⟩,⟨Y,f Z⟩}\{\langle X,f\,(f\,Z)\rangle,\langle Y,f\,Z\rangle\} in the sense of the book’s Section 1.5 (Chapter 1). The formula, however, is provable only if some closed term of type 𝗂\mathsf{i} exists [MN p. 109].

Definition 4.15 (Legitimate substitution, unifier, solution [MN p. 109]). Consider the ∀∃∀ problem

∀u1…∀up ∃x1…∃xn ∀w1…∀wq [t1=s1∧⋯∧tm=sm] \forall u_1\dots\forall u_p\,\exists x_1\dots\exists x_n\,\forall w_1\dots\forall w_q\,[t_1=s_1\wedge\dots\wedge t_m=s_m]

and let θ\theta be a substitution for x1,…,xnx_1,\dots,x_n.

  • θ\theta is legitimate if no wjw_j occurs free in any θ(xi)\theta(x_i).
  • A legitimate θ\theta is a unifier if θ(tj)\theta(t_j) and θ(sj)\theta(s_j) are λ-convertible for every jj.
  • A unifier is a solution if the only free variables in the terms θ(xi)\theta(x_i) are among u1,…,upu_1,\dots,u_p.

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 (𝗂→𝗂)→𝗂→𝗂(\mathsf{i}\to\mathsf{i})\to\mathsf{i}\to\mathsf{i} only if 𝗂\mathsf{i} has no closed term tt, since otherwise λf λx t\lambda f\,\lambda x\,t would be a further, non-numeral inhabitant [MN p. 109–110].

Example 4.16 (Unifier but no solution). Let Σ\Sigma contain only u,v:𝗂→𝗂u,v:\mathsf{i}\to\mathsf{i}, so 𝗂\mathsf{i} is empty. The problem ∃x [x=x]\exists x\,[x=x] has the unifier {x↦X}\{x\mapsto X\} with XX a fresh logic variable. It has no solution, because there is no closed term of type 𝗂\mathsf{i}. Add a constant a:𝗂a:\mathsf{i} and {x↦a}\{x\mapsto a\} becomes a solution.

Kanren angle (miniKanren answers are unifiers). The third answer of scope.scm above, ((λ (α) α)) for ∃x [x=x]\exists x\,[x=x], 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 g:𝗂→𝗂→𝗂g:\mathsf{i}\to\mathsf{i}\to\mathsf{i} be a constructor of 𝗂\mathsf{i}.

  • ∀a ∃F [(F a)=(g a a)]\forall a\,\exists F\,[(F\,a)=(g\,a\,a)] has four solutions: F∈{λx g a a, λx g x a, λx g a x, λx g x x}F\in\{\lambda x\,g\,a\,a,\ \lambda x\,g\,x\,a,\ \lambda x\,g\,a\,x,\ \lambda x\,g\,x\,x\}.
  • ∃F ∀a [(F a)=(g a a)]\exists F\,\forall a\,[(F\,a)=(g\,a\,a)] has the unique solution F=λa g a aF=\lambda a\,g\,a\,a.

Walk-through. F:𝗂→𝗂F:\mathsf{i}\to\mathsf{i} is closed, so F=λx bF=\lambda x\,b with bb built from gg, xx and whatever FF may use. The β-normal form of F aF\,a is b[a/x]b[a/x], and it must be g a ag\,a\,a. So bb is g s1 s2g\,s_1\,s_2 where each sis_i either is aa or becomes aa under the substitution, that is, si∈{a,x}s_i\in\{a,x\}. In the first problem aa is to the left of FF, so both choices are allowed for each position: 2×2=42\times 2=4. In the second, FF may not mention aa, only si=xs_i=x 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 FF 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 FF’s body as a first-order term in which x stands for the bound variable, and relate a body to its instance b[a/x]b[a/x] with a relation inst°. The universal aa is the symbol a. The ∃F∀a prefix, “FF may not mention aa”, 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 𝗂\mathsf{i} be u,v:𝗂→𝗂u,v:\mathsf{i}\to\mathsf{i}. Then 𝗂\mathsf{i} has no closed terms, and the closed terms of type 𝗂→𝗂\mathsf{i}\to\mathsf{i} are words: λw w\lambda w\,w is the empty word ε\varepsilon, λw u w\lambda w\,u\,w is “u”, and λw u (v (u w))\lambda w\,u\,(v\,(u\,w)) is “uvu”. Function composition is concatenation [MN p. 110]. Three problems, all with F,G:𝗂→𝗂F,G:\mathsf{i}\to\mathsf{i}:

  1. ∃F ∃G [(λw F (G w))=(λw u (v (u w)))]\exists F\,\exists G\,[(\lambda w\,F\,(G\,w))=(\lambda w\,u\,(v\,(u\,w)))] has four solutions, the four ways of splitting uvu: (F,G)∈{(uvu,ε),(uv,u),(u,vu),(ε,uvu)}(F,G)\in\{(\mathrm{uvu},\varepsilon),(\mathrm{uv},\mathrm{u}),(\mathrm{u},\mathrm{vu}),(\varepsilon,\mathrm{uvu})\}. Replacing the right-hand side by any other closed term asks for all ways of splitting that word.
  2. ∃F [(λw u (F (u w)))=(λw u (v (v (u w))))]\exists F\,[(\lambda w\,u\,(F\,(u\,w)))=(\lambda w\,u\,(v\,(v\,(u\,w))))] has the only solution F=λw v (v w)F=\lambda w\,v\,(v\,w). The left-hand side is a pattern that checks whether a word starts and ends with u.
  3. ∃F [(λw u (F w))=(λw F (u w))]\exists F\,[(\lambda w\,u\,(F\,w))=(\lambda w\,F\,(u\,w))] is the word equation u⋅F=F⋅u\mathrm{u}\cdot F=F\cdot\mathrm{u}. Its solutions are infinitely many: F∈{λw w, λw u w, λw u (u w),… }F\in\{\lambda w\,w,\ \lambda w\,u\,w,\ \lambda w\,u\,(u\,w),\dots\}, that is, uk\mathrm{u}^k for every k≥0k\ge 0. 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 𝗂\mathsf{i} is empty, a closed term of type 𝗂→𝗂\mathsf{i}\to\mathsf{i} 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 n=5n=5) 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 𝗂\mathsf{i} have at least the constants a,b,c,d:𝗂a,b,c,d:\mathsf{i}. Then ∃F [(F a)=b∧(F c)=d]\exists F\,[(F\,a)=b\wedge(F\,c)=d] has no solution. The first equation is solved only by F=λx bF=\lambda x\,b: FF cannot produce bb by projecting its argument aa, so it must be the constant function. That FF fails the second equation [MN p. 110–111]. A function that maps a↦ba\mapsto b and c↦dc\mapsto d 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: ∀a ∃F\forall a\,\exists F and ∃F ∀a\exists F\,\forall a 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-unify does, cannot express this.
  • λ-terms are not arbitrary functions: no case analysis, so F a=b∧F c=dF\,a=b\wedge F\,c=d is unsolvable.

4.8Vocabulary for a unification procedure

Chapter 7 presents Huet’s procedure Gérard Huet. A unification algorithm for typed λ\lambda-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

λx1…λxn (h  t1⋯tp)(n,p≥0), \lambda x_1\dots\lambda x_n\,(h\;t_1\cdots t_p)\qquad(n,p\ge 0),

where hh is a constant or a variable and every tit_i is β-normal. x1,…,xnx_1,\dots,x_n is the binder, hh the head, t1,…,tpt_1,\dots,t_p the arguments, and (h t1⋯tp)(h\,t_1\cdots t_p) 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 tit_i 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 f:(𝗂→𝗂)→𝗂f:(\mathsf{i}\to\mathsf{i})\to\mathsf{i}. The term ff is β-normal but not long, since its body has functional type. One η-expansion gives λw f w\lambda w\,f\,w with w:𝗂→𝗂w:\mathsf{i}\to\mathsf{i}. This is still not long, because the argument ww has a non-primitive type. Expanding ww gives λw f (λu w u)\lambda w\,f\,(\lambda u\,w\,u) with u:𝗂u:\mathsf{i}, 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 λx¯ (h t1⋯tp)\lambda\bar x\,(h\,t_1\cdots t_p) is rigid if hh is ∀-bound in the prefix (constants included) or belongs to the binder x¯\bar x. It is flexible if hh 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: λx¯ (h t1⋯tp)\lambda\bar x\,(h\,t_1\cdots t_p) and λx¯ (k s1⋯sq)\lambda\bar x\,(k\,s_1\cdots s_q). Since neither head can change, a unifier can exist only if hh and kk are the same symbol [MN p. 112]. With F,GF,G logic variables and c,dc,d constants, none of the following has a unifier:

{(λx (d (c (F x))))=(λx (c (d (G x))))}{(λx (x (F x)))=(λx (c (G x)))}{(λx λy (x (F x y)))=(λx λy (y (G x y)))} \begin{gathered} \{(\lambda x\,(d\,(c\,(F\,x))))=(\lambda x\,(c\,(d\,(G\,x))))\}\qquad \{(\lambda x\,(x\,(F\,x)))=(\lambda x\,(c\,(G\,x)))\}\\ \{(\lambda x\,\lambda y\,(x\,(F\,x\,y)))=(\lambda x\,\lambda y\,(y\,(G\,x\,y)))\} \end{gathered}

The first one, written precisely, is

∀c ∀d ∃F ∃G [λx (d (c (F x)))=λx (c (d (G x)))]. \forall c\,\forall d\,\exists F\,\exists G\,[\lambda x\,(d\,(c\,(F\,x)))=\lambda x\,(c\,(d\,(G\,x)))].

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

{(λx λy x (F x y))=(λx λy G y y)} \{(\lambda x\,\lambda y\,x\,(F\,x\,y))=(\lambda x\,\lambda y\,G\,y\,y)\}

has no unifier [MN p. 112–113]. Every instance of the left side has head xx. No instance of the right side can contain the bound xx: GG may be instantiated with a term containing a free xx, but that is a different xx.

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, λx λy F (f x (G x))\lambda x\,\lambda y\,F\,(f\,x\,(G\,x)) can become any λx λy t\lambda x\,\lambda y\,t with x,yx,y not free in tt: take F:=λz tF:=\lambda z\,t, which throws its argument away. Some instances also contain xx, such as λx λy (f x x)\lambda x\,\lambda y\,(f\,x\,x), obtained with F:=λz zF:=\lambda z\,z and G:=λz zG:=\lambda z\,z. But no instance contains yy [MN p. 113], because yy is passed to neither FF nor GG, and by Observation 2 substitution cannot introduce it.

Observation 4: a flex–flex pair. Unify λx λy G x\lambda x\,\lambda y\,G\,x with λx λy H y\lambda x\,\lambda y\,H\,y. Instances of the first ignore yy, and instances of the second ignore xx, so a common instance is λx λy t\lambda x\,\lambda y\,t with neither variable free in tt. The “most general” unifier, derived in Chapter 7, is G:=λw TG:=\lambda w\,T and H:=λw TH:=\lambda w\,T, with TT a new variable [MN p. 113]. (Pattern unification calls this step pruning, Chapter 7.)

Tutorial (classifying heads in practice). Take the prefix ∀c ∃F ∃G\forall c\,\exists F\,\exists G and three occurrences:

termheadstatus
λx (c (F x))\lambda x\,(c\,(F\,x))cc, ∀-boundrigid: every instance starts with cc
λx (x (F x))\lambda x\,(x\,(F\,x))xx, in the binderrigid: every instance starts with the bound xx
λx (F (c x))\lambda x\,(F\,(c\,x))FF, ∃-boundflexible: F:=λz zF:=\lambda z\,z makes the head cc

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 n≥1n\ge 1 and two lists s1,…,sns_1,\dots,s_n and t1,…,tnt_1,\dots,t_n of words over {u,v}\{u,v\}, decide whether there is a non-empty sequence i1,…,iki_1,\dots,i_k with 1≤ij≤n1\le i_j\le n such that si1⋯sik=ti1⋯tiks_{i_1}\cdots s_{i_k}=t_{i_1}\cdots t_{i_k}. This problem is undecidable.

Encode a word r=r1⋯rmr=r_1\cdots r_m as r^=λw (r1 (⋯(rm w)⋯ ))\hat r=\lambda w\,(r_1\,(\cdots(r_m\,w)\cdots)), as in Section 4.7.2. Concatenation is then λw (r^ (q^ w))\lambda w\,(\hat r\,(\hat q\,w)). Take a sort 𝗂\mathsf{i} with no constructors, and introduce u,v:𝗂→𝗂u,v:\mathsf{i}\to\mathsf{i} by universal quantifiers [MN p. 114]:

∃F ∃G ∀u ∀v [ (F s^1⋯s^n)=(F t^1⋯t^n)  ∧  (F u⋯u)=λw (u (G u w)) ], \exists F\,\exists G\,\forall u\,\forall v\, [\,(F\,\hat s_1\cdots\hat s_n)=(F\,\hat t_1\cdots\hat t_n)\;\wedge\;(F\,u\cdots u)=\lambda w\,(u\,(G\,u\,w))\,],

with G:(𝗂→𝗂)→𝗂→𝗂G:(\mathsf{i}\to\mathsf{i})\to\mathsf{i}\to\mathsf{i}. For the lists uv,u\mathrm{uv},\mathrm{u} and u,vu\mathrm{u},\mathrm{vu} [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 FF has the second-order type (𝗂→𝗂)→(𝗂→𝗂)→𝗂→𝗂(\mathsf{i}\to\mathsf{i})\to(\mathsf{i}\to\mathsf{i})\to\mathsf{i}\to\mathsf{i}.

Tutorial (why the encoding is correct). Read the prefix. FF and GG come before ∀u ∀v\forall u\,\forall v, so they may not mention uu or vv. They can only rearrange their arguments. 𝗂\mathsf{i} has no constructors, so a closed FF must be λx1…λxn λw d\lambda x_1\dots\lambda x_n\,\lambda w\,d with d:𝗂d:\mathsf{i} built only from x1,…,xn,wx_1,\dots,x_n,w. The only possible shape is d=xi1(⋯(xik w)⋯ )d=x_{i_1}(\cdots(x_{i_k}\,w)\cdots) with k≥0k\ge 0 [MN p. 114].

Read off the index sequence. F s^1⋯s^nF\,\hat s_1\cdots\hat s_n normalises to the word si1⋯siks_{i_1}\cdots s_{i_k}, and the right side to ti1⋯tikt_{i_1}\cdots t_{i_k}. So the first equation says exactly that i1,…,iki_1,\dots,i_k solves the PCP, except in the degenerate case k=0k=0, where both sides are λw w\lambda w\,w.

Exclude k=0k=0. The second equation says that F u⋯uF\,u\cdots u starts with uu, which forces k≥1k\ge 1. In the other direction, a PCP solution gives a unification solution directly [MN p. 114–115]. The argument extends to unifiers and to types 𝗂\mathsf{i} with constructors [MN p. 115].

Check the instance. For uv,u\mathrm{uv},\mathrm{u} / u,vu\mathrm{u},\mathrm{vu}, the sequence 1,21,2 works: uv⋅u=u⋅vu=uvu\mathrm{uv}\cdot\mathrm{u}=\mathrm{u}\cdot\mathrm{vu}=\mathrm{uvu}. This suggests F=λx1 λx2 λw x1 (x2 w)F=\lambda x_1\,\lambda x_2\,\lambda w\,x_1\,(x_2\,w) and G=λy λw y wG=\lambda y\,\lambda w\,y\,w. GG may not mention uu and has to obtain it from its argument. The book does not print this solution. The normaliser of Section 4.3, with u,vu,v 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, ++, ×\times over ℕ\mathbb N) has a solution. No such algorithm exists [MN p. 115]. It is enough to treat equations of the forms x=1x=1, x+y=zx+y=z and x×y=zx\times y=z. Take a sort 𝗂\mathsf{i} without constructors, so that the closed terms of (𝗂→𝗂)→𝗂→𝗂(\mathsf{i}\to\mathsf{i})\to\mathsf{i}\to\mathsf{i} are exactly the Church numerals ⌜n⌝\ulcorner n\urcorner, and give every existential this type. Then [MN p. 115]:

  1. The flex–flex problem ∃N [(λf λx N f (N f x))=(λf λx (N f (f x)))]\exists N\,[(\lambda f\,\lambda x\,N\,f\,(N\,f\,x))=(\lambda f\,\lambda x\,(N\,f\,(f\,x)))] has the unique solution N=⌜1⌝N=\ulcorner 1\urcorner. With N=⌜n⌝N=\ulcorner n\urcorner the sides are f2nxf^{2n}x and fn+1xf^{n+1}x, so 2n=n+12n=n+1.
  2. The flex–flex problem ∃M ∃N ∃P [(λf λx N f (M f x))=(λf λx P f x)]\exists M\,\exists N\,\exists P\,[(\lambda f\,\lambda x\,N\,f\,(M\,f\,x))=(\lambda f\,\lambda x\,P\,f\,x)] has the solution {(N,r),(M,s),(P,t)}\{(N,r),(M,s),(P,t)\} iff r=⌜n⌝r=\ulcorner n\urcorner, s=⌜m⌝s=\ulcorner m\urcorner and t=⌜n+m⌝t=\ulcorner n+m\urcorner for some n,m≥0n,m\ge 0.
  3. The flex–flex problem ∃M ∃N ∃P [(λf λx N (M f) x)=(λf λx P f x)]\exists M\,\exists N\,\exists P\,[(\lambda f\,\lambda x\,N\,(M\,f)\,x)=(\lambda f\,\lambda x\,P\,f\,x)] has the solution {(N,r),(M,s),(P,t)}\{(N,r),(M,s),(P,t)\} iff r=⌜n⌝r=\ulcorner n\urcorner, s=⌜m⌝s=\ulcorner m\urcorner and t=⌜n×m⌝t=\ulcorner n\times m\urcorner.

Remark 4.22 (An erratum in the addition gadget). The book prints the left side of item 2 as λf λx (N f) (M f) x\lambda f\,\lambda x\,(N\,f)\,(M\,f)\,x [MN p. 115]. This parses as ((N f) (M f)) x((N\,f)\,(M\,f))\,x, which is ill-typed, since N f:𝗂→𝗂N\,f:\mathsf{i}\to\mathsf{i} is applied to M f:𝗂→𝗂M\,f:\mathsf{i}\to\mathsf{i}. The intended term is the addition combinator of Section 4.3.1, λf λx N f (M f x)\lambda f\,\lambda x\,N\,f\,(M\,f\,x), 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 ℕ\mathbb N-variable and one equation per equation. The problem has a solution iff the system has a solution in ℕ\mathbb N. 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 U:𝗂U:\mathsf{i} and set every existential to λf λx U\lambda f\,\lambda x\,U. Both sides of every gadget then normalise to λf λx U\lambda f\,\lambda x\,U. This term is not closed, so it is not a solution [MN p. 116]. The run above confirms both facts for gadget 1. Among ⌜0⌝,…,⌜3⌝\ulcorner 0\urcorner,\dots,\ulcorner 3\urcorner only ⌜1⌝\ulcorner 1\urcorner works, and λf λx U\lambda f\,\lambda x\,U 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 𝗈\mathsf{o}, the quantifiers are constants ∀,∃:(A→𝗈)→𝗈\forall,\exists:(A\to\mathsf{o})\to\mathsf{o} 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 (22n2^{2^n} in the book’s series, see the erratum). Practical programs avoid this through built-in data, order-0 binders and LλL_\lambda.
  • A unification problem is a quantified formula Q1x1…Qnxn [⋀tj=sj]Q_1x_1\dots Q_nx_n\,[\bigwedge t_j=s_j]. An existential may use only what is quantified to its left. pi and λ both introduce universals, which is why pi y\ X = y and (y\ X) = (y\ y) fail.
  • Raising (∀y ∃x G⇝∃h ∀y G[(h y)/x]\forall y\,\exists x\,G\rightsquigarrow\exists h\,\forall y\,G[(h\,y)/x]) 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.