Chapter 9

Higher-order miniKanren: the literature

The previous chapters described what λProlog is. It has a logic, higher-order hereditary Harrop formulas (Chapter 3). It has a term language, simply typed λ-terms used as λ-tree syntax (Chapter 4 and Chapter 6). It has a unifier, Huet’s procedure or its decidable core, pattern unification (Chapter 7). And it has a style of programming (Chapter 8). This chapter changes the point of view. Several people have tried to put these ideas into a miniKanren, and several systems implement λProlog efficiently. What did they actually do, and what went wrong?

The user named one paper as the key reference: Ma and Friedman, A New Higher-order Unification Algorithm for λKanren Weixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2021. We present it in full in Section 9.2, followed by a critical assessment against pattern unification and nominal unification (Section 9.3). Then we survey the rest of the literature. The earlier λKanren paper Weixi Ma, Kuang-Chen Lu, and Daniel P. Friedman. Higher-order logic programming with λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2020 comes first (Section 9.4). Then nominal unification and αKanren Christian Urban, Andrew M. Pitts, and Murdoch J. Gabbay. Nominal unification. Theoretical Computer Science, 323(1–3):473–497, 2004; and William E. Byrd and Daniel P. Friedman. α\alphaKanren: A fresh name in nominal logic programming. In Proceedings of the 2007 Workshop on Scheme and Functional Programming, Université Laval Technical Report DIUL-RT-0701, pages 79–90, 2007 (Section 9.5). Then eigenvariables, negation and ∀ inside miniKanren Jason Hemann, William E. Byrd, and Daniel P. Friedman. The eigen operator of miniKanren-with-symbolic-constraints. Software, 2013. URL https://github.com/webyrd/miniKanren-with-symbolic-constraints; Evgenii Moiseenko. Constructive negation for miniKanren. In miniKanren and Relational Programming Workshop, 2019; and Ende Jin, Gregory Rosenblatt, Matthew Might, and Lisa Zhang. Universal quantification and implication in miniKanren. In miniKanren and Relational Programming Workshop, 2021 (Section 9.6). Last come the techniques used by real λProlog systems, Teyjus, ELPI and Makam (Section 9.7). The chapter ends with a comparison table of the design options (Section 9.8). It does not choose between them: the choice is made in Chapter 11.

9.1The map of the territory

The book gives the logic and an operational semantics. It has the search rules and, augment, generic and backchain, plus unification of λ-terms. A miniKanren that wants to host this must answer six concrete questions. The rest of the chapter is organized around them.

  • Q1. Representation of λ-terms. The options are named binders, de Bruijn indices, de Bruijn levels, locally nameless terms, nominal atoms, or explicit substitutions. The goal is to make α-equivalence cheap and to avoid β as far as possible.
  • Q2. Which unification runs inside =°. There are five candidates: first-order (today), nominal (αKanren), Miller’s pattern unification LλL_\lambda (λKanren 2020, Teyjus 2, ELPI), Huet’s full pre-unification, or the “static closures” of Ma and Friedman 2021.
  • Q3. How to implement generic (∀x.G\forall x.G). You need fresh eigen-constants plus a scope check. The check can use an explicit quantifier prefix Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991; and Weixi Ma, Kuang-Chen Lu, and Daniel P. Friedman. Higher-order logic programming with λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2020, numeric universe indices or levels Gopalan Nadathur, Bharat Jayaraman, and Keehang Kwon. Scoping constructs in logic programming: implementation problems and their solution. Journal of Logic Programming, 25(2):119–161, 1995; and Cvetan Dunchev, Ferruccio Guidi, Claudio Sacerdoti Coen, and Enrico Tassi. ELPI: fast, embeddable, λ\lambdaProlog interpreter. In Logic for Programming, Artificial Intelligence, and Reasoning (LPAR-20), volume 9450 of LNCS, pages 460–468. Springer, 2015, or an absento-like constraint over the variables in scope Jason Hemann, William E. Byrd, and Daniel P. Friedman. The eigen operator of miniKanren-with-symbolic-constraints. Software, 2013. URL https://github.com/webyrd/miniKanren-with-symbolic-constraints.
  • Q4. How to implement augment (D⊃GD\supset G). A hypothetical clause must be visible to every relation call made during the proof of GG, and only there. In a shallow embedding this clashes with the lexical scope of host-language procedures.
  • Q5. What to do outside the decidable fragment. You can fail, delay the equation as a constraint, or enumerate unifiers.
  • Q6. How the new features meet the other constraints ≠°, absent° and the type tags. Eigen-constants and disequality do not mix naively.

The historical arc, in the notes’ order: Miller 1991 (LλL_\lambda, mixed prefixes, raising and pruning) Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991; Nipkow 1993 (functional, de Bruijn) 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; Nadathur, Jayaraman and Kwon 1995 (universe indices) 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; Dowek, Hardin, Kirchner and Pfenning 1996 (explicit substitutions) 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; Urban, Pitts and Gabbay 2004 (nominal unification) Christian Urban, Andrew M. Pitts, and Murdoch J. Gabbay. Nominal unification. Theoretical Computer Science, 323(1–3):473–497, 2004; Nadathur and Linnell 2005 (on-the-fly raising) 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; αKanren 2007 William E. Byrd and Daniel P. Friedman. α\alphaKanren: A fresh name in nominal logic programming. In Proceedings of the 2007 Workshop on Scheme and Functional Programming, Université Laval Technical Report DIUL-RT-0701, pages 79–90, 2007; ELPI 2015 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; then the miniKanren papers of 2019–2021 Evgenii Moiseenko. Constructive negation for miniKanren. In miniKanren and Relational Programming Workshop, 2019; Weixi Ma, Kuang-Chen Lu, and Daniel P. Friedman. Higher-order logic programming with λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2020; Weixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2021; and Ende Jin, Gregory Rosenblatt, Matthew Might, and Lisa Zhang. Universal quantification and implication in miniKanren. In miniKanren and Relational Programming Workshop, 2021.

9.2Ma and Friedman 2021: static closures

9.2.1What kind of paper this is

The paper is a ten-page workshop paper, presented at the miniKanren Workshop 2021. Its abstract states the thesis (p. 1):

“λKanren, adapted from λProlog, extends miniKanren with higher-order logic programming. The existing higher-order unification algorithms, however, are neither sound nor complete w.r.t. an “intuitive” understanding of α-equivalence. This paper shows these gaps and proposes a new method to handle α-equivalence in higher-order unification.”

It opens provocatively: “Is there a world where true is equal to false? Indeed, there is, if higher-order unification and miniKanren meet each other” (p. 1).

The background section recalls the one notion from Chapter 7 that the whole paper argues about, in its own words (p. 1): “For an application form FaFa, if FF is a unification variable, then aa must be a list of zero or more distinct bound variables. Such restricted application forms are called patterns and we hereafter refer to the problem identified by Miller as pattern unification.” The related work (p. 7–8) adds Huet’s vocabulary: a term is rigid “if its head symbol is a bound variable or a constant”, and flex “if its head symbol is a unification variable”. Keep in mind one fact for later: in every query of §2–4, the unknown XX sits under a λ but is not applied to anything. It is a pattern with zero arguments, so pattern unification lets it depend on none of the bound variables.

Pitfall (a preview, not an algorithm). The conclusion says: “This paper shows a preview of static closures” (p. 9). The paper has no algorithm listing, no inference rules for unification, no theorems and no proofs. Its formal content is two grammars, three operations on scopes and three worked examples. Its code is a set of REPL transcripts. Soundness and completeness are explicitly future work: “We anticipate extending the formulation of higher-order unification with static closures and derive a sound and complete algorithm for α-equivalence” (p. 9). The rules in Section 9.2.5 below are our own reconstruction, not the paper’s, and we flag them as such. (Where this chapter says “the notes”, it means the unpublished working notes from which this survey was written.)

The paper has seven sections. §1 gives background. §2 asks “grafting or substitution?” (p. 2–4). §3 shows how one can “turn false to true” (p. 4). §4 introduces static closures (p. 5–6). §5 describes a shallow-embedding implementation of the language (p. 6–7). §6 is related work (p. 7–8) and §7 the conclusion. The paper uses two box styles for examples: “solid boxes for examples that are complete and dash boxes for examples that are incomplete or somewhat questionable” (footnote 2, p. 2). In every (run 1 X ...) of the paper, X is simply existentially quantified at the top, outside every λ (footnote 1, p. 2).

9.2.2Grafting versus substitution

First-order miniKanren already has a word for what unification produces. For

