Chapter 7

Unification of λ-terms and higher-order patterns

7.1What this chapter is about

The previous chapters built programs whose execution keeps asking one question: find values for the logic variables that make two λ\lambda-terms equal modulo α\alpha, β\beta and η\eta. Chapter 4 showed how such questions are written as quantified formulas; Chapter 5 and Chapter 6 produced them by the thousand, from higher-order predicates such as mappred and from the pi x\ ... goals that walk under binders in λ\lambda-tree syntax. Chapter 6 also isolated the fragment LλL_\lambda, in which a logic variable is applied only to distinct bound variables. This chapter, which follows Chapter 8 of the bookDale Miller and Gopalan Nadathur. Programming with Higher-Order Logic. Cambridge University Press, Cambridge, 2012, explains how an implementation solves these questions, and why LλL_\lambda is the fragment to aim for.

The story has two halves.

  1. General higher-order unification is hard: there may be no most general unifier, complete sets of unifiers may be infinite, and unifiability is undecidable (Section 7.3). Still, Huet’s procedureGérard Huet. A unification algorithm for typed λ\lambda-calculus. Theoretical Computer Science, 1:27–57, 1975 organises the search (Section 7.4): it simplifies rigid-rigid equations, guesses imitation or projection substitutions for flexible-rigid ones, and stops when only flexible-flexible equations are left. Its search space is a matching tree, which can be infinite.
  2. Higher-order pattern unification (LλL_\lambda-unification, Section 7.5 and Section 7.6) is the same procedure restricted to patterns. There it becomes deterministic, has most general unifiers and, with an occurs-check, terminatesDale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991. Its final form, variable elimination, is “computationally similar to first-order unification” [MN p. 224]: one walk over the rigid side that inverts it, prunes, and checks occurrences and scope.

We then do the algorithm by hand on the book’s examples (Section 7.7), rebuild Nipkow’s de Bruijn implementationTobias Nipkow. Functional unification of higher-order patterns. In M. Vardi, editor, 8th Symposium on Logic in Computer Science, pages 64–74, New York, 1993. IEEE and run a Scheme transliteration of it (Section 7.8), and finish with what real systems do: universe levels instead of raising, and delayed non-pattern equations (Section 7.9). If you only need the implementer’s digest, read Definition 7.21 and Theorem 7.22 and Section 7.8 and Section 7.9.

Conventions. As in the book’s Chapter 8, uppercase F,G,H,U,V,W,X,YF,G,H, U,V,W, X,Y are existentially quantified variables (logic variables), and lowercase a,b,c,d,f,g,u,w,x,y,za,b,c,d, f,g,u, w,x,y,z are universally quantified ones (signature constants or eigenvariables). x¯\bar x abbreviates x1…xnx_1\dots x_n, and (F x¯)(F\,\bar x) is (F x1…xn)(F\,x_1\dots x_n).

7.2Unification problems and their normal form

Definition 7.1 (Unification problem [MN p. 211]). A unification problem is a formula

Q1x1…Qnxn [ t1=s1∧⋯∧tm=sm ] Q_1x_1\dots Q_nx_n\,[\,t_1=s_1\wedge\dots\wedge t_m=s_m\,]

where n,m≥0n,m\ge 0, each QiQ_i is ∀\forall or ∃\exists, and tjt_j, sjs_j are λ\lambda-terms of the same type. The quantifier sequence is the prefix, the conjunction is the matrix. A unifier is a substitution for the existentially quantified variables that makes every tjt_j λ\lambda-convertible to sjs_j.

Reading the problem as a formula is what makes the scoping right. In ∃X ∀y [X=y]\exists X\,\forall y\,[X=y] no unifier exists, because XX is chosen before yy and cannot mention it; in ∀y ∃X [X=y]\forall y\,\exists X\,[X=y] the unifier is X:=yX:=y. A miniKanren with only first-order terms never sees the difference because it has no universal quantifier in goals; a λProlog with pi sees it all the time.

Chapter 4 distinguished a unifier from a solution, which in addition uses only closed terms and therefore “embodies an actual proof of the quantified formula”; following common practice the book’s Chapter 8 limits itself to unifiers [MN p. 211].The difference matters with empty types; see the last pitfall of Section 7.9.1.

7.2.1The normal form assumed by the algorithms

