Chapter 1

Introduction

(aux kanren micro) is a small, fast miniKanren. Its terms are first-order Scheme data, its unifier is first-order unification with an occurs check, and its goals are conjunctions, disjunctions and existentials. In logical terms it runs first-order Horn clauses (Section 2.12). λProlog, the language of Miller and Nadathur’s Programming with Higher-Order Logic Dale Miller and Gopalan Nadathur. Programming with Higher-Order Logic. Cambridge University Press, Cambridge, 2012, runs a much larger logic. Goals may say “for every new name xx” and “assuming DD”, terms may contain λ-binders, and unification works modulo α, β and η. With these three features, programs over syntax with binders (type checkers, evaluators, provers, program transformations) contain no code for renaming, fresh names or capture-avoiding substitution, because the logic does that work.

This document asks what it would take to give (aux kanren micro) the same power, and it ends with a concrete answer: a module, (aux kanren lambda), prototyped, tested, benchmarked, and merged into aux. This chapter says what the document is for (Section 1.1), runs one example through the whole story (Section 1.2), maps the chapters (Section 1.3), proposes three ways to read them (Section 1.4), and fixes the conventions (Section 1.5).

1.1What this document is for

The goal. The goal is to bring three ideas of λProlog into (aux kanren micro):

  1. hereditary Harrop goals, that is the universal goal ∀x G\forall x\,G (pi x\ G, proved with a new scoped constant) and the hypothetical goal D⊃GD\supset G (D => G, proved with the program temporarily extended by the clause DD);
  2. λ-tree syntax: object-level binders represented by meta-level λ-abstractions, so that α-equivalence is built in and object-level substitution is meta-level β-reduction;
  3. higher-order pattern unification (LλL_\lambda): unification of λ-terms restricted to the fragment where it is decidable and has most general unifiers, with the other equations delayed.

The three are not independent. pi is what lets a program walk under a λ-binder, and pattern unification is what lets it build a λ-term back. The book’s programs use all three together.

The sources. There are two. The first is the book itself, which Part I summarizes chapter by chapter, with its core examples run on (aux kanren micro) wherever that is possible today. The second is the miniKanren literature on these features, which Part II surveys. Its center is Ma and Friedman’s 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, read together with its predecessor λKanren Weixi Ma, Kuang-Chen Lu, and Daniel P. Friedman. Higher-order logic programming with λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2020, 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, the eigenvariable and negation work 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, and the techniques of real λProlog systems: universe levels Gopalan Nadathur, Bharat Jayaraman, and Keehang Kwon. Scoping constructs in logic programming: implementation problems and their solution. Journal of Logic Programming, 25(2):119–161, 1995, Miller’s and Nipkow’s pattern unification 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 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, delayed equations 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, Teyjus Gopalan Nadathur and Natalie Linnell. Practical higher-order pattern unification with on-the-fly raising. In ICLP 2005: 21st International Logic Programming Conference, volume 3668 of LNCS, pages 371–386, Sitges, Spain, 2006. Springer and 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.

The outcome. Part III is a proposal in two pieces, now merged.

  • A generic extension protocol in (aux kanren micro) (commit 26b4708, +286/−65+286/{-}65 lines, comments included, and +31/−9+31/{-}9 in d501822). The state gains one slot that (aux kanren micro) never reads, and a registry of hooks opens the points that are closed in (aux kanren micro)’s core: the unifier’s structural clause, the occurs check, the step after each =°, the disequality, type and absento stores, and reification. Nothing in the edit mentions λ, levels or clauses.
  • A client module, (aux kanren lambda), src/aux.kanren.lambda.scm, 1427 lines, which registers one extension. It provides λ-terms (ƛ, @), the goals ∀° and ⊃° with define-dynamic-relation, and LλL_\lambda unification with universe levels and delayed non-patterns. Through the hooks it also makes (aux kanren micro)’s own ≠°, absent°, symbol° and number° λ-aware; it exports no second version of them.