> (run 1 X
    (== X 'cat))
'(cat)

the paper says “internally, the answer is a grafting … written as {X↦’cat}\{X\mapsto \texttt{'cat}\}” (p. 2).

Definition 9.1 (Grafting and substitution, p. 2–3).Weixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2021 A grafting {X↦t}\{X\mapsto t\} is a purely textual replacement of the unification variable XX by tt. It is not capture-avoiding: grafting X↦aX\mapsto a into λa. X\lambda a.\, X yields λa. a\lambda a.\, a, so the name aa gets captured. A substitution is the capture-avoiding instantiation of standard higher-order unification: “Standard higher-order unification relies on substitution, but not grafting, to instantiate unification variables. Substitution is capture-avoiding, whereas grafting is not” (p. 3).

In first-order unification the two notions coincide, because there are no binders. They part ways as soon as terms have binders. The paper follows a “novice” through three queries. The first one, α-equivalence of closed terms, is unproblematic:

> (run 1 X
    (== (λ (a) a) (λ (b) b)))
'(_0)

(_0 means that XX is unrestricted). Then, “out of curiosity”, the novice puts the query variable under a binder and asks “Does this query succeed?”:

> (run 1 X
    (== (λ (a) X) (λ (b) b)))
'()

“Surprisingly enough, with higher-order unification, there is no answer.” The novice expects X=aX = a. The reason is the scope restriction.

Definition 9.2 (Scope restriction, p. 3).Weixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2021 “Unification variables are ∃-quantified and lambda variables are ∀-quantified. A scope is a list of those quantifiers. Further, a ∀-quantified variable may instantiate (or occurs in the instantiation of) an ∃-quantified variable, only if the ∀ variable precedes the ∃ variable in the scope.” As a side condition on a binding in a mixed prefix QQ:

X is ∃-quantified in Q∀y∈FV∀(t).  y≺QXX↦t is allowed \dfrac{X \text{ is } \exists\text{-quantified in } Q \qquad \forall y\in FV_\forall(t).\; y \prec_Q X} {X\mapsto t \text{ is allowed}}

For λa.X =? λb.b the scope is '((∃ X) (∀ a)). The variable aa comes after XX, so it cannot instantiate XX. This is exactly λProlog’s behaviour: it is the eigenvariable condition of generic (Chapter 3), and in unification it is what raising and pruning enforce (Chapter 7). The paper draws the opposite conclusion (p. 3): “It is fair to say that the existing pattern unification algorithms are not complete w.r.t. the natural sense of α-equivalence.” It also says (p. 3): “For beginners who are not familiar with higher-order unification, α-equivalence is only decided by the binder positions. But pattern unification imposes an appendage limitation by taking unification variables into account.”

A conjunction shows why the restriction has a reason to exist (dashed box, p. 3):

> (run 1 X
    (== (λ (a) X) (λ (b) b))
    (== (λ (c) X) (λ (d) d)))

“Associating X with a cannot work, neither does c. If we text-replace X with either, then the other one fails.” The paper’s first proposal is to stop treating λ-variables as names: “We first propose to treat unification variables and lambda variables differently. In particular, lambda variables are effectively constants if they are represented by de Bruijn levels” (p. 3).

Definition 9.3 (de Bruijn levels and indices, footnote 3, p. 4).Weixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2021 “There are two ways to implement de Bruijn’s nameless syntax, indices and levels. Both use numbers to represent variables” N. G. de Bruijn. Lambda calculus notation with nameless dummies, a tool for automatic formula manipulation, with application to the Church–Rosser theorem. Indagationes Mathematicae, 34(5):381–392, 1972. A level counts binders from the outside: the outermost binder is 00. An index counts binders from the inside: the nearest binder is 00.

Example 9.4. In λc. λd. c\lambda c.\, \lambda d.\, c, the variable cc has level 00 and index 11, and dd has level 11 and index 00. The term is λ.λ. 0\lambda.\lambda.\,0 with levels and λ.λ. 1\lambda.\lambda.\,1 with indices. The paper writes the level ℓ\ell as dℓ\ell. So d0 names the outermost enclosing binder, whatever it is called, and the answer '(d0) reads: “these two terms can be made α-equal, if X corresponds to de Bruijn level 0” (p. 3).

With levels, the two problematic queries succeed (solid boxes, p. 3):

> (run 1 X
    (== (λ (a) X) (λ (b) b)))
'(d0)
> (run 1 X
    (== (λ (a) X) (λ (b) b))
    (== (λ (c) X) (λ (d) d)))
'(d0)

“If we instantiate X with d0 and reify these levels w.r.t. their binders, we have the problem solved with no surprise”: the two equations become (== (λ (a) a) (λ (b) b)) and (== (λ (c) c) (λ (d) d)). The paper goes on (p. 3–4): “using grafting with de Bruijn levels captures the essence of α-equivalence: names don’t matter. A unification algorithm based on de Bruijn levels would also be more straightforward because it’s practically first-order. But, we cannot yet lift the scope restriction on lambda variables and drop in de Bruijn levels, because sometimes names do matter and …”. The sentence continues in the title of §3.

Kanren angle ((aux kanren micro) already grafts). Grafting is what a first-order unifier does on nameless terms. Today’s (aux kanren micro) unifies records slot by slot, so a define-record is a new term constructor for free. If we write λ-terms with de Bruijn indices as records, =° grafts. It reproduces the paper’s answers, and also the problems discussed below. The demonstration uses indices, not levels; for the examples here only the outermost binder matters, and it is index 00 under one λ.

(import scheme (chicken base) (chicken pretty-print)
        (aux base) (aux stream) (aux kanren micro))

(define-syntax-rule (show label expr)
  (begin (display ";; ") (display label) (newline)
         (pretty-print expr)))

;; 1. Named binders as plain lists: syntactic unification ignores alpha.
(show "named: (λ a a) = (λ b b)"
  (°->list #f (fresh° (q) (=° '(λ a a) '(λ b b)))))

;; 2. Nameless binders as records with de Bruijn indices.
(define-record lam body)
(define-record dbi n)
(define (λ. t) (make-lam t))
(define (ix n) (make-dbi n))

(show "de Bruijn: λ.0 = λ.0"
  (°->list #f (fresh° (q) (=° (λ. (ix 0)) (λ. (ix 0))))))
(show "grafting: λa.X = λb.b"
  (°->list #f (fresh° (x) (=° (λ. x) (λ. (ix 0))))))
(show "grafting: λa.X = λb.b  and  λc.X = λd.d"
  (°->list #f (fresh° (x) (=° (λ. x) (λ. (ix 0)))
                          (=° (λ. x) (λ. (ix 0))))))
(show "true = false: λa.λa.X = λc.λd.c"
  (°->list #f (fresh° (x) (=° (λ. (λ. x)) (λ. (λ. (ix 1)))))))
(show "dangling: λa.X = λb.b, then Q = X at top level"
  (°->list #f (fresh° (q) (fresh° (x) (=° (λ. x) (λ. (ix 0)))
                                      (=° q x)))))
;; named: (λ a a) = (λ b b)
()
;; de Bruijn: λ.0 = λ.0
((λ (α) α))
;; grafting: λa.X = λb.b
((λ () (make-record-instance 'dbi 0)))
;; grafting: λa.X = λb.b  and  λc.X = λd.d
((λ () (make-record-instance 'dbi 0)))
;; true = false: λa.λa.X = λc.λd.c
((λ () (make-record-instance 'dbi 1)))
;; dangling: λa.X = λb.b, then Q = X at top level
((λ () (make-record-instance 'dbi 0)))

The first query shows that named binders as plain data are useless: α-equivalent terms do not unify. The next three reproduce the paper’s '(_0), '(d0), '(d0). The fifth is the “true = false” problem of the next subsection. The answer (dbi 1) is perfectly correct for the nameless terms, but it denotes the outer binder. In the user’s named term λa. λa. X\lambda a.\, \lambda a.\, X that binder is shadowed. The last query shows a dangling index: QQ lives at top level, outside every binder, yet it is bound to “the nearest binder”. Section 9.3 returns to it.

9.2.3Binder-merging and “true = false”

Definition 9.5 (Binder-merging, p. 4).Weixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2021 “When two terms are unified, one term’s binders are replaced by the other’s. Then α-equivalence is as simple as structural equivalence.” The paper says that it is “used in all pattern unification algorithms, except for those with de Bruijn numbers”.

Example 9.6 (binder-merging at work, p. 4).

λx. λy. X x y=?λa. λb. a b  ⟶  λa. λb. X a b=?λa. λb. a b \lambda x.\, \lambda y.\, X\,x\,y \stackrel{?}{=} \lambda a.\, \lambda b.\, a\,b \;\longrightarrow\; \lambda a.\, \lambda b.\, X\,a\,b \stackrel{?}{=} \lambda a.\, \lambda b.\, a\,b

This is solved by {X↦λa. λb. a b}\{X\mapsto \lambda a.\, \lambda b.\, a\,b\}. Instantiating gives

λa. λb. ((λa. λb. a b) a b), \lambda a.\, \lambda b.\, ((\lambda a.\, \lambda b.\, a\,b)\,a\,b),

which β-reduces to λa. λb. a b\lambda a.\, \lambda b.\, a\,b.

Now take a binder name that is reused, i.e. shadowing (dashed box, p. 4):

> (run 1 X
    (== (λ (a) (λ (a) X)) (λ (c) (λ (d) c))))

“With either binder-merging or de Bruijn syntax, the unification problem is effectively reduced to” λc. λd. X=?λc. λd. c\lambda c.\, \lambda d.\, X\stackrel{?}{=}\lambda c.\, \lambda d.\, c. “Then it appears to be solvable by {X↦c}\{X\mapsto c\}, or equivalently {X↦d0}\{X\mapsto \texttt{d0}\}, that associates XX with the outer-binder.” Naive reification, which writes each level back as the name of its binder, then gives

(== (λ (a) (λ (a) a)) (λ (c) (λ (d) c)))

“which claims that the λ-encoded false is true!” With Church booleans 𝗍𝗋𝗎𝖾=λt. λf. t\mathsf{true}=\lambda t.\, \lambda f.\, t and 𝖿𝖺𝗅𝗌𝖾=λt. λf. f\mathsf{false}=\lambda t.\, \lambda f.\, f, the left-hand side λa. λa. a\lambda a.\, \lambda a.\, a is α-equivalent to 𝖿𝖺𝗅𝗌𝖾\mathsf{false}, because the occurrence aa refers to the inner binder. The right-hand side is 𝗍𝗋𝗎𝖾\mathsf{true}.

The paper argues that binder-merging goes wrong “even without lifting the scope restrictions”:

λx. λy. x y=?λa. λa. a ais converted toλa. λa. a a=?λa. λa. a a, \lambda x.\, \lambda y.\, x\,y \stackrel{?}{=} \lambda a.\, \lambda a.\, a\,a \quad\text{is converted to}\quad \lambda a.\, \lambda a.\, a\,a \stackrel{?}{=} \lambda a.\, \lambda a.\, a\,a,

“which then ends up with another false positive”. The correct answer is failure: λa. λa. a a≡αλa. λb. b b\lambda a.\, \lambda a.\, a\,a\equiv_\alpha\lambda a.\, \lambda b.\, b\,b applies the inner variable to itself. The paper’s claim: “binder-merging does not handle the name shadowing problem. This is overlooked by all pattern unification algorithms. Algorithms that use what we call binder-merging state upfront that they don’t consider name shadowing”. Nipkow–Prehofer and Qian are cited as examples. The existing remedies are “a pre-processor that adds gensyms to lambda variables to make each individual unique or a smart reifier that detects name shadowing” (p. 4). Their downsides are unreadable gensyms and extra complexity. The related work gives a real case (p. 8): Agda uses de Bruijn numbers in its core language, so it “must make all variable names unique in a “gensym” manner”, which “bloats type checking with randomly generated symbols and makes the error messages painful to read”.

9.2.4Static closures

“We propose a simple and efficient alternative, static closures. Static closures are integrated into the unification process and they decide α-equivalence while correctly handling name shadowing. We obtain a new algorithm by extending traditional pattern unification with static closures” (p. 5). No efficiency evidence or complexity bound is given.

Definition 9.7 (Terms, scopes, static closures, Fig. 1, p. 5).Weixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2021

t::=Xunification variable∣t  tfunction application∣λa. tnamed binder∣aname∣λ tnameless binder (derived)∣ℓlevel (derived)ϕ::=ϵ∣a,ϕscopeκ::=⟨ϕ; t⟩static closure \begin{array}{rcll} t & ::= & X & \text{unification variable}\\ & \mid & t\;t & \text{function application}\\ & \mid & \lambda a.\, t & \text{named binder}\\ & \mid & a & \text{name}\\ & \mid & \lambda\,t & \text{nameless binder (derived)}\\ & \mid & \ell & \text{level (derived)}\\[2pt] \phi & ::= & \epsilon \mid a,\phi & \text{scope}\\ \kappa & ::= & \langle \phi;\,t\rangle & \text{static closure} \end{array}

“The nameless syntax, i.e., nameless-binders and levels are derived during unification” (p. 5): the user writes only XX, t tt\,t, λa. t\lambda a.\, t and aa. “A static closure is a pair of a scope and a unification term. A scope is a list of binders. In essence, a static closure captures the surrounding binders of a term. E.g., the term λa.λb.X reduces to the static closure ⟨a,b; X⟩\langle a,b;\,X\rangle.”

Two remarks from our notes. First, the grammar has no constants, although the examples use them ('cat); read “name” as covering free constants too. Second, the grammar conses on the left (a,ϕa,\phi), but the example writes the scope of λa. λb. X\lambda a.\, \lambda b.\, X as a,ba,b, outermost first. We adopt outermost first: then the level of a binder is its position in the scope.

Definition 9.8 (Operations on scopes, p. 5).Weixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2021 In the paper’s words:

  • “ext(ϕ,a)\mathrm{ext}(\phi,a) adds the name aa to the scope ϕ\phi. If aa has been previously added to ϕ\phi, then this older one is shadowed and its corresponding level becomes unusable.”
  • “db(ϕ,a)\mathrm{db}(\phi,a) is 𝖩𝗎𝗌𝗍  ℓ\mathsf{Just}\;\ell where ℓ\ell is the de Bruijn level of aa w.r.t. the scope ϕ\phi, if aa is not shadowed in ϕ\phi; otherwise, the result is 𝖭𝗈𝗍𝗁𝗂𝗇𝗀\mathsf{Nothing}.”
  • “db(ϕ,ℓ)\mathrm{db}(\phi,\ell) is 𝖩𝗎𝗌𝗍  ℓ\mathsf{Just}\;\ell, if ℓ\ell is available in ϕ\phi; otherwise, the result is 𝖭𝗈𝗍𝗁𝗂𝗇𝗀\mathsf{Nothing}.”

So db\mathrm{db} is overloaded. On a name it converts the name to a level; on a level it checks that the level is available. The notes make this precise. Write ϕ=a0,…,an−1\phi=a_0,\dots,a_{n-1} outermost first:

ext(ϕ,a)=ϕ,aavail(ϕ)={ℓ<∣ϕ∣  :  aℓ∉{aℓ+1,…,an−1}} \mathrm{ext}(\phi,a)=\phi,a\qquad \mathrm{avail}(\phi)=\{\ell<|\phi| \;:\; a_\ell\notin\{a_{\ell+1},\dots,a_{n-1}\}\} db(ϕ,a)={𝖩𝗎𝗌𝗍  max⁡{ℓ:aℓ=a}a∈ϕ𝖭𝗈𝗍𝗁𝗂𝗇𝗀a∉ϕ \mathrm{db}(\phi,a)=\begin{cases}\mathsf{Just}\;\max\{\ell : a_\ell=a\} & a\in\phi\\ \mathsf{Nothing} & a\notin\phi\end{cases} db(ϕ,ℓ)={𝖩𝗎𝗌𝗍  ℓℓ∈avail(ϕ)𝖭𝗈𝗍𝗁𝗂𝗇𝗀otherwise \mathrm{db}(\phi,\ell)=\begin{cases}\mathsf{Just}\;\ell & \ell\in\mathrm{avail}(\phi)\\ \mathsf{Nothing}&\text{otherwise}\end{cases}

In words: a level is available if its binder’s name is not rebound further in. The name-to-level case needs an interpretation. An occurrence of a name always refers to its innermost binder, which is never shadowed, so the paper’s “if aa is not shadowed” can only mean “the innermost aa”. The other reading would make λa. λa. a\lambda a.\, \lambda a.\, a impossible to convert, which is absurd. This remains an interpretation.

Tutorial (the three examples of §4, step by step). Example 1 (p. 5). Both sides are turned into closures:

λa. λb. X=?λc. λd. c  ⟶  ⟨a,b; X⟩=?⟨c,d; c⟩. \lambda a.\, \lambda b.\, X \stackrel{?}{=} \lambda c.\, \lambda d.\, c \;\longrightarrow\; \langle a,b;\,X\rangle \stackrel{?}{=} \langle c,d;\,c\rangle.

“We first apply db on the right-hand side”: db((c,d),c)=𝖩𝗎𝗌𝗍  0\mathrm{db}((c,d),c)=\mathsf{Just}\;0, so the problem is ⟨a,b; X⟩=?𝖩𝗎𝗌𝗍  0\langle a,b;\,X\rangle\stackrel{?}{=}\mathsf{Just}\;0. “Then we try to solve X by applying db on the scope of the left-hand side and 0”: db((a,b),0)=𝖩𝗎𝗌𝗍  0\mathrm{db}((a,b),0)=\mathsf{Just}\;0, because aa is not rebound. Then 𝖩𝗎𝗌𝗍  0=?𝖩𝗎𝗌𝗍  0\mathsf{Just}\;0\stackrel{?}{=}\mathsf{Just}\;0. “It works. So, the solution is {X↦d0}\{X\mapsto\texttt{d0}\}.”

Example 2 (p. 5–6), the shadowing case:

λa. λa. X=?λc. λd. c  ⟶  ⟨a,a; X⟩=?⟨c,d; c⟩. \lambda a.\, \lambda a.\, X \stackrel{?}{=} \lambda c.\, \lambda d.\, c \;\longrightarrow\; \langle a,a;\,X\rangle \stackrel{?}{=} \langle c,d;\,c\rangle.

As before, the right side gives 𝖩𝗎𝗌𝗍  0\mathsf{Just}\;0. “This time, db(⟨a,a;0⟩\langle a, a; 0\rangle) is Nothing because the outer binder a is shadowed”. Here the paper puts the 00 inside the closure brackets, an abuse of notation for db((a,a),0)\mathrm{db}((a,a),0). We get 𝖭𝗈𝗍𝗁𝗂𝗇𝗀=?𝖩𝗎𝗌𝗍  0\mathsf{Nothing}\stackrel{?}{=}\mathsf{Just}\;0, “and we know the unification fails”. True is not false any more.

Example 3 (p. 6), two unknowns:

λa. λb. X=?λc. λd. Y  ⟶  ⟨a,b; X⟩=?⟨c,d; Y⟩. \lambda a.\, \lambda b.\, X \stackrel{?}{=} \lambda c.\, \lambda d.\, Y \;\longrightarrow\; \langle a,b;\,X\rangle \stackrel{?}{=} \langle c,d;\,Y\rangle.

“Here, the grafting itself is not able to describe the solution. Now our solution needs a context: the set of equations between static closures of unification variables. This problem has the solution: the grafting being empty and the context being {⟨a,b; X⟩=?⟨c,d; Y⟩}\{\langle a,b;\,X\rangle\stackrel{?}{=}\langle c,d;\,Y\rangle\}.” The paper adds that, in practice, “the accumulated equations between closures of one unification problem are usually solved and reduced to grafting, during the unification on other problems”.

So a solution is a pair (θ,C)(\theta,C): a grafting θ\theta and a context CC of postponed flex-flex equations between closures. This is analogous to the flex-flex pairs that Huet’s procedure leaves unsolved (Chapter 7).

9.2.5A reconstruction of the rules (not in the paper)

To check that the three examples fit together, we wrote a minimal rule system that reproduces all of them. It was implemented as a standalone CHICKEN program of about 150 lines, which does not use (aux kanren micro). We repeat that this is our reconstruction, not the authors' algorithm.

Level form. A surface term tt under scope ϕ\phi is converted to internal syntax ⟦t⟧ϕ\llbracket t\rrbracket_\phi:

⟦X⟧ϕ=⟨ϕ; X⟩⟦a⟧ϕ={ℓdb(ϕ,a)=𝖩𝗎𝗌𝗍  ℓaotherwise (a constant) \llbracket X\rrbracket_\phi=\langle \phi;\,X\rangle\qquad \llbracket a\rrbracket_\phi=\begin{cases}\ell & \mathrm{db}(\phi,a)=\mathsf{Just}\;\ell\\ a&\text{otherwise (a constant)}\end{cases} ⟦λa. t⟧ϕ=λ ⟦t⟧ext(ϕ,a)⟦t u⟧ϕ=⟦t⟧ϕ ⟦u⟧ϕ \llbracket \lambda a.\, t\rrbracket_\phi=\lambda\,\llbracket t\rrbracket_{\mathrm{ext}(\phi,a)}\qquad \llbracket t\,u\rrbracket_\phi=\llbracket t\rrbracket_\phi\,\llbracket u\rrbracket_\phi

Both sides of an equation are converted from ϵ\epsilon, so they are always compared at equal depth. A binding is θ(X)=(ϕ0,t)\theta(X)=(\phi_0,t), where tt is in level form at depth ∣ϕ0∣|\phi_0|. Levels below ∣ϕ0∣|\phi_0| are free (scope) levels; the others are bound inside tt. To instantiate θ(X)\theta(X) at an occurrence ⟨ϕ; X⟩\langle \phi;\,X\rangle:

  • a free level ℓ\ell must satisfy db(ϕ,ℓ)=𝖩𝗎𝗌𝗍  ℓ\mathrm{db}(\phi,\ell)=\mathsf{Just}\;\ell, or else the occurrence fails;
  • a local level ℓ≥∣ϕ0∣\ell\ge|\phi_0| is shifted to ℓ+∣ϕ∣−∣ϕ0∣\ell+|\phi|-|\phi_0|;
  • a nested closure is re-rooted at ϕ\phi.

Rules. The judgement is θ;C⊢t=?u⇒θ′;C′\theta;C\vdash t\stackrel{?}{=} u\Rightarrow\theta';C'. Terms are walked first, i.e. a bound closure is replaced by its instance. Any pair of head constructors not listed fails.

θ;C⊢ℓ=?ℓ⇒θ;C  Lvlc a constantθ;C⊢c=?c⇒θ;C  Constθ;C⊢t=?u⇒θ′;C′θ;C⊢λt=?λu⇒θ′;C′  Lam \dfrac{}{\theta;C\vdash \ell\stackrel{?}{=}\ell \Rightarrow \theta;C}\;\text{Lvl} \qquad\qquad \dfrac{c\text{ a constant}}{\theta;C\vdash c\stackrel{?}{=} c \Rightarrow \theta;C}\;\text{Const} \qquad\qquad \dfrac{\theta;C\vdash t\stackrel{?}{=} u\Rightarrow\theta';C'}{\theta;C\vdash \lambda t\stackrel{?}{=}\lambda u\Rightarrow\theta';C'}\;\text{Lam} θ;C⊢t1=?u1⇒θ1;C1θ1;C1⊢t2=?u2⇒θ2;C2θ;C⊢t1 t2=?u1 u2⇒θ2;C2  App \dfrac{\theta;C\vdash t_1\stackrel{?}{=} u_1\Rightarrow\theta_1;C_1 \qquad \theta_1;C_1\vdash t_2\stackrel{?}{=} u_2\Rightarrow\theta_2;C_2} {\theta;C\vdash t_1\,t_2\stackrel{?}{=} u_1\,u_2\Rightarrow\theta_2;C_2}\;\text{App} X∉dom θFL<∣ϕ∣(t)⊆avail(ϕ)X∉FV(t)θ[X↦(ϕ,t)];∅⊢C⇒θ′;C′θ;C⊢⟨ϕ; X⟩=?t⇒θ′;C′  Graft \dfrac{X\notin\mathrm{dom}\,\theta \qquad FL_{<|\phi|}(t)\subseteq\mathrm{avail}(\phi) \qquad X\notin FV(t) \qquad \theta[X\mapsto(\phi,t)];\emptyset\vdash C\Rightarrow\theta';C'} {\theta;C\vdash\langle \phi;\,X\rangle\stackrel{?}{=} t\Rightarrow\theta';C'}\;\text{Graft} θ;C⊢⟨ϕ; X⟩=?⟨ϕ; X⟩⇒θ;C  ReflX,Y∉dom θ(X,ϕ)≠(Y,ψ)θ;C⊢⟨ϕ; X⟩=?⟨ψ; Y⟩⇒θ;C∪{⟨ϕ; X⟩=?⟨ψ; Y⟩}  Postpone \dfrac{}{\theta;C\vdash\langle \phi;\,X\rangle\stackrel{?}{=}\langle \phi;\,X\rangle\Rightarrow\theta;C}\;\text{Refl} \qquad\qquad \dfrac{X,Y\notin\mathrm{dom}\,\theta \qquad (X,\phi)\neq(Y,\psi)} {\theta;C\vdash\langle \phi;\,X\rangle\stackrel{?}{=}\langle \psi;\,Y\rangle\Rightarrow\theta;C\cup\{\langle \phi;\,X\rangle\stackrel{?}{=}\langle \psi;\,Y\rangle\}}\;\text{Postpone}

In Graft, tt is not an unbound closure. FV(t)FV(t) is the set of unification variables of tt (the occurs check). FL<∣ϕ∣(t)FL_{<|\phi|}(t) is the set of levels below ∣ϕ∣|\phi| that occur in tt: those that point into the scope ϕ\phi rather than to a nameless binder inside tt. The availability premise says that a solution may mention only scope binders that are visible, i.e. not shadowed, at the occurrence of XX. The premise “⊢C\vdash C” means that every postponed equation is solved again, the wake-up. Example 2 fails in the availability premise of Graft: FL(0)={0}⊈avail(a,a)={1}FL(0)=\{0\}\not\subseteq\mathrm{avail}(a,a)=\{1\}.

Tutorial (a wake-up, step by step). Take Example 3 and then bind YY, in two variants. Both start from λa. λb. X=?λc. λd. Y\lambda a.\, \lambda b.\, X\stackrel{?}{=}\lambda c.\, \lambda d.\, Y (first variant) or λa. λa. X=?λc. λd. Y\lambda a.\, \lambda a.\, X\stackrel{?}{=}\lambda c.\, \lambda d.\, Y (second variant).

  1. Conversion gives λλ⟨a,b; X⟩=?λλ⟨c,d; Y⟩\lambda\lambda\langle a,b;\,X\rangle\stackrel{?}{=}\lambda\lambda\langle c,d;\,Y\rangle. Lam twice, then Postpone: θ=∅\theta=\emptyset, C={⟨a,b; X⟩=?⟨c,d; Y⟩}C=\{\langle a,b;\,X\rangle\stackrel{?}{=}\langle c,d;\,Y\rangle\}. This is the line (X ctx: 1) below.
  2. The second equation λc. λd. Y=?λc. λd. c\lambda c.\, \lambda d.\, Y\stackrel{?}{=}\lambda c.\, \lambda d.\, c converts to λλ⟨c,d; Y⟩=?λλ 0\lambda\lambda\langle c,d;\,Y\rangle\stackrel{?}{=}\lambda\lambda\,0. Graft checks FL(0)={0}⊆avail(c,d)={0,1}FL(0)=\{0\}\subseteq\mathrm{avail}(c,d)=\{0,1\} and binds Y↦((c,d),0)Y\mapsto((c,d),0).
  3. Wake-up: CC is solved again. Walking ⟨c,d; Y⟩\langle c,d;\,Y\rangle instantiates YY’s solution at (c,d)(c,d), giving 00. The equation becomes ⟨a,b; X⟩=?0\langle a,b;\,X\rangle\stackrel{?}{=} 0, and Graft checks 0∈avail(a,b)0\in\mathrm{avail}(a,b). It holds, so X↦((a,b),0)X\mapsto((a,b),0), printed d0.
  4. In the second variant the same wake-up yields ⟨a,a; X⟩=?0\langle a,a;\,X\rangle\stackrel{?}{=} 0, but avail(a,a)={1}\mathrm{avail}(a,a)=\{1\}, so the whole conjunction fails.

The second variant is “true = false” again, smuggled through the context. A wake-up that only re-unified, without the availability check, would accept it.

Running the prototype gives the following results. In (λ d1) the level is printed absolute, at the depth where XX was solved.

X = cat                               => (cat ctx: 0)
λa.a = λb.b                           => (X ctx: 0)
λa.X = λb.b                           => (d0 ctx: 0)
λa.X = λb.b ∧ λc.X = λd.d             => (d0 ctx: 0)
λa.λa.X = λc.λd.c  (true=false)       => FAIL
λx.λy.(x y) = λa.λa.(a a)             => FAIL
Ex1 λa.λb.X = λc.λd.c                 => (d0 ctx: 0)
Ex2 λa.λa.X = λc.λd.c                 => FAIL
Ex3 λa.λb.X = λc.λd.Y                 => (X ctx: 1)
Ex3 then λc.λd.Y = λc.λd.c            => (d0 ctx: 0)
λa.λa.X = λc.λd.Y then Y = d0         => FAIL
λa.X = λb.λc.c ; λa.λb.X = λ_.λ_.λc.c => ((λ d1) ctx: 0)
λa.X = λb.λc.b                        => ((λ d0) ctx: 0)
λa.X = λb.b ∧ X = cat                 => FAIL
λa.X = λb.b ∧ λa.λa.X = λc.λd.d       => FAIL
λa.λb.X = λa.λb.a ∧ λb.λa.X = λc.λd.c => (d0 ctx: 0)

Three lines are worth reading closely. In “λa.λa.X = λc.λd.Y then Y = d0”, the wake-up must re-run the availability check, or the shadowing bug comes back through the context. In “λa.X = λb.λc.c ; …”, a binder inside a grafted solution must be shifted when the solution is used at a different depth. The last line shows that the semantics is positional: the binder names above XX are irrelevant as long as no level is shadowed.

9.2.6The language: Horn clauses, assume, all

§5 of the paper (p. 6–7) recalls the logic from the 2020 paper Weixi Ma, Kuang-Chen Lu, and Daniel P. Friedman. Higher-order logic programming with λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2020. Its Fig. 2 contrasts Horn clauses with hereditary Harrop formulas. In the figure the shared rows are D::=G⊃D∣D∧D∣∀x DD::=G\supset D\mid D\wedge D\mid\forall x\,D and G::=G∧G∣G∨G∣∃x GG::=G\wedge G\mid G\vee G\mid\exists x\,G, and the HH-only rows are D⊃GD\supset G and ∀x G\forall x\,G for goals. The atoms AA and ⊤\top are missing from the figure. With them it is exactly the book’s grammar (3.1) [MN p. 91]:

G::=⊤∣A∣G∧G∣G∨G∣∃x G∣D⊃G∣∀x GD::=A∣G⊃D∣D∧D∣∀x D. \begin{gathered} G ::= \top \mid A \mid G\wedge G \mid G\vee G \mid \exists x\,G \mid D\supset G \mid \forall x\,G\\ D ::= A \mid G\supset D \mid D\wedge D \mid \forall x\,D . \end{gathered}

The four code boxes are these (all solid, p. 6–7):

> (run* (X Y)
    (conde
      [(== X Y) (== X 'cat)]
      [(== X 'cat) (== Y 'dog)]))
'((cat cat) (cat dog))

(define (empty? X)
  (== X '()))

>(run 2 X
   (assume (== 'apple 'orange)
     (== 'apple X)))
'(apple orange)

>(run 1 F
   (all (A)
     (== A (F A))))
'((lambda (_0) _0))

The paper prints conde with a superscript e. The first box is ∃X∃Y((X=Y∧X=’cat)∨(X=’cat∧Y=’dog))\exists X\exists Y((X=Y\wedge X=\texttt{'cat})\vee(X=\texttt{'cat}\wedge Y=\texttt{'dog})). The define is the clause ∀X (X=’())⊃(empty?  X)\forall X\,(X=\texttt{'()})\supset(\texttt{empty?}\;X). assume “introduces hypotheses in its clause. As an example, we may use the assume operator to temporarily extend the == relation”. Our reading, inferred because the paper gives no operational account: the first answer comes from ordinary unification, and the second from the hypothesis used as a clause whose head matches (== 'apple X) with X=orangeX=\texttt{orange}. For all, “we may synthesize a function that yields whatever it takes in”. Also, “the == operator recognizes β-equivalence. Indeed, it will be powered by the unification algorithm proposed in the last section and recognize αβ-equivalence” (p. 7). Note that (F A) is a Miller pattern (Chapter 7): a variable applied to a distinct eigenvariable.

9.3A critical assessment of static closures

The paper attacks pattern unification. The fair comparison also includes nominal unification (Section 9.5), which the paper mentions only in related work. This section gives our own analysis. In the λProlog column, XX (and YY) are quantified outside the λ, as in the paper’s queries.

problemλProlog (patterns)αKanren (nominal)static closures
λa. a=?λb. b\lambda a.\, a\stackrel{?}{=}\lambda b.\, b✓✓✓
λa. X=?λb. b\lambda a.\, X\stackrel{?}{=}\lambda b.\, b✗ (scope)✓ X=aX=a✓ X=d0X=\texttt{d0}
… ∧ λc. X=?λd. d\wedge\ \lambda c.\, X\stackrel{?}{=}\lambda d.\, d✗✗ (a≠ca\neq c)✓ d0
λa. λa. X=?λc. λd. c\lambda a.\, \lambda a.\, X\stackrel{?}{=}\lambda c.\, \lambda d.\, c✗✗ (needs a#aa\#a)✗
λx. λy. x y=?λa. λa. a a\lambda x.\, \lambda y.\, x\,y\stackrel{?}{=}\lambda a.\, \lambda a.\, a\,a✗✗✗
λa. λb. X=?λc. λd. Y\lambda a.\, \lambda b.\, X\stackrel{?}{=}\lambda c.\, \lambda d.\, Y✓ X=YX=Y (neither may depend on a,b,c,da,b,c,d)X=(a c)(b d)⋅YX=(a\,c)(b\,d)\cdot Y with a#Ya\#Y, b#Yb\#Ypostponed
Table 9.1: The paper’s examples under three semantics (our analysis, after).Weixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2021

Tutorial (what λProlog offers the novice instead: make the dependency explicit). The paper calls the failure of λa. X=?λb. b\lambda a.\, X\stackrel{?}{=}\lambda b.\, b counter-intuitive. Miller’s 1991 paper Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, p. 4–5 explains why it is the intended behaviour, and how to get the novice’s answer anyway. Its program is the usual append, and its goal is ∀y (𝚊𝚙𝚙𝚎𝚗𝚍  (𝚌𝚘𝚗𝚜  a  (𝚌𝚘𝚗𝚜  b  𝚗𝚒𝚕))  y  X)\forall y\,(\mathtt{append}\;(\mathtt{cons}\;a\;(\mathtt{cons}\;b\;\mathtt{nil}))\;y\;X). generic replaces yy by a new constant kk, and backchaining twice would need X=𝚌𝚘𝚗𝚜  a  (𝚌𝚘𝚗𝚜  b  k)X=\mathtt{cons}\;a\;(\mathtt{cons}\;b\;k). This is rejected, and Miller says why: “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.” If we do want a value that depends on yy, we must say so, by writing (H  y)(H\;y) instead of XX. Then (H  k)(H\;k) must equal 𝚌𝚘𝚗𝚜  a  (𝚌𝚘𝚗𝚜  b  k)\mathtt{cons}\;a\;(\mathtt{cons}\;b\;k). Two λ-terms would do, λw. 𝚌𝚘𝚗𝚜  a  (𝚌𝚘𝚗𝚜  b  k)\lambda w.\, \mathtt{cons}\;a\;(\mathtt{cons}\;b\;k) and λw. 𝚌𝚘𝚗𝚜  a  (𝚌𝚘𝚗𝚜  b  w)\lambda w.\, \mathtt{cons}\;a\;(\mathtt{cons}\;b\;w), but “since HH cannot contain kk free, only the second” is legal. Miller calls this “discharging the constant kk”.

The same move answers the novice. Write λa. (X  a)=?λb. b\lambda a.\, (X\;a)\stackrel{?}{=}\lambda b.\, b: this is a pattern (XX applied to one bound variable), and its most general unifier is X↦λx. xX\mapsto\lambda x.\, x. The conjunction with λc. (X  c)=?λd. d\lambda c.\, (X\;c)\stackrel{?}{=}\lambda d.\, d is solved by the same XX, and a top-level Q=XQ=X gets the closed term λx. x\lambda x.\, x, with nothing dangling. Both λKanren papers show this style of query: (== (tie (a b) (app a b)) (tie (x y) (app f x y))) of 2020 and (all (A) (== A (F A))) of 2021 (Section 9.2.6 and Section 9.4). Static closures make this dependency implicit: ⟨ϕ; X⟩\langle \phi;\,X\rangle behaves like XX applied to the available levels of ϕ\phi (observation 1 below).

9.3.1Three counter-examples

The notes isolate three examples that pin down what static closures really are. They are worth keeping as regression tests for any implementation, whatever it chooses.

Tutorial (Counter-example 1: the conjunction separates static closures from nominal unification). Problem: λa. X=?λb. b ∧ λc. X=?λd. d\lambda a.\, X\stackrel{?}{=}\lambda b.\, b\ \wedge\ \lambda c.\, X\stackrel{?}{=}\lambda d.\, d.

Nominal, using the rule a.t≈?b.s⇒t≈?(a b)⋅s, a#?sa.t\approx^? b.s\Rightarrow t\approx^?(a\,b)\cdot s,\ a\#^? s of Section 9.5. The first equation gives X≈?(a b)⋅b=aX\approx^?(a\,b)\cdot b=a with a#ba\#b, which holds, so X:=aX:=a. The second becomes c.a≈?d.dc.a\approx^?d.d, i.e. a≈?(c d)⋅d=ca\approx^?(c\,d)\cdot d=c, which fails. Nominal unification thus agrees with static closures on the single equation (XX is the bound name) and disagrees on the conjunction.

Pattern: both equations fail at once, by the scope restriction.

Static closures: X↦d0X\mapsto\texttt{d0} satisfies both.

So static closures are neither pattern unification nor nominal unification. XX denotes an open term relative to the binder depth. This is grafting on de Bruijn terms without the “pre-cooking” step of Dowek et al. (Section 9.7.3).

Tutorial (Counter-example 2: the same variable at two depths dangles). Problem: (== Q X) together with (== (λ (a) X) (λ (b) b)).

Under static closures, X↦d0X\mapsto\texttt{d0}, so the top-level answer is Q=d0Q=\texttt{d0}. That is a level which is not available in the empty scope where QQ lives. The answer is meaningful only relative to the occurrence of XX under one binder. The reading becomes incoherent as soon as the same variable occurs at different depths. Our (aux kanren micro) run above shows the same thing with indices. The prototype chooses to check availability inside unification, so “λa.X = λb.b then top-level Y = X” fails there. But it skips the check when printing, which is how the paper can print '(d0). Dowek et al. fix this with X[↑n]X[\uparrow^n]; Teyjus and ELPI fix it with levels on variables. The 2021 paper does not address it. It also gives no rules for application and β, nor for flex-flex closures beyond postponing them.

Tutorial (Counter-example 3: “true = false” is a bug of binder-merging, not of pattern unification). Problem: λa. λa. X=?λc. λd. c\lambda a.\, \lambda a.\, X\stackrel{?}{=}\lambda c.\, \lambda d.\, c.

Pattern: XX cannot depend on the bound variables at all, so this fails.

Nominal: a.(a.X)≈?c.(d.c)a.(a.X)\approx^? c.(d.c) gives a.X≈?(a c)⋅(d.c)=d.aa.X\approx^?(a\,c)\cdot(d.c)=d.a, with a#(d.c)a\#(d.c), which holds. Then a.X≈?d.aa.X\approx^?d.a gives X≈?(a d)⋅a=dX\approx^?(a\,d)\cdot a=d, with a#aa\#a, which is false. So it fails.

Static closures: fails (Example 2).

All three agree. The “false = true” danger is specific to binder-merging implementations that do not rename apart. The earlier λKanren paper renames apart: its ξ step uses gensyms (Section 9.4), so it does not have the bug.

9.3.2Further observations

The notes add several observations that a porter must know. The paper does not say them.

  1. The meaning of a unification variable changes. In λProlog, XX in λa. X\lambda a.\, X cannot mention aa. With static closures, XX implicitly depends on the positions of its enclosing binders. Logically, ⟨ϕ; X⟩\langle \phi;\,X\rangle behaves like Miller’s raising X ℓi1⋯ℓikX\,\ell_{i_1}\cdots\ell_{i_k} over the available levels of ϕ\phi, with one twist: the “function” is indexed by absolute position, so occurrences under scopes of different lengths share it. The paper’s related work quotes Huet’s “elementary substitution”: “Each unification variable should capture all its visible bound variables” (p. 8). Static closures make that idea implicit, minus the shadowed binders.
  2. α-equivalence is no longer a congruence on open terms. λa. λa. X\lambda a.\, \lambda a.\, X and λa. λb. X\lambda a.\, \lambda b.\, X are α-equivalent in the usual sense, because XX is a metavariable with no free names. Yet against the same λc. λd. c\lambda c.\, \lambda d.\, c, Example 2 fails and Example 1 succeeds. With grafting, the names of the binders above a metavariable matter. Nominal logic manages exactly this with suspended permutations π⋅X\pi\cdot X and freshness a#Xa\#X. The paper’s “names don’t matter” holds for the levels, not for the closures.
  3. Levels are stable for scope variables, not for binders inside solutions. A grafted λ.ℓ1\lambda.\ell_1 solved at depth 1 must become λ.ℓ2\lambda.\ell_2 at depth 2. A locally nameless representation avoids the shift Conor McBride and James McKinna. Functional pearl: I am not a number — I am a free variable. In Proceedings of the ACM SIGPLAN Workshop on Haskell, 2004; and Arthur Charguéraud. The locally nameless representation. Journal of Automated Reasoning, 49(3):363–408, 2012: levels for scope variables, indices for binders inside solutions.
  4. Flex-flex need not be postponed. With levels, ⟨ϕ; X⟩=?⟨ψ; Y⟩\langle \phi;\,X\rangle\stackrel{?}{=}\langle \psi;\,Y\rangle at equal depth has a most general solution: X↦YX\mapsto Y, plus the restriction that YY may use only levels in avail(ϕ)∩avail(ψ)\mathrm{avail}(\phi)\cap\mathrm{avail}(\psi). This is Miller-style pruning, phrased as a freshness-like constraint.
  5. The trick must not reach all. For ∀-goals the eigenvariable must respect the scope restriction, or (run 1 X (all (A) (== X A))) would succeed. That is unsound for ∀. The level semantics is meant only for λ-binders inside terms.
  6. β brings undecidability back. Once == “recognizes αβ-equivalence”, unification outside the pattern fragment is undecidable (Chapter 7). One must restrict to patterns, delay, or enumerate.

The paper’s related work (p. 8) recalls that “nominal unification and pattern unification are equally expressive”. Cheney reduces pattern unification to nominal unification James Cheney. Relating nominal and higher-order pattern unification. In Proceedings of UNIF 2005, pages 104–119, 2005, and Levy and Villaret give the converse reduction Jordi Levy and Mateu Villaret. Nominal unification from a higher-order perspective. In Rewriting Techniques and Applications (RTA 2008), volume 5117 of LNCS, pages 246–260. Springer, 2008. Pattern unification is linear (Qian, although the paper notes that Qian’s algorithm “has not been implemented”); for nominal unification “O(n2)O(n^2) is the state-of-the-art” (p. 8). The notes summarize the correspondence like this: the static closure ⟨ϕ; X⟩\langle \phi;\,X\rangle is close to the nominal suspension π⋅X\pi\cdot X (both record the context around an unknown); db\mathrm{db} is close to the action of π\pi on names; and “level unavailable in ϕ\phi” is close to the freshness ℓ#X\ell\#X. But static closures are positional where nominal terms are name-based, as counter-example 1 shows. The design is closer to de Bruijn-level “contextual” metavariables than to nominal logic.

Kanren angle (what static closures would demand of a miniKanren). The notes list what a static-closure layer on (aux kanren micro) would need. This is a requirements list, not a design (see Chapter 11):

  • New term kinds, dispatched early. λ, level and closure records must be handled before the generic record branch. Today μkanren-structure? matches any record instance and unifies it slot by slot, names included. The same applies to every walker: the occurs check, μkanren-state-find/value, reification, μkanren-hasvar?, and so on.
  • Conversion at the boundary. Converting both sides of =° to level form under ϵ\epsilon leaves a unifier that is “practically first-order” except for closures.
  • A walk that can fail. Walking ⟨ϕ; X⟩\langle \phi;\,X\rangle instantiates XX at ϕ\phi, which can fail on an unavailable level. So the walk needs a third outcome besides “value” and “unbound”. The first-order hot path should stay untouched.
  • A context store with wake-up. The postponed equations must be re-checked when their variables get bound. The μkanren-verify-D/touched idiom, which re-runs only the entries that mention a just-bound variable, already does this for disequalities.
  • Disequality. With postponement, a tentative unification inside ≠° may succeed by only adding a context equation, producing no bindings. An empty prefix in D means “already equal”, so this would be wrong. A disequality entry would then have to carry its postponed part as well.

9.4λKanren 2020: Miller’s algorithm in a shallow embedding

The earlier paper, Higher-order Logic Programming with λKanren Weixi Ma, Kuang-Chen Lu, and Daniel P. Friedman. Higher-order logic programming with λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2020, is the “[17]” of the 2021 paper. Its workshop title is “λKanren: Higher-order Logic Programming with Shallow Embedding”. It adds four operators to μKanren Jason Hemann and Daniel P. Friedman. μ\muKanren: A minimal functional core for relational programming. In Proceedings of the 2013 Workshop on Scheme and Functional Programming (Scheme ’13), 2013: tie (a binder), app (application), assume-rel (an implication goal D⊃GD\supset G) and all (a universal goal ∀x G\forall x\,G). In it, == “recognizes αβ-conversions”. The paper claims “about 40 lines” added to μKanren (p. 7); the repository’s unify.rkt has 648 lines.

Terms and state. The terms are Term::=Constant∣Var∣𝖠𝗉𝗉(rator,rand)∣𝖳𝗂𝖾(var,body)∣(Term . Term)\mathit{Term}::=\mathit{Constant}\mid\mathit{Var}\mid\mathsf{App}(\mathit{rator},\mathit{rand})\mid \mathsf{Tie}(\mathit{var},\mathit{body})\mid(\mathit{Term}\,.\,\mathit{Term}). Pairs stay a separate first-order constructor. The state is the list (qs es σ name->idx). Here qs is an explicit quantifier prefix of (∃ x) and (∀ x) entries, appended at the end by fresh and all. es holds postponed equations and σ is the substitution.

The unifier is a direct transcription of Miller 1991 §6 Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991: ξ, rigid-rigid, raising, pruning, flex-flex and flex-rigid (Section 9.7.1). Its ξ step strips the Ties on both sides and renames both binder lists to the same fresh gensyms by capture-avoiding substitution. It then pushes a (∀ w) onto the prefix for each name. So shadowing is handled by renaming apart, and the 2021 problem does not arise. Non-pattern applications are not delayed; they make the unifier fail.

(define-syntax tie
  (syntax-rules ()
    [(_ () t) t]
    [(_ (x0 x ...) body)
     (let ([x0 (Var 'x0)])
       (Tie x0 (tie (x ...) body)))]))

(define-syntax app
  (syntax-rules ()
    [(_ rator rand) (App rator rand)]
    [(_ rator rand0 rand ...)
     (app (App rator rand0) rand ...)]))

(The paper prints [(_ () t) body]; the repository has t.) The paper reports these unification queries (p. 2–3):

(run 1 q (== (tie (a b) (app a b)) (tie (x y) (app x y))))      ; ⇒ '(_0)
(run 2 f (== (tie (a b) (app a b)) (tie (x y) (app f x y))))    ; ⇒ '((tie (_0) (tie (_1) (app _0 _1))))
(run 1 f (== (tie (a) a) (tie (b) (app f b b))))                ; ⇒ '()   not a pattern
(run 1 q (== (tie (a b) (app a b)) (tie (x y) (app x q))))      ; ⇒ '()   scope restriction

The second query is a pattern, so run 2 still finds one answer, the most general unifier: “There is only one instantiation” (p. 3). Binders and unification variables are both reified as _nn symbols. The third is not a pattern (ff is applied to bb twice) and fails, even though it has solutions (λx. λy. x\lambda x.\, \lambda y.\, x and λx. λy. y\lambda x.\, \lambda y.\, y); in the paper’s words, “we cannot decide which b takes control”. The fourth fails by the scope restriction, which the paper phrases as visibility: “A binding variable x is visible to a unification variable q if the introduction of x lexically precedes that of q” (p. 3). Here qq would have to be the bound yy, which is introduced after qq.

Implication and the shallow-embedding problem. The motivating program is a curriculum:

(defrel (taken name class)
  (conde
    [(== 'Josh name) (== 'B521 class)]
    [(== 'Josh name) (== 'B522 class)]))
(defrel (pl-major name)
  (taken name 'B521)
  (taken name 'B523)
  (taken name 'B522))
> (run 1 q
    (assume-rel [(taken name class) (== 'Josh name) (== q class)]
      (pl-major 'Josh)))
'(B523)

The hypothetical clause extends taken, and pl-major, which was defined before, must see it. In a shallow embedding, relation definitions live in the host language’s lexical scope, so pl-major cannot see the new clause. The paper describes a dynamic-scope layer: a map name->idx threaded through the query, a global idx->def, and calls that go through both.Our notes write (== q class); the extracted text has a quote, 'q, which could not produce B523. Concretely, before the query name->idx is ((pl-major . 2) (taken . 1)); assume-rel pushes a new index, so inside it the map is ((taken . 3) (pl-major . 2) (taken . 1)), and the newer pair shadows the older one when pl-major calls taken (p. 5).

The paper also offers assume, “a shorter version of the assume-rel operator” that “only takes an atomic hypothesis” (p. 5), and uses it on a relation eq that is reflexive, transitive and symmetric. Plain (run 1 q (eq 'apple 'orange)) does not terminate in μKanren, because the recursive clauses never run out (p. 5). With hypotheses (p. 5–6):

(defrel (eq x y)
  (conde
    [(== x y)]
    [(fresh (z) (eq x z) (eq z y))]
    [(eq y x)]))
> (run 5 q (assume (eq 'orange 'apple) (assume (eq 'orange 'dog) (eq 'orange q))))
'(dog apple orange orange dog)
> (run 1 q (assume (eq 'orange q) (eq 'apple 'orange)))
'(apple)

In the first query the answers come from the two hypotheses (dog, apple) and from reflexivity (orange); run 5 reports repetitions, because the recursive clauses derive the same facts again along different paths. The second query “runs backward”: “the hypothesis can be inferred as well” (p. 6). The hypothesis (eq 'orange q) mentions the query variable qq, and it is not renamed when it is used. The goal (eq 'apple 'orange) can use the symmetry clause to become (eq 'orange 'apple), which matches the hypothesis with q=appleq=\texttt{apple}. This is the book’s semantics for a clause with a free logic variable (Chapter 3): only a clause’s own ∀-bound variables are freshened per use.

Universal goals. “the all operator effectively creates a constant … we create an all variable as a free binding variable. Thus, the all variable cannot be unified with anything but itself” (p. 6). The scope restriction is enforced by the prefix. The examples (p. 6–7):

> (run 1 q (all (x)
             (assume-rel (taken x 'B521)
               (assume-rel (taken x 'B522)
                 (assume-rel (taken x 'B523)
                   (pl-major x))))))
'(_0)
> (run 1 f (all (x) (== x (app f x))))
'((tie (_0) _0))
(defrel (proved x) (== x 'trivial))
> (run 1 g (all (p) (proved p)))            '()
> (run 1 g (proved g))                      '(trivial)
> (run 1 g (all (p q) (assume ((proved p) (proved q)) (proved q) (proved p))))   '(_0)
> (run 1 goal (all (p q) (assume ((proved p)) (conde [(proved p)] [(proved q)]))))  '(_0)

The query (all (p) (proved p)) shows generic at work. proved holds only of trivial, and a generic pp is not trivial, so ∀p. proved  p\forall p.\,\texttt{proved}\;p is not provable, whereas the same goal without all succeeds with g=trivialg=\texttt{trivial}. The last two queries use λKanren “as a theorem prover” (§5, p. 6–7). The first proves the commutativity of conjunction, ∀p,q (p∧q)⊃(q∧p)\forall p,q\,(p\wedge q)\supset(q\wedge p): generic makes pp and qq new constants, augment adds (proved p) and (proved q) as hypotheses, and the two conjuncts of the body are then proved by backchaining on them. The second proves disjunction introduction, ∀p,q  p⊃(p∨q)\forall p,q\;p\supset(p\vee q), by the first conde branch. The answers '(_0) only say that the query variable was left unconstrained: the information is in the success.

Pitfall (hypotheses in a host dynamic parameter get lost). The repository’s active code does not use the described state-threaded design. It uses Racket parameters: defrel makes each body a make-parameter, and assume is a parameterize that extends it. We reproduced this structure in CHICKEN. The body of pl-major is only constructed when the goal is applied to a state, which happens after parameterize has returned. So the inner call to taken reads the original parameter, and the output was (orig Josh B523). Relation calls nested inside other relations’ delayed bodies therefore lose the hypotheses. The described name->idx design does not have this problem.

Kanren angle (hypotheses belong to the state). (aux kanren micro)’s define-relation is inverse-η-delayed: it expands to (λ (s) (δ ((and° g ...) s))). This is exactly the situation of the experiment above. A hypothetical clause database for augment must therefore be a field of the state, pushed on entry to GG and invisible outside it. It can never be a host parameter. A further remark from the notes: a hypothetical clause ∀x¯(G⊃A)\forall\bar x(G\supset A) can be a host closure whose body runs fresh°. Each use then renames the clause’s own variables, while the variables captured from the enclosing scope stay shared. This is exactly λProlog’s semantics for clauses with free logic variables. How the module does this is shown in Section 12.4.

9.5Nominal unification and αKanren

Nominal unification Christian Urban, Andrew M. Pitts, and Murdoch J. Gabbay. Nominal unification. Theoretical Computer Science, 323(1–3):473–497, 2004 takes a different route to α-equivalence. Bound names stay names, called atoms. Metavariables are holes, and substitution of a term for a metavariable is capturing, i.e. grafting. Capture is controlled by two devices: permutations suspended on variables, and freshness constraints. Our presentation of the rules follows Urban’s survey Christian Urban. Nominal unification revisited. In Proceedings of UNIF 2010, volume 42 of EPTCS, pages 1–11, 2010. doi: 10.4204/EPTCS.42.1.

Definition 9.9 (Nominal terms and permutations).

t::=⟨⟩∣⟨t1,t2⟩∣f t∣a∣a.t∣π⋅X t ::= \langle\rangle \mid \langle t_1,t_2\rangle \mid f\,t \mid a \mid a.t \mid \pi\cdot X

where a.ta.t abstracts the atom aa in tt, and π⋅X\pi\cdot X is a variable with a suspended permutation. A permutation π\pi is a list of swappings (a b)(a\,b):

[]⋅a=a,((a1 a2)::π)⋅a={a2π⋅a=a1a1π⋅a=a2π⋅aotherwise. []\cdot a=a,\qquad ((a_1\,a_2)::\pi)\cdot a=\begin{cases}a_2 & \pi\cdot a=a_1\\ a_1 & \pi\cdot a=a_2\\ \pi\cdot a&\text{otherwise.}\end{cases}

Composition is list append and the inverse is reversal. The disagreement set is ds(π,π′)={a∣π⋅a≠π′⋅a}ds(\pi,\pi')=\{a\mid \pi\cdot a\neq\pi'\cdot a\}. A permutation acts on an abstraction on both the binder and the body, and it suspends on variables: π⋅(π′⋅X)=(π@π′)⋅X\pi\cdot(\pi'\cdot X)=(\pi @ \pi')\cdot X. Substitution is capturing: σ(a.t)=a.σ(t)\sigma(a.t)=a.\sigma(t) with no side condition, and σ(π⋅X)=π⋅σ(X)\sigma(\pi\cdot X)=\pi\cdot\sigma(X).

Definition 9.10 (Freshness and α-equality, Fig. 1).Christian Urban. Nominal unification revisited. In Proceedings of UNIF 2010, volume 42 of EPTCS, pages 1–11, 2010. doi: 10.4204/EPTCS.42.1 With a freshness context ∇\nabla, a set of pairs a#Xa\#X:

∇⊢a#⟨⟩∇⊢a#t1∇⊢a#t2∇⊢a#⟨t1,t2⟩∇⊢a#t∇⊢a#f t∇⊢a#a.t \dfrac{}{\nabla\vdash a\#\langle\rangle} \qquad \dfrac{\nabla\vdash a\#t_1 \qquad \nabla\vdash a\#t_2}{\nabla\vdash a\#\langle t_1,t_2\rangle} \qquad \dfrac{\nabla\vdash a\#t}{\nabla\vdash a\#f\,t} \qquad \dfrac{}{\nabla\vdash a\#a.t} ∇⊢a#ta≠b∇⊢a#b.ta≠b∇⊢a#b(π−1⋅a,X)∈∇∇⊢a#π⋅X \dfrac{\nabla\vdash a\#t \qquad a\neq b}{\nabla\vdash a\#b.t} \qquad \dfrac{a\neq b}{\nabla\vdash a\#b} \qquad \dfrac{(\pi^{-1}\cdot a,X)\in\nabla}{\nabla\vdash a\#\pi\cdot X} ∇⊢t1≈t2∇⊢a.t1≈a.t2a≠b∇⊢a#t2∇⊢t1≈(a b)⋅t2∇⊢a.t1≈b.t2∀c∈ds(π,π′). (c,X)∈∇∇⊢π⋅X≈π′⋅X \dfrac{\nabla\vdash t_1\approx t_2}{\nabla\vdash a.t_1\approx a.t_2} \qquad \dfrac{a\neq b \qquad \nabla\vdash a\# t_2 \qquad \nabla\vdash t_1\approx(a\,b)\cdot t_2}{\nabla\vdash a.t_1\approx b.t_2} \qquad \dfrac{\forall c\in ds(\pi,\pi').\ (c,X)\in\nabla}{\nabla\vdash\pi\cdot X\approx\pi'\cdot X}

plus the congruence rules for unit, pairs, function symbols and atoms.

The intuition: a#ta\#t says that aa does not occur free in tt, also after any later instantiation of the variables of tt. To compare a.t1a.t_1 with b.t2b.t_2, rename bb to aa in t2t_2 by a swapping, which is always safe because it is a bijection, and require that aa was not already free in t2t_2.

Definition 9.11 (Nominal unification, p. 9).Christian Urban. Nominal unification revisited. In Proceedings of UNIF 2010, volume 42 of EPTCS, pages 1–11, 2010. doi: 10.4204/EPTCS.42.1

{⟨t1,t2⟩≈?⟨s1,s2⟩,… }⇒{t1≈?s1, t2≈?s2,… }{a.t≈?a.s,… }⇒{t≈?s,… } \{\langle t_1,t_2\rangle\approx^?\langle s_1,s_2\rangle,\dots\}\Rightarrow\{t_1\approx^?s_1,\ t_2\approx^?s_2,\dots\}\qquad \{a.t\approx^?a.s,\dots\}\Rightarrow\{t\approx^?s,\dots\} {a.t≈?b.s,… }⇒{t≈?(a b)⋅s, a#?s,… }{π⋅X≈?π′⋅X,… }⇒{a#?X∣a∈ds(π,π′)}∪{… } \{a.t\approx^?b.s,\dots\}\Rightarrow\{t\approx^?(a\,b)\cdot s,\ a\#^?s,\dots\}\qquad \{\pi\cdot X\approx^?\pi'\cdot X,\dots\}\Rightarrow\{a\#^?X\mid a\in ds(\pi,\pi')\}\cup\{\dots\}

and π⋅X≈?t\pi\cdot X\approx^?t, with XX not in tt, gives X:=π−1⋅tX:=\pi^{-1}\cdot t. A solution is a pair (∇,σ)(\nabla,\sigma) with ∇⊢σ(t1)≈σ(t2)\nabla\vdash\sigma(t_1)\approx\sigma(t_2). For example, a.X≈?b.Xa.X\approx^?b.X has the solution ({a#X, b#X},[ ])(\{a\#X,\,b\#X\},[\,]).

Most general solutions exist, and no fresh names are ever generated: every atom of a solution occurs in the problem. Naive rules are exponential; quadratic algorithms exist.

9.5.1αKanren

αKanren William E. Byrd and Daniel P. Friedman. α\alphaKanren: A fresh name in nominal logic programming. In Proceedings of the 2007 Workshop on Scheme and Functional Programming, Université Laval Technical Report DIUL-RT-0701, pages 79–90, 2007; and William E. Byrd. Relational Programming in miniKanren: Techniques, Applications, and Implementations. PhD thesis, Indiana University, 2009 embeds nominal unification in miniKanren. fresh introduces noms: “a nom behaves more like a constant than a variable, since it only unifies with itself or with an unassociated variable”. The constructor (tie a t), typeset ⋈\bowtie, binds the nom aa in tt; it delimits scope and does not create noms. (# a t), entered hash, asserts that aa does not occur free in tt. Ordinary logic variables are introduced by exist. The thesis examples (ch. 9; ◃▹ is the thesis glyph for tie):

(run* (q) (fresh (a b) (≡ (◃▹ a a) (◃▹ b b))))      ⇒ (_.0)
(run* (q) (fresh (a b) (≡ (◃▹ a q) (◃▹ b b))))      ⇒ (a.0)
(run* (q) (fresh (a b) (# a (◃▹ b a))))             ⇒ ()
(run* (q) (fresh (a) (# a (◃▹ a a))))               ⇒ (_.0)
(run* (q) (fresh (a b) (exist (x y) (≡ (◃▹ a (◃▹ a x)) (◃▹ a (◃▹ b y))) (≡ `(,x ,y) q))))
  ⇒ ((((susp ((a.0 a.1)) _.0) _.0) : ((a.0 . _.0))))

The second line is counter-example 1’s single equation: qq becomes the bound nom. The last line shows a suspension in an answer, with a freshness constraint printed after the colon. The capture-avoiding substitution relation shows the programming style:

(define substo
  (λ (e new a out)
    (matche (e out)
      (((var ,a) ,new))
      (((var ,y) (var ,y)) (# a y))
      (((app ,rator ,rand) (app ,rator-res ,rand-res))
       (substo rator new a rator-res)
       (substo rand new a rand-res))
      (((lam ,(◃▹ @c body)) (lam ,(◃▹ c body-res)))
       (# c a)
       (# c new)
       (substo body new a body-res)))))
(run* (q) (fresh (a b) (substo `(lam ,(◃▹ a `(app (var ,a) (var ,b)))) `(var ,b) a q)))
  ⇒ ((lam (tie a.0 (app (var a.0) (var a.1)))))     ; [b/a]λa.ab = λc.cb

(@c in a matche pattern introduces cc as a nom.) The unifier works in two phases. First the σ-rules turn equations into a substitution plus pending freshness constraints. Then the ∇-rules reduce freshness constraints until each is a#xa\#x with xx an unbound variable. Variables are suspensions with an empty permutation. A triangular-substitution version, due to Joe Near, is reported “as much as ten times faster”. The thesis states a limitation (p. 178): “neither currently supports disequality constraints”. αKanren also powers αleanTAP Joseph P. Near, William E. Byrd, and Daniel P. Friedman. α\alphaleanTAP: A declarative theorem prover for first-order classical logic. In Logic Programming (ICLP 2008), volume 5366 of LNCS, pages 238–252. Springer, 2008, where ∀-bound variables of the object logic are noms. There, “Universally quantified formulas are used as templates, rather than instantiated directly”.

Kanren angle (what nominal unification asks of a miniKanren). It needs three new term kinds (nom, tie, suspension π⋅X\pi\cdot X) and a freshness store ∇ of a#Xa\#X pairs, re-reduced after each unification. That re-reduction works like (aux kanren micro)’s post-=° verification of D, A and T. Note that absent° is not freshness: freshness is about free occurrences, so (# a (◃▹ a a)) succeeds, whereas absento forbids any occurrence. Nominal unification has no function variables and no β, so it is a different logic from λProlog’s. Noms are distinct constants, not eigenvariables, and ∀-goals still need their own mechanism (see Chapter 11).

9.6Eigenvariables, negation and ∀ inside miniKanren

9.6.1The scope-extrusion problem

generic proves ∀x.G\forall x.G by proving G[c/x]G[c/x] for a new constant cc. If the constant is only a gensym, nothing stops an older logic variable from being bound to it later. That “proves” ∃X∀y. X=y\exists X\forall y.\,X=y, which must fail. Contrast ∀y∃X. X=y\forall y\exists X.\,X=y, which must succeed. The fixes in the literature are exactly four: (i) an explicit prefix Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991; and Weixi Ma, Kuang-Chen Lu, and Daniel P. Friedman. Higher-order logic programming with λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2020; (ii) universe indices or levels Gopalan Nadathur, Bharat Jayaraman, and Keehang Kwon. Scoping constructs in logic programming: implementation problems and their solution. Journal of Logic Programming, 25(2):119–161, 1995; and Cvetan Dunchev, Ferruccio Guidi, Claudio Sacerdoti Coen, and Enrico Tassi. ELPI: fast, embeddable, λ\lambdaProlog interpreter. In Logic for Programming, Artificial Intelligence, and Reasoning (LPAR-20), volume 9450 of LNCS, pages 460–468. Springer, 2015; (iii) an absento-like eigen constraint over the variables in scope Jason Hemann, William E. Byrd, and Daniel P. Friedman. The eigen operator of miniKanren-with-symbolic-constraints. Software, 2013. URL https://github.com/webyrd/miniKanren-with-symbolic-constraints; (iv) an end-of-scope check. The notes call (iv) the weakest. It is sound only if nothing created inside the scope survives it in a form that can be bound later, and its failures are detected late.

9.6.2eigen in miniKanren with symbolic constraints

Hemann, Byrd and Friedman added eigen to miniKanren-with-symbolic-constraints in 2013 Jason Hemann, William E. Byrd, and Daniel P. Friedman. The eigen operator of miniKanren-with-symbolic-constraints. Software, 2013. URL https://github.com/webyrd/miniKanren-with-symbolic-constraints. The header comment of mk.scm reads: “E = (e* . x*), where e is a list of eigens and x* is a list of variables. Each e in e* is checked for any of its eigens be in any of its x*. Then it fails.” The state carries B, the list of all variables created so far. eigen creates fresh eigen objects and installs an eigen-absento constraint (e∗ . B)(e^*\,.\,B): none of the variables that existed before the eigen may ever walk to a term containing it.

(define-syntax eigen
  (syntax-rules ()
    ((_ (x ...) g0 g ...)
     (lambdag@ (c : B E S)
       (let ((x (eigen-var)) ...)
         ((fresh () (eigen-absento `(,x ...) B) g0 g ...) c))))))

(define eigen-absento
  (lambda (e* x*)
    (lambdag@ (c : B E S D Y N T)
      (cond
        ((eigen-occurs-check e* x* S) (mzero))
        (else (unit `(,B ((,e* . ,x*) . ,E) ,S ,D ,Y ,N ,T)))))))

This is the universe-index check implemented with explicit sets instead of numbers. Its cost is O(∣B∣⋅∣term∣)O(|B|\cdot|\text{term}|) per check. The README warns: “Beware: this implementation does not support use of eigen with constraints other than ==.”

Kanren angle (the eigen-absento idea, by hand, on today’s engine). (aux kanren micro) already has absent°, which takes any datum as its tag, including a record. So the Hemann–Byrd–Friedman check can be written by hand. Here there is one outer variable QQ, and the eigen is a fresh record that QQ may never contain. This illustrates the idea; it is not an API proposal.

(import scheme (chicken base) (chicken pretty-print)
        (aux base) (aux stream) (aux kanren micro))

(define-syntax-rule (show label expr)
  (begin (display ";; ") (display label) (newline)
         (pretty-print expr)))

;; A generic constant as a fresh, unique record: no scope check at all.
(define-record eigen id)
(show "naive: exists Q forall x. Q = x"
  (°->list #f (fresh° (q) (=° q (make-eigen 1)))))

;; The eigen-absento idea, by hand with absent°: the constant
;; may never occur in a variable that existed before it.
(show "with absent°: exists Q forall x. Q = x"
  (°->list #f
    (fresh° (q)
      (let ((c (make-eigen 1)))
        (and° (absent° c q) (=° q c))))))
(show "with absent°: forall x exists Y. Y = x, then Q = ok"
  (°->list #f
    (fresh° (q)
      (let ((c (make-eigen 1)))
        (and° (absent° c q) (fresh° (y) (=° y c)) (=° q 'ok))))))
(show "with absent°: escape through an alias is caught"
  (°->list #f
    (fresh° (q)
      (let ((c (make-eigen 1)))
        (and° (absent° c q)
              (fresh° (y) (=° q (list y)) (=° y c)))))))
;; naive: exists Q forall x. Q = x
((λ () (make-record-instance 'eigen 1)))
;; with absent°: exists Q forall x. Q = x
()
;; with absent°: forall x exists Y. Y = x, then Q = ok
((λ () 'ok))
;; with absent°: escape through an alias is caught
()

Three cautions come from the notes on (aux kanren micro). First, μkanren-state-find/value rebuilds records, so eigens must be compared by an identifier (with equal?), never by eq?; and two eigens must never share an identifier. Second, (aux kanren micro) binds the older variable to the newer one in a variable-variable equation. So “rank = creation index” is not a scope discipline by itself, and creation time is not scope depth. Third, the check is first-order only: there is no higher-order unification here.

9.6.3Moiseenko 2019: constructive negation

Moiseenko Evgenii Moiseenko. Constructive negation for miniKanren. In miniKanren and Relational Programming Workshop, 2019 builds the answers to ¬g\neg g by collecting all answers of gg and negating them. To make this closed under negation, states become formulas (eq. (1), p. 6):

∃x¯.(⋀ivi=ti ∧ ⋀j∀y¯j.⋁kwjk≠ujk). \exists\bar x.\Big(\bigwedge_i v_i=t_i\ \wedge\ \bigwedge_j\forall\bar y_j.\bigvee_k w_{jk}\neq u_{jk}\Big).

This needs a solver for universally quantified disequalities:

Lemma 9.12 (Lemma 3, p. 9).Evgenii Moiseenko. Constructive negation for miniKanren. In miniKanren and Relational Programming Workshop, 2019 t≠ut\neq u is satisfiable iff mgu(t,u)≠⊤\mathrm{mgu}(t,u)\neq\top.

This is exactly what (aux kanren micro)’s ≠° implements.

Lemma 9.13 (Def. 11, Lemma 4, p. 10).Evgenii Moiseenko. Constructive negation for miniKanren. In miniKanren and Relational Programming Workshop, 2019 Let θ=mgu(t,u)\theta=\mathrm{mgu}(t,u), oriented so that x¯⊈codom θ\bar x\not\subseteq\mathrm{codom}\,\theta. Then ∀x¯. t≠u\forall\bar x.\,t\neq u is satisfiable iff θ=⊥\theta=\bot or dom(θ)⊈x¯\mathrm{dom}(\theta)\not\subseteq\bar x, and unsatisfiable iff dom(θ)⊆x¯\mathrm{dom}(\theta)\subseteq\bar x.

The orientation is a normalization: if the mgu maps an outer variable vv to some x∈x¯x\in\bar x, flip that binding to x↦vx\mapsto v. In words: ∀x¯. t≠u\forall\bar x.\,t\neq u is unsatisfiable exactly when tt and uu can be made equal by choosing values for the universal variables alone. Example: for ∀x. x≠α\forall x.\,x\neq\alpha, the mgu is {x↦α}\{x\mapsto\alpha\}, its domain is {x}⊆x¯\{x\}\subseteq\bar x, so the constraint is unsatisfiable. For ∀x. α≠(1,x)\forall x.\,\alpha\neq(1,x) the mgu {α↦(1,x)}\{\alpha\mapsto(1,x)\} binds the outer α\alpha, so it is satisfiable (by any α\alpha that is not a pair with first component 11).

Lemma 9.14 (Def. 12, Lemma 5, p. 10–11).Evgenii Moiseenko. Constructive negation for miniKanren. In miniKanren and Relational Programming Workshop, 2019 For ∀x¯∃y¯. t≡u\forall\bar x\exists\bar y.\,t\equiv u, let θ\theta be idempotent and θ^\hat\theta its restriction to the non-y¯\bar y variables. The formula is satisfiable iff dom(θ^)∩x¯=∅\mathrm{dom}(\hat\theta)\cap\bar x=\emptyset and no p∈codom(θ^)p\in\mathrm{codom}(\hat\theta) has Vars(p)∩x¯≠∅\mathrm{Vars}(p)\cap\bar x\neq\emptyset.

The notes observe that Lemma 5 is exactly the eigenvariable condition. Universal variables may not be bound, and they may not appear in the bindings of outer variables. With negation one gets ifte  c  t  e=(c∧t)∨(¬c∧e)\mathit{ifte}\;c\;t\;e=(c\wedge t)\vee(\neg c\wedge e), g1⇒g2=¬g1∨(g1∧g2)g_1\Rightarrow g_2=\neg g_1\vee(g_1\wedge g_2) and forall  g=¬ fresh (x) (¬ g x)\mathit{forall}\;g=\neg\,\mathit{fresh}\,(x)\,(\neg\,g\,x). The price: stratification is required, negating a goal with infinitely many answers diverges, and infinitely many constructors of each arity are assumed. A remark on p. 4: “there is no sound implementation of eigen variables with the support of disequality constraints. We observed that our implementation of universal quantifications through double negation works nicely with disequalities”.

Pitfall (eigen-constants and disequality). λProlog’s generic ∀ is sound because λProlog has no negation. Add ≠° and consider ∀x. x≠α\forall x.\,x\neq\alpha, with α\alpha an outer variable. It must fail: take x:=αx:=\alpha. Moiseenko’s Lemma 4 agrees, since the mgu {x↦α}\{x\mapsto\alpha\} has domain ⊆{x}\subseteq\{x\}. A naive eigen-constant cc makes c≠αc\neq\alpha hold forever, because α\alpha can never be bound to cc, and the query wrongly succeeds. The same issue arises for type constraints: cc stands for an arbitrary term, so symbol° of cc should not be provable unless assumed. It also arises for absent°.

9.6.4Jin, Rosenblatt, Might and Zhang 2021: ∀ and ⇒ by relative complement

Jin et al. Ende Jin, Gregory Rosenblatt, Matthew Might, and Lisa Zhang. Universal quantification and implication in miniKanren. In miniKanren and Relational Programming Workshop, 2021 build on the first-order miniKanren representation Gregory Rosenblatt, Lisa Zhang, William E. Byrd, and Matthew Might. First-order miniKanren representation: great for tooling and search. In miniKanren and Relational Programming Workshop, 2019, where goals are data that can be inspected. (forall (v) domain goal) works in four steps: it checks the domain’s satisfiability; it extracts candidates by running (exists (v) (conj domain body)) and splitting the states into disjunction-free ones; it computes a relative complement, recursing on (forall (v) (conj relcomp domain) body); and it applies a domain relative negation. This is an extensional ∀ over the universe of literal values: the classical “for every value” reading, not λProlog’s generic one. (implies A B) combines semantic solving, which rewrites to ¬A∨B\neg A\vee B when AA is negatable, with syntactic solving. In the latter, an assumptions list is threaded through, a user-relation call can be solved by an assumed call, and relations are unfolded under a closed-world reading. The paper’s opening examples (p. 1):

> (run 1 (a) (forall (v) () (== v a)))                                   '()
> (run 1 () (forall (a) () (exists (v) () (== v a))))                    '(())
> (run 1 (a b) (forall (v) () (disj* (== v a) (=/= v b))))              '((_.0 _.0))
> (run 1 (b) (forall (a) () (disj* (not-symbolo a) (=/= a b))))         '((#f))
> (run 1 (f) (implies (evalo f 1) (exists (a) (evalo f a))))            '((_.0))

The third query is the instructive one. ∀v. (v=a∨v≠b)\forall v.\,(v=a\vee v\neq b) holds when a=ba=b. That is a classical case split on vv, which λProlog’s generic ∀ cannot do; λProlog has no ≠\neq at all. The authors list the limitations themselves (§7): the system is slow, produces duplicates, is incomplete, and soundness is unproven. Their related work notes that λKanren 2020 supports only relation calls and equalities in antecedents, with “no unfolding … consistent with an open-world interpretation”.

Pitfall (three different ∀). λProlog’s ∀ is generic: intuitionistic, proved by a new constant, with no case analysis (Chapter 3). Jin et al.’s ∀ is extensional: “for every value in the universe”, by relative complements. Moiseenko’s ∀ is ¬∃¬\neg\exists\neg: classical, stratified, and it needs finitely many answers. A query that succeeds in one may fail or diverge in another. For instance, Jin et al.’s §6.6 shows that (forall (expr) () (disj (neg (halto expr)) (halto expr))) does not terminate. Only the first ∀ is the book’s.

9.7How λProlog systems do it

9.7.1Miller 1991: LλL_\lambda by transitions over a mixed prefix

Chapter 7 presents pattern unification as the book does. Here we recall only the shape of Miller’s original formulation Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, because both λKanren 2020 and Nipkow transcribe it. The book’s statement of the restriction is: “a program clause or goal formula BB is in LλL_\lambda if all quantification in BB is over nonpredicate 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]. Then only β0_0 is needed: (λy. s) x=s[x/y](\lambda y.\, s)\,x=s[x/y] when xx is a variable not free in λy. s\lambda y.\, s.

Miller’s interpreter turns generic into a meta-level universal quantifier, and backchain turns the clause’s ∀s into ∃s placed at the point of use. This is why mixed prefixes ∀∃∀…\forall\exists\forall\dots arise dynamically. The unification transitions are ξ (descend under binders, renaming apart), rigid-rigid, raising, pruning, flex-flex and flex-rigid. The algorithm terminates (Theorem 7.1), and when it succeeds it yields a most general unifier (Proposition 7.3). One of Miller’s worked examples (p. 14–15):

Q∃u∃v∀y [f(λx. f(u x y))=f(λw. v y)]→rigidλx. f(u x y)=λw. v y→ξ∀y∀x [f(u x y)=v y] Q\exists u\exists v\forall y\,[f(\lambda x.\, f(u\,x\,y))=f(\lambda w.\, v\,y)] \xrightarrow{\text{rigid}}\lambda x.\, f(u\,x\,y)=\lambda w.\, v\,y \xrightarrow{\xi}\forall y\forall x\,[f(u\,x\,y)=v\,y] →pruning[u↦λx. λy. u′ y]→flex-rigid[v↦λy. f(u′ y)]. \xrightarrow{\text{pruning}}[u\mapsto\lambda x.\, \lambda y.\, u'\,y] \xrightarrow{\text{flex-rigid}}[v\mapsto\lambda y.\, f(u'\,y)].

Read the last two steps with the prefix in mind, which is now Q∃u∃v∀y∀xQ\exists u\exists v\forall y\forall x. The equation is flex-rigid: v yv\,y against f(u x y)f(u\,x\,y). The universal xx is quantified after vv and is not among vv’s arguments, so vv’s solution may not mention it. Every occurrence of xx sits under the flexible head uu, so the problem is not hopeless: pruning removes uu’s dependency on its first argument, u↦λx. λy. u′ yu\mapsto\lambda x.\, \lambda y.\, u'\,y. After that the rigid side is f(u′ y)f(u'\,y), and flex-rigid abstracts vv’s argument: v↦λy. f(u′ y)v\mapsto\lambda y.\, f(u'\,y). Had xx occurred outside any flexible head, pruning would fail and so would the equation.

In the untyped version (§9.3), rigid-rigid with different arities fails, and η-expansion is used only on terms that must have functional type. This matters for an untyped Scheme term language. Miller also shows how to stay inside LλL_\lambda by replacing meta-level β with copy clauses and hypothetical reasoning, as in the book’s Figure 7.10 [MN p. 200]:

subst M T S :- pi x\ copy x T => copy (M x) S.

The same trick encodes a non-pattern problem inside LλL_\lambda Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, §10.3, p. 30–31. With copy clauses copyterm a a, copyterm (f X) (f U) :- copyterm X U. and so on for the signature, define

substterm M T N :- pi c\(copyterm c T => copyterm (M c) N).

The unifiers of F a=?g a aF\,a\stackrel{?}{=} g\,a\,a, which is not a pattern because aa is a constant, are exactly the FF that make substterm F a (g a a) provable. Miller lists the four answers an LλL_\lambda interpreter should return: w\(g w w), w\(g w a), w\(g a w), w\(g a a). The choice “is this aa the argument or the constant?” is made by backchaining, either on the hypothesis copyterm c a or on the clause copyterm a a. Huet’s branching has become ordinary proof search, which a miniKanren would interleave.

The book’s position on programs outside LλL_\lambda is pragmatic. A common resolution 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”. One “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. 225–226].

9.7.2Nipkow 1993: functional pattern unification on de Bruijn terms

Nipkow 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 restricts attention to ∀∃∀\forall\exists\forall problems, where raising is never needed. Existential variables are global (V F), outer universals are constants (C c), and inner universals are loose de Bruijn indices (B i). The substitution is triangular. From the author’s ML code, the algorithm is:

  1. head-normalize both sides through the substitution, with β0_0 done by renaming indices;
  2. λs=λt⇒s=t\lambda s=\lambda t\Rightarrow s=t; η on demand, λs=t⇒s=(↑t) 0\lambda s=t\Rightarrow s=(\uparrow t)\,0;
  3. rigid-rigid: equal heads give pairwise unification, different heads fail;
  4. flex-rigid F y¯=tF\,\bar y=t: occurs check, then invert tt with respect to y¯\bar y and prune the flexible subterms that mention indices outside y¯\bar y;
  5. flex-flex, same head: F y¯=F z¯⇒F:=λ∣y¯∣.H (positions where yi=zi)F\,\bar y=F\,\bar z\Rightarrow F:=\lambda^{|\bar y|}.H\,(\text{positions where }y_i=z_i);
  6. flex-flex, different heads: if ı¯⊆ȷ¯\bar\imath\subseteq\bar\jmath then G:=λȷ¯.F ı¯G:=\lambda\bar\jmath.F\,\bar\imath, symmetrically in the other case, and otherwise both are bound to a fresh HH applied to ı¯∩ȷ¯\bar\imath\cap\bar\jmath.

9.7.3Dowek, Hardin, Kirchner, Pfenning 1996: explicit substitutions

DHKP 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 work in the λσ-calculus, where substitution a[s]a[s] is syntax. Meta-variables are grafted, i.e. replaced first-order. To recover the logical, capture-avoiding reading, terms are pre-cooked: F(λa,n)=λF(a,n+1)F(\lambda a,n)=\lambda F(a,n+1), F(a b,n)=F(a,n) F(b,n)F(a\,b,n)=F(a,n)\,F(b,n), F(k,n)=1[↑k−1]F(k,n)=1[\uparrow^{k-1}], F(X,n)=X[↑n]F(X,n)=X[\uparrow^n]. A metavariable under nn binders is explicitly shifted past them. This is precisely the step that makes grafting agree with substitution, and that static closures omit (counter-example 1). In a λσ-pattern, every X[s] b1…bqX[s]\,b_1\dots b_q has s=a1…ap⋅↑ns=a_1\dots a_p\cdot\uparrow^n with the aa’s and bb’s distinct indices. Pattern substitutions are injective and have a right inverse, so 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, inversion). Unification of λσ-patterns is decidable and unitary (Theorem 17), and “our presentation does not need mixed prefixes”: raising is just a rule. Outside the fragment, §5.4 says that equations “should be postponed as constraints in the hope that they will be instantiated further”, which “avoids all branching during constraint simplification”. Empirically, “almost all dynamically arising equations fall within the pattern fragment” (p. 2).

9.7.4Universe indices: Nadathur, Jayaraman and Kwon 1995

The idea behind every efficient implementation of generic is numeric 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: “Each time a universal quantifier is encountered, a new constant must be introduced, giving rise to the next universe in the hierarchy. This requirement can be accounted for by increasing the “universe index” by 1 and introducing a new constant tagged with this index. … When an existential quantifier is encountered, it is instantiated by a logic variable. This variable may be tagged with the current value of the universe index, the intended interpretation of the tag being 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. 15–16).

Definition 9.15 (Binding with universe indices, 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 To bind a variable XX with tag ii to tt: (1) perform the usual occurs check; (2) check that tt contains no constant with tag >i>i; (3) before binding, change to ii the tags of the variables of tt whose tag is >i>i.

Step (3) is lowering. It is “required in order to prevent a later instantiation of these variables from violating the restrictions on instantiations for X”.

Tutorial (why lowering is needed). 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)).

  1. ∃x\exists x creates XX with tag 1. ∀y\forall y raises the index to 2 and creates cc with tag 2. augment adds q(c)q(c). The goal is now p(X1)p(X^1).
  2. backchain on the clause gives a new variable ZZ tagged with the current index, 2. Unifying p(X1)=p(d(Z2))p(X^1)=p(d(Z^2)) binds X:=d(Z)X:=d(Z), and lowers ZZ to tag 1.
  3. The subgoal q(Z1)q(Z^1) meets the hypothesis q(c2)q(c^2). Binding Z1:=c2Z^1:=c^2 violates step (2), so it fails.

Without lowering, Z2:=cZ^2:=c would be accepted and XX would become d(c)d(c). That smuggles the eigen-constant into a variable quantified outside its scope. The failure is correct: the goal would need x=d(y)x=d(y), but xx is quantified before yy.

The abstract interpreter works on tuples ⟨G,P,I⟩\langle G,P,I\rangle. A ∃-goal tags its new variable with II; a ∀-goal goes to ⟨[c/x]G,P,I+1⟩\langle[c/x]G,P,I{+}1\rangle; and backchaining instantiates the clause’s variables with tag II. The interpreter is sound and complete with respect to intuitionistic provability, and goal selection order is irrelevant (Prop. 4.1). In the WAM, a UI register is incremented on entering a universal goal and decremented on its completion, and choice points save it.

9.7.5Teyjus: suspensions and on-the-fly raising

Teyjus represents term-bound variables by de Bruijn indices and logic variables by mutable cells Gopalan Nadathur. A treatment of higher-order features in logic programming. Theory and Practice of Logic Programming, 5(3):305–354, 2005. arXiv:cs/0404020. β-reduction is made lazy with the suspension notation [[t,ol,nl,e]][[t,ol,nl,e]]: “a term tt that used to occur inside olol abstractions but now appears within nlnl of them”, with an environment ee. Some of the rules:

(βs) (λt1) t2→[[t1,1,0,(t2,0)::nil]](r9) [[t,0,0,nil]]→t(r7) [[λt,ol,nl,e]]→λ[[t,ol+1,nl+1,@nl::e]] \begin{gathered} (\beta_s)\ (\lambda t_1)\,t_2\to[[t_1,1,0,(t_2,0)::nil]]\qquad (r_9)\ [[t,0,0,nil]]\to t\\ (r_7)\ [[\lambda t,ol,nl,e]]\to\lambda[[t,ol{+}1,nl{+}1,@nl::e]] \end{gathered}

Terms also carry a closed/open annotation bit; empirically, substitution walks were reduced to “a third to an eighth”.

Nadathur and Linnell Gopalan Nadathur and Natalie Linnell. Practical higher-order pattern unification with on-the-fly raising. In ICLP 2005: 21st International Logic Programming Conference, volume 3668 of LNCS, pages 371–386, Sitges, Spain, 2006. Springer eliminate the explicit prefix. Each variable gets a tag l(y)l(y), the number of ∃-followed-by-∀ alternations up to its quantifier, and “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)”. Raising is restricted to the universals that actually appear as arguments. A single traversal of the rigid side (mksubst/bnd) computes the binding, i.e. the inversion, and does pruning and raising on the fly. A non-pattern subterm met during the traversal can be replaced by a fresh h(y¯)h(\bar y) with the equation h(y¯)=th(\bar y)=t deferred. The book describes the same idea of “attaching numerical indices to the quantified variables” [MN p. 225]. It also notes that Teyjus 2 implements only LλL_\lambda unification [MN p. 228].

Example 9.16 (no mgu outside the fragment, p. 5).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 The problem ∀u1∀u2∃x (x(u2)=u1(u2))\forall u_1\forall u_2\exists x\,(x(u_2)=u_1(u_2)) is not a pattern: u2u_2 is quantified outside the scope of xx, so it is a constant for xx. It has “two incomparable solutions”, x↦λw. u1(w)x\mapsto\lambda w.\, u_1(w) and x↦λw. u1(u2)x\mapsto\lambda w.\, u_1(u_2) (written λ(1,u1(1))\lambda(1,u_1(1)) and λ(1,u1(u2))\lambda(1,u_1(u_2)) in the paper’s de Bruijn notation), and no most general one. Move the quantifier, ∀u1∃x∀u2 (x(u2)=u1(u2))\forall u_1\exists x\forall u_2\,(x(u_2)=u_1(u_2)), and it becomes a pattern with the single solution x↦λw. u1(w)x\mapsto\lambda w.\, u_1(w). A unifier that must return one mgu can only defer the first problem. An enumerating one would return both answers, as Miller’s substterm does for F a=?g a aF\,a\stackrel{?}{=} g\,a\,a (Section 9.7.1).

9.7.6ELPI: de Bruijn levels and a reduction-free fragment

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 starts from an observation about the two roles of β:

of (lam F) (arr A B) :- pi x\ of x A => of (F x) B.
cbn (app (lam F) N) M :- cbn (F N) M.

In of, β only replaces a bound name with a fresh constant. In cbn, β is genuine object-level substitution. The design has three parts.

Levels for the prefix. “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). Level lowering is done by pruning: the higher-level variable is bound to a fresh lower-level one.

De Bruijn levels, not indices. The example is λx. (λy. λz. f x y z) x\lambda x.\, (\lambda y.\, \lambda z.\, f\,x\,y\,z)\,x:

indices:λx.(λy.λz.f x2 y1 z0) x0→βλx.λz.f x1 x1 z0(x is renumbered),levels:λx.(λy.λz.f x0 y1 z2) x0→βλx.λz.f x0 x0 z1(x keeps its number). \begin{aligned} \text{indices:}\quad& \lambda x.(\lambda y.\lambda z.f\,x_2\,y_1\,z_0)\,x_0\to_\beta\lambda x.\lambda z.f\,x_1\,x_1\,z_0 && (x \text{ is renumbered}),\\ \text{levels:}\quad& \lambda x.(\lambda y.\lambda z.f\,x_0\,y_1\,z_2)\,x_0\to_\beta\lambda x.\lambda z.f\,x_0\,x_0\,z_1 && (x \text{ keeps its number}). \end{aligned}

Three properties follow. A variable bound in Γ keeps its name in any extension of Γ (DBL1) and in a β-reduct (DBL2), and pushing a binder into the context needs no lifting (DBL3). “variables already pushed in the context are treated exactly as constants, and … the two notions of level — De Bruijn’s and the position in the context — coincide”. Terms are t::=xi∣Xj∣λxi.t∣t tt::=x_i\mid X^j\mid\lambda x_i.t\mid t\,t, with global constants as negative ii; XjX^j sees the names below jj.

Definition 9.17 (Reduction-free fragment Lλβ, Def. 1).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 Every occurrence of a unification variable XjX^j is applied to xj…xj+k−1x_j\dots x_{j+k-1}, for k≥0k\ge0: exactly the next kk context names, in order.

This fragment is contained in LλL_\lambda (Property 1). Head reductions of (Xj xj…xj+k−1)σ(X^j\,x_j\dots x_{j+k-1})\sigma take constant time (Property 2), and so does solving Xj xj…xj+k−1≡tX^j\,x_j\dots x_{j+k-1}\equiv t when no occurs check is needed and the maximum level of tt is cached (Property 3). But LλβL^\beta_\lambda is not stable under resolution (p. 7), so the fast path must fall back to general pattern unification. ELPI reports large speed-ups: typeof in 0.27 s versus 5.64 s for Teyjus, reduce-cbv in 0.15 s versus 11.11 s.

Outside the fragment, ELPI’s default is an error: “Unification problem outside the pattern fragment. … Pass -delay-problems-outside-pattern-fragment … in order to delay (deprecated, for Teyjus compatibility)”. Delay is offered instead through syntactic constraints. declare_constraint (even X) [X] suspends a goal on variables, and the goal is resumed when any of them is assigned, so declare_constraint (even X) [X], X = 1. fails. Suspended goals keep their hypothetical context. The documentation’s example (ELPI.md, “Syntactic constraints”):

goal> pi x\ sigma Y\ even x => declare_constraint (even Y) [Y].
Success:
Constraints:
 {x} : even x ?- even (W x)  /* suspended on W */

The residual constraint remembers the eigenvariable x and the hypothesis even x. Note also the automatic raising: Y was created inside the scope of x, so it is printed as W x. Constraint Handling Rules can operate on suspended goals.

9.7.7Makam

Makam Antonis Stampoulis and Adam Chlipala. Prototyping a functional language using higher-order logic programming: a functional pearl on learning the ways of λ\lambdaProlog/Makam. Proceedings of the ACM on Programming Languages, 2(ICFP):Article 93, 2018. doi: 10.1145/3236788 is a λProlog dialect with polymorphism, used to prototype type systems. Two idioms are relevant for us. bindmany is a binder over a list of variables, with openmany/applymany to open many binders at once. And reflective predicates such as refl.isunif test whether a term is an uninstantiated unification variable. That test is non-logical, and is the analogue of (aux kanren micro)’s project°.

Kanren angle (what the implementations ask of a miniKanren). The real systems agree on three mechanisms: (i) a level on every logic variable and eigen-constant, with the binding check and lowering of Definition 9.15; (ii) pattern unification with inversion and pruning (Nipkow, Nadathur–Linnell, ELPI); (iii) a store of delayed equations or goals, woken on assignment (DHKP §5.4, Teyjus, ELPI’s syntactic constraints). (aux kanren micro) has no notion of level. Its creation index is a time stamp, not a scope depth: a variable created after a ∀-scope has closed has a larger index, but it must not see that scope’s constant. On the other hand, the assocs-driven re-verification of D is exactly the wake-up hook that a delay store needs. Search is unchanged: or°’s fair interleaving can host Huet’s branching. That fits Miller’s remark that a breadth-first search could compute the converse of his prenex relation, which the depth-first interpretation cannot Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991. The design itself is in Chapter 11.

9.8Comparison of the design options

Table 9.2 sets the four candidate meanings of =° on λ-terms side by side. The rows summarize the analysis of Section 9.2, Section 9.3, Section 9.5 and Section 9.7. The table records trade-offs and does not rank the options: the choice, and the reasons for it, are the subject of Chapter 11.

A. Pattern unification, de Bruijn + levels (Miller, Nipkow, Nadathur–Linnell, ELPI)B. Nominal (Urban–Pitts–Gabbay, αKanren)C. Static closures (Ma–Friedman 2021)D. Huet pre-unification, enumerated by the stream
Fidelity to the bookexact: LλL_\lambda is what Teyjus 2 and ELPI runa different logic (nominal); no function variables, no βnon-standard grafting semantics: λa. X=?λb. b\lambda a.\, X\stackrel{?}{=}\lambda b.\, b succeeds, unlike λPrologexact for full higher-order unification (pre-unifiers)
Decidable / unitaryyes / yes (mgu)yes / yes, with a freshness contextclaimed; no full algorithm published (a “preview”)semi-decidable; possibly infinitely many pre-unifiers
New term formsλ node (indices), eigen-constant with level, flexible application X y¯X\,\bar ynom, tie, suspension π⋅X\pi\cdot Xnamed and nameless binders, levels, closuresas A, plus imitation and projection
New statea level per variable, current depth, delayed-equation storefreshness store ∇ of a#Xa\#Xa “context” of closure equationsas A; branching via or°
Cost of αfree (syntactic on indices)swappings on the fly, suspensionslevelsfree
βonly β0_0; general β via copy/subst relations, or delayednone (write substo)“will be powered” (not given)full
∀-goals (generic)eigen-constant + level check + loweringa separate mechanism is still needed: noms are distinct constants, not eigenvariablesall from λKanren 2020 (prefix)as A
With ≠°, absent°, typeseigens need a ∀-aware check (Moiseenko)αKanren has no disequality at allnot discussedas A
Effort in auxmedium–high: a Nipkow-size core, plus levels and a delay storemedium: Byrd’s ch. 11 is about 300 lines; a triangular version existsunclearhigh, plus control of infinite branching
Table 9.2: Design options for higher-order unification in a miniKanren. No option is chosen here; see Chapter 11.

Some combinations are possible and appear in the literature. Option D can sit on top of A as a separate, explicitly nondeterministic relation; the book itself presents Huet’s procedure as a search over a matching tree (Chapter 7), and miniKanren’s interleaving could explore it fairly. Option B can live beside A, for users who want names as data. Option C behaves differently from all the others on the three counter-examples of Section 9.3.1; any implementation should state its answers to them explicitly. The smaller alternatives for ∀ alone are the explicit prefix of λKanren 2020 (simplest, but each check walks the prefix and the prefix only grows), the eigen-absento of Hemann–Byrd–Friedman (smallest change, O(∣B∣)O(|B|) per check, first-order only), and the end-of-scope check (weakest). The constructive ∀/⇒/¬ of Moiseenko and Jin et al. is orthogonal: it has a classical, extensional reading and does not implement the book’s generic and augment.

9.9Summary

  • Ma and Friedman 2021 Weixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2021 is a workshop preview. It has two grammars, the operations ext\mathrm{ext} and db\mathrm{db}, three examples, and no algorithm, rules or theorems.
  • Its first complaint is that pattern unification rejects λa. X=?λb. b\lambda a.\, X\stackrel{?}{=}\lambda b.\, b. That is the scope restriction, which λProlog needs for the soundness of ∀. Its fix is to graft de Bruijn levels, giving X↦d0X\mapsto\texttt{d0}. λProlog’s own answer is to make the dependency explicit: λa. (X a)=?λb. b\lambda a.\, (X\,a)\stackrel{?}{=}\lambda b.\, b is a pattern with mgu X↦λx. xX\mapsto\lambda x.\, x (Miller’s “discharging a constant”).
  • Its second complaint is that binder-merging plus naive reification makes λa. λa. X=?λc. λd. c\lambda a.\, \lambda a.\, X\stackrel{?}{=}\lambda c.\, \lambda d.\, c succeed, so “true = false”. Static closures ⟨ϕ; t⟩\langle \phi;\,t\rangle make shadowed levels unavailable, and the equation fails. Flex-flex closure equations are postponed in a context.
  • The assessment uses three counter-examples. The conjunction separates static closures from nominal unification. The dangling d0 at top level shows that XX has no depth-independent meaning. “True = false” also fails under pattern and nominal unification, so it is a bug of binder-merging only. Static closures are grafting on de Bruijn terms without DHKP’s pre-cooking, and α is no longer a congruence on open terms.
  • λKanren 2020 transcribes Miller 1991 with an explicit prefix and gensym renaming. Non-patterns fail. Hypotheses must be threaded in the state, because a host parameter loses them under delayed relation bodies.
  • Nominal unification (αKanren) handles α with swappings and freshness, using capturing substitution. It has no function variables, no β and no disequality, and noms are not eigenvariables.
  • Eigenvariables in miniKanren: a fresh constant without a scope check is unsound. Hemann, Byrd and Friedman implement the check as an absento over the earlier variables. Disequality and eigen-constants conflict (Moiseenko). Jin et al.’s ∀ is extensional, not generic.
  • Real λProlog systems use universe indices or levels with lowering (Nadathur et al., Teyjus, ELPI), pattern unification with inversion and pruning (Nipkow, Nadathur–Linnell), and delayed non-pattern equations (DHKP, Teyjus, ELPI’s syntactic constraints). Teyjus adds the suspension calculus; ELPI uses de Bruijn levels and the LλβL^\beta_\lambda fast path.
  • The options are pattern+levels, nominal, static closures, and Huet enumerated by the stream (Table 9.2). The choice is made in Chapter 11.