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 Kanren. 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 Kanren. 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. Kanren: 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 (λKanren 2020, Teyjus 2, ELPI), Huet’s full pre-unification, or the “static closures” of Ma and Friedman 2021. - Q3. How to implement generic (). 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 Kanren. 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, Prolog 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 (). A hypothetical clause must be visible to every relation call made during the proof of , 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 (, 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. Kanren: 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, Prolog 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 Kanren. In miniKanren and Relational Programming Workshop, 2020; Weixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for Kanren. 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 , if is a unification variable, then 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 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 ” (p. 2).
Definition 9.1 (Grafting and substitution, p. 2–3).Weixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for Kanren. In miniKanren and Relational Programming Workshop, 2021 A grafting is a purely textual replacement of the unification variable by . It is not capture-avoiding: grafting into yields , so the name 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 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 . 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 Kanren. 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 :
For λa.X =? λb.b the scope is '((∃ X) (∀ a)). The variable comes after , so
it cannot instantiate . 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 Kanren. 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 . An index counts binders from the inside: the nearest binder is .
Example 9.4. In , the variable has level and index , and has level and
index . The term is with levels and with indices. The
paper writes the level as d. 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 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 that binder is shadowed. The last query shows a dangling
index: 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 Kanren. 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).
This is solved by . Instantiating gives
which β-reduces to .
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” . “Then it appears to be solvable by , or equivalently , that associates 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 and , the left-hand side is α-equivalent to , because the occurrence refers to the inner binder. The right-hand side is .
The paper argues that binder-merging goes wrong “even without lifting the scope restrictions”:
“which then ends up with another false positive”. The correct answer is failure: 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 Kanren. In miniKanren and Relational Programming Workshop, 2021
“The nameless syntax, i.e., nameless-binders and levels are derived during unification” (p. 5): the user writes only , , and . “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 .”
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 (), but the example writes the scope of as , 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 Kanren. In miniKanren and Relational Programming Workshop, 2021 In the paper’s words:
- “ adds the name to the scope . If has been previously added to , then this older one is shadowed and its corresponding level becomes unusable.”
- “ is where is the de Bruijn level of w.r.t. the scope , if is not shadowed in ; otherwise, the result is .”
- “ is , if is available in ; otherwise, the result is .”
So 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 outermost first:
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 is not shadowed” can only mean “the innermost ”. The other reading would make 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:
“We first apply db on the right-hand side”: , so the problem is . “Then we try to solve X by applying db on the scope of the left-hand side and 0”: , because is not rebound. Then . “It works. So, the solution is .”
Example 2 (p. 5–6), the shadowing case:
As before, the right side gives . “This time, db() is Nothing because the outer binder a is shadowed”. Here the paper puts the inside the closure brackets, an abuse of notation for . We get , “and we know the unification fails”. True is not false any more.
Example 3 (p. 6), two unknowns:
“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 .” 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 : a grafting and a context 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 under scope is converted to internal syntax :
Both sides of an equation are converted from , so they are always compared at equal depth. A binding is , where is in level form at depth . Levels below are free (scope) levels; the others are bound inside . To instantiate at an occurrence :
- a free level must satisfy , or else the occurrence fails;
- a local level is shifted to ;
- a nested closure is re-rooted at .
Rules. The judgement is . Terms are walked first, i.e. a bound closure is replaced by its instance. Any pair of head constructors not listed fails.
In Graft, is not an unbound closure. is the set of unification variables of (the occurs check). is the set of levels below that occur in : those that point into the scope rather than to a nameless binder inside . The availability premise says that a solution may mention only scope binders that are visible, i.e. not shadowed, at the occurrence of . The premise “” means that every postponed equation is solved again, the wake-up. Example 2 fails in the availability premise of Graft: .
Tutorial (a wake-up, step by step). Take Example 3 and then bind , in two variants. Both start from (first variant) or (second variant).
- Conversion gives . Lam
twice, then Postpone: , . This is the
line
(X ctx: 1)below. - The second equation converts to . Graft checks and binds .
- Wake-up: is solved again. Walking instantiates ’s solution at
, giving . The equation becomes , and Graft checks
. It holds, so , printed
d0. - In the second variant the same wake-up yields , but , 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 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 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 Kanren. In miniKanren and Relational Programming Workshop, 2020. Its Fig. 2 contrasts Horn clauses with hereditary Harrop formulas. In the figure the shared rows are and , and the HH-only rows are and for goals. The atoms and are missing from the figure. With them it is exactly the book’s grammar (3.1) [MN p. 91]:
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
. The
define is the clause . 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 . 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, (and ) are quantified outside the λ, as in the paper’s queries.
| problem | λProlog (patterns) | αKanren (nominal) | static closures |
|---|---|---|---|
| ✓ | ✓ | ✓ | |
| ✗ (scope) | ✓ | ✓ | |
| … | ✗ | ✗ () | ✓ d0 |
| ✗ | ✗ (needs ) | ✗ | |
| ✗ | ✗ | ✗ | |
| ✓ (neither may depend on ) | with , | postponed |
Tutorial (what λProlog offers the novice instead: make the dependency explicit). The paper calls the failure of 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
.
generic replaces by a new constant , and backchaining twice would need
. This is rejected, and Miller says why: “Such a failure
here is quite sensible since the value of should be independent of the choice of the constant used
to instantiate .” If we do want a value that depends on , we must say so, by writing
instead of . Then must equal . Two λ-terms
would do, and
, but “since cannot contain free, only
the second” is legal. Miller calls this “discharging the constant ”.
The same move answers the novice. Write : this is a pattern ( applied
to one bound variable), and its most general unifier is . The conjunction with
is solved by the same , and a top-level gets the closed term
, 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: behaves like applied to the available
levels of (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: .
Nominal, using the rule of Section 9.5. The first equation gives with , which holds, so . The second becomes , i.e. , which fails. Nominal unification thus agrees with static closures on the single equation ( is the bound name) and disagrees on the conjunction.
Pattern: both equations fail at once, by the scope restriction.
Static closures: satisfies both.
So static closures are neither pattern unification nor nominal unification. 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, , so the top-level answer is . That is a
level which is not available in the empty scope where lives. The answer is meaningful only
relative to the occurrence of 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 ; 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: .
Pattern: cannot depend on the bound variables at all, so this fails.
Nominal: gives , with , which holds. Then gives , with , 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.
- The meaning of a unification variable changes. In λProlog, in cannot mention . With static closures, implicitly depends on the positions of its enclosing binders. Logically, behaves like Miller’s raising over the available levels of , 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.
- α-equivalence is no longer a congruence on open terms. and are α-equivalent in the usual sense, because is a metavariable with no free names. Yet against the same , 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 and freshness . The paper’s “names don’t matter” holds for the levels, not for the closures.
- Levels are stable for scope variables, not for binders inside solutions. A grafted solved at depth 1 must become 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.
- Flex-flex need not be postponed. With levels, at equal depth has a most general solution: , plus the restriction that may use only levels in . This is Miller-style pruning, phrased as a freshness-like constraint.
- 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. - β 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 “ is the state-of-the-art” (p. 8). The notes summarize the correspondence like this: the static closure is close to the nominal suspension (both record the context around an unknown); is close to the action of on names; and “level unavailable in ” is close to the freshness . 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 leaves a unifier that is “practically first-order” except for closures. - A walk that can fail. Walking instantiates at , 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/touchedidiom, 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 Kanren. 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. Kanren: 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 ) and
all (a universal goal ). 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
. 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 restrictionThe 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 _ symbols. The third is not a pattern ( is applied to twice) and fails,
even though it has solutions ( and ); 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 would have to be the bound , which
is introduced after .
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 , 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 .
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 is not trivial, so is not
provable, whereas the same goal without all succeeds with . The last two queries
use λKanren “as a theorem prover” (§5, p. 6–7). The first proves the commutativity of
conjunction, : generic makes and 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,
, 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 and invisible outside it. It can never be a host parameter. A further remark
from the notes: a hypothetical clause 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).
where abstracts the atom in , and is a variable with a suspended permutation. A permutation is a list of swappings :
Composition is list append and the inverse is reversal. The disagreement set is . A permutation acts on an abstraction on both the binder and the body, and it suspends on variables: . Substitution is capturing: with no side condition, and .
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 , a set of pairs :
plus the congruence rules for unit, pairs, function symbols and atoms.
The intuition: says that does not occur free in , also after any later instantiation of the variables of . To compare with , rename to in by a swapping, which is always safe because it is a bijection, and require that was not already free in .
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
and , with not in , gives . A solution is a pair with . For example, has the solution .
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. Kanren: 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
, binds the nom in ; it delimits scope and does not create noms. (# a t),
entered hash, asserts that does not occur free in . 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: 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 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 with 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. leanTAP: 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 ) and a freshness store ∇ of
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 by proving for a new constant . If the constant is only a gensym, nothing stops an older logic variable from being bound to it later. That “proves” , which must fail. Contrast , 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 Kanren. 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, Prolog 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 :
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 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 , and the
eigen is a fresh record that 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 by collecting all answers of and negating them. To make this closed under negation, states become formulas (eq. (1), p. 6):
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 is satisfiable iff .
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 , oriented so that . Then is satisfiable iff or , and unsatisfiable iff .
The orientation is a normalization: if the mgu maps an outer variable to some , flip that binding to . In words: is unsatisfiable exactly when and can be made equal by choosing values for the universal variables alone. Example: for , the mgu is , its domain is , so the constraint is unsatisfiable. For the mgu binds the outer , so it is satisfiable (by any that is not a pair with first component ).
Lemma 9.14 (Def. 12, Lemma 5, p. 10–11).Evgenii Moiseenko. Constructive negation for miniKanren. In miniKanren and Relational Programming Workshop, 2019 For , let be idempotent and its restriction to the non- variables. The formula is satisfiable iff and no has .
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 , and . 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
, with an outer variable. It must fail: take .
Moiseenko’s Lemma 4 agrees, since the mgu has domain . A naive
eigen-constant makes hold forever, because can never be bound to , and
the query wrongly succeeds. The same issue arises for type constraints: stands for an arbitrary
term, so symbol° of 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 when 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. holds when . That is a classical case split on , which λProlog’s generic ∀ cannot do; λProlog has no 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 : 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: 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 is in if all quantification in is over nonpredicate types and every subterm of of the form in which is an essentially existentially quantified variable is such that are distinct variables that are universally quantified within the scope of the quantifier binding ” [MN p. 220]. Then only β is needed: when is a variable not free in .
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 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):
Read the last two steps with the prefix in mind, which is now . The equation is flex-rigid: against . The universal is quantified after and is not among ’s arguments, so ’s solution may not mention it. Every occurrence of sits under the flexible head , so the problem is not hopeless: pruning removes ’s dependency on its first argument, . After that the rigid side is , and flex-rigid abstracts ’s argument: . Had 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 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 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 , which is not a pattern because is a constant, are exactly
the that make substterm F a (g a a) provable. Miller lists the four answers an
interpreter should return: w\(g w w), w\(g w a), w\(g a w), w\(g a a). The choice
“is this 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 is pragmatic. A common resolution is “to not impose the restriction on program clauses statically but rather to expect the condition to be satisfied by the unification problems that are encountered dynamically”. 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 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:
- head-normalize both sides through the substitution, with β done by renaming indices;
- ; η on demand, ;
- rigid-rigid: equal heads give pairwise unification, different heads fail;
- flex-rigid : occurs check, then invert with respect to and prune the flexible subterms that mention indices outside ;
- flex-flex, same head: ;
- flex-flex, different heads: if then , symmetrically in the other case, and otherwise both are bound to a fresh applied to .
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 is syntax. Meta-variables are grafted, i.e. replaced first-order. To recover the logical, capture-avoiding reading, terms are pre-cooked: , , , . A metavariable under 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 has with the ’s and ’s distinct indices. Pattern substitutions are injective and have a right inverse, so is solved by when every index of occurs in (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 with tag to : (1) perform the usual occurs check; (2) check that contains no constant with tag ; (3) before binding, change to the tags of the variables of whose tag is .
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: . Goal: .
- creates with tag 1. raises the index to 2 and creates with tag 2. augment adds . The goal is now .
- backchain on the clause gives a new variable tagged with the current index, 2. Unifying binds , and lowers to tag 1.
- The subgoal meets the hypothesis . Binding violates step (2), so it fails.
Without lowering, would be accepted and would become . That smuggles the eigen-constant into a variable quantified outside its scope. The failure is correct: the goal would need , but is quantified before .
The abstract interpreter works on tuples . A ∃-goal tags its new variable with ; a ∀-goal goes to ; and backchaining instantiates the clause’s variables with tag . 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 : “a term that used to occur inside abstractions but now appears within of them”, with an environment . Some of the rules:
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 , the number of ∃-followed-by-∀ alternations up to its quantifier, and “a universal
variable is quantified within the scope of the quantifier for an existential variable just in
case ”. 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 with the equation 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 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 is not a pattern: is quantified
outside the scope of , so it is a constant for . It has “two incomparable solutions”,
and (written and
in the paper’s de Bruijn notation), and no most general one. Move the quantifier,
, and it becomes a pattern with the single solution
. 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
(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, Prolog 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 , the universally quantified variables of the clause are instantiated to unification variables where the level records that has only visibility of the initial prefix of length of the context. If later a fresh constant is added by the pi rule, the constant occupies position … and it will not be allowed to occur in instances of the variable ” (p. 4). 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 :
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 , with global constants as negative ; sees the names below .
Definition 9.17 (Reduction-free fragment Lλβ, Def. 1).Cvetan Dunchev, Ferruccio Guidi, Claudio Sacerdoti Coen, and Enrico Tassi. ELPI: fast, embeddable, Prolog interpreter. In Logic for Programming, Artificial Intelligence, and Reasoning (LPAR-20), volume 9450 of LNCS, pages 460–468. Springer, 2015 Every occurrence of a unification variable is applied to , for : exactly the next context names, in order.
This fragment is contained in (Property 1). Head reductions of take constant time (Property 2), and so does solving when no occurs check is needed and the maximum level of is cached (Property 3). But 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 Prolog/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 book | exact: is what Teyjus 2 and ELPI run | a different logic (nominal); no function variables, no β | non-standard grafting semantics: succeeds, unlike λProlog | exact for full higher-order unification (pre-unifiers) |
| Decidable / unitary | yes / yes (mgu) | yes / yes, with a freshness context | claimed; no full algorithm published (a “preview”) | semi-decidable; possibly infinitely many pre-unifiers |
| New term forms | λ node (indices), eigen-constant with level, flexible application | nom, tie, suspension | named and nameless binders, levels, closures | as A, plus imitation and projection |
| New state | a level per variable, current depth, delayed-equation store | freshness store ∇ of | a “context” of closure equations | as A; branching via or° |
| Cost of α | free (syntactic on indices) | swappings on the fly, suspensions | levels | free |
| β | only β; general β via copy/subst relations, or delayed | none (write substo) | “will be powered” (not given) | full |
| ∀-goals (generic) | eigen-constant + level check + lowering | a separate mechanism is still needed: noms are distinct constants, not eigenvariables | all from λKanren 2020 (prefix) | as A |
With ≠°, absent°, types | eigens need a ∀-aware check (Moiseenko) | αKanren has no disequality at all | not discussed | as A |
Effort in aux | medium–high: a Nipkow-size core, plus levels and a delay store | medium: Byrd’s ch. 11 is about 300 lines; a triangular version exists | unclear | high, plus control of infinite branching |
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, 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 Kanren. In miniKanren and Relational Programming Workshop, 2021 is a workshop preview. It has two grammars, the operations and , three examples, and no algorithm, rules or theorems.
- Its first complaint is that pattern unification rejects . That is the scope restriction, which λProlog needs for the soundness of ∀. Its fix is to graft de Bruijn levels, giving . λProlog’s own answer is to make the dependency explicit: is a pattern with mgu (Miller’s “discharging a constant”).
- Its second complaint is that binder-merging plus naive reification makes succeed, so “true = false”. Static closures 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
d0at top level shows that 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 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.