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 -terms equal modulo , and . 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 -tree syntax. Chapter 6 also isolated the fragment , 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 is the fragment to aim for.
The story has two halves.
- 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 -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.
- Higher-order pattern unification (-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 are existentially quantified variables (logic variables), and lowercase are universally quantified ones (signature constants or eigenvariables). abbreviates , and is .
7.2Unification problems and their normal form#
Definition 7.1 (Unification problem [MN p. 211]). A unification problem is a formula
where , each is or , and , are -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 -convertible to .
Reading the problem as a formula is what makes the scoping right. In no unifier exists, because is chosen before and cannot mention it; in the unifier is . 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.
A prefix. Using raising [MN p. 107–108], the formulas and are equiprovable when for , . Moving every to the left of every in this way yields a prefix . The outer 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].
Substitution as -redex. For , the book defines [MN p. 212]
Thus and are equal whenever and are -convertible, and we may assume all terms are in -normal form.
Equal binders. By -conversion the two sides of every equation get binders of the same length.
Binders become universals. Using and moving such 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]
Step 4 turns it into . Now and are universals quantified inside the scope of and . Any common instance must be a term in which neither nor occurs, and the book announces that the “most general” unifier substitutes for both and , with 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 : open both binders with one fresh eigenvariable and continue. Because the new 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 rigid head), and every logic variable is an existential. There is no inner block and no logic variable is ever applied to arguments, so every flexible term is a bare , which is a pattern with . The unifier μkanren-state-unify is precisely the rigid-rigid decomposition plus the case of variable elimination (bind 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 , , and consider . It has exactly four unifiers,
because each occurrence of on the right can come either from the argument of 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 of substitutions is a complete set of unifiers (CSU) for a problem if every member of is a unifier, and every unifier is obtained from some member of by a further substitution. One would like to be finite.
Example 7.7 (No finite CSU [MN p. 213]). With and , the problem
is solved by , , , …, that is, by every power . 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 .
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 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#
Here , are universally quantified in ; for , 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
with primitive. “This equation can be proved only by making the head of the left term identical to ” [MN p. 215], and there are only two ways to do that: the term substituted for has head itself, or it uses one of ’s arguments as head.
Definition 7.8 (Imitation and projection [MN p. 215–216]).
The imitation substitution, allowed only if “the quantification over occurs within the scope of the quantifier that binds ”, is
with fresh .
The -th projection substitution, allowed only if the target type of is , say , is
with fresh .
In both cases is replaced in the prefix by the new at the same place, is applied to the matrix, and the result is -normalised.
The design idea is minimal commitment. Imitation fixes only the head and leaves “all choices of what the arguments should be to the determination of substitutions for the variables in subsequent steps” [MN p. 215]; each receives all of ’s arguments, so nothing is lost. Projection commits “only to projecting onto its th argument” [MN p. 216]. For one flexible-rigid equation there may or may not be an imitation and there are between and projections, so “up to substitutions may have to be considered” [MN p. 216].
Pitfall (imitation is scope-sensitive, projection is type-sensitive). Imitating is illegal when is quantified inside the scope of : cannot mention it. This side condition is the logical root of every “eigenvariable escape” check. Projection needs the target type and the arity of , and imitation needs the arity of and its argument types : 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].
- The only equation is flexible-rigid with head , and is to the left of , so imitation is allowed: with . The single projection is (the argument type is the target type).
- Projection gives : a rigid-rigid clash, a dead end.
- Imitation gives , which Dec simplifies to .
- For both the imitation and the projection work; either leaves .
- The same two choices for empty the matrix.
Composing the substitutions along the four successful paths gives the four unifiers , , , [MN p. 217], in the order of a left-to-right depth-first walk of Figure 7.1.
![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.](/images/higher-order-kanren/hounif-tree.png)
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 and , take . Imitation and simplification give , which no rule can reduce further. (The other alternative for , the projection , gives , a rigid-rigid clash.) The residue has the unifier (making ), and many more: any term built from , and other existentials, abstracted over some of the occurrences of , 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 a fixed new existential variable , and with each type ( primitive) the canonical constant term . 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 . For Example 7.11, with the variable chosen for , the canonical substitution is [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 and : . The single projection solves it. The imitation followed by simplification gives : the same problem with in place of . Repeating forever, the paths of the tree yield
Example 7.14 (An infinite branch and no answer [MN p. 220]). Add a second equation, with constants : . “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]: gives , 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 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 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 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 is in if all quantification in is over non-predicate types and “every subterm of of the form in which is an essentially existentially quantified variable is such that are distinct variables that are universally quantified within the scope of the quantifier binding ” [MN p. 220]. Transposed to a unification problem: every flexible subterm has as arguments distinct universal variables quantified to the right of in the prefix. Such a term is a (higher-order) pattern.
The case 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 relative to a prefix , whose key rule says that is well formed when “ is existentially quantified in to the left of where the distinct variables are universally quantified”. Table 7.1 gives a feel for the definition.
| problem | pattern? | why |
|---|---|---|
| yes | distinct universals, right of | |
| (Example 7.5) | no | is quantified outside |
| no | arguments not distinct | |
| (Example 7.13) | no | argument is not a variable |
(the subst clause) | no | argument is existential |
| yes |
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
try to find such that is provable. The introduces a new constant , and two backchaining steps succeed only if is instantiated with , which is impossible because was chosen before existed. “Such a failure here is quite sensible since the value of should be independent of the choice of the constant used to instantiate ”. Now ask instead for . The same steps produce the pattern equation
Two -terms for make it true,
but “since cannot contain free, only the second of these possible substitutions will succeed”. Miller calls this discharging the constant from the term: is the computed answer with the choice of eigenvariable abstracted away. In terms of Huet’s procedure: imitation of , , , is forced, and at the leaf only the projection is legal, because imitating would violate the scope condition. The pattern algorithm below does this in one walk.
Definition 7.17 (β₀ [MN p. 206]). -conversion is the special case of ; with it is equivalent to , provided is not free in .
Under the condition, instantiating a logic variable only ever creates -redexes: “simply replacing the bound variables within the body of an abstraction with a new set of names” [MN p. 220]. A -step makes the term smaller, so we may expect its inverse, -unification, to be much better behaved than inverting full [MN p. 220].
Pitfall (β₀ alone is not enough). problems are unification problems modulo , but not conversely. The problem needs only , yet has the two incomparable unifiers and [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 condition [MN p. 208, 220–221], so we may still assume a 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 with existential and distinct universals quantified in the scope of . Then at most one imitation or projection substitution avoids an immediate clash.
Argument. If is in the scope of ( is to the left of , e.g. a signature constant), then differs from every , which are to the right of ; every projection produces a head and clashes, so only imitation can succeed. If is in the scope of , imitation is not allowed, and the -th projection succeeds only if ; since the are distinct, at most one qualifies, and if 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
with either or some and the quantified where was; substituted into and -reduced, it yields again patterns [MN p. 221].
7.5.2Flexible-flexible pattern equations have mgus#
Here is the second change. In a flexible-flexible equation has the form
with the and universals in the scope of and , and in a prefix and are “effectively bound ‘at the same place’” [MN p. 222].
Proposition 7.19 (Flexible-flexible mgus [MN p. 222]). Let be a new existential quantified at the place of .
Different heads (). Let list the variables common to and . Then
is an mgu.
Same head (, so ). Let list the such that . Then
is an mgu.
In the first case a common instance cannot contain a that is not also among the , and conversely; every such is an instance of . 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 , so in the ’s are bound.)
Pitfall (same head: positions, not sets). For the arguments are the same set, but no position agrees, so and the mgu is . 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 setting, it follows that the higher-order pattern unification problem possesses the property of having most general unifiers” [MN p. 222]. For 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 the only useful substitution is the imitation , which produces , “identical to the one with which we started” [MN p. 222]. In 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 every occurrence of 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 , where are the signature constants and is the growing list of inner universals, or eigenvariables. A state is a pair of a multiset of equations and the substitution computed so far. Equations are symmetric. is applied eagerly, and terms are kept -normal.
Side conditions:
- Abs, Eta: is a fresh eigenvariable appended to ; in Eta, is not an abstraction. This is step 4 of the normal form, applied on demand.
- Dec, Clash: are rigid heads (signature constants or eigenvariables) and 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: is a pattern, is rigid, and the elimination of Definition 7.21 succeeds with result and pruning substitution ; then . If fails, the state goes to .
- FlexFlex: both sides are patterns and 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 be a pattern. The elimination of a -normal term , relative to a set of variables bound by s inside (initially ), either fails or returns a term, and may record pruning bindings in . It is defined by cases on , after applying the pruning bindings recorded so far:
In the last case is the subsequence of of the variables in . If , nothing is pruned and . Otherwise the pruning substitution , with new and quantified at the place of , is added to .
This is the book’s description [MN p. 223], case by case. “This pruning substitution replaces with the term , where is a new existentially quantified variable, and is some listing of the variables that are common to and . Now let the result of applying these auxiliary substitutions to the term be . Then the main part of variable elimination checks whether there are occurrences in either of or of variables different from the ones in that are quantified universally within the scope of the quantifier binding . If there are such occurrences, then it marks the problem as one for which no unifiers exist. Otherwise, it generates the substitution for and replaces the equation under consideration by .”
Read the definition as an inversion. applied to must produce , so must “undo” the application: every in becomes the -th bound variable of ’s binder. A universal that cannot see and that 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 it can be removed by pruning, that is, by committing to ignore that argument. Imitation (rigid heads copied) and projection (a copied as a bound variable) are both inside this single walk.
Pitfall (four things the prose leaves implicit).
- 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].
- Variables bound by s inside are always allowed, both in rigid positions and as kept arguments of pruned terms; this is the set . The book never needs because its normal form has no inner binders at the top, but terms like have them below the top.
- Pruning binds other variables () as a side effect, although the equation is about . If occurs twice, the second occurrence must be examined after the first pruning, which may prune again (Example 7.29).
- Pruning never meets itself: that is the occurs failure.
Theorem 7.22 (Pattern unification is unitary and terminating). On a problem whose flexible subterms are all patterns, the rules terminate. If they reach the problem has no unifier; otherwise they end in and 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 is traded for one ; and are traded for one ); the same-head case trades for one , so the number of existentials stays put, but the equation disappears (both sides become ); and the other rules shrink the problem. The occurs-check is what prevents the 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 -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 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 , and , solve
Tutorial (the book’s main example, step by step).
Both sides are rigid with head : Dec leaves .
The left side is the pattern applied to , and the right side is rigid: Elim. Walk with :
- is a signature constant, so it is kept (this is the imitation part);
- is a flexible pattern with . Of these, is kept and must go: prune , so the subterm becomes .
Now . does not occur in it, and its only inner universal is in , so bind .
The matrix is empty. The mgu is [MN p. 224].
Check: and , so both sides become .
Example 7.24 (Occurs failure [MN p. 224]). : the walk meets , whose head is the variable being eliminated, so the problem fails, “because of the occurrence of , the head of the flexible term, in the rigid term”. Note that pruning cannot help: whatever does with its arguments, the right side is one larger than the left.
Example 7.25 (Scope failure [MN p. 224]). “has no unifiers because the universally quantified variable , which is not one of the arguments in , appears on the right-hand side of the equation and in a position that is not the argument of a flexible term”. Logically: is chosen before and does not receive it, so it cannot produce it.
Example 7.26 (Discharging, by elimination). For Example 7.16, with : the walk keeps the signature constants , , (imitation), meets and maps it to ’s bound variable (projection), finds no flexible subterm to prune and no occurrence of , and returns , 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 Kanren. 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 : Example 7.25 with , so the failure is the correct answer under the quantifier reading (no single equals every ). 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, : here and have nothing in common, , and Proposition 7.19 gives
the book’s “ for both” [MN p. 113]. Had the equation been , then and the mgu would be , .
Example 7.28 (Pruning under an inner binder). . Elim with walks (kept), then the abstraction, adding to , then : is kept and is pruned, . Result: . The local is legal everywhere below its binder, which is item 2 of the pitfall after Definition 7.21.
Example 7.29 (Two occurrences, two prunings). , with . The first occurrence prunes the second argument: . The second occurrence now reads , and must be pruned again: . So and . This is correct: must not mention , so ignores its second argument, and must not mention , so it ignores its first.
Example 7.30 (η on demand). : Eta gives with fresh, and Elim binds , which is -equal to . Without Eta, an abstraction facing a constant would be a spurious clash.
| problem (matrix) | ? | pattern unification | Huet pre-unification |
|---|---|---|---|
| no | not applicable (delay) | 4 answers | |
| yes | already flex-flex; residue kept | ||
| yes | fail (occurs) | diverges (no occurs-check) | |
| yes | mgu of Example 7.23 | , residue | |
| yes | fail (occurs) | diverges | |
| yes | fail (scope) | fail | |
| no | delay | infinitely many answers | |
| no | delay | 2 answers | |
| yes | already flex-flex; residue kept |
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 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 block is not represented at all. To unify with , the algorithm simply strips the binders, which is rule Abs, and the loose indices of and then play the inner universals: under three binders, is B 0, is B 1, 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; 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.
flexrigidbinds to before pruning, so may still contain markers•inside the arguments of other flexible terms. That is harmless:projthen binds each such to a term that drops those positions, and since is triangular, every laterdevarthrough also goes through and never sees a marker.Nipkow’s ML encodes the marker as the indexB(~10000), which shifting keeps negative. - One walk. Imitation is the copying of
Cheads, projection the renaming of loose indices, the scope check the•in rigid position, and pruning theVcase: this is the book’s “variable elimination”. Inner binders need no set : belowA, indices that refer to local binders are never shifted into markers. devaris . 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 ; 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- implementation adds a test there and delays (Section 7.9.1).
Tutorial (Example 8.H in de Bruijn form). Under the three binders the equation is . Dec on leaves . Here : index (that is ) sits at position from the right, index () at position , and index () is absent. So and . proj meets and prunes: , i.e. . Walking ’s binding through gives , 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 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 :
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. H2Every 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 . The third binds to “ applied to index ” outside any binder: a dangling index, where the mgu is (dup above). The fourth fails, where the mgu is . 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 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 [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
Eagerly, raise over :
Variable elimination immediately prunes , giving , so two of the three raised arguments were wasted work.
Delayed: record that may be raised over and over . When solving, “noting the presence of as an argument of the flexible term and the possibility of raising over , we would replace with the term , where is a new variable quantified at the same place in the prefix as and would produce the unifying substitution for ” [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 then requires (1) the usual occurs-check; (2) that contains no constant with tag greater than ; and (3) that, before binding, the tags of the variables of greater than be lowered to , “to prevent a later instantiation of these variables from violating the restrictions on instantiations for ” (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 , goal . After the quantifiers the goal is . Backchaining on the clause with a new unifies with ; binding lowers to . The remaining goal must be matched against the hypothesis and fails, because has tag . Without step (3), would be bound to and would end up as , mentioning a constant introduced after .
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 with , “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 is quantified within the scope of the quantifier for an existential variable just in case ” (p. 8), so the pattern test becomes local. Raising is restricted to what is needed: for with , needs to be raised only over , the universals among ’s arguments that may depend on. A combined rule (9) binds and to a common new with , 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 for levels, with signature constants at the lowest level. To eliminate in , where pattern means that the are distinct universals with :
- a universal in rigid position is kept if or (since may mention it directly), and fails otherwise;
- a flexible pattern keeps the and the with , prunes the rest, and, if , is also raised over the with that it does not already receive; the new gets level . In Example 7.31, and , so (no arguments) is raised over : with , and , as in the book;
- when no qualifies, raising degenerates to lowering: with 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, Prolog 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 , the universally quantified variables of the clause are instantiated to unification variables where the level records that has only visibility of the initial prefix of length of the context. If later a fresh constant is added by the pi rule, the constant occupies position … and it will not be allowed to occur in instances of the variable ” (p. 4). Lowering a level is done by pruning: “unifying with prunes and to level ” (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.
- 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.
- Orientation of var-var bindings. Today the older variable is bound to the newer one. With scopes, binding a low-level to a high-level lets a later binding of smuggle a young eigenvariable into . Either the orientation must follow levels, or the binding must lower , as in step (3) above.
- Unification allocates. Pruning, raising and the flexible-flexible 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 restriction “can rule out some useful programming idioms” [MN p. 225], the standard one being substitution by meta-level -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 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 -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 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 Prolog 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: is solved by when every index of occurs in (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
bndcan 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 Prolog. 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 unification”; Twelf and Minlog also implement only 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 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 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 : 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 ), and in 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 prefix by raising, to -normal terms, to equal binders by , 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 , flexible terms are patterns with distinct universals bound inside ’s scope. Only 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 to ’s -th bound variable, keep local binders, prune the arguments of other flexible terms that cannot see, and fail on itself (occurs) or on an unseeable universal in rigid position (scope). Then [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,
devaris 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, Prolog interpreter. In Logic for Programming, Artificial Intelligence, and Reasoning (LPAR-20), volume 9450 of LNCS, pages 460–468. Springer, 2015.
- Dynamic : 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 case; the extension needs eigenvariables, binders, flexible applications, levels, allocation inside unification, and a store of delayed equations; see Chapter 11.