The design was not chosen on paper. Three prototypes were built: one that leaves (aux kanren micro) untouched, one with a hook protocol, one with λ-terms native in the core. They were compared by three reviews, on engineering, on fidelity to the book and on pedagogy. The hook design, ranked first by two of the three, became the base, and about twenty grafts proposed from the other two were each adopted or explicitly declined. Three adversarial review rounds then attacked the result and sent thirteen, eight and twelve reports. All were real. Every defect but one was fixed and pinned by a regression caseA cost reported by the third round among them.; the exception, the cost of the scope check on first-order search once a ∀° has run, reported by the second round, is measured and documented as a limitation. The prototype, frozen at commit f84cf9c in doc/hol-kanren/prototype/, was then ported onto a (aux kanren micro) that had changed under it and merged in five commits, whose reviews found and fixed more defects (Section 14.4.3). The merged suite has 93 cases with 421 hand-written assertions, plus 6 cases that pin the known limits, and (aux kanren micro)’s own 187 cases pass unchanged, with and without the module loaded: with the protocol’s 6, 479 cases, no failures. The protocol costs 0–2.2% on first-order search when no extension is loaded, and 1 ms more on three rows of about 30 ms. The module and its suites are src/aux.kanren.lambda.scm and src/test/microkanren-lambda*.scm.

1.2The whole story in brief

This section follows one program from the book through the whole document: type inference for the untyped λ-calculus [MN p. 190–191]. It is two clauses of λProlog, and it uses every feature at once.

1.2.1The program, twice

Object-level λ-terms are built with two constructors, app for application and abs for abstraction. abs takes a meta-level abstraction: the identity is abs x\ x. Types are built with arr. The relation typeof M T says that term M has type T:

typeof (app M N) A :- typeof M (arr B A), typeof N B.
typeof (abs M) (arr A B) :- pi x\ typeof x A => typeof (M x) B.

The second clause reads: “to type abs M, take a new constant x, assume that x has type A, and type the body (M x) with B”. There is no clause for variables and no context argument. The hypothesis typeof x A is the context, and it disappears when the proof of the body is over. In the proposed module the same program reads:

(define-dynamic-relation (typeof° m t)
  (cond°
    ((fresh° (M N B) (=° m `(app ,M ,N)) (typeof° M `(arr ,B ,t)) (typeof° N B)))
    ((fresh° (R A B) (=° m `(abs ,R)) (=° t `(arr ,A ,B))
       (∀° (x) (⊃° ((typeof° x A)) (typeof° (@ R x) B)))))))

The dictionary is short. pi x\ G is (∀° (x) G), D => G is (⊃° (D) G), the application (M x) of a logic variable is (@ R x), and x\ t is (ƛ (x) t). The relation is made by define-dynamic-relation instead of define-relation because it receives hypotheses. The first-order structure (abs, app, arr) stays ordinary Scheme data, as everywhere in (aux kanren micro).

1.2.2Running it forwards

The book types the identity and fails on self-application [MN p. 191]:

?- typeof (abs x\x) Ty.          Ty = arr T1 T1
?- typeof (abs x\ app x x) Ty.   no

The module gives the same answers. °->list/datum lists the answers as plain data, and α is a variable that the answer leaves unbound:

(°->list/datum (fresh° (q) (typeof° `(abs ,(ƛ (x) x)) q)))
(°->list/datum (fresh° (q) (typeof° `(abs ,(ƛ (x) `(app ,x ,x))) q)))
((arr α α))
()

Two rules of the book’s proof search are at work, GENERIC for ∀\forall and AUGMENT for ⊃\supset (Section 3.2). In the sequent Σ;𝒫⟶G\Sigma; \mathcal{P} \longrightarrow G, Σ\Sigma is the signature, the constants in scope, and 𝒫\mathcal{P} is the program:

Σ∪{c};𝒫⟶G[c/x]Σ;𝒫⟶∀x G  GENERIC(c∉Σ)Σ;𝒫∪{D}⟶GΣ;𝒫⟶D⊃G  AUGMENT \dfrac{\Sigma\cup\{c\}; \mathcal{P} \longrightarrow G[c/x]}{\Sigma; \mathcal{P} \longrightarrow \forall x\,G}\;\text{\small GENERIC} \quad (c\notin\Sigma) \qquad\qquad \dfrac{\Sigma; \mathcal{P}\cup\{D\} \longrightarrow G}{\Sigma; \mathcal{P} \longrightarrow D\supset G}\;\text{\small AUGMENT}

Read bottom-up, GENERIC proves a universal goal by inventing a constant, and AUGMENT proves an implication by assuming its antecedent. Both changes are local: they hold for the proof of the premise only.

Tutorial (What happens to the state while typeof° types λx.x). Write dd for the current depth, the number of enclosing ∀°, and Γ\Gamma for the assumed clauses. Both live in the search state, in the slot that the protocol adds; the substitution is (aux kanren micro)’s, as before. Each row of the table below is one step towards the first answer, and two of them carry the ideas. At step 5, RR is already bound to λx. x\lambda x.\, x, so (@ R c) reduces by β to cc itself: object-level substitution is meta-level β. At step 6 the dynamic relation tries its hypotheses first, most recent first, and then its two static clauses, which both fail on cc, since an eigenvariable is neither an app nor an abs. The hypothesis typeof° c A mentions the variable AA of the enclosing clause, and AA is shared, not renamed. That is how typing the body tells the outer goal what AA is (Section 3.5).

goalddeffect
1typeof° (abs (ƛ (x) x)) q0the app clause fails; the abs clause applies
2(abs R) = (abs (ƛ (x) x))0first-order: R:=λx. xR := \lambda x.\, x, q := (arr A B)
3∀° (x)1a new eigenvariable cc, of level 1
4⊃° ((typeof° c A))1Γ={\Gamma = \{typeof° c A}\}
5typeof° (@ R c) B1(@ R c) head-normalizes by β to cc
6backchain on the hypothesis1typeof° c A = typeof° c B: AA, BB unified
7answer leaves ⊃° and ∀°0Γ=∅\Gamma=\emptyset; q = (arr A A), printed (arr α α)

Self-application fails at the same step. For (abs (ƛ (x) (app x x))), the body needs typeof° c (arr B′ B) and typeof° c B′, so the hypothesis forces A=A = (arr B′ B) and A=B′A = B': first-order unification fails on its occurs check, as in the book.

The book explains this program in Section 6.5.4; Section 12.4.6 traces it again at the level of the module’s state, and Section 13.5 runs it on the book’s whole session, the combinator S included.

1.2.3Running it backwards

Ask instead for terms of type i→ii\to i. λProlog’s depth-first search loops on this query, because it tries the app clause first and descends forever. The interleaving search of (aux kanren micro) does not:

(°->list/datum (take° 3 (fresh° (q) (typeof° q '(arr i i)))))
((abs (ƛ (x) x))
 (abs (ƛ (x) (app (abs (ƛ (x1) x1)) x)))
 (abs (ƛ (x) (app (abs (ƛ (x1) x)) x))))

The second answer is λx. (λx1.x1) x\lambda x.\,(\lambda x_1.x_1)\,x. The printer renames the inner binder to x1, apart from the outer one. The first answer is the instructive one. Now RR is unknown when step 5 is reached, so backchaining on the hypothesis must solve the equation R c≐cR\,c \doteq c, where RR was created outside the ∀° and cc inside it. That is a higher-order unification problem, and it is one of the easy ones.

Definition 1.1 (Levels and patterns). Every logic variable XX has a level ℓ(X)\ell(X), the depth at which it was created. Every eigenvariable cc has the level ℓ(c)\ell(c) of the ∀° that made it, one more than the depth outside.

  1. Scope check. A binding X:=tX := t, made by any =°, is accepted only if every eigenvariable cc in tt has ℓ(c)≤ℓ(X)\ell(c)\le\ell(X). Each unbound variable YY of tt with ℓ(Y)>ℓ(X)\ell(Y)>\ell(X) is then lowered: replaced by a new variable of level ℓ(X)\ell(X) or, when YY occurs applied, pruned of the arguments that XX may not see.
  2. Pattern. An application F a1…anF\,a_1\dots a_n of an unbound variable FF is a pattern when its arguments, after head normalization, are distinct eigenvariables, each with ℓ(ai)>ℓ(F)\ell(a_i)>\ell(F).

The full rule, including the cases that must wait for a later binding, is in Section 12.3.

The first condition is the scope check. It is the operational content of the order of quantifiers in ∃R ∀c\exists R\,\forall c: RR was chosen before cc existed, so its value cannot mention cc (Section 3.4.3 and Section 4.4). Levels replace the book’s explicit quantifier prefix, as Teyjus does 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. The second condition defines Miller’s fragment LλL_\lambda, in which unification is decidable and has most general unifiers Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991 (Section 7.5).

Example 1.2 (Scope and patterns). Here ℓ(R)=0\ell(R)=0 and ℓ(c)=1\ell(c)=1. The equation R≐cR\doteq c violates the scope check and fails. The equation R c≐cR\,c\doteq c is a pattern: abstracting cc out of the right-hand side gives the most general unifier R:=λx. xR := \lambda x.\, x. In the module, with q in the role of RR:

(°->list #f (fresh° (q) (∀° (x) (=° q x))))
(°->list/datum (fresh° (q) (∀° (x) (=° (@ q x) x))))
()
((ƛ (x) x))

The first is the book’s sigma x\ pi y\ x = y, which is not provable [MN p. 85]: no single term equals every new constant.

The other two answers of the backwards run come from the app clause under the binder: the body (@ R c) must unify with (app M N), where MM and NN were created inside the ∀°, at level 1. Variable elimination (Section 7.6) builds R:=λy. (𝚊𝚙𝚙 (𝙼′ 𝚢) (𝙽′ 𝚢))R := \lambda y.\, \mathtt{(app\ (M'\ y)\ (N'\ y))} and lowers MM and NN to new variables M′M', N′N' of level 0, applied to cc: M:=M′ cM := M'\,c, N:=N′ cN := N'\,c. Scheme code built none of these λ-terms; unification did.

When an equation is not a pattern. Some equations have no most general unifier. The book’s ∀x. F x x≐x\forall x.\,F\,x\,x\doteq x [MN p. 208] has two incomparable solutions, λa. λb. a\lambda a.\, \lambda b.\, a and λa. λb. b\lambda a.\, \lambda b.\, b, and F x xF\,x\,x is not a pattern, since its arguments repeat. The module does what Teyjus does, “dynamic LλL_\lambda” (Section 7.9.1): it suspends the equation, retries it after every later binding, which may have turned it into a pattern, and reports it in the answer if it is still there at the end. Under °->pretty, which prints constraints in the style of αKanren, the residual equation is closed over xx when it leaves the scope of the ∀°. A later binding decides it:

(°->pretty (fresh° (q) (∀° (x) (=° (@ q x x) x))))
(°->list/datum (fresh° (q) (∀° (x) (=° (@ q x x) x)) (=° q (ƛ (a b) b))))
((α : (= (ƛ (x) (@ α x x)) (ƛ (x) x))))
((ƛ (a b) b))

1.2.4What the engine had to learn

None of the above runs on today’s (aux kanren micro). Table 1.1 lists what the example needed, where the book explains it, and where this document builds it.

conceptin the exampletheory / in the module
λ-tree syntax, α-equivalence(abs (ƛ (x) x)), binders printed apartChapter 6 / Chapter 12
β-reduction, application(@ R x) is x once R := (ƛ (x) x)Chapter 4 / Chapter 12
GENERIC, eigenvariables(∀° (x) …)Chapter 3 / Chapter 11 and Chapter 12
AUGMENT, dynamic relations(⊃° ((typeof° x A)) …)Chapter 3 / Chapter 12
scope check and levelsR = x failsChapter 3 and Chapter 7 / Chapter 12
pattern unificationR x = x gives R := λx.xChapter 7 / Chapter 12
dynamic LλL_\lambda, residualsF x x = x waitsChapter 7 / Chapter 12
interleaving searchtyping backwards terminatesChapter 2 / Chapter 10
Table 1.1: The running example, concept by concept.

The state of (aux kanren micro) has a fixed set of fields, and its unifier, walks and reifier are closed (Section 10.9). The proposal opens them once, generically, and puts everything λ-specific in a client module. In the state’s new slot the module keeps the depth, the level of each variable, the assumed clauses Γ\Gamma, the suspended constraints (equations, and types or absentos on flexible terms), and the disequalities that involve λ-terms or eigenvariables. Through the hooks it receives every unification problem that contains one of its terms, it checks the scope of the bindings that =° makes, and it takes part in printing. Because the hooks sit inside (aux kanren micro)’s own =°, every relation built on =°, such as (aux kanren micro)’s cons° or the user’s own, respects the scope of ∀° with no change. A prototype that wrapped (aux kanren micro) from the outside instead let eigenvariables escape through exactly such relations (Chapter 11).

Kanren angle (Why not just use Scheme closures?). A Scheme procedure can stand for a binder as long as it is only called: mappred and continuation passing work on today’s (aux kanren micro) (Section 5.11). The backwards run above needs more: unification must look inside the abstraction, compare it modulo α, and build one. A closure can do none of these, so ƛ builds a data structure, a locally nameless term whose binders are de Bruijn indices N. G. de Bruijn. Lambda calculus notation with nameless dummies, a tool for automatic formula manipulation, with application to the Church–Rosser theorem. Indagationes Mathematicae, 34(5):381–392, 1972; and Arthur Charguéraud. The locally nameless representation. Journal of Automated Reasoning, 49(3):363–408, 2012, which prints with the user’s names.

Pitfall (Hypotheses need a dynamic relation). In λProlog every predicate can receive clauses through =>. In the module only a relation made by define-dynamic-relation can, because a relation made by define-relation is a closed Scheme procedure. Assuming a clause for it is an error, not a silent no-op:

(define-relation (static° x) (=° x 1))
(define-dynamic-relation (dynamic° x) (=° x 1))
(°->list/datum (fresh° (q) (⊃° ((static° 2)) (static° q))))   ; an error
(°->list/datum (fresh° (q) (⊃° ((dynamic° 2)) (dynamic° q))))
Error: (⊃°) not a dynamic relation, see define-dynamic-relation: #<procedure (static° x)>
(2 1)

The first line is what csi prints for the error, which stops the script; the last query was run on its own. In the second answer the hypothesis comes first, then the static clause, as in the book [MN p. 78].

1.3Map of the document

The document has three parts and two appendices. Part I follows the book, Part II the literature, and Part III builds the proposal.

Part I: the book

Chapter 2, Logic programming as proof search. The book’s Introduction and Chapters 1–2: typed first-order terms, first-order unification, the search semantics of goals, and backchaining on Horn clauses (fohc). It establishes that pure miniKanren is fohc without types and with an interleaving search, and it shows where the interleaving finds answers that depth-first search misses.

Chapter 3, Hereditary Harrop formulas. Chapter 3 of the book: AUGMENT and GENERIC, hypothetical reasoning on a course database, scoped constants, why ∃∀\exists\forall and ∀∃\forall\exists differ, and how assumed clauses share variables with their context. The logic is intuitionistic, indeed minimal, not classical. Its last section lists what ∀\forall and ⊃\supset ask of a miniKanren: the program context must live in the search state, and scoped constants need a scope check.

Chapter 4, Typed λ-terms and unification problems. Chapter 4: simply typed λ-terms, conversion by α, β and η as the equality of the logic, normal forms, unification problems as quantified formulas, raising, and why higher-order unification is undecidable (Post’s correspondence problem, Hilbert’s tenth problem).

Chapter 5, Higher-order programming. Chapters 5–6: rigid and flexible atoms, the languages hohc and hohh, predicate variables (mappred, folds, continuation passing), function variables solved by unification (functional difference lists), and modules as logic. It sorts the book’s programs into those that run on today’s (aux kanren micro) (they only call a predicate) and those that need λ-terms (they look inside one).

Chapter 6, λ-tree syntax. Chapter 7, the chapter that motivates the proposal: object-level binders as meta-level abstractions, substitution as β, the mobility of binders (term-level λ, then pi, then an eigenvariable), and the book’s programs over λ-terms and formulas: evaluators, type inference, de Bruijn translation, normal forms, prenex forms, copy clauses, and substitution run backwards. It ends with the LλL_\lambda subset.

Chapter 7, Unification of λ-terms and higher-order patterns. Chapter 8: Huet’s procedure and its matching trees, the pattern fragment, the pattern unification algorithm as one walk of variable elimination (inversion, pruning, occurs and scope checks), traces of the book’s examples, Nipkow’s de Bruijn algorithm with a running Scheme transliteration, and the pragmatics of real systems: universe levels in place of raising, and delayed non-patterns.

Chapter 8, Applications. Chapters 9–11: provers for intuitionistic and classical logic, natural deduction with proof terms, tactics, typing and evaluation of functional programs, partial evaluation, CPS conversion, and the π-calculus. For each application it records which of ∀\forall, ⊃\supset and λ-term unification it needs, and which parts run on (aux kanren micro) today.

Part II: the literature

Chapter 9, Higher-order miniKanren. Ma and Friedman 2021 in full: grafting versus substitution, binder merging and its “true = false” hazard, static closures, and a critical assessment with three counter-examples. Then λKanren 2020, nominal unification and αKanren, eigenvariables and negation inside miniKanren, and the implementation techniques of Miller, Nipkow, Dowek et al., Nadathur et al., Teyjus, ELPI and Makam. It ends with a comparison of the design options (Section 9.8) and deliberately does not choose.

Part III: the proposal

Chapter 10, Anatomy of (aux kanren micro). The engine’s first-order core, on master after the merge (commit c0ff08c): terms and variables, the state with its records of the variables, the walk, unification and its spared occurs check, the stores D (disequalities), A (type tags) and T (absento), the interleaving search, reification and aggregation. It closes with what the core leaves open to extension and what it closes, and with three tricks that need no edit (including working AUGMENT and GENERIC prototypes) together with their limits.

Chapter 11: requirements, design space, protocol. The nine acceptance items A1–A9 collected from Parts I and II (the scope of ∀\forall at every binding, AUGMENT with the book’s clause order, type inference, λ-tree syntax, LλL_\lambda with delay, λProlog’s answers where Ma and Friedman differ, the book’s programs, (aux kanren micro)’s stores on λ-terms, and (aux kanren micro)’s own suites unchanged). Then the design space, the four meanings of =° on λ-terms left open by Section 9.8, of which pattern unification with levels is retained; the three prototypes (a layer on top of (aux kanren micro), hooks in (aux kanren micro), a native engine) and the three reviews that ranked them; and the extension protocol that came out of it, as merged: the state’s slot X, the registry, the fourteen hooks with their contracts and call sites, the invariants every client must keep, what changed from the prototype’s patch, and its cost. It ends with the history of the adversarial review rounds.

Chapter 12: the module. (aux kanren lambda) in detail: locally nameless terms built by ƛ and @; the extension’s state (depth, levels, Γ\Gamma, suspended constraints, λ-disequalities), copied and never mutated; the unification rules with variable elimination, the eager scope check, the fast paths and the wake-up loop, with worked traces; ∀° and ⊃°, including the discharge of constraints at the exit of a scope and backchaining in define-dynamic-relation; disequality, absento and types on λ-terms; reification; and the API reference.

Chapter 13: the book’s examples in the module. The core programs of Part I, each beside its λProlog original and with its actual output: α, β and shadowing; the scope of eigenvariables; the course database, jars and bugs, and reverse with assumed clauses; type inference; call-by-name evaluation, copy and substitution, existential generalization; de Bruijn translation and prenex forms; mappred and palindromes with functional difference lists; Fischer’s CPS transformation; and the unification examples of the book’s Chapter 8 one by one. It also runs Ma and Friedman’s queries and explains each difference, and closes with a table of all the examples.

Chapter 14: tests, limitations, performance, the merge. How the module is tested (three layers of tests, and (aux kanren micro)’s suites run twice); nine documented limitations and deviations from λProlog, each pinned by a test (among them: only dynamic relations take hypotheses, terms are untyped, non-patterns are suspended and never enumerated, answers come in (aux kanren micro)’s interleaving order); the performance measurements of the merged tree; the merge as it was done, in five commits, with what changed against the prototype, the defects it found and fixed, the whole test and what stays open; six later work items; and ten questions only the maintainer of aux can answer.

Appendices

Appendix A, Reference card. The formal rules on a few pages: λProlog syntax and its logical reading, the goal and clause grammars, uniform proofs, typing, λ-conversion, raising, first-order unification, Huet’s procedure, pattern unification and universe levels, each with its page in the book.

Appendix B, Glossary. The vocabulary of the three communities (proof theory, unification, miniKanren) in one alphabetical list, with pointers to the chapters and to the book, and a bridge between their names for the same idea.

1.4Reading paths

The chapters are written to be read in order, but they need not be. Table 1.2 summarizes the three paths below; page counts are approximate.

The fast path. The minimum to understand the proposal, about 45 pages before Chapter 11 and Chapter 12:

  1. Section 1.2 of this chapter (4 pages);
  2. the two rules, the scope condition, and how quantification links goals and clauses: Section 3.2, Section 3.4.3 and Section 3.5 (5 pages);
  3. λ-tree syntax: Section 6.2, Section 6.3, Section 6.4 and Section 6.5.4 (9 pages);
  4. what rigid and flexible terms and the normal form of a unification problem are: Section 7.1 and Section 7.2 (the introduction says enough about imitation and projection to skip Section 7.4); then patterns, their unification, the worked traces and what real systems do: Section 7.5, Section 7.6, Section 7.7 and Section 7.9 (13 pages in all);
  5. the options: Section 9.8 and Section 9.9 (3 pages; the summary defines each term the comparison uses);
  6. the engine’s state, its constraint stores and its extension points: Section 10.2, Section 10.5 and Section 10.9 (11 pages; skip Section 10.5 if you know micro’s D/A/T chain);
  7. then Chapter 11 and Chapter 12 (about 60 pages), the limitations in Section 14.2, and the merge in Section 14.4 (5 pages), which says what each commit brought and what stays open.

The λProlog path. Part I alone, Chapter 2 to Chapter 8, about 185 pages, is a self-contained reading of the book. The Kanren angle boxes can be skipped. Appendix A serves as a reference card along the way.

The implementer path. For whoever will merge or extend the code: Chapter 7 (the algorithm), Chapter 10 (the engine), Chapter 11 (the protocol), Chapter 12 (the module), and Chapter 14 (tests, costs, the merge), about 135 pages, with Section A.9 and Section A.10 at hand. Chapter 13 then serves as a set of worked tests.

Table 1.2: Three reading paths. A filled bullet means read in full, a hollow one read the sections named in the text. Pages are those of this document.
chapterpagesfastλPrologimplementer
Chapter 1, Introduction12∘\circ∙\bullet∙\bullet
Chapter 2, proof search28∙\bullet
Chapter 3, hereditary Harrop24∘\circ∙\bullet
Chapter 4, λ-terms22∙\bullet
Chapter 5, higher-order programming30∙\bullet
Chapter 6, λ-tree syntax30∘\circ∙\bullet
Chapter 7, pattern unification24∘\circ∙\bullet∙\bullet
Chapter 8, applications28∙\bullet
Chapter 9, the literature30∘\circ
Chapter 10, the engine24∘\circ∙\bullet
Chapter 11, design and protocol30∙\bullet∙\bullet
Chapter 12, the module32∙\bullet∙\bullet
Chapter 13, the examples28∙\bullet
Chapter 14, limits, costs, the merge24∘\circ∙\bullet
Appendix A, reference card12∘\circ∘\circ

1.5Conventions

Boxes. Three kinds of box interrupt the text, and each can be skipped on a first reading. A Tutorial box walks through a computation step by step: a trace of unification, of a ∀\forall or ⊃\supset step, of the changes of a state (see the box in Section 1.2). A Kanren angle box says how a concept maps to (aux kanren micro), what runs there today, and what the proposal changes. A Pitfall box marks a trap: one the book stresses, or one that a Scheme programmer is likely to fall into.

Code. Three environments, told apart by the color of the rule on their left:

typeof (abs M) (arr A B) :- pi x\ typeof x A => typeof (M x) B.   % λProlog
(°->list/datum (fresh° (q) (typeof° `(abs ,(ƛ (x) x)) q)))       ; aux Scheme
((arr α α))

The last one, answers, is always the actual output of a run of the Scheme code above it, pasted verbatim, never written by hand. Inline, pi x\ G is λProlog and (∀° (x) g) is Scheme. Answers come in three forms. °->list/datum gives plain data, comparable with equal?. °->list #f gives (aux kanren micro)’s own form, a closed λ-expression whose parameters are the answer’s unbound variables, such as (λ () (ƛ (x) x)). °->pretty, from (aux kanren micro show), gives the αKanren-style view with constraints, such as (α : (= …)). Reified variables print as α, β, γ; a working variable that a constraint keeps prints as _3. Names follow aux: goals end in °, their applicative forms in ª, term constructors carry no suffix (ƛ, @), and internals carry the prefix μkanren-.

Pages of the book. [MN p. n] refers to the printed page nn of Dale Miller and Gopalan Nadathur. Programming with Higher-Order Logic. Cambridge University Press, Cambridge, 2012, the number at the top of the page, which is the PDF page minus 16.

Pitfall (Two page numberings). The comments in the module’s files (its header, its test suites, the prototype’s examples.scm) cite the book as p.N with the PDF page. So p.207 in examples.scm, next to the typeof queries, is [MN p. 191] here.

Notation. A sequent Σ;𝒫⟶G\Sigma; \mathcal{P} \longrightarrow G asks for a proof of goal GG from program 𝒫\mathcal{P} over signature Σ\Sigma. Implication is written ⊃\supset, as in the book, and D⊃GD\supset G is D => G. The logics are fohc and fohh (first-order Horn and hereditary Harrop) and hohc and hohh (their higher-order versions). LλL_\lambda is the pattern fragment, =βη=_{\beta\eta} is λ-convertibility, t[s/x]t[s/x] substitutes ss for xx in tt, and ≐\doteq is an equation to be solved. ℓ(X)\ell(X) and ℓ(c)\ell(c) are the levels of Definition 1.1. Logic variables are upper case (FF, XX, RR), eigenvariables lower case (cc, xx, yy). Rules of proof search are set in small capitals (generic, augment, backchain).

Where the outputs come from. Snippets in Parts I and II, and in Chapter 10, run on (aux kanren micro) alone, with no extension loaded, unless a box says otherwise; some define a small throwaway interpreter first (Section 3.8.3). In Parts I and II “today’s (aux kanren micro)” means (aux kanren micro) alone. Those snippets were first run at commit f53bdcb of the aux-lambdakanren branch; run again on master after the merge, at commit c0ff08c, they print the same, but for a few gensym counters, which the outputs now show as printed there. The outputs of the module, in this chapter and from Chapter 11 on, come from that same merged tree: (aux kanren micro) with its protocol, the show module and (aux kanren lambda). The prototype’s examples.scm, run on it, prints its recorded examples.out byte for byte. Every snippet was run by csi from CHICKEN 6.0.1pre1 (rev 55615603), as installed; the benchmarks were compiled with csc -O2 -d1.The document was typeset with LuaLaTeX, in Libertinus and Euler.

1.6Summary

  • The goal is to bring λProlog’s universal and hypothetical goals, λ-tree syntax and higher-order pattern unification into (aux kanren micro), following Miller and Nadathur’s book (Part I) and the miniKanren literature, Ma and Friedman 2021 first (Part II).
  • The outcome (Part III) is a generic extension protocol in (aux kanren micro) plus the client module (aux kanren lambda), merged into aux in five commits. Three prototypes were compared by three reviews, three adversarial rounds hardened the result, and the merge’s own reviews fixed more defects: 99 λ cases and (aux kanren micro)’s 187 cases, run with and without the module, pass, and the protocol costs 0–2.2% on first-order search (1 ms more on three rows of about 30 ms).
  • The running example is typeof. ∀° gives the body an eigenvariable one level deeper, and ⊃° assumes its type. Backchaining on that hypothesis unifies the types, and the assumption disappears with the answer.
  • Run backwards, the same program needs R c≐cR\,c\doteq c: a pattern, solved by R:=λx. xR:=\lambda x.\, x, while R≐cR\doteq c fails the scope check. Non-patterns wait and are reported as residual equations.
  • Three reading paths: a fast path of about 45 pages before the design and the module, the λProlog path (Part I), and the implementer path.
  • Answers are actual outputs, run on the merged tree; [MN p. n] is a printed page; the comments of the module and of the prototype use PDF pages (printed +16+16).