Before solving, the book puts every problem in a fixed shape [MN p. 212]. The four steps are worth knowing one by one, because an implementation performs each of them lazily.

  1. A ∀∃∀\forall\exists\forall prefix. Using raising [MN p. 107–108], the formulas ∀y ∃x G\forall y\,\exists x\,G and ∃h ∀y G[(h y)/x]\exists h\,\forall y\,G[(h\,y)/x] are equiprovable when h:σ→τh:\sigma\to\tau for y:σy:\sigma, x:τx:\tau. Moving every ∃\exists to the left of every ∀\forall in this way yields a prefix ∀a¯  ∃X¯  ∀y¯\forall\bar a\;\exists\bar X\;\forall\bar y. The outer ∀a¯\forall\bar a represent “the ambient signature comprising the declared constants in a λProlog program, and we will interpret them as such” [MN p. 212]. The price: “the type of the variable that is existentially quantified needs to be ‘raised’ by the type of the universally quantified variable” [MN p. 108].

  2. Substitution as β\beta-redex. For θ={⟨x1,t1⟩,…,⟨xn,tn⟩}\theta=\{\langle x_1,t_1\rangle,\dots,\langle x_n,t_n\rangle\}, the book defines [MN p. 212]

    θ(t):=((λx1…λxn t) t1…tn). \theta(t):=((\lambda x_1\dots\lambda x_n\,t)\,t_1\dots t_n).

    Thus θ(t)\theta(t) and θ(t′)\theta(t') are equal whenever tt and t′t' are λ\lambda-convertible, and we may assume all terms are in β\beta-normal form.

  3. Equal binders. By η\eta-conversion the two sides of every equation get binders of the same length.

  4. Binders become universals. Using (λx t=λx s)≡∀x (t=s)(\lambda x\,t=\lambda x\,s)\equiv\forall x\,(t=s) and moving such ∀x\forall x out of the conjunction, the binders at the heads of the equations turn into universals that extend the inner block. After this step “the equations in the matrix are between terms that have empty binders. We shall assume that all unification problems are of this kind” [MN p. 212].

Example 7.2 (Normalising a flexible-flexible problem). Chapter 4 met the problem [MN p. 113]

∃G ∃H [λxλy (G x)=λxλy (H y)]. \exists G\,\exists H\,[\lambda x\lambda y\,(G\,x)=\lambda x\lambda y\,(H\,y)].

Step 4 turns it into ∃G ∃H ∀x ∀y [(G x)=(H y)]\exists G\,\exists H\,\forall x\,\forall y\,[(G\,x)=(H\,y)]. Now xx and yy are universals quantified inside the scope of GG and HH. Any common instance must be a term in which neither xx nor yy occurs, and the book announces that the “most general” unifier substitutes λw T\lambda w\,T for both GG and HH, with TT new [MN p. 113]. We derive it in Example 7.27.

Remark 7.3. Step 4 is exactly what an implementation does when it meets λx s=λx t\lambda x\,s=\lambda x\,t: open both binders with one fresh eigenvariable and continue. Because the new ∀\forall goes at the end of the prefix, no existing logic variable may depend on it, which is what a “newest level” eigenvariable gives you (Section 7.9).

Definition 7.4 (Rigid and flexible [MN p. 214], [MN p. 113]). In a normalised problem, a term on either side of an equation is rigid if its head is bound by a universal quantifier of the prefix, and flexible if its head is bound by an existential one. Equations are accordingly rigid-rigid, rigid-flexible, flexible-rigid or flexible-flexible; a problem is flexible-flexible if all its equations are.

The key fact about a rigid term is that “its head is unaffected by any substitutions that might be made for existentially quantified variables” [MN p. 214]. A flexible head, on the other hand, can be replaced by any term, including one that throws away or reorders the head’s arguments. This asymmetry drives every rule below.

Kanren angle (first-order unification is the degenerate case). In (aux kanren micro) every Scheme atom, pair, vector or record constructor plays the role of an outer universal ∀a¯\forall\bar a (a rigid head), and every logic variable is an existential. There is no inner ∀\forall block and no logic variable is ever applied to arguments, so every flexible term is a bare XX, which is a pattern with n=0n=0. The unifier μkanren-state-unify is precisely the rigid-rigid decomposition plus the n=0n=0 case of variable elimination (bind XX after an occurs-check). Everything in this chapter is an extension of that code path, not a replacement. What a higher-order extension needs is: inner universals (eigenvariables) as a new kind of rigid head, binders, applications of logic variables, and a scope discipline; see Chapter 11.

7.3Why general higher-order unification is hard

Recall from first-order unification (Chapter 2) that a most general unifier (mgu) is a unifier from which every other unifier is obtained “by making further substitutions” [MN p. 212]. It satisfies all the constraints while leaving every other way of satisfying them open, which is what makes Prolog’s and miniKanren’s “one substitution per answer” work. At higher order this breaks down in three ways.

Example 7.5 (No mgu [MN p. 213]). Let a:ia:i, g:i→i→ig:i\to i\to i, F:i→iF:i\to i and consider ∀a ∀g ∃F [(F a)=(g a a)]\forall a\,\forall g\,\exists F\,[(F\,a)=(g\,a\,a)]. It has exactly four unifiers,

F:=λx (g x x),F:=λx (g a x),F:=λx (g x a),F:=λx (g a a), F:=\lambda x\,(g\,x\,x),\qquad F:=\lambda x\,(g\,a\,x),\qquad F:=\lambda x\,(g\,x\,a),\qquad F:=\lambda x\,(g\,a\,a),

because each occurrence of aa on the right can come either from the argument of FF or from the constant itself. All four are closed, so none is an instance of another: there is no mgu.

Definition 7.6 (Complete set of unifiers [MN p. 213]). A set 𝒰\mathcal U of substitutions is a complete set of unifiers (CSU) for a problem if every member of 𝒰\mathcal U is a unifier, and every unifier is obtained from some member of 𝒰\mathcal U by a further substitution. One would like 𝒰\mathcal U to be finite.

Example 7.7 (No finite CSU [MN p. 213]). With w:iw:i and F,u:i→iF,u:i\to i, the problem

∀u ∃F ∀w [(u (F w))=(F (u w))] \forall u\,\exists F\,\forall w\,[(u\,(F\,w))=(F\,(u\,w))]

is solved by F:=λy yF:=\lambda y\,y, λy (u y)\lambda y\,(u\,y), λy (u (u y))\lambda y\,(u\,(u\,y)), …, that is, by every power uku^k. Each of these is closed, so every CSU contains all of them.

One might settle for a CSU without redundancy, in which no two members have a common instance; but “a general guarantee of this kind of nonredundancy cannot be given in the higher-order setting” [MN p. 213]. Worse, unifiability itself is undecidable: Chapter 4 encoded the Post correspondence problem as a unification problem [MN p. 114], so “higher-order unification also must be undecidable” [MN p. 214]. The bibliographic notes add that undecidability already holds at third order (Huet; Lucchesi) and even at second order (Goldfarb, 1981), while matching, where only one side contains existential variables, is decidable (second order: Huet and Lang 1978; third order: Dowek 1992; general case: Stirling 2009) [MN p. 226–227].

Pitfall (do not promise “the” answer). A higher-order equation in general has no single best answer, may have infinitely many incomparable ones, and may run forever without being able to report “no”. Any design that represents an answer as one substitution, as (aux kanren micro) does, can be exact only on a fragment that has mgus. That fragment is LλL_\lambda.

7.4Huet’s procedure

Despite all of the above there is a systematic, complete search [MN p. 214]. We present it as a rewrite system on pairs ⟨𝒬;E⟩\langle\mathcal Q;E\rangle of a prefix and a multiset of equations, in the style of Snyder and Gallier that the book mentions as an alternative presentation [MN p. 227]. The side conditions and substitution terms are the book’s; the rule names are ours.

7.4.1Simplification of rigid-rigid equations

⟨𝒬; {(c s1…sn)=(c t1…tn)}⊎E⟩⟨𝒬; {s1=t1,…,sn=tn}∪E⟩  Dec⟨𝒬; {(c s¯)=(d t¯)}⊎E⟩⊥  Clash  (c≠d) \dfrac{\langle\mathcal Q;\ \{(c\,s_1\dots s_n)=(c\,t_1\dots t_n)\}\uplus E\rangle}{\langle\mathcal Q;\ \{s_1=t_1,\dots,s_n=t_n\}\cup E\rangle}\;\text{Dec} \qquad \dfrac{\langle\mathcal Q;\ \{(c\,\bar s)=(d\,\bar t)\}\uplus E\rangle}{\bot}\;\text{Clash}\ \ (c\neq d)

Here cc, dd are universally quantified in 𝒬\mathcal Q; for n=0n=0, Dec just deletes the equation. Since the head of a rigid term can never change, an equation between rigid terms with different heads is hopeless, and one with equal heads is equivalent to the equations between the arguments. Dec removes two symbols from the problem [MN p. 214]. “The process of repeatedly treating all rigid-rigid pairs in this fashion will be called simplification” [MN p. 214]. Rigid-flexible equations are turned around and treated as flexible-rigid ones.

7.4.2Imitation and projection

Take a flexible-rigid equation

(F t1…tn)=(c s1…sm),F:τ1→⋯→τn→β,c:σ1→⋯→σm→β, (F\,t_1\dots t_n)=(c\,s_1\dots s_m),\qquad F:\tau_1\to\dots\to\tau_n\to\beta,\quad c:\sigma_1\to\dots\to\sigma_m\to\beta,

with β\beta primitive. “This equation can be proved only by making the head of the left term identical to cc” [MN p. 215], and there are only two ways to do that: the term substituted for FF has head cc itself, or it uses one of FF’s arguments as head.

Definition 7.8 (Imitation and projection [MN p. 215–216]).

  • The imitation substitution, allowed only if “the quantification over FF occurs within the scope of the quantifier that binds cc”, is

    θimit={⟨F, λx1…λxn (c (H1 x1…xn)⋯(Hm x1…xn))⟩} \theta_{\mathrm{imit}}=\{\langle F,\ \lambda x_1\dots\lambda x_n\,(c\,(H_1\,x_1\dots x_n)\cdots(H_m\,x_1\dots x_n))\rangle\}

    with fresh Hi:τ1→⋯→τn→σiH_i:\tau_1\to\dots\to\tau_n\to\sigma_i.

  • The ii-th projection substitution, allowed only if the target type of τi\tau_i is β\beta, say τi=φ1→⋯→φk→β\tau_i=\varphi_1\to\dots\to\varphi_k\to\beta, is

    θproji={⟨F, λx1…λxn (xi (H1 x1…xn)⋯(Hk x1…xn))⟩} \theta_{\mathrm{proj}_i}=\{\langle F,\ \lambda x_1\dots\lambda x_n\,(x_i\,(H_1\,x_1\dots x_n)\cdots(H_k\,x_1\dots x_n))\rangle\}

    with fresh Hj:τ1→⋯→τn→φjH_j:\tau_1\to\dots\to\tau_n\to\varphi_j.

In both cases ∃F\exists F is replaced in the prefix by the new ∃Hj\exists H_j at the same place, θ\theta is applied to the matrix, and the result is β\beta-normalised.

The design idea is minimal commitment. Imitation fixes only the head cc and leaves “all choices of what the arguments should be to the determination of substitutions for the HjH_j variables in subsequent steps” [MN p. 215]; each HjH_j receives all of FF’s arguments, so nothing is lost. Projection commits FF “only to projecting onto its iith argument” [MN p. 216]. For one flexible-rigid equation there may or may not be an imitation and there are between 00 and nn projections, so “up to n+1n+1 substitutions may have to be considered” [MN p. 216].

Pitfall (imitation is scope-sensitive, projection is type-sensitive). Imitating cc is illegal when cc is quantified inside the scope of FF: FF cannot mention it. This side condition is the logical root of every “eigenvariable escape” check. Projection needs the target type and the arity of τi\tau_i, and imitation needs the arity mm of cc and its argument types σi\sigma_i: Huet’s procedure cannot run without types. Pattern unification can (Section 7.6).

7.4.3A complete run, and the matching tree

Tutorial (Huet’s procedure on (F a) = (g a a)). We solve Example 7.5, following the book [MN p. 216–217].

  1. The only equation is flexible-rigid with head gg, and ∀g\forall g is to the left of ∃F\exists F, so imitation is allowed: F:=λx (g (H1 x) (H2 x))F:=\lambda x\,(g\,(H_1\,x)\,(H_2\,x)) with H1,H2:i→iH_1,H_2:i\to i. The single projection is F:=λx xF:=\lambda x\,x (the argument type ii is the target type).
  2. Projection gives ∀a ∀g [a=(g a a)]\forall a\,\forall g\,[a=(g\,a\,a)]: a rigid-rigid clash, a dead end.
  3. Imitation gives ∀a ∀g ∃H1 ∃H2 [(g (H1 a) (H2 a))=(g a a)]\forall a\,\forall g\,\exists H_1\,\exists H_2\,[(g\,(H_1\,a)\,(H_2\,a))=(g\,a\,a)], which Dec simplifies to [(H1 a)=a∧(H2 a)=a][(H_1\,a)=a\wedge(H_2\,a)=a].
  4. For (H1 a)=a(H_1\,a)=a both the imitation λx a\lambda x\,a and the projection λx x\lambda x\,x work; either leaves [⊤∧(H2 a)=a][\top\wedge(H_2\,a)=a].
  5. The same two choices for H2H_2 empty the matrix.

Composing the substitutions along the four successful paths gives the four unifiers λx (g a a)\lambda x\,(g\,a\,a), λx (g a x)\lambda x\,(g\,a\,x), λx (g x a)\lambda x\,(g\,x\,a), λx (g x x)\lambda x\,(g\,x\,x) [MN p. 217], in the order of a left-to-right depth-first walk of Figure 7.1.

Figure 7.1: The matching tree for ∀a ∀g ∃F ((F a)=(g a a))\forall a\,\forall g\,\exists F\,((F\,a)=(g\,a\,a)), after Figure 8.1 of the book [MN p. 219]. Arcs are labelled by substitutions; 𝐅\mathbf{F} marks a failure node; the four {}\{\} leaves are success nodes.The matching tree for $\forall a\,\forall g\,\exists F\,((F\,a)=(g\,a\,a))$, after Figure 8.1 of the book [MN p. 219]. Arcs are labelled by substitutions; $\mathbf{F}$ marks a failure node; the four $\{\}$ leaves are success nodes.

Definition 7.9 (Matching tree [MN p. 219]). The matching tree of a problem has as nodes the simplified matrices, viewed as multisets of equations (the prefix is implicit), and as arcs the imitation and projection substitutions for one selected flexible-rigid equation. Leaves are failure nodes, “for which it is immediately apparent that there are no solutions”, or success nodes, whose matrix contains at most flexible-flexible equations. The pre-unifier of a success node is the composition of the arc labels on the path to it.

Theorem 7.10 (Completeness of matching trees [MN p. 219–220]). If the problem at the root has a unifier, then the tree has a success node at a finite depth, and that unifier is obtained by composing the pre-unifier of the success node with a unifier of the problem at that node. This holds however the flexible-rigid equation to expand is chosen at each node.

So the choice of which equation to work on is don’t-care nondeterminism, while the choice of which substitution is don’t-know nondeterminism. The bibliographic notes add that Huet’s procedure, “which is limited to determining unifiability, is nonredundant” [MN p. 227].

7.4.4Flexible-flexible equations and pre-unification

Why stop at flexible-flexible equations? Because they always have a unifier, and their unifiers are uncontrollable.

Example 7.11 (A flexible-flexible residue [MN p. 217]). With a:ia:i and X,Y,g:i→iX,Y,g:i\to i, take ∀a ∀g ∃X ∃Y [(X a)=(g (Y a))]\forall a\,\forall g\,\exists X\,\exists Y\,[(X\,a)=(g\,(Y\,a))]. Imitation X:=λx (g (H x))X:=\lambda x\,(g\,(H\,x)) and simplification give ∀a ∀g ∃H ∃Y [(H a)=(Y a)]\forall a\,\forall g\,\exists H\,\exists Y\,[(H\,a)=(Y\,a)], which no rule can reduce further. (The other alternative for XX, the projection X:=λx xX:=\lambda x\,x, gives a=(g (Y a))a=(g\,(Y\,a)), a rigid-rigid clash.) The residue has the unifier H,Y:=λx aH,Y:=\lambda x\,a (making X=λx (g a)X=\lambda x\,(g\,a)), and many more: any term built from aa, gg and other existentials, abstracted over some of the occurrences of aa, will do, “too large and uncontrolled a set to try to generate explicitly” [MN p. 218].

Proposition 7.12 (Canonical substitution [MN p. 217–218]). Associate with each primitive type τ\tau a fixed new existential variable HτH^\tau, and with each type τ1→⋯→τn→σ\tau_1\to\dots\to\tau_n\to\sigma (σ\sigma primitive) the canonical constant term λx1…λxn Hσ\lambda x_1\dots\lambda x_n\,H^\sigma. The canonical substitution maps every existential variable of the prefix to the canonical constant term of its type. For a problem with only flexible-flexible equations, the canonical substitution is a unifier.

The reason is simple: under it both sides of every equation become HβH^\beta. For Example 7.11, with WW the variable chosen for ii, the canonical substitution is {⟨H,λx W⟩,⟨Y,λx W⟩}\{\langle H,\lambda x\,W\rangle,\langle Y,\lambda x\,W\rangle\} [MN p. 217]. Hence: “The reduction of a unification problem to a flexible-flexible form thus constitutes success from the perspective of determining unifiability. The process of carrying out such a reduction is known as pre-unification, and the substitution that leads to the corresponding success is called a pre-unifier” [MN p. 218].

7.4.5Non-termination

Example 7.13 (An infinite branch with infinitely many answers [MN p. 218]). Let x:ix:i and g,F:i→ig,F:i\to i: ∀g ∃F ∀x [(F (g x))=(g (F x))]\forall g\,\exists F\,\forall x\,[(F\,(g\,x))=(g\,(F\,x))]. The single projection F:=λx xF:=\lambda x\,x solves it. The imitation F:=λx (g (H x))F:=\lambda x\,(g\,(H\,x)) followed by simplification gives ∀g ∃H ∀x [(H (g x))=(g (H x))]\forall g\,\exists H\,\forall x\,[(H\,(g\,x))=(g\,(H\,x))]: the same problem with HH in place of FF. Repeating forever, the paths of the tree yield F:=λx x, λx (g x), λx (g (g x)),…F:=\lambda x\,x,\ \lambda x\,(g\,x),\ \lambda x\,(g\,(g\,x)),\dots

Example 7.14 (An infinite branch and no answer [MN p. 220]). Add a second equation, with constants a,b:ia,b:i: ∀g ∃F ∀x [((F (g x))=(g (F x)))∧(F a)=(F b)]\forall g\,\exists F\,\forall x\,[((F\,(g\,x))=(g\,(F\,x)))\wedge(F\,a)=(F\,b)]. “The second equation in the matrix here causes each of the unifiers that we have seen for the first equation to be rejected” [MN p. 220]: F=gkF=g^k gives gk a=gk bg^k\,a=g^k\,b, a clash. The tree has no success node but has an infinite path. As unifiability is undecidable, such problems must exist [MN p. 220].

Kanren angle (the matching tree is a miniKanren search tree). Imitation versus projection is don’t-know choice among at most n+1n+1 alternatives, i.e. a disjunction; the matching tree is the search tree of those disjunctions. A depth-first interpreter, like λProlog’s, can be trapped in the infinite imitation branch of Example 7.13 before it ever tries the projection. miniKanren’s interleaving or° instead reaches every success node at finite depth, provided each expansion step is guarded by a suspension (as define-relation and fresh° provide). The fairness is skewed: or° nests the binary interleaving to the right, so with kk alternatives the first one gets about half of the steps; and conjunction gives no fairness guarantee across an infinite first conjunct. Two hard limits remain. First, Example 7.14 makes even (run 1 ...) diverge, and no search strategy can fix that. Second, imitation and projection need types at run time, which (aux kanren micro) does not have. A Huet layer is therefore at best an opt-in, typed search over equations that the deterministic core has set aside; see Section 14.5.4 (and Section 11.2 for why Huet’s search is not the meaning of =°).

7.5Higher-order patterns

Chapter 6 introduced LλL_\lambda as a programming discipline. The book recalls it as follows.

Definition 7.15 (The Lλ condition [MN p. 220]).Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991 A program clause or goal formula BB is in LλL_\lambda if all quantification in BB is over non-predicate types and “every subterm of BB of the form (x t1…tn)(x\,t_1\dots t_n) in which xx is an essentially existentially quantified variable is such that t1,…,tnt_1,\dots,t_n are distinct variables that are universally quantified within the scope of the quantifier binding xx” [MN p. 220]. Transposed to a unification problem: every flexible subterm (F t1…tn)(F\,t_1\dots t_n) has as arguments distinct universal variables quantified to the right of FF in the prefix. Such a term is a (higher-order) pattern.

The case n=0n=0 is allowed, so a bare logic variable is a pattern, and first-order unification is a special case. Miller’s formal definitionDale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, Fig. 3, p. 10–11 is a judgement Q⊢0t:τQ\vdash_0 t:\tau relative to a prefix QQ, whose key rule says that x y1⋯ynx\,y_1\cdots y_n is well formed when “xx is existentially quantified in QQ to the left of where the distinct variables y1…yny_1\dots y_n are universally quantified”. Table 7.1 gives a feel for the definition.

Table 7.1: Patterns and non-patterns among the chapter’s examples.
problempattern?why
∃F ∀x ∀y [(F x y)=… ]\exists F\,\forall x\,\forall y\,[(F\,x\,y)=\dots]yesdistinct universals, right of FF
∀a ∃F [(F a)=… ]\forall a\,\exists F\,[(F\,a)=\dots] (Example 7.5)noaa is quantified outside FF
∃F ∀x [(F x x)=x]\exists F\,\forall x\,[(F\,x\,x)=x]noarguments not distinct
∀g ∃F ∀x [(F (g x))=… ]\forall g\,\exists F\,\forall x\,[(F\,(g\,x))=\dots] (Example 7.13)noargument is not a variable
∃F ∃N [(F N)=… ]\exists F\,\exists N\,[(F\,N)=\dots] (the subst clause)noargument is existential
∀f ∃X [X=(f X)]\forall f\,\exists X\,[X=(f\,X)]yesn=0n=0

Example 7.16 (Discharging a constant, p. 4–5).Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991 Miller motivates the fragment with append. With the program

∀x ∀l ∀k ∀m (append l k m⊃append (cons x l) k (cons x m)),∀k (append nil k k), \forall x\,\forall l\,\forall k\,\forall m\,(\mathit{append}\ l\ k\ m\supset\mathit{append}\ (\mathit{cons}\ x\ l)\ k\ (\mathit{cons}\ x\ m)), \qquad\forall k\,(\mathit{append}\ \mathit{nil}\ k\ k),

try to find XX such that ∀y (append (cons a (cons b nil)) y X)\forall y\,(\mathit{append}\ (\mathit{cons}\ a\ (\mathit{cons}\ b\ \mathit{nil}))\ y\ X) is provable. The ∀y\forall y introduces a new constant kk, and two backchaining steps succeed only if XX is instantiated with (cons a (cons b k))(\mathit{cons}\ a\ (\mathit{cons}\ b\ k)), which is impossible because XX was chosen before kk existed. “Such a failure here is quite sensible since the value of XX should be independent of the choice of the constant used to instantiate ∀y\forall y”. Now ask instead for ∀y (append (cons a (cons b nil)) y (H y))\forall y\,(\mathit{append}\ (\mathit{cons}\ a\ (\mathit{cons}\ b\ \mathit{nil}))\ y\ (H\,y)). The same steps produce the pattern equation

(H k)=(cons a (cons b k)). (H\,k)=(\mathit{cons}\ a\ (\mathit{cons}\ b\ k)).

Two λ\lambda-terms for HH make it true,

λw (cons a (cons b k))andλw (cons a (cons b w)), \lambda w\,(\mathit{cons}\ a\ (\mathit{cons}\ b\ k))\quad\text{and}\quad \lambda w\,(\mathit{cons}\ a\ (\mathit{cons}\ b\ w)),

but “since HH cannot contain kk free, only the second of these possible substitutions will succeed”. Miller calls this discharging the constant kk from the term: HH is the computed answer with the choice of eigenvariable abstracted away. In terms of Huet’s procedure: imitation of cons\mathit{cons}, aa, cons\mathit{cons}, bb is forced, and at the leaf kk only the projection is legal, because imitating kk would violate the scope condition. The pattern algorithm below does this in one walk.

Definition 7.17 (β₀ [MN p. 206]). β0\beta_0-conversion is the special case (λx s) x=s(\lambda x\,s)\,x=s of β\beta; with α\alpha it is equivalent to (λy s) x=s[x/y](\lambda y\,s)\,x=s[x/y], provided xx is not free in λy s\lambda y\,s.

Under the LλL_\lambda condition, instantiating a logic variable only ever creates β0\beta_0-redexes: “simply replacing the bound variables within the body of an abstraction with a new set of names” [MN p. 220]. A β0\beta_0-step makes the term smaller, so we may expect its inverse, LλL_\lambda-unification, to be much better behaved than inverting full β\beta [MN p. 220].

Pitfall (β₀ alone is not enough). LλL_\lambda problems are unification problems modulo α,β0,η\alpha,\beta_0,\eta, but not conversely. The problem ∀x (F x x=x)\forall x\,(F\,x\,x=x) needs only β0\beta_0, yet has the two incomparable unifiers λuλv u\lambda u\lambda v\,u and λuλv v\lambda u\lambda v\,v [MN p. 208]. The distinctness of the arguments is what buys most general unifiers, not merely the shape of the redexes.

7.5.1Why the procedure becomes deterministic

Raising preserves the LλL_\lambda condition [MN p. 208, 220–221], so we may still assume a ∀a¯ ∃X¯ ∀y¯\forall\bar a\,\exists\bar X\,\forall\bar y prefix, and rigid-rigid simplification “applies unchanged” [MN p. 221]. The interesting case is flexible-rigid.

Lemma 7.18 (At most one useful substitution [MN p. 221]). Let (F c1…cn)=(c t1…tm)(F\,c_1\dots c_n)=(c\,t_1\dots t_m) with FF existential and c1,…,cnc_1,\dots,c_n distinct universals quantified in the scope of FF. Then at most one imitation or projection substitution avoids an immediate clash.

Argument. If FF is in the scope of cc (cc is to the left of FF, e.g. a signature constant), then cc differs from every cic_i, which are to the right of FF; every projection produces a head ci≠cc_i\ne c and clashes, so only imitation can succeed. If cc is in the scope of FF, imitation is not allowed, and the ii-th projection succeeds only if ci=cc_i=c; since the cic_i are distinct, at most one ii qualifies, and if c∉c¯c\notin\bar c the equation fails. “The preceding observations can be built into the substitution selection process so as to make it entirely deterministic” [MN p. 221]. □

Moreover the class is preserved: the substitutions considered have the form

λx1…λxn (@ (H1 x1…xn)⋯(Hk x1…xn)) \lambda x_1\dots\lambda x_n\,(@\,(H_1\,x_1\dots x_n)\cdots(H_k\,x_1\dots x_n))

with @@ either cc or some xix_i and the HjH_j quantified where FF was; substituted into (F c1…cn)(F\,c_1\dots c_n) and β0\beta_0-reduced, it yields again patterns (Hj c1…cn)(H_j\,c_1\dots c_n) [MN p. 221].

7.5.2Flexible-flexible pattern equations have mgus

Here is the second change. In LλL_\lambda a flexible-flexible equation has the form

(F c1…cn)=(G d1…dm), (F\,c_1\dots c_n)=(G\,d_1\dots d_m),

with the cic_i and djd_j universals in the scope of FF and GG, and in a ∀∃∀\forall\exists\forall prefix FF and GG are “effectively bound ‘at the same place’” [MN p. 222].

Proposition 7.19 (Flexible-flexible mgus [MN p. 222]). Let HH be a new existential quantified at the place of FF.

  • Different heads (F≠GF\ne G). Let e1,…,eℓe_1,\dots,e_\ell list the variables common to c1,…,cnc_1,\dots,c_n and d1,…,dmd_1,\dots,d_m. Then

    {⟨F, λc1…λcn (H e1…eℓ)⟩, ⟨G, λd1…λdm (H e1…eℓ)⟩} \{\langle F,\ \lambda c_1\dots\lambda c_n\,(H\,e_1\dots e_\ell)\rangle,\ \langle G,\ \lambda d_1\dots\lambda d_m\,(H\,e_1\dots e_\ell)\rangle\}

    is an mgu.

  • Same head (F=GF=G, so n=mn=m). Let e1,…,eℓe_1,\dots,e_\ell list the cic_i such that ci=dic_i=d_i. Then

    {⟨F, λc1…λcn (H e1…eℓ)⟩} \{\langle F,\ \lambda c_1\dots\lambda c_n\,(H\,e_1\dots e_\ell)\rangle\}

    is an mgu.

In the first case a common instance tt cannot contain a cic_i that is not also among the djd_j, and conversely; every such tt is an instance of (H e¯)(H\,\bar e). In the second case the same substitution acts on both sides, so a variable survives only if it sits in the same argument position on both sides [MN p. 222]. (The binders reuse the names cic_i, so in λc1…λcn (H e1…eℓ)\lambda c_1\dots\lambda c_n\,(H\,e_1\dots e_\ell) the ee’s are bound.)

Pitfall (same head: positions, not sets). For ∀x ∀y [(F x y)=(F y x)]\forall x\,\forall y\,[(F\,x\,y)=(F\,y\,x)] the arguments are the same set, but no position agrees, so ℓ=0\ell=0 and the mgu is F:=λxλy HF:=\lambda x\lambda y\,H. Intersecting sets, as in the different-heads case, would wrongly keep both arguments.

Theorem 7.20 (Mgus for higher-order patterns [MN p. 222]).Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991 “By combining the completeness property of matching trees with the observations that there is at most one productive path in the tree and that most general unifiers can be provided for flexible-flexible pairs in the LλL_\lambda setting, it follows that the higher-order pattern unification problem possesses the property of having most general unifiers” [MN p. 222]. For ∀∃∀\forall\exists\forall problems the mgu is unique up to renaming of variablesDale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, Prop. 9.2.

7.5.3Termination needs the occurs-check

The procedure so far may still loop, even on first-order problems. For ∀f ∃X [X=(f X)]\forall f\,\exists X\,[X=(f\,X)] the only useful substitution is the imitation X:=(f H)X:=(f\,H), which produces ∀f ∃H [H=(f H)]\forall f\,\exists H\,[H=(f\,H)], “identical to the one with which we started” [MN p. 222]. In LλL_\lambda such behaviour arises only when the flexible head occurs in the rigid side; so “we can ensure termination for the unification procedure by adding an ‘occurs-check’ to the substitution-generation step” [MN p. 223]. Note that in LλL_\lambda every occurrence of FF in the rigid side is fatal: since pattern arguments are variables, there is no flexible occurrence that a later substitution could erase.

7.6The pattern unification algorithm

The book’s final step is to fuse the imitation and projection traversal with the occurs-check traversal into “a larger, more efficient substitution generation operation” [MN p. 223], called variable elimination “because of its similarity to an operation of the same name discussed for first-order unification” [MN p. 223]. We now state the whole algorithm precisely. The rules restate the book’s §8.3 and Miller’s transitionsDale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, §6, p. 14–16. Two things the book leaves implicit are made explicit here: binders inside terms, and the order of pruning.

Setting. The prefix is ∀a¯  ∃X¯  ∀Γ\forall\bar a\;\exists\bar X\;\forall\Gamma, where a¯\bar a are the signature constants and Γ\Gamma is the growing list of inner universals, or eigenvariables. A state is a pair ⟨E;θ⟩\langle E;\theta\rangle of a multiset of equations and the substitution computed so far. Equations are symmetric. θ\theta is applied eagerly, and terms are kept β0\beta_0-normal.

⟨{λx s=λx t}⊎E;θ⟩⟨{s[z/x]=t[z/x]}∪E;θ⟩  Abs⟨{λx s=t}⊎E;θ⟩⟨{s[z/x]=(t z)}∪E;θ⟩  Eta⟨{(h s1…sn)=(h t1…tn)}⊎E;θ⟩⟨{s1=t1,…,sn=tn}∪E;θ⟩  Dec⟨{(h s¯)=(k t¯)}⊎E;θ⟩⊥  Clash⟨{(F c¯)=t}⊎E;θ⟩⟨ρ′(ρ(E)); ρ′∘ρ∘θ⟩  Elim⟨{(F c¯)=(G d¯)}⊎E;θ⟩⟨σ(E); σ∘θ⟩  FlexFlex \begin{gathered} \dfrac{\langle\{\lambda x\,s=\lambda x\,t\}\uplus E;\theta\rangle}{\langle\{s[z/x]=t[z/x]\}\cup E;\theta\rangle}\;\text{Abs} \qquad \dfrac{\langle\{\lambda x\,s=t\}\uplus E;\theta\rangle}{\langle\{s[z/x]=(t\,z)\}\cup E;\theta\rangle}\;\text{Eta} \\[2ex] \dfrac{\langle\{(h\,s_1\dots s_n)=(h\,t_1\dots t_n)\}\uplus E;\theta\rangle}{\langle\{s_1=t_1,\dots,s_n=t_n\}\cup E;\theta\rangle}\;\text{Dec} \qquad \dfrac{\langle\{(h\,\bar s)=(k\,\bar t)\}\uplus E;\theta\rangle}{\bot}\;\text{Clash} \\[2ex] \dfrac{\langle\{(F\,\bar c)=t\}\uplus E;\theta\rangle}{\langle\rho'(\rho(E));\ \rho'\circ\rho\circ\theta\rangle}\;\text{Elim} \qquad \dfrac{\langle\{(F\,\bar c)=(G\,\bar d)\}\uplus E;\theta\rangle}{\langle\sigma(E);\ \sigma\circ\theta\rangle}\;\text{FlexFlex} \end{gathered}

Side conditions:

  • Abs, Eta: zz is a fresh eigenvariable appended to Γ\Gamma; in Eta, tt is not an abstraction. This is step 4 of the normal form, applied on demand.
  • Dec, Clash: h,kh,k are rigid heads (signature constants or eigenvariables) and h≠kh\ne k in Clash. Untyped, an arity mismatch for the same head is also a clashDale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, §9.3.
  • Elim: (F c¯)(F\,\bar c) is a pattern, tt is rigid, and the elimination ℰF,c¯(t)\mathcal E_{F,\bar c}(t) of Definition 7.21 succeeds with result t′t' and pruning substitution ρ\rho; then ρ′={⟨F,λc¯. t′⟩}\rho'=\{\langle F,\lambda\bar c.\,t'\rangle\}. If ℰ\mathcal E fails, the state goes to ⊥\bot.
  • FlexFlex: both sides are patterns and σ\sigma is the mgu of Proposition 7.19; for the same head with all positions agreeing, the equation is simply deleted.
  • A flexible term that is not a pattern blocks the rules; we come back to it in Section 7.9.1.

Definition 7.21 (Variable elimination). Let (F c1…cn)(F\,c_1\dots c_n) be a pattern. The elimination ℰL(t)\mathcal E_L(t) of a β0\beta_0-normal term tt, relative to a set LL of variables bound by λ\lambdas inside tt (initially L=∅L=\emptyset), either fails or returns a term, and may record pruning bindings in ρ\rho. It is defined by cases on tt, after applying the pruning bindings recorded so far:

ℰL(a)=aa a signature constant (outer ∀)ℰL(y)=yy∈c¯∪LℰL(y)=fail (scope)y∈Γ∖(c¯∪L)ℰL(λz s)=λz ℰL∪{z}(s)ℰL(h s1…sk)=ℰL(h) ℰL(s1)…ℰL(sk)h rigidℰL(F s¯)=fail (occurs)ℰL(G d1…dm)=G′ e1…eℓG≠F a pattern; see below \begin{array}{lll} \mathcal E_L(a) &= a & a \text{ a signature constant (outer } \forall)\\ \mathcal E_L(y) &= y & y\in\bar c\cup L\\ \mathcal E_L(y) &= \text{fail (scope)} & y\in\Gamma\setminus(\bar c\cup L)\\ \mathcal E_L(\lambda z\,s) &= \lambda z\,\mathcal E_{L\cup\{z\}}(s) & \\ \mathcal E_L(h\,s_1\dots s_k) &= \mathcal E_L(h)\,\mathcal E_L(s_1)\dots\mathcal E_L(s_k) & h \text{ rigid}\\ \mathcal E_L(F\,\bar s) &= \text{fail (occurs)} & \\ \mathcal E_L(G\,d_1\dots d_m) &= G'\,e_1\dots e_\ell & G\ne F \text{ a pattern; see below} \end{array}

In the last case e1…eℓe_1\dots e_\ell is the subsequence of d1…dmd_1\dots d_m of the variables in c¯∪L\bar c\cup L. If ℓ=m\ell=m, nothing is pruned and G′=GG'=G. Otherwise the pruning substitution ⟨G, λd1…λdm (G′ e1…eℓ)⟩\langle G,\ \lambda d_1\dots\lambda d_m\,(G'\,e_1\dots e_\ell)\rangle, with G′G' new and quantified at the place of GG, is added to ρ\rho.

This is the book’s description [MN p. 223], case by case. “This pruning substitution replaces GG with the term λd1…λdm (G′ e1…eℓ)\lambda d_1\dots\lambda d_m\,(G'\,e_1\dots e_\ell), where G′G' is a new existentially quantified variable, and e1,…,eℓe_1,\dots,e_\ell is some listing of the variables that are common to c1,…,cnc_1,\dots,c_n and d1,…,dmd_1,\dots,d_m. Now let the result of applying these auxiliary substitutions to the term tt be t′t'. Then the main part of variable elimination checks whether there are occurrences in t′t' either of FF or of variables different from the ones in c1,…,cnc_1,\dots,c_n that are quantified universally within the scope of the quantifier binding FF. If there are such occurrences, then it marks the problem as one for which no unifiers exist. Otherwise, it generates the substitution λc1…λcn t′\lambda c_1\dots\lambda c_n\,t' for FF and replaces the equation under consideration by ⊤\top.”

Read the definition as an inversion. FF applied to c¯\bar c must produce tt, so λc¯. t′\lambda\bar c.\,t' must “undo” the application: every cic_i in tt becomes the ii-th bound variable of FF’s binder. A universal that FF cannot see and that FF does not receive as an argument has no preimage. In a rigid position it makes the problem unsolvable; inside the arguments of another flexible term GG it can be removed by pruning, that is, by committing GG to ignore that argument. Imitation (rigid heads copied) and projection (a cic_i copied as a bound variable) are both inside this single walk.

Pitfall (four things the prose leaves implicit).

  1. An out-of-scope universal is fatal only in a rigid position. Inside the argument list of a flexible subterm it is pruned. The book’s Example 7.25 below says exactly this: “in a position that is not the argument of a flexible term” [MN p. 224].
  2. Variables bound by λ\lambdas inside tt are always allowed, both in rigid positions and as kept arguments of pruned terms; this is the set LL. The book never needs LL because its normal form has no inner binders at the top, but terms like h (λz (G z w))h\,(\lambda z\,(G\,z\,w)) have them below the top.
  3. Pruning binds other variables (GG) as a side effect, although the equation is about FF. If GG occurs twice, the second occurrence must be examined after the first pruning, which may prune again (Example 7.29).
  4. Pruning never meets FF itself: that is the occurs failure.

Theorem 7.22 (Pattern unification is unitary and terminating). On a ∀∃∀\forall\exists\forall problem whose flexible subterms are all patterns, the rules terminate. If they reach ⊥\bot the problem has no unifier; otherwise they end in ⟨∅;θ⟩\langle\emptyset;\theta\rangle and θ\theta is an mgu ([MN p. 222–224]; Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, Thm. 7.1, Prop. 7.3).

Miller proves termination with a lexicographic measure: the number of existentials, the total size of the equations, the number of equations, a weight of the universals, and the number of possibly prunable occurrencesDale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, Thm. 7.1, p. 18. Intuitively, Elim and the different-heads case of FlexFlex each remove one existential for good (a pruned GG is traded for one G′G'; FF and GG are traded for one HH); the same-head case trades FF for one HH, so the number of existentials stays put, but the equation disappears (both sides become H e¯H\,\bar e); and the other rules shrink the problem. The occurs-check is what prevents the X=(f X)X=(f\,X) loop.Qian later showed the problem can be solved in linear time.Zhenyu Qian. Unification of higher-order patterns in linear time and space. Journal of Logic and Computation, 6(3):315–341, 1996

Two remarks complete the picture. First, “types have no bearing on the shapes of unifiers”: the algorithm “makes no use at all of type information in determining unifying substitutions”, though types are still needed to guarantee correctness, for example that same-head flexible terms have equal arity [MN p. 224]. Miller’s untyped variant replaces the type guarantee by two failures, an arity mismatch in Dec and same-head flexible terms of different arity, and uses η\eta-expansion “only on terms which, if typed, must have functional type”Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, §9.3. That is the variant an untyped Scheme host needs. Second, the result is a genuine algorithm, as for first-order unification: “In both cases, term simplification and variable elimination constitute the critical parts of the computation, although variable elimination has a more involved structure in the higher-order pattern unification case” [MN p. 224].

7.7Worked traces

Every result below was also checked mechanically with the Scheme transliteration of Section 7.8. The book does not number its unification problems. We label them 8.A–8.M in their order of appearance in the book’s Chapter 8, as the proposal’s test suite does, except 8.M, the problem ∀x (F x x=x)\forall x\,(F\,x\,x=x) of [MN p. 208] in the book’s Chapter 7. The main example below is 8.H, the occurs and scope failures are 8.I and 8.J, and the eager-versus-delayed raising of Example 7.31 is 8.K.

Example 7.23 (The book’s main example [MN p. 223–224]). With x,y,w:ix,y,w:i, f,g:i→if,g:i\to i and U,V:i→i→iU,V:i\to i\to i, solve

∀f ∀g ∃U ∃V ∀w ∀x ∀y [(f (U x y))=(f (g (V y w)))]. \forall f\,\forall g\,\exists U\,\exists V\,\forall w\,\forall x\,\forall y\,[(f\,(U\,x\,y))=(f\,(g\,(V\,y\,w)))].

Tutorial (the book’s main example, step by step).

  1. Both sides are rigid with head ff: Dec leaves (U x y)=(g (V y w))(U\,x\,y)=(g\,(V\,y\,w)).

  2. The left side is the pattern UU applied to c¯=(x,y)\bar c=(x,y), and the right side is rigid: Elim. Walk t=g (V y w)t=g\,(V\,y\,w) with L=∅L=\emptyset:

    • gg is a signature constant, so it is kept (this is the imitation part);
    • (V y w)(V\,y\,w) is a flexible pattern with d¯=(y,w)\bar d=(y,w). Of these, y∈c¯y\in\bar c is kept and w∉c¯w\notin\bar c must go: prune V:=λy λw (V′ y)V:=\lambda y\,\lambda w\,(V'\,y), so the subterm becomes (V′ y)(V'\,y).

    Now t′=g (V′ y)t'=g\,(V'\,y). UU does not occur in it, and its only inner universal yy is in c¯\bar c, so bind U:=λx λy (g (V′ y))U:=\lambda x\,\lambda y\,(g\,(V'\,y)).

  3. The matrix is empty. The mgu is {⟨V,λyλw (V′ y)⟩, ⟨U,λxλy (g (V′ y))⟩}\{\langle V,\lambda y\lambda w\,(V'\,y)\rangle,\ \langle U,\lambda x\lambda y\,(g\,(V'\,y))\rangle\} [MN p. 224].

Check: U x y→β0g (V′ y)U\,x\,y\to_{\beta_0}g\,(V'\,y) and V y w→β0V′ yV\,y\,w\to_{\beta_0}V'\,y, so both sides become f (g (V′ y))f\,(g\,(V'\,y)).

Example 7.24 (Occurs failure [MN p. 224]). ∀f ∀g ∃U ∃V ∀w ∀x ∀y [(U x y)=(g (U y w))]\forall f\,\forall g\,\exists U\,\exists V\,\forall w\,\forall x\,\forall y\,[(U\,x\,y)=(g\,(U\,y\,w))]: the walk meets (U y w)(U\,y\,w), whose head is the variable being eliminated, so the problem fails, “because of the occurrence of UU, the head of the flexible term, in the rigid term”. Note that pruning cannot help: whatever UU does with its arguments, the right side is one gg larger than the left.

Example 7.25 (Scope failure [MN p. 224]). ∀f ∀g ∃U ∃V ∀w ∀x ∀y [(U x y)=(g w)]\forall f\,\forall g\,\exists U\,\exists V\,\forall w\,\forall x\,\forall y\,[(U\,x\,y)=(g\,w)] “has no unifiers because the universally quantified variable ww, which is not one of the arguments in (U x y)(U\,x\,y), appears on the right-hand side of the equation and in a position that is not the argument of a flexible term”. Logically: UU is chosen before ww and does not receive it, so it cannot produce it.

Example 7.26 (Discharging, by elimination). For Example 7.16, (H k)=(cons a (cons b k))(H\,k)=(\mathit{cons}\ a\ (\mathit{cons}\ b\ k)) with c¯=(k)\bar c=(k): the walk keeps the signature constants cons\mathit{cons}, aa, bb (imitation), meets k∈c¯k\in\bar c and maps it to HH’s bound variable (projection), finds no flexible subterm to prune and no occurrence of HH, and returns H:=λw (cons a (cons b w))H:=\lambda w\,(\mathit{cons}\ a\ (\mathit{cons}\ b\ w)), Miller’s unique answer.

Kanren angle (the scope failure that surprised λKanren). Ma and FriedmanWeixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2021 open with the miniKanren query (run 1 X (== (λ (a) X) (λ (b) b))) and observe that it “fails. Under any existing higher-order unification algorithm, X and a cannot be unified due to the scope restrictions”, while a novice expects X = a. Read through Abs, the equation is ∃X ∀z [X=z]\exists X\,\forall z\,[X=z]: Example 7.25 with n=0n=0, so the failure is the correct answer under the quantifier reading (no single XX equals every zz). Their proposal changes the semantics with de Bruijn levels so that the query answers (d0); Chapter 9 examines that choice. Whichever semantics a new module picks, it must say so explicitly; see Chapter 11.

Example 7.27 (Flexible-flexible, different heads). For Example 7.2, ∃G ∃H ∀x ∀y [(G x)=(H y)]\exists G\,\exists H\,\forall x\,\forall y\,[(G\,x)=(H\,y)]: here c¯=(x)\bar c=(x) and d¯=(y)\bar d=(y) have nothing in common, ℓ=0\ell=0, and Proposition 7.19 gives

{⟨G,λx T⟩, ⟨H,λy T⟩}, \{\langle G,\lambda x\,T\rangle,\ \langle H,\lambda y\,T\rangle\},

the book’s “λw T\lambda w\,T for both” [MN p. 113]. Had the equation been (G x y)=(H y)(G\,x\,y)=(H\,y), then e¯=(y)\bar e=(y) and the mgu would be G:=λxλy (T y)G:=\lambda x\lambda y\,(T\,y), H:=λy (T y)H:=\lambda y\,(T\,y).

Example 7.28 (Pruning under an inner binder). ∀h ∃F ∃G ∀w ∀x [(F x)=(h (λz (G z w)))]\forall h\,\exists F\,\exists G\,\forall w\,\forall x\,[(F\,x)=(h\,(\lambda z\,(G\,z\,w)))]. Elim with c¯=(x)\bar c=(x) walks hh (kept), then the abstraction, adding zz to LL, then (G z w)(G\,z\,w): z∈Lz\in L is kept and ww is pruned, G:=λzλw (G′ z)G:=\lambda z\lambda w\,(G'\,z). Result: F:=λx (h (λz (G′ z)))F:=\lambda x\,(h\,(\lambda z\,(G'\,z))). The local zz is legal everywhere below its binder, which is item 2 of the pitfall after Definition 7.21.

Example 7.29 (Two occurrences, two prunings). ∀g ∃F ∃G ∀w ∀x [(F x)=(g (G x w) (G w x))]\forall g\,\exists F\,\exists G\,\forall w\,\forall x\,[(F\,x)=(g\,(G\,x\,w)\,(G\,w\,x))], with c¯=(x)\bar c=(x). The first occurrence prunes the second argument: G:=λd1λd2 (G′ d1)G:=\lambda d_1\lambda d_2\,(G'\,d_1). The second occurrence now reads (G′ w)(G'\,w), and ww must be pruned again: G′:=λd G′′G':=\lambda d\,G''. So G:=λd1λd2 G′′G:=\lambda d_1\lambda d_2\,G'' and F:=λx (g G′′ G′′)F:=\lambda x\,(g\,G''\,G''). This is correct: G x wG\,x\,w must not mention ww, so GG ignores its second argument, and G w xG\,w\,x must not mention ww, so it ignores its first.

Example 7.30 (η on demand). ∀g ∃F [λx (F x)=g]\forall g\,\exists F\,[\lambda x\,(F\,x)=g]: Eta gives (F z)=(g z)(F\,z)=(g\,z) with zz fresh, and Elim binds F:=λz (g z)F:=\lambda z\,(g\,z), which is η\eta-equal to gg. Without Eta, an abstraction facing a constant would be a spurious clash.

problem (matrix)LλL_\lambda?pattern unificationHuet pre-unification
(F a)=(g a a)(F\,a)=(g\,a\,a)nonot applicable (delay)4 answers
(G x)=(H y)(G\,x)=(H\,y)yesG,H:=λw TG,H:=\lambda w\,Talready flex-flex; residue kept
X=(f X)X=(f\,X)yesfail (occurs)diverges (no occurs-check)
(f (U x y))=(f (g (V y w)))(f\,(U\,x\,y))=(f\,(g\,(V\,y\,w)))yesmgu of Example 7.23U:=λxλy g (H x y)U:=\lambda x\lambda y\,g\,(H\,x\,y), residue (H x y)=(V y w)(H\,x\,y)=(V\,y\,w)
(U x y)=(g (U y w))(U\,x\,y)=(g\,(U\,y\,w))yesfail (occurs)diverges
(U x y)=(g w)(U\,x\,y)=(g\,w)yesfail (scope)fail
(F (g x))=(g (F x))(F\,(g\,x))=(g\,(F\,x))nodelayinfinitely many answers
(F x x)=x(F\,x\,x)=xnodelay2 answers
(F x y)=(F y x)(F\,x\,y)=(F\,y\,x)yesF:=λxλy HF:=\lambda x\lambda y\,Halready flex-flex; residue kept
Table 7.2: A test battery. The Huet column describes the pre-unification procedure exactly as the book presents it in its §8.2: it stops at flexible-flexible equations, and it has no occurs-check, since that is added only for LλL_\lambda [MN p. 223]. The pattern column assumes the delaying discipline of Section 7.9.1.

7.8Nipkow’s de Bruijn algorithm

NipkowTobias Nipkow. Functional unification of higher-order patterns. In M. Vardi, editor, 8th Symposium on Logic in Computer Science, pages 64–74, New York, 1993. IEEE turned the transformation rules into “a directly executable functional program” and then adapted it “to lambda-terms in de Bruijn’s notation”, for typed and untyped terms alike. It is short and complete, so we reconstruct it from the author’s ML code. It assumes a ∀∃∀\forall\exists\forall prefix, raised in a preprocessing phase [MN p. 227].

Encoding the prefix in the terms. Existentials are global names V F, signature constants are C c, and an abstraction A t has a body in which bound variables are de Bruijn indices B i (Chapter 6). The inner ∀\forall block is not represented at all. To unify λwλxλy. s\lambda w\lambda x\lambda y.\,s with λwλxλy. t\lambda w\lambda x\lambda y.\,t, the algorithm simply strips the binders, which is rule Abs, and the loose indices of ss and tt then play the inner universals: under three binders, yy is B 0, xx is B 1, ww is B 2. Because every existential is quantified outside every inner universal, the values bound to the Vs are closed terms, and “fresh eigenvariable” costs nothing.

The algorithm in pseudo-code; SS is a triangular substitution, i.e. an association list that is walked rather than applied.

devar(S, s):                          ; β0 by renaming
  if s = (V F) b1..bk and S binds F to λ^k.body
  then devar(S, body with each bound index renamed to the matching b)  else s
unif(S, s, t):  s := devar(S, s);  t := devar(S, t);  case
  A s', A t'  → unif(S, s', t')                          ; Abs
  A s', t     → unif(S, s', (↑t) (B 0))                  ; Eta (and symmetric)
  F ȳ,  G z̄   → flexflex(F, ȳ, G, z̄, S)
  F ȳ,  t     → flexrigid(F, ȳ, t, S)                    ; (and symmetric)
  a s̄,  b t̄   → if a = b and |s̄| = |t̄| then fold unif over the pairs else FAIL
flexrigid(F, ȳ, t, S):
  if F occurs in t through S then FAIL                   ; occurs-check
  u := t with each loose index i replaced by the position
       of (B i) in ȳ counted from the right, or by •     ; inversion
  return proj(S + [F ↦ λ^|ȳ|. u], u)
proj(S, s):  case devar(S, s) of                         ; scope check and pruning
  A s'               → proj(S, s')
  (C c) s̄, (B i) s̄   → fold proj over s̄
  • s̄                → FAIL                              ; out of scope, rigid position
  (V G) b̄            → S + [G ↦ λ^|b̄|. H (positions of b̄ that are not •)],  H new
flexflex(F, ȳ, F, z̄, S):                                ; same head
  if ȳ = z̄ then S else S + [F ↦ λ^|ȳ|. H (positions i with y_i = z_i)]
flexflex(F, ī, G, j̄, S):                                ; different heads
  if ī ⊆ j̄ then S + [G ↦ λj̄. F ī]  elif j̄ ⊆ ī then S + [F ↦ λī. G j̄]
  else S + [F ↦ λī. H (ī ∩ j̄),  G ↦ λj̄. H (ī ∩ j̄)]

Compare it with the rules of Section 7.6.

  • Inversion first, pruning second. flexrigid binds FF to λ∣y¯∣.u\lambda^{|\bar y|}.u before pruning, so uu may still contain markers • inside the arguments of other flexible terms. That is harmless: proj then binds each such GG to a term that drops those positions, and since SS is triangular, every later devar through FF also goes through GG and never sees a marker.Nipkow’s ML encodes the marker as the index B(~10000), which shifting keeps negative.
  • One walk. Imitation is the copying of C heads, projection the renaming of loose indices, the scope check the • in rigid position, and pruning the V case: this is the book’s “variable elimination”. Inner binders need no set LL: below A, indices that refer to local binders are never shifted into markers.
  • devar is β0\beta_0. Arguments of a bound existential are indices, so “substituting” only renames indices; no shifting of arbitrary terms is needed.
  • An optimisation in flexflex. If one argument list is contained in the other, one variable is bound directly to the other instead of introducing HH; up to renaming, this is the mgu of Proposition 7.19.
  • No pattern test. The code assumes its input is a pattern problem; a non-pattern argument would simply not be handled correctly. A dynamic-LλL_\lambda implementation adds a test there and delays (Section 7.9.1).

Tutorial (Example 8.H in de Bruijn form). Under the three binders w,x,yw,x,y the equation is f (U 1 0)=f (g (V 0 2))f\,(U\,1\,0)=f\,(g\,(V\,0\,2)). Dec on ff leaves U 1 0=g (V 0 2)U\,1\,0=g\,(V\,0\,2). Here y¯=(1,0)\bar y=(1,0): index 11 (that is xx) sits at position 11 from the right, index 00 (yy) at position 00, and index 22 (ww) is absent. So u=g (V 0 ∙)u=g\,(V\,0\,\bullet) and U:=λλ. g (V 0 ∙)U:=\lambda\lambda.\,g\,(V\,0\,\bullet). proj meets V 0 ∙V\,0\,\bullet and prunes: V:=λλ. H 1V:=\lambda\lambda.\,H\,1, i.e. λyλw (H y)\lambda y\lambda w\,(H\,y). Walking UU’s binding through SS gives λxλy (g (H y))\lambda x\lambda y\,(g\,(H\,y)), the book’s answer.

7.8.1An executable transliteration

The following plain Scheme is a line-by-line transliteration of the de Bruijn ML code (file lics93-db.ML). It is not a proposal for the new module’s interface (that is Chapter 11); it is here so that you can run, trace and modify the algorithm. Terms are tagged lists, failure escapes through a continuation, and (OUT) is the marker •.

(define (tag t) (car t))
(define (V n) (list 'V n))  (define (C n) (list 'C n))  (define (B i) (list 'B i))
(define (A t) (list 'A t))  (define ($ s t) (list '$ s t))  (define OUT '(OUT))
(define escape #f)
(define (fail) (escape 'fail))

(define (strip t)                       ; head and arguments of an application spine
  (let loop ((t t) (ts '()))
    (if (eq? (tag t) '$) (loop (cadr t) (cons (caddr t) ts)) (cons t ts))))
(define (apps h ts) (fold (λ (t h) ($ h t)) h ts))  ; foldl op $
(define (abs n t) (if (zero? n) t (abs (- n 1) (A t))))
(define (hnf n h ts) (abs n (apps h ts)))           ; λ^n. h ts

(define (mapbnd f t)                    ; f on the loose indices of t; #f gives OUT
  (let mpb ((d 0) (t t))
    (case (tag t)
      ((B) (let ((i (cadr t)))
             (if (< i d) t (let ((j (f (- i d)))) (if j (B (+ j d)) OUT)))))
      ((A) (A (mpb (+ d 1) (cadr t))))
      (($) ($ (mpb d (cadr t)) (mpb d (caddr t))))
      (else t))))
(define (incr t) (mapbnd add1 t))

(define (red s bs js)                   ; β0: (λ^k s) applied to indices renames them
  (if (and (eq? (tag s) 'A) (pair? bs) (memq (tag (car bs)) '(B OUT)))
      (red (cadr s) (cdr bs) (cons (and (eq? (tag (car bs)) 'B) (cadr (car bs))) js))
      (apps (mapbnd (λ (i) (list-ref js i)) s) bs)))

(define (devar S s)                     ; walk the head through the triangular S
  (let ((ht (strip s)))
    (cond ((and (eq? (tag (car ht)) 'V) (assoc (cadr (car ht)) S))
           => (λ (p) (devar S (red (cdr p) (cdr ht) '()))))
          (else s))))

(define (occ F S t)
  (let occ ((t t))
    (case (tag t)
      ((V) (or (equal? F (cadr t))
               (cond ((assoc (cadr t) S) => (λ (p) (occ (cdr p)))) (else #f))))
      (($) (or (occ (cadr t)) (occ (caddr t))))
      ((A) (occ (cadr t)))
      (else #f))))

(define counter 0)
(define (newV)
  (set! counter (add1 counter)) (V (string->symbol (format "H~a" counter))))

(define (pos p xs)                      ; indices (from the right) of the xs with p
  (let loop ((xs xs))
    (cond ((null? xs) '())
          ((p (car xs)) (cons (B (length (cdr xs))) (loop (cdr xs))))
          (else (loop (cdr xs))))))
(define (idx bs b)                      ; the index of b in the binder list bs, or #f
  (let loop ((bs bs))
    (cond ((null? bs) #f)
          ((equal? (car bs) b) (length (cdr bs)))
          (else (loop (cdr bs))))))

(define (proj S s)                      ; scope check + pruning, one walk over s
  (let* ((ht (strip (devar S s))) (h (car ht)) (ss (cdr ht)))
    (case (tag h)
      ((A) (proj S (cadr h)))
      ((C B) (fold (λ (t S) (proj S t)) S ss))
      ((OUT) (fail))                    ; out-of-scope universal, rigid position
      ((V) (let ((keep (pos (λ (b) (eq? (tag b) 'B)) ss)))
             (cons (cons (cadr h) (hnf (length ss) (newV) keep)) S))))))

(define (flexflex1 F ym zn S)           ; same head: keep the positions that agree
  (if (equal? ym zn) S
      (let ((keep (pos (λ (p) (equal? (car p) (cdr p))) (map cons ym zn))))
        (cons (cons F (hnf (length ym) (newV) keep)) S))))
(define (lam im G jn) (hnf (length im) G (map (λ (j) (B (idx im j))) jn)))
(define (subset? xs ys) (every (λ (x) (member x ys)) xs))
(define (flexflex2 F im G jn S)         ; different heads
  (cond ((subset? im jn) (cons (cons G (lam jn (V F) im)) S))
        ((subset? jn im) (cons (cons F (lam im (V G) jn)) S))
        (else (let ((kl (filter (λ (i) (member i jn)) im)) (H (newV)))
                (cons (cons F (lam im H kl)) (cons (cons G (lam jn H kl)) S))))))
(define (flexflex F ym G zn S)
  (if (equal? F G) (flexflex1 F ym zn S) (flexflex2 F ym G zn S)))

(define (flexrigid F im t S)            ; occurs check, inversion, then pruning
  (if (occ F S t) (fail)
      (let ((u (mapbnd (λ (i) (idx im (B i))) t)))
        (proj (cons (cons F (abs (length im) u)) S) u))))

(define (unif S s t)
  (let ((s (devar S s)) (t (devar S t)))
    (cond ((and (eq? (tag s) 'A) (eq? (tag t) 'A)) (unif S (cadr s) (cadr t)))
          ((eq? (tag s) 'A) (unif S (cadr s) ($ (incr t) (B 0))))     ; η on demand
          ((eq? (tag t) 'A) (unif S ($ (incr s) (B 0)) (cadr t)))
          (else (cases S s t)))))
(define (cases S s t)
  (let ((hs (strip s)) (ht (strip t)))
    (cond ((and (eq? (tag (car hs)) 'V) (eq? (tag (car ht)) 'V))
           (flexflex (cadr (car hs)) (cdr hs) (cadr (car ht)) (cdr ht) S))
          ((eq? (tag (car hs)) 'V) (flexrigid (cadr (car hs)) (cdr hs) t S))
          ((eq? (tag (car ht)) 'V) (flexrigid (cadr (car ht)) (cdr ht) s S))
          ((and (equal? (car hs) (car ht)) (= (length (cdr hs)) (length (cdr ht))))
           (fold (λ (a b S) (unif S a b)) S (cdr hs) (cdr ht)))
          (else (fail)))))

The test driver, a printer that applies SS and turns indices back into names (omitted here), and the problems are in writers/ch07-hounif/nipkow.scm. For instance, Example 7.23 is posed as

(define f (C 'f)) (define g (C 'g)) (define h (C 'h))
(define (lam3 t) (A (A (A t))))     ; ∀w ∀x ∀y as three binders: y = 0, x = 1, w = 2
;; Example 8.H: ∀f∀g∃U∃V∀w∀x∀y [(f (U x y)) = (f (g (V y w)))]
(run "8.H  f (U x y) = f (g (V y w))" '(U V)
     (lam3 ($ f ($ ($ (V 'U) (B 1)) (B 0))))
     (lam3 ($ f ($ g ($ ($ (V 'V) (B 0)) (B 2))))))

and the whole battery prints, with H1, H2 the fresh variables and V1 standing for the book’s V′V':

8.H  f (U x y) = f (g (V y w))
  U := λx1. λx2. g (H1 x2)
  V := λx1. λx2. H1 x1
8.I  U x y = g (U y w)
  no unifier
8.J  U x y = g w
  no unifier
4.5  λx λy (G x) = λx λy (H y)
  G := λx1. H1
  H := λx1. H1
ff   λx λy (F x y) = λx λy (F y x)
  F := λx1. λx2. H1
8.K  U x = f (V1 x y z)
  U := λx1. f (H1 x1)
  V1 := λx1. λx2. λx3. H1 x1
eta  λx (F x) = g
  F := λx1. g x1
dup  λx (F x) = λx (g x x)
  F := λx1. g x1 x1
loc  F x = h (λz (G z w))
  F := λx1. h (λx2. H1 x2)
  G := λx1. λx2. H1 x1
two  F x = g (G x w) (G w x)
  F := λx1. g H2 H2
  G := λx1. λx2. H2

Every line agrees with the hand derivations: Example 7.23, Example 7.24, Example 7.25, Example 7.27, Example 7.28 and Example 7.29, the same-head pitfall, and the eagerly raised form of Example 7.31 below.

Kanren angle (what first-order unification does with the same terms). (aux kanren micro) can already store de Bruijn terms as records, but its unifier treats an application of a logic variable as a pair of slots. This sometimes gives the right answer by luck, sometimes an ill-scoped one, and sometimes a wrong failure. With (define-record lam body), (define-record app rator rand) and (define-record dbi n):

(show "X = (f X)"
      (°->list #f (fresh° (q) (=° q (list 'f q)))))
(show "λx (F x) = λx (g x)"
      (°->list #f (fresh° (f) (=° (make-lam (make-app f (make-dbi 0)))
                                  (make-lam (make-app 'g (make-dbi 0)))))))
(show "λx (F x) = λx (g x x)"
      (°->list #f (fresh° (f) (=° (make-lam (make-app f (make-dbi 0)))
                                  (make-lam (make-app (make-app 'g (make-dbi 0)) (make-dbi 0)))))))
(show "λx (F x) = λx (g x 7)"
      (°->list #f (fresh° (f) (=° (make-lam (make-app f (make-dbi 0)))
                                  (make-lam (make-app (make-app 'g (make-dbi 0)) 7))))))
;; X = (f X)
()
;; λx (F x) = λx (g x)
((λ () 'g))
;; λx (F x) = λx (g x x)
((λ () (make-record-instance 'app 'g (make-record-instance 'dbi 0))))
;; λx (F x) = λx (g x 7)
()

The occurs-check case is already right. The second answer is right up to η\eta. The third binds FF to “gg applied to index 00” outside any binder: a dangling index, where the mgu is F:=λy (g y y)F:=\lambda y\,(g\,y\,y) (dup above). The fourth fails, where the mgu is F:=λy (g y 7)F:=\lambda y\,(g\,y\,7). A higher-order extension must therefore recognise a flexible application and run Elim on it rather than decomposing it structurally; see Chapter 11.

7.9Mixed prefixes, levels and delayed equations

Everything so far assumed a ∀∃∀\forall\exists\forall prefix. Real proof search does not deliver one. Each pi x\ G adds a universal, and each backchaining step adds existentials after it, giving prefixes such as ∀∃∀∃∀…\forall\exists\forall\exists\forall\dots [MN p. 224]. Raising them eagerly “has to be performed dynamically”, may raise existentials “over long lists of universally quantified variables” (typical of the pi-based recursion of Chapter 6), and “often can be redundant and may have to be undone by a pruning substitution at a later point” [MN p. 224].

Example 7.31 (Eager versus delayed raising [MN p. 224–225]). Consider

∀f ∃U ∀x ∀y ∀z ∃V [(U x)=(f V)]. \forall f\,\exists U\,\forall x\,\forall y\,\forall z\,\exists V\,[(U\,x)=(f\,V)].
  • Eagerly, raise VV over x,y,zx,y,z:

    ∀f ∃U ∃V′ ∀x ∀y ∀z [(U x)=(f (V′ x y z))]. \forall f\,\exists U\,\exists V'\,\forall x\,\forall y\,\forall z\,[(U\,x)=(f\,(V'\,x\,y\,z))].

    Variable elimination immediately prunes V′:=λxλyλz (W x)V':=\lambda x\lambda y\lambda z\,(W\,x), giving U:=λx (f (W x))U:=\lambda x\,(f\,(W\,x)), so two of the three raised arguments were wasted work.

  • Delayed: record that UU may be raised over ff and VV over x,y,z,fx,y,z,f. When solving, “noting the presence of xx as an argument of the flexible term and the possibility of raising VV over xx, we would replace VV with the term (V′ x)(V'\,x), where V′V' is a new variable quantified at the same place in the prefix as UU and would produce the unifying substitution λx (f (V′ x))\lambda x\,(f\,(V'\,x)) for UU” [MN p. 225].

The lists of universals that each existential may depend on “are all initial segments of the sequence of variables that are universally quantified in the prefix, … and this information can be maintained and used efficiently by attaching numerical indices to the quantified variables” [MN p. 225]. This idea has two literature sources.

Universe indices for pi goals.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 In a WAM-style interpreter for first-order hereditary Harrop formulas, “each time a universal quantifier is encountered, a new constant must be introduced, giving rise to the next universe in the hierarchy”: the universe index is incremented and the new constant is tagged with it. A logic variable is tagged with the current index, meaning “that a term may be substituted for the variable only if all the constants appearing in the term have a smaller or identical tag” (p. 16). Binding Xi:=tX^i:=t then requires (1) the usual occurs-check; (2) that tt contains no constant with tag greater than ii; and (3) that, before binding, the tags of the variables of tt greater than ii be lowered to ii, “to prevent a later instantiation of these variables from violating the restrictions on instantiations for XX” (p. 16).

Example 7.32 (Why tags must be lowered, p. 16).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 Program ∀z (q(z)⊃p(d(z)))\forall z\,(q(z)\supset p(d(z))), goal ∃x ∀y (q(y)⊃p(x))\exists x\,\forall y\,(q(y)\supset p(x)). After the quantifiers the goal is q(c2)⊃p(X1)q(c^2)\supset p(X^1). Backchaining on the clause with a new Z2Z^2 unifies p(d(Z2))p(d(Z^2)) with p(X1)p(X^1); binding X:=d(Z)X:=d(Z) lowers ZZ to Z1Z^1. The remaining goal q(Z1)q(Z^1) must be matched against the hypothesis q(c2)q(c^2) and fails, because cc has tag 2>12>1. Without step (3), ZZ would be bound to cc and XX would end up as d(c)d(c), mentioning a constant introduced after XX.

Prefix erasure for patterns.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 Nadathur and Linnell tag every variable yy with l(y)l(y), “the number of times an existential quantifier is immediately followed by a universal one in the prefix up to and including the quantifier binding that occurrence”. Then “a universal variable uu is quantified within the scope of the quantifier for an existential variable xx just in case l(x)<l(u)l(x)<l(u)” (p. 8), so the pattern test becomes local. Raising is restricted to what is needed: for f(y¯)=g(z¯)f(\bar y)=g(\bar z) with l(f)≤l(g)l(f)\le l(g), gg needs to be raised only over y¯⇑g={u∈y¯∣l(u)≤l(g)}\bar y{\Uparrow}g=\{u\in\bar y\mid l(u)\le l(g)\}, the universals among ff’s arguments that gg may depend on. A combined rule (9′') binds ff and gg to a common new hh with l(h)=l(f)l(h)=l(f), applied first to those universals and then to the common arguments (p. 9). Their Theorem 2 states that prefix erasure preserves termination and mgus (p. 10), and their Figure 2 gives the single-traversal mksubst/bnd that computes the binding, the pruning and the raising together (p. 11). The algorithm is used in Bedwyr, Abella and Teyjus 2 [MN p. 228].

Variable elimination with levels. Combining the two, Definition 7.21 generalises to tagged variables. This is our reconstruction, checked by hand on Example 7.23 and Example 7.31; Nadathur and Linnell’s Figure 2 is the authoritative version. Write l(⋅)l(\cdot) for levels, with signature constants at the lowest level. To eliminate FF in (F c¯)=t(F\,\bar c)=t, where pattern means that the cic_i are distinct universals with l(ci)>l(F)l(c_i)>l(F):

  • a universal uu in rigid position is kept if u∈c¯∪Lu\in\bar c\cup L or l(u)≤l(F)l(u)\le l(F) (since FF may mention it directly), and fails otherwise;
  • a flexible pattern (G d¯)(G\,\bar d) keeps the dj∈c¯∪Ld_j\in\bar c\cup L and the djd_j with l(dj)≤l(F)l(d_j)\le l(F), prunes the rest, and, if l(G)>l(F)l(G)>l(F), is also raised over the cic_i with l(ci)≤l(G)l(c_i)\le l(G) that it does not already receive; the new G′G' gets level l(F)l(F). In Example 7.31, l(U)=0l(U)=0 and l(x)=l(V)=1l(x)=l(V)=1, so VV (no arguments) is raised over xx: V:=(V′ x)V:=(V'\,x) with l(V′)=0l(V')=0, and U:=λx (f (V′ x))U:=\lambda x\,(f\,(V'\,x)), as in the book;
  • when no cic_i qualifies, raising degenerates to lowering: G:=λd¯. (G′ e¯)G:=\lambda\bar d.\,(G'\,\bar e) with l(G′)=l(F)l(G')=l(F) and nothing added, which is step (3) of the universe-index discipline above.

De Bruijn levels in ELPI.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 ELPI makes the two notions of level coincide. “When a clause’s head is unified with the goal in a context of length nn, the universally quantified variables of the clause are instantiated to unification variables XnX^n where the level nn records that XX has only visibility of the initial prefix of length nn of the context. If later a fresh constant is added by the pi rule, the constant occupies position n+1n+1 … and it will not be allowed to occur in instances of the variable XnX^n” (p. 4). Lowering a level is done by pruning: “unifying B0B_0 with (arr C1 D1)(\mathit{arr}\ C_1\ D_1) prunes CC and DD to level 00” (p. 7), i.e. the higher-level variable is bound to a fresh lower-level one.

Kanren angle (levels and (aux kanren micro)). (aux kanren micro) already allocates variables from a monotone counter, vars-count, so creation order is a linearisation of the dynamically built prefix. If eigenvariables were allocated from the same counter, the creation index would give every variable its initial level for free. Three facts of the current engine matter for any level discipline.

  1. Level is not index. Pruning and raising create a new variable “quantified at the same place” as an old one [MN p. 225], so a variable’s level must be stored separately from its index.
  2. Orientation of var-var bindings. Today the older variable is bound to the newer one. With scopes, binding a low-level XX to a high-level YY lets a later binding of YY smuggle a young eigenvariable into XX. Either the orientation must follow levels, or the binding must lower YY, as in step (3) above.
  3. Unification allocates. Pruning, raising and the flexible-flexible HH create variables, so the unifier must return an updated vars-count, and the bindings it reports must include the prunings of other variables (item 3 of the pitfall after Definition 7.21), because constraint re-verification keys on them.

How these requirements are met is the subject of Chapter 11.

7.9.1Dynamic Lλ: delay what is not a pattern

A static LλL_\lambda restriction “can rule out some useful programming idioms” [MN p. 225], the standard one being substitution by meta-level β\beta-reduction:

type   subst   (tm -> tm) -> tm -> tm -> o.
subst R N (R N).

Here R and N are essentially existential, so (R N) is not a pattern. “A common practical resolution to this dilemma is to not impose the LλL_\lambda restriction on program clauses statically but rather to expect the condition to be satisfied by the unification problems that are encountered dynamically” [MN p. 225–226]: when subst is called, R and N are expected to be instantiated, and (R N) is then just a β\beta-redex to reduce. More generally: “we would treat any unification problem as if it is a higher-order pattern-unification one. In the course of such a treatment, we might discover that a particular equation does not respect the LλL_\lambda condition. In this case, we might defer further consideration of this equation until such time that substitutions resulting from solving other parts of the problem have altered its status” [MN p. 226].

The literature agrees on this design.

  • Dowek, Hardin, Kirchner and PfenningGilles Dowek, Thérèse Hardin, Claude Kirchner, and Frank Pfenning. Unification via explicit substitutions: the case of higher-order patterns. In M. Maher, editor, Joint International Conference and Symposium on Logic Programming (JICSLP), pages 259–273. MIT Press, 1996, §5.4 (p. 13): equations outside the pattern fragment “should be postponed as constraints in the hope that they will be instantiated further”, which “avoids all branching during constraint simplification”. Their motivation is empiricalSpiro Michaylov and Frank Pfenning. An empirical study of the runtime behavior of higher-order logic programs. In Proceedings of the Workshop on the λ\lambdaProlog Programming Language, 1992: the static restriction is too severe, but “almost all dynamically arising equations fall within the pattern fragment” (p. 2). Their algorithm phrases Elim as the inversion of a pattern substitution: X[s]=bX[s]=b is solved by X=b[s−1]X=b[s^{-1}] when every index of bb occurs in ss (Prop. 8), with pruning computed together with the inverse (p. 11–12).
  • Nadathur and LinnellGopalan 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, §6: a non-pattern subterm met inside bnd can be replaced by a fresh flexible term, with the equation between them deferred.
  • Systems: Teyjus 1Gopalan Nadathur and Dustin J. Mitchell. System description: Teyjus — a compiler and abstract machine based implementation of λ\lambdaProlog. In Automated Deduction (CADE-16), volume 1632 of LNAI, pages 287–291. Springer, 1999 implemented (pre-)unification for unrestricted terms, while Teyjus 2 “only implements LλL_\lambda unification”; Twelf and Minlog also implement only LλL_\lambda unification, over an unrestricted term language [MN p. 228]. ELPI’s default for a problem outside the fragment is an error, with a deprecated option to delay it “for Teyjus compatibility”; its supported mechanism for suspension is instead a general syntactic constraint on goals, resumed when a variable is assigned.

Going the other way, subst can be written inside LλL_\lambda by making the object signature explicit with copy clauses (Chapter 6), and by extension “it also may be possible to describe general higher-order unification as a logic program in the LλL_\lambda language” [MN p. 226]Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991.

Pitfall (unifier versus solution; delayed is not solved). A state with suspended equations has succeeded only conditionally: its answer is a pre-unifier together with residual constraints, and those must be printed with it. The canonical substitution of Proposition 7.12 would make flexible-flexible residues “true”, but it introduces new existentials HτH^\tau: it is a unifier, not a solution, and in a typed setting with an empty type there may be no closed solution at all [MN p. 211]. Untyped Scheme terms avoid that last problemDale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, §9.3, but not the first.

Kanren angle (what delaying asks of a miniKanren). Following the book’s “defer further consideration” [MN p. 226], an (aux kanren micro)-style engine needs: a place in the state for suspended equations; a wake-up step after each successful unification that retries the suspended equations mentioning a variable just bound (the same “touched variables” mechanism that already re-verifies disequalities); and reification that prints what is still suspended. Soft-cut, projection and disequality must be audited, because each of them can observe a state whose success is only conditional. Disequality needs care even without delays: the mgu of a pattern problem may contain new variables (pruning, the flexible-flexible HH), and in ¬∃H.(X=λx H)\neg\exists H.(X=\lambda x\,H) these are existentially quantified inside the negation (equivalently, universally outside it), which a store of plain bindings would get wrong (Definition 12.21). The concrete design is in Chapter 11.

7.10Summary

  • A unification problem is a quantified formula; its prefix decides who may depend on whom. The book normalises to a ∀∃∀\forall\exists\forall prefix by raising, to β\beta-normal terms, to equal binders by η\eta, and turns top binders into inner universals [MN p. 212].
  • General higher-order unification has no mgus, may need infinite complete sets of unifiers, and is undecidable [MN p. 213–214].
  • Huet’s procedure: Dec/Clash on rigid-rigid pairs, imitation (scope-sensitive) or projection (type-sensitive) on flexible-rigid ones, success when only flexible-flexible equations remain (pre-unification; the canonical substitution unifies them). Its matching tree is complete but may have infinite branches, with or without answers [MN p. 214–220].
  • In LλL_\lambda, flexible terms are patterns F c¯F\,\bar c with distinct universals bound inside FF’s scope. Only β0\beta_0 arises, at most one imitation or projection is useful, flexible-flexible pairs have explicit mgus (common arguments for different heads, agreeing positions for the same head), and with an occurs-check the procedure terminates: pattern unification is decidable and unitary [MN p. 220–224], Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991.
  • Variable elimination in one walk: keep rigid heads, map each cic_i to FF’s ii-th bound variable, keep local binders, prune the arguments of other flexible terms that FF cannot see, and fail on FF itself (occurs) or on an unseeable universal in rigid position (scope). Then F:=λc¯. t′F:=\lambda\bar c.\,t' [MN p. 223].
  • Nipkow’s de Bruijn version is short (our Scheme transliteration of its core is under a hundred lines); loose indices are the inner universals, devar is β0\beta_0 by renaming, and inversion uses a marker that pruning removes Tobias Nipkow. Functional unification of higher-order patterns. In M. Vardi, editor, 8th Symposium on Logic in Computer Science, pages 64–74, New York, 1993. IEEE. No types are needed [MN p. 224].
  • In practice prefixes are mixed and dynamic: replace raising by levels on variables and eigenvariables, lower levels when binding, raise lazily only over the arguments needed [MN p. 225], 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; 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; 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.
  • Dynamic LλL_\lambda: treat every equation as a pattern problem and delay the non-patterns until bindings make them patterns; report what remains as residual constraints [MN p. 226], Gilles Dowek, Thérèse Hardin, Claude Kirchner, and Frank Pfenning. Unification via explicit substitutions: the case of higher-order patterns. In M. Maher, editor, Joint International Conference and Symposium on Logic Programming (JICSLP), pages 259–273. MIT Press, 1996.
  • For (aux kanren micro): first-order unification is the n=0n=0 case; the extension needs eigenvariables, binders, flexible applications, levels, allocation inside unification, and a store of delayed equations; see Chapter 11.