Chapter 12

The module (aux kanren lambda)

What and why

Chapter 10 took (aux kanren micro) apart and ended, in Section 10.9, with the list of points an extension cannot reach from outside: the state has no free slot, and the unifier, the walkers and the reifier are closed. Chapter 11 opened exactly those points with a small, λ-agnostic protocol of hooks and explained why the proposal is a client module of that protocol rather than a native engine. This chapter is about the client itself: the module (aux kanren lambda), which brings into (aux kanren micro) the three ingredients of Part I,

  • λ-tree syntax (Chapter 6): object-level binders are meta-level abstractions;
  • higher-order pattern unification, LλL_\lambda (Chapter 7), with universe levels in place of the mixed prefix and with non-patterns suspended (“dynamic LλL_\lambda”);
  • universal and hypothetical goals, generic and augment, over hereditary Harrop formulas (Chapter 3).

The chapter is the formal heart of the proposal. It states what the terms are (Section 12.1), what the module keeps in the state (Section 12.2), the unification rules with their side conditions and the termination argument (Section 12.3), the rules for ∀° and ⊃° and why levels make them sound (Section 12.4), how micro’s disequality, absence and type constraints read λ-terms (Section 12.5), how answers are printed (Section 12.6), and, as a reference, the exported API (Section 12.7). The curated book examples are the subject of Chapter 13; the known limits, the costs and the merge are in Chapter 14.

The module is src/aux.kanren.lambda.scm, 1427 lines, 984 of them neither blank nor comment, on master since the commits of Section 14.4. Its suites are src/test/microkanren-lambda.scm (93 cases, 421 assertions) and src/test/microkanren-lambda-limits.scm (6 cases), with the book’s programs in src/test/microkanren-lambda-programs.scm; the prototype it was ported from stays in doc/hol-kanren/prototype/, frozen at f84cf9c. Every Scheme snippet below was run on the merged tree, master at c0ff08c; its output is pasted verbatim under it. The snippets import

(import scheme (chicken base) (chicken pretty-print)
        (chicken condition) (chicken memory representation)
        (aux base) (aux stream) (aux kanren micro) (aux kanren micro show)
        (aux kanren lambda))

Several of them use a probe: a goal that prints part of the state and succeeds. A goal of (aux kanren micro) is a procedure from a state to a stream of states (Definition 10.7), so a probe is three lines; each snippet shows the one it uses.

12.1Terms

12.1.1Four records

First-order structure stays Scheme data, exactly as in (aux kanren micro): pairs, vectors, foreign records and atoms (Definition 10.1). The module adds four record types, defined at the top of the file:

(define-record μkanren-lam hint body)        ; λ.body, locally nameless
(define-record μkanren-app head args)        ; head applied to a list of arguments
(define-record μkanren-eigen name level id)  ; a scoped constant of GENERIC
(define-record μkanren-bvar index)           ; a de Bruijn index, only inside bodies

Definition 12.1 (λ-terms of the module). Extend the terms of (aux kanren micro) (Definition 10.1) with

t  ::=  …  ∣  cℓ  ∣  #i  ∣  λh. t  ∣  t  @  ⟨t1,…,tn⟩ t \;::=\; \dots \;\mid\; c^{\ell} \;\mid\; \#i \;\mid\; \lambda^{h}.\,t \;\mid\; t\;@\;\langle t_1,\dots,t_n\rangle

where cℓc^\ell is an eigenvariable of level ℓ∈ℕ∪{∞}\ell\in\mathbb N\cup\{\infty\} (μkanren-eigen), #i\#i a bound variable with de Bruijn index i≥0i\ge 0 (μkanren-bvar), λh.t\lambda^h.t an abstraction whose binder carries the printing hint hh, a symbol (μkanren-lam), and t @ t¯t\,@\,\bar t an application with n≥1n\ge 1 (μkanren-app). A term is locally closed when every #i\#i in it lies below at least i+1i+1 abstractions. Only locally closed terms are ever bound to variables or stored in constraints.

The representation is locally nameless Arthur Charguéraud. The locally nameless representation. Journal of Automated Reasoning, 49(3):363–408, 2012: bound variables 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, free ones are names (logic variables and eigenvariables). Three design choices follow from it.

  • The hint is only for printing, and it is an interned symbol. The binder’s identity is its position. Two terms built alike are therefore equal?, so λ-terms can be grouped by groupby° and compared by the host.
  • An eigenvariable’s identity is its id, an uninterned symbol, compared with eq?. Its name is a hint and its level is the universe it lives in (Section 12.2). Level ∞\infty (+inf.0) marks the names that the unifier opens when it descends under binders and the placeholders that ƛ uses while building a body.
  • The first 64 bound variables are preallocated in a vector, so the common indices allocate nothing.

The de Bruijn operations (shift, instantiate, close) never walk the substitution: a term bound to a variable is locally closed, so a binding never contributes a loose index. Instantiation shifts the substituted term only when it has loose indices itself, which is decided once per instantiation.

12.1.2The constructors ƛ and @

The user never builds these records by hand. Two constructors give the surface syntax of λ-tree terms:

(define-syntax ƛ
  (syntax-rules ()
    ((_ () body) body)
    ((_ (x y ...) body) (μkanren-abstract 'x (λ (x) (ƛ (y ...) body))))))

; λ.(f p), with the placeholder p closed into #0
(define (μkanren-abstract name f)
  (let1 (p (μkanren-eigen* name +inf.0))
    (μkanren-lam/η name (μkanren-close (f p) p))))

(define (@ f . args) (μkanren-beta f args))   ; β at once on an abstraction

(ƛ (x) body) binds the Scheme variable x to a fresh placeholder eigenvariable while body is evaluated, then closes that placeholder into the index #0. The object binder is thus a Scheme binder: shadowing, lexical scope and quasiquotation all behave as a Scheme programmer expects, which is the point of λ-tree syntax [MN p. 177]. Two invariants are enforced at construction.

  • η-short. μkanren-lam/η builds λx. (h a¯ x)\lambda x.\,(h\,\bar a\,x) as h a¯h\,\bar a when xx is not free in h a¯h\,\bar a. The unifier builds its abstractions the same way. This matters because micro’s own occurs check runs before any hook can see an equation: λx. (F x)=F\lambda x.\,(F\,x) = F holds by η, but in η-long form micro would see FF inside the value it binds FF to and fail; built η-short, the left side is FF and the equation is trivial.
  • β at construction. @ applied to an abstraction β-reduces at once, and nested applications are flattened: (@ (@ f a) b) is (@ f a b).

Example 12.2 (Construction and printing). Every record has a printer that shows its term as data. The raw record of λx. (f x)\lambda x.\,(f\ x) shows the hint x and the index in the body:

(ƛ (x y) (cons x y))
(record->vector (ƛ (x) `(f ,x)))     ; from (chicken memory representation)
(equal? (ƛ (x) `(f ,x)) (ƛ (x) `(f ,x)))
(equal? (ƛ (x) x) (ƛ (y) y))
(μkanren-α=? (ƛ (x) x) (ƛ (y) y))
(@ (ƛ (x) `(g ,x ,x)) 'a)
(ƛ (x) (@ 'g x))
(ƛ (x) `(g ,x))
(@ 'g 'a)
(equal? (@ 'g 'a) '(g a))
(ƛ (a) (ƛ (a) a))
  => (ƛ (x y) (x . y))
  => #(aux.kanren.lambda#μkanren-lam x (f #<aux.kanren.lambda#μkanren-bvar>))
  => #t
  => #f
  => #t
  => (g a a)
  => g
  => (ƛ (x) (g x))
  => (@ g a)
  => #f
  => (ƛ (a a1) a1)

Line by line: nested binders print merged, (ƛ (x y) ...); the body of a μkanren-lam holds an index, not the name; terms built alike are equal?; α-variants with different hints are not equal? but are α-equal; @ reduced the redex; λx. (g x)\lambda x.\,(g\,x) written with @ is the η-redex of gg and was built as g; written with a quasiquoted list it is no η-redex (the list (g x) is data, not an application), so it stays an abstraction; the λ-tree application of a constant prints with @ and is not the list (g a); shadowing is lexical, and the printer renames the inner binder apart (Section 12.6).

12.1.3Three kinds of application

An application is classified by its head after walking it in the current substitution:

Definition 12.3 (Flexible, β-redex, rigid; head normal form). An application h @ t¯h\,@\,\bar t is flexible if hh walks to an unbound logic variable, a β-redex if hh walks to an abstraction, and rigid otherwise (a constant, an eigenvariable, a bound variable). The head normal form hnf(t)\mathrm{hnf}(t) (μkanren-hnorm) walks tt, flattens nested applications, contracts head β-redexes, and contracts an abstraction whose body has become an η-redex through a binding (e.g. λx. F (G x)\lambda x.\,F\,(G\,x) once G:=λz.zG:=\lambda z.z).

Under the LλL_\lambda restriction every contraction hnf performs is a β0\beta_0 renaming (Definition 6.13). On instantiated heads @ gives full β, which is what the book calls dynamic LλL_\lambda [MN p. 225–226].

(μkanren-hnorm (@ (ƛ (x) (@ x 'b)) (ƛ (y) `(g ,y ,y))) μkanren-state-empty)
(°->list #f (fresh° (q F) (=° q (@ F 'a))))
(°->list/datum (fresh° (q F) (=° q (list F (@ F 'a))) (=° F (ƛ (z) `(h ,z)))))
(g b b)
((λ (α) (@ α 'a)))
(((ƛ (z) (h z)) (h a)))

The second answer is a flexible term, printed as (@ α 'a); once FF is bound (third line) the same term is a β-redex and its value is (h a).

12.1.4Scheme lists versus λ-tree application

The object language of the book’s programs is written with Scheme lists, as (aux kanren micro) always did: 𝚊𝚋𝚜 M\mathtt{abs}\ M is `(abs ,M), 𝚊𝚙𝚙 M N\mathtt{app}\ M\ N is `(app ,M ,N), with MM a meta-level abstraction for a binder. The λ-tree application (@ 'g 'a) and the list '(g a) are distinct terms and never unify:

(°->list #f (fresh° (q) (=° (@ 'g 'a) '(g a))))
  => ()

This is deliberate. One of the three prototypes identified the two (a spine notation for lists) and lost commutativity of conjunction: with η, the same pair of goals gave different answers in the two orders. Keeping lists as data and @ as the only application keeps (aux kanren micro)’s first-order unification untouched for lists, and confines the higher-order rules to terms that contain a λ-record.

Pitfall (What is and is not an η-redex). η-contraction applies to λ-tree applications only. (ƛ (x) (@ 'g x)) is g, but (ƛ (x) `(g ,x)) is an abstraction over a two-element list, and stays one. The module is untyped, so it cannot η-expand a term against its type: η-expansion happens only on demand, when one side of an equation is an abstraction (rule η below), as in Miller’s untyped treatment Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, §9.3. A rigid list such as '(g a) therefore equals an abstraction only when the abstraction’s body equals the λ-tree application (@ '(g a) x) of the list to the bound variable (and ƛ already builds such an η-redex as the list itself); never when the body is a list such as `(g a ,x).

12.2The extension’s state

12.2.1The record in X

The protocol gives (aux kanren micro)’s state a slot X that micro copies but never reads (Chapter 11). The module keeps one record in it (aux.kanren.lambda.scm:231–240):

(define-record μkanren-hh depth top L Ln Γ E N W)
(define μkanren-hh0 (make-μkanren-hh 0 0 empty/sbral 0 '() '() '() empty/sbral))
(define (μkanren-hh s) (let1 (x (μkanren-state-X s)) (if (null? x) μkanren-hh0 x)))

X = '(), the value in μkanren-state-empty, reads as “everything empty”, so the initial state of every runner works unchanged.

Definition 12.4 (The λ state). The record ⟨d, top, L, Ln, Γ, E, N, W⟩\langle d,\ \mathit{top},\ L,\ L_n,\ \Gamma,\ E,\ N,\ W\rangle holds:

  • dd (depth)
    the current universe level, raised by ∀° for the extent of its body;

  • top\mathit{top}
    the highest level reached so far in this branch;

  • L, LnL,\,L_n
    the levels of the logic variables: LL is a skew-binary random-access list (aux’s sbral) indexed like the substitution SS, holding the levels of the variables with index <Ln<L_n. The level of variable ii is

    ℓ(i)  =  {0i<0 (a reified variable)L[Ln−1−i]0≤i<Lndi≥Ln \ell(i) \;=\; \begin{cases} 0 & i<0 \text{ (a reified variable)}\\ L[L_n-1-i] & 0\le i<L_n\\ d & i \ge L_n \end{cases}

    so a variable created since LL was last extended has the current depth. LL is padded with dd exactly when the depth changes and whenever the unifier creates a variable of another level; lookup is O(log⁡n)O(\log n);

  • Γ\Gamma
    the assumed clauses: an alist from a relation to its clauses, most recent first, one entry per distinct relation;

  • EE
    the suspended constraints: equations (= u v) outside LλL_\lambda (or bindings whose scope check a non-pattern decides), types (tag tag u) on flexible terms, and absentos (absent d u) whose datum outlived its eigenvariable’s scope;

  • NN
    the disequalities that involve λ-terms or eigenvariables, as (reading u . v). micro’s D never holds one (Section 12.5);

  • WW
    an sbral indexed like SS: for each variable, the ids of the prefixes of D that reach it where micro’s records do not list them, below a compound side or through a binding. It lets the post hook find the prefixes a binding reaches without walking D (Section 12.5).

Levels are the module’s whole account of quantifier order. A logic variable created at depth dd stands for an ∃\exists placed after the first dd universals of its branch; an eigenvariable created by the (d+1)(d{+}1)-th ∀° has level d+1d+1. The binding conditions of Nadathur, Jayaraman and Kwon 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 (Definition A.34 and Definition 9.15) are then stated on levels: a variable of level ℓ\ell may be bound only to a term whose eigenvariables have level ≤ℓ\le\ell, and the variables of level >ℓ>\ell in that term are lowered to ℓ\ell.

12.2.2Copied, never mutated

The record is immutable. Every change builds a new one with μkanren-hh-with, a keyword-argument copy, and installs it with (μkanren-state-with s X: x). Since a state is a value and or° gives each branch the state it was given, two branches can never see each other’s depth, Γ or suspended constraints. What needs care is the end of a scope: ∀° and ⊃° change the record for their body only, and each answer of the body must give the change back. Both do so on every answer state (Section 12.4). The following probe shows depth and levels through two nested ∀°:

(define ((probe label . vars) s)
  (display label) (display ": depth ") (display (μkanren-λ-depth s))
  (display ", levels ") (write (map (λ (v) (μkanren-λ-level v s)) vars))
  (display ", E ") (write (μkanren-λ-delayed s))
  (display ", N ") (write (μkanren-λ-disequalities s)) (newline)
  (✓° s))
(°->list #f
  (fresh° (q)
    (probe "start" q)
    (∀° (x)
      (fresh° (Y)
        (probe "inside ∀x" q Y)
        (∀° (z) (fresh° (W) (probe "inside ∀x∀z" q Y W)))
        (probe "back in ∀x" q Y)
        (=° (@ q x) (@ Y x x))
        (probe "after q x = Y x x" q Y)))
    (probe "after ∀x" q)))
(°->list #f (fresh° (q) (or° (∀° (x) (probe "branch 1" q) (=° q 1))
                              (and° (probe "branch 2" q) (=° q 2)))))
start: depth 0, levels (0), E (), N ()
inside ∀x: depth 1, levels (0 1), E (), N ()
inside ∀x∀z: depth 2, levels (0 1 2), E (), N ()
back in ∀x: depth 1, levels (0 1), E (), N ()
after q x = Y x x: depth 1, levels (0 1), E (), N ()
after ∀x: depth 0, levels (0), E (), N ()
((λ (α) (ƛ (x) (@ α x x x))))
branch 1: depth 1, levels (0), E (), N ()
branch 2: depth 0, levels (0), E (), N ()
((λ () 1) (λ () 2))

Tutorial (Reading the probe). qq is created at depth 0, YY inside ∀° (x) at depth 1, WW at depth 2; after each ∀° the depth is back where it was. Written as a mixed prefix, the goal is ∃q ∀x ∃Y ∀z ∃W\exists q\,\forall x\,\exists Y\,\forall z\,\exists W, and each level is the number of universals to the left of the quantifier: q:0q{:}0, x:1x{:}1, Y:1Y{:}1, z:2z{:}2, W:2W{:}2. The equation q x≐Y x xq\,x \doteq Y\,x\,x is solved inside the scope, and its answer shows the levels at work. qq has level 0 and its argument xx (level 1) is a pattern for it, so the unifier eliminates qq: q:=λx. t′q := \lambda x.\,t' where t′t' is Y x xY\,x\,x with xx turned into the bound variable. But YY has level 1 and qq level 0: qq’s value may not mention a variable that could see xx unless xx is passed explicitly. Y x xY\,x\,x is no pattern (xx is repeated), but both its arguments are qq’s own argument xx, so none of them has to be dropped. YY is therefore lowered and raised at once, Y:=λa b. Y′ a b xY := \lambda a\,b.\,Y'\,a\,b\,x with ℓ(Y′)=0\ell(Y')=0, and q:=λx. Y′ x x xq := \lambda x.\,Y'\,x\,x\,x. The answer (ƛ (x) (@ α x x x)) is that binding; the rules responsible are FR and case (6c) of variable elimination, Definition 12.7. The last two lines show the branches: ∀° raised the depth in branch 1 only.

The module’s hooks keep the protocol invariants E1–E6 of Definition 11.13; in particular, every function of the module that may leave the state unchanged is written to return it eq? (E1).

12.3Unification

12.3.1Where the rules run

(aux kanren micro)’s unifier μkanren-state-unify still does all first-order work: variables, pairs, vectors, foreign records and atoms. Through the protocol’s unify hook it hands any pair with a walked λ-record on one side, neither side a variable, to μkanren-λ-unify, which applies the rules of Rules 12.6. The rules call back into μkanren-state-unify for subterms, so the two unifiers interleave freely. After =° has made its bindings, the post hook μkanren-λ-post runs before micro verifies D, A and T:

  1. settle: the scope check Check of every new binding, then the wake-up of EE, in rounds while a round binds (Section 12.3.7);
  2. migrate: the prefixes of D that a new binding has brought a λ-term or an eigenvariable into move to N, found from the bound variables, and the types of A on variables just bound to λ-terms go to the tag hook when micro hands them on (Section 12.5);
  3. verify N: every λ-disequality is tried again.

12.3.2Notation

Write ℓ(X)\ell(X) for the level of a logic variable and ℓ(c)\ell(c) for that of an eigenvariable; the names the unifier opens under binders have ℓ(c)=∞\ell(c)=\infty. A name is an eigenvariable or, inside variable elimination, a bound variable of the term being walked.

Definition 12.5 (Pattern, read off levels). A list of arguments a¯=a1…an\bar a = a_1\dots a_n is a pattern for a variable FF if every hnf(ai)\mathrm{hnf}(a_i) is an eigenvariable, the aia_i are pairwise distinct, and ℓ(ai)>ℓ(F)\ell(a_i) > \ell(F) for every ii (μkanren-pattern?). A flexible term F a¯F\,\bar a is a pattern when a¯\bar a is a pattern for FF.

For example, inside (∀° (x y) ...) with ℓ(F)=0\ell(F)=0, ℓ(x)=1\ell(x)=1, ℓ(y)=2\ell(y)=2, the lists ⟨x,y⟩\langle x,y\rangle and ⟨y⟩\langle y\rangle are patterns for FF, while ⟨x,x⟩\langle x,x\rangle (repeated), ⟨𝚊⟩\langle \mathtt{a}\rangle (a constant) and ⟨Y⟩\langle Y\rangle (a variable) are not. The same definition, with a bound variable of the term being walked counted as an eigenvariable of level ∞\infty, is used inside variable elimination (case (6b) below). This is Miller’s LλL_\lambda condition (Definition 7.15): the arguments are distinct variables “quantified inside the scope of FF”. With a prefix, “inside the scope” means “to the right of FF”; with levels it means “of a level above FF‘s”, which is how Nadathur and Linnell read the condition without a prefix 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, §4. An eigenvariable FF could already see is not a pattern argument: in ∀x ∃F. F x=…\forall x\,\exists F.\ F\,x = \dots the term F xF\,x is no pattern, since FF may use xx directly and the equation has several incomparable solutions.

Throughout, λ.b\lambda.b is an abstraction with body bb, b[c/0]b[c/0] its body with #0 instantiated to cc, h u¯h\,\bar u an application, and F,G,H,X,YF,G,H,X,Y logic variables. Both sides are put in hnf before a rule is chosen.

12.3.3The rules

The rules of Rules 12.6 are transformations, read top-down as in Rules A.22 and Rules A.30: the equation above the line is replaced by the equations, bindings or suspension below it. They are the rules of Rules A.30 with the prefix erased into levels; Section 7.6 gives the same rules under other names, recalled in parentheses. ξ is abs (Abs), η is eta (Eta), Rigid is rr-dec and rr-clash (Dec and Clash), FF-same is ff-same (the same-head case of FlexFlex), Delay is delay. FR covers elim (Elim) with its pruning, occurs and scope, and also ff-diff (FlexFlex with distinct heads): instead of binding both heads to a new HH, it eliminates FF and prunes GG only where needed, which gives the same mgu up to the name of HH (Example 12.13). Var and Occurs are elim and occurs for a variable with no arguments, a case that micro’s first-order unifier meets first, and they are where the eager scope check, Check, enters; FF-one orients a flexible–flexible pair as swap orients a flexible–rigid one.

Rules 12.6 (Unification rules of μkanren-λ-unify).

X≐tX:=t  (micro, occurs check)Check(X:=t)  (Var)λ.b≐λ.b′b[c/0]≐b′[c/0]Check its bindings  (ξ) \dfrac{X \doteq t}{X := t\ \ \text{(micro, occurs check)}\quad\textbf{Check}(X := t)}\;(\text{Var}) \qquad\qquad \dfrac{\lambda.b \doteq \lambda.b'}{b[c/0] \doteq b'[c/0]\quad \textbf{Check}\ \text{its bindings}}\;(\xi) λ.b≐tb[c/0]≐t  @  cCheck its bindings  (η) \dfrac{\lambda.b \doteq t}{b[c/0] \doteq t\;@\;c\quad \textbf{Check}\ \text{its bindings}}\;(\eta) h u¯≐h′ v¯h≐h′u¯≐v¯  (Rigid)F a¯≐F b¯F:=λx¯. H ⟨xi∣ai=bi⟩  (FF-same) \dfrac{h\,\bar u \doteq h'\,\bar v}{h \doteq h' \quad \bar u \doteq \bar v}\;(\text{Rigid}) \qquad\qquad \dfrac{F\,\bar a \doteq F\,\bar b}{F := \lambda\bar x.\,H\,\langle x_i \mid a_i = b_i\rangle}\;(\text{FF-same}) F a¯≐tF:=λx¯. t′t′=Elim(ℓ(F),F,a¯,t)  (FR)F a¯≐G b¯G b¯≐F a¯  by FR  (FF-one) \dfrac{F\,\bar a \doteq t}{F := \lambda\bar x.\,t'\qquad t' = \mathrm{Elim}(\ell(F),F,\bar a,t)}\;(\text{FR}) \qquad\qquad \dfrac{F\,\bar a \doteq G\,\bar b}{G\,\bar b \doteq F\,\bar a\ \ \text{by FR}}\;(\text{FF-one}) u≐vE:=E∪{λL. u≐λL. v}  (Delay) \dfrac{u \doteq v}{E := E \cup \{\lambda L.\,u \doteq \lambda L.\,v\}}\;(\text{Delay}) X≐tX occurs in t⊤ if hnf(t)=X; else X:=Elim(ℓ(X),X,⟨⟩,t)  (Occurs) \dfrac{X \doteq t \qquad X \text{ occurs in } t}{\top\ \text{if } \mathrm{hnf}(t)=X;\ \text{else } X := \mathrm{Elim}(\ell(X),X,\langle\rangle,t)}\;(\text{Occurs})

The unification rules of μkanren-λ-unify, applied after hnf of both sides; above the line the equation, below what is done with it. In ξ and η, cc is a new eigenvariable of level ∞\infty. In FF-same and FR, x¯\bar x are new binders, one per argument aia_i, and Elim replaces each aia_i in tt by the bound variable of xix_i. Variable elimination, Elim, is Definition 12.7; Check is Definition 12.8. Each rule may also answer ⊥\bot or suspend, as its side conditions say.

The side conditions, in the order the code tests them (μkanren-λ-unify and the functions it calls):

  • Var
    One side is an unbound variable. micro binds it, with its occurs check; the scope check Check runs afterwards, in the post hook. Variable–variable pairs are micro’s as well.
  • ξ
    Both sides are abstractions. cc is a new eigenvariable of level ∞\infty, so no variable can capture it except through its own pattern arguments. Because cc is local to this very unification, the bindings made under it are checked at once (μkanren-scoped), not at the end of =°.
  • η
    One side is an abstraction and the other is not. The other side is applied to the new cc. This is the only η-expansion the module performs.
  • Rigid
    Both sides are rigid applications with the same number of arguments: heads and argument lists are unified by micro. Two eigenvariables unify iff they are the same (eq? ids), two bound variables iff their indices agree. Any other pair with a λ-term on one side fails: different rigid heads, different arities (untyped), a λ-record against a pair or an atom.
  • FF-same
    Same head on both sides, both argument lists patterns. Equal lists: success with no binding. Different lengths: ⊥\bot. Otherwise FF keeps the positions where the arguments agree, with a new HH of level ℓ(F)\ell(F) [MN p. 222]. If b¯\bar b is no pattern, Delay.
  • FR
    One side is a pattern F a¯F\,\bar a; the other side tt is rigid, or flexible with another head (“FF-diff”: variable elimination prunes GG as needed [MN p. 222]). If Elim fails the rule fails; if Elim suspends, Delay. The binding λx¯. t′\lambda\bar x.\,t' is built η-short, its binders named after the eigenvariables a¯\bar a.
  • FF-one
    Two flexible terms, only the right one a pattern: FR on GG.
  • Delay
    No side is a usable pattern. The equation is pushed on EE, closed over the names LL that the unifier had opened so far (λL.u≐λL.v\lambda L.u \doteq \lambda L.v, so no ∞\infty-level name escapes the unification that created it), unless uu and vv are already α-equal, in which case it is dropped.
  • Occurs
    Not a rule of μkanren-λ-unify but of the protocol’s occurs hook: micro’s occurs check failed on X:=tX := t and tt holds a λ-term. If hnf(t)\mathrm{hnf}(t) is XX itself the equation holds (q=F qq = F\,q with F:=λz.zF := \lambda z.z); otherwise XX is eliminated with no arguments, which may fail, succeed, or suspend (F=λx. G (F x)F = \lambda x.\,G\,(F\,x) holds with G:=λz.zG := \lambda z.z). A first-order cycle, X=f XX = f\,X, holds no λ-term and fails in micro as before.

12.3.4Variable elimination

FR is the book’s variable elimination [MN p. 223] (Definition 7.21) with levels in place of the prefix. It walks the right-hand side once and builds the body of FF’s binding, pruning, lowering and raising the variables it meets on the way. Compared with Definition 7.21, three things are added: lowering with delayed raising (case (4)), where Definition 7.21 assumes a prefix already raised into ∀∃\forall\exists form (the eager raising of Example 7.31); the treatment of non-patterns inside the right-hand side (cases (6c) and (7)), which the book never meets since it stays in LλL_\lambda; and a finer occurs test (case (6a)), since an occurrence of FF is fatal only when no instance can make it smaller. The contexts below exist to decide these three cases.

Definition 12.7 (Variable elimination). Elim(ℓ,F,a¯,t)\mathrm{Elim}(\ell, F, \bar a, t), with a¯\bar a a pattern for FF and ℓ=ℓ(F)\ell=\ell(F) (or FF absent and a¯\bar a empty, for Check), walks hnf(t)\mathrm{hnf}(t) at a local depth kk (the binders crossed inside tt) and in a context: strict (top: below binders only; rigid: below a first rigid constructor that is an application headed by a bound variable or by an aia_i; firm: below a first rigid constructor that is a constant, an eigenvariable not in a¯\bar a, a pair, a vector or a record, a root no instance of FF can project onto) or soft (inside an argument of a flexible term that is no pattern, or weak: below a flexible head inside such an argument). It answers a term t′t' with new bindings, ⊥\bot, or suspend. By cases on the walked subterm:

  1. Eigenvariable cc: if c=aic = a_i, the bound variable of aia_i; else if ℓ(c)≤ℓ\ell(c)\le\ell, cc itself; else ⊥\bot (scope failure, Example 7.25). In a weak context the last case is trouble, not ⊥\bot.
  2. Bound variable: itself.
  3. Abstraction λ.b\lambda.b: λ.Elim(b)\lambda.\mathrm{Elim}(b) at depth k+1k+1.
  4. Unbound variable YY: if Y=FY=F, ⊥\bot when a¯\bar a is empty (the first-order occurs check) and suspend otherwise; if ℓ(Y)≤ℓ\ell(Y)\le\ell, YY; in a soft context, trouble; otherwise lower and raise: Y:=Y′ a¯YY := Y'\,\bar a_Y with ℓ(Y′)=ℓ\ell(Y')=\ell and a¯Y=⟨ai∣ℓ(ai)≤ℓ(Y)⟩\bar a_Y = \langle a_i \mid \ell(a_i)\le\ell(Y)\rangle, the arguments of FF that YY could see; the result is Y′Y' applied to their bound variables (“delayed raising”, Example 7.31).
  5. Rigid application, pair, vector, record: homomorphic. A top context becomes rigid below an application whose head is a bound variable or in a¯\bar a, and firm below any other head, a pair, a vector or a record; any other context is passed on unchanged.
  6. Flexible G b¯G\,\bar b in a strict context:
    • (a) if G=FG=F: ⊥\bot (occurs failure) when the context is not top, no bjb_j is functional (an abstraction, a variable or a flexible term, which may become an abstraction), and either the context is firm or ∣b¯∣=∣a¯∣+ktop|\bar b| = |\bar a| + k_{\mathrm{top}}, with ktopk_{\mathrm{top}} the binders on top of tt; otherwise suspend;
    • (b) if b¯\bar b is a pattern for GG (each bjb_j a local bound variable or an eigenvariable of level >ℓ(G)>\ell(G), pairwise distinct): keep bjb_j iff it is local, or in a¯\bar a, or ℓ(bj)≤ℓ\ell(b_j)\le\ell; let extra=⟨ai∣ℓ(ai)≤ℓ(G)⟩\mathit{extra}=\langle a_i \mid \ell(a_i)\le\ell(G)\rangle if ℓ(G)>ℓ\ell(G)>\ell, else empty. If every bjb_j is kept, extra\mathit{extra} is empty and ℓ(G)≤ℓ\ell(G)\le\ell, G b¯G\,\bar b is unchanged. Otherwise prune: G:=λy¯. G′ y¯∣keep extraG := \lambda\bar y.\,G'\,\bar y|_{\mathit{keep}}\,\mathit{extra} with ℓ(G′)=min⁡(ℓ,ℓ(G))\ell(G')=\min(\ell,\ell(G)), and the result is G′G' applied to the images of the kept arguments and of extra\mathit{extra} (Example 7.23);
    • (c) if b¯\bar b is no pattern: each bjb_j is walked on its own in a soft context, binding nothing; it is kept, as the walk rebuilt it (its aia_i turned into bound variables), if the walk succeeds, dropped if it fails by scope on a rigid path (it holds a forbidden eigenvariable that every instance keeps), and any other trouble suspends the whole equation. Then, if nothing was dropped and GG needs no lowering, G b¯G\,\bar b stays as it is; otherwise, if some bjb_j is functional, suspend; else prune and lower as in (b).
  7. Flexible G b¯G\,\bar b in a soft context: G=FG=F or ℓ(G)>ℓ\ell(G)>\ell is trouble; otherwise the arguments are walked in a weak context and kept as they are. Inside an argument, the application of a variable bound inside that argument is treated as flexible too.

Inside an argument of a non-pattern, case (6c) reinterprets every failure: a scope failure of case (1) in a soft, non-weak context drops the argument, and any other ⊥\bot or trouble suspends the equation.

Tutorial (Reading the contexts). The context answers one question about the subterm being walked: will every instance of the right-hand side still contain it? At top and below rigid constructors (rigid, firm) the answer is yes, because no substitution can remove a rigid constructor; so a forbidden eigenvariable there is a definite failure, and a variable there can be lowered or pruned without losing solutions. Inside an argument of a non-pattern G b¯G\,\bar b the answer is “not necessarily”, since GG may become a function that ignores that argument; so nothing is bound there and doubts turn into a suspension. firm and rigid differ only in the occurs test (6a): below a constant, an eigenvariable outside a¯\bar a or a pair, FF’s instance cannot be a projection, so an inner F b¯F\,\bar b with rigid arguments is fatal whatever their number; below a bound variable or an aia_i at the head, the number matters. The next two tutorials give the reasons in detail.

Tutorial (Strict and non-strict occurrences). Pruning removes an argument from a variable; lowering makes a variable forget the eigenvariables it could see. Both are sound only on strict occurrences, those not inside an argument of a flexible term that is no pattern (Dowek, Hardin, Kirchner and Pfenning 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). The reason is that the flexible head GG may later turn out to drop that argument. Take ∃q ∃G ∀y ∃Y. q=G Y∧Y=y∧G=λa. k\exists q\,\exists G\,\forall y\,\exists Y.\ q = G\,Y \wedge Y = y \wedge G = \lambda a.\,k: it has the solution q=kq=k. If elimination of qq lowered YY inside the argument of G YG\,Y, the later Y=yY=y would fail by scope and the answer would be lost in that goal order, which breaks the commutativity of conjunction. So nothing is bound inside such an argument: a variable to lower (case (4)) or a flexible term to prune (case (7)) is trouble there, and trouble suspends the equation. The exception of case (6c) is the one pruning that is strict: an argument that holds, on a rigid path, an eigenvariable that FF may not see is held by every instance of that argument, so GG must drop it. This makes ∃q ∃F ∀x. q=F x x\exists q\,\exists F\,\forall x.\ q = F\,x\,x solvable as F:=λa b. F′F := \lambda a\,b.\,F', q:=F′q := F'. Even that pruning waits when an argument is, or may become, an abstraction: GG could apply it to another argument and drop that one (Section 12.3.8 shows ∃q ∀x ∃G. q=G (λw. k)∧G=λy. y x\exists q\,\forall x\,\exists G.\ q = G\,(\lambda w.\,k)\wedge G = \lambda y.\,y\,x, solved in both orders).

Tutorial (When an occurrence of F is fatal). Case (6a) is Nipkow’s size argument 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: F b¯F\,\bar b inside the body of F a¯F\,\bar a makes the equation unsolvable only if no instance of F b¯F\,\bar b can be smaller than the instance of F a¯F\,\bar a. That holds when the bjb_j are rigid (no substitution makes them reduce) and are as many as a¯\bar a plus the binders on top (F a¯=λy¯. t′F\,\bar a = \lambda\bar y.\,t' is F a¯ y¯=t′F\,\bar a\,\bar y = t' by η), as in F=λx. g (F x)F = \lambda x.\,g\,(F\,x) and Example 7.24. The count does not matter when the root of the body is a constant, an eigenvariable not in a¯\bar a or a pair (context firm): no instance λx¯.M\lambda\bar x.M of FF can then be a projection, so MM has that root and F b¯F\,\bar b sits strictly inside it. So the η-short F=λx y. g (F y)F = \lambda x\,y.\,g\,(F\,y) fails as Miller and Nipkow fail it. Otherwise the instance may shrink and the equation is outside LλL_\lambda: it is suspended. For instance ∀x. F x=x (F (λz.z))\forall x.\ F\,x = x\,(F\,(\lambda z.z)) holds with F:=λa. a cF := \lambda a.\,a\,c, and ∀x ∀y. F x y=x (F y)\forall x\,\forall y.\ F\,x\,y = x\,(F\,y) holds with F:=λw.wF := \lambda w.w.

12.3.5The eager scope check

Definition 12.8 (Check). For a binding X:=tX := t that micro has just made, Check(X:=t)\textbf{Check}(X:=t) is Elim(ℓ(X),−,⟨⟩,t)\mathrm{Elim}(\ell(X), -, \langle\rangle, t) with no head to eliminate (μkanren-enforce). If it answers ⊥\bot, =° fails. If it suspends, the binding is taken back: μkanren-state-forget unbinds XX and the equation X≐tX \doteq t is pushed on EE. Otherwise its own bindings (lowerings, prunings) are kept.

Check is NJK’s binding rule with its lowering (Definition A.34): “tt contains no constant with tag >i>i; change to ii the tags of the variables in tt whose tag is >i>i” 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, p. 16, extended from variables to flexible terms by pruning. Taking a binding back is what Teyjus does with a binding whose check depends on a non-pattern. Its effect is an invariant:

Proposition 12.9 (No captured eigenvariable). After every =°, no binding X:=tX := t in the substitution has an eigenvariable of level >ℓ(X)>\ell(X) in the value of tt.

Argument. Every binding made by micro goes through Check unless the fast paths of Section 12.3.6 prove it unnecessary; Check either fails, or rewrites the variables of tt so that it holds, or unbinds XX. The bindings that Check itself makes are lowerings and prunings, which by construction respect the levels. The remaining gap is host code (project° and set!), discussed in Chapter 14. □

12.3.6Fast paths

Check on every binding would be costly on first-order search, so three cheap tests come first.

  • No ∀° yet. While no ∀° has run, the depth is 0 and LL is empty (μkanren-levels? is false): every level is 0, no check can fail, none runs.
  • Plain terms. μkanren-plain? is an allocation-free walk, like micro’s occurs check. It accepts tt when tt holds no eigenvariable or variable of a level above ℓ(X)\ell(X) and no application with a variable or abstraction head (which Elim might prune, lower or reduce). Only otherwise does Elim run.
  • Top-level variables. A variable of level top\mathit{top}, the highest level reached, can see every eigenvariable and every variable there is, so its bindings are skipped. The bindings made under ξ or η are checked anyway, by μkanren-scoped.

The protocol’s atom? hook belongs here as well: it tells micro’s occurs check that an eigenvariable or a bound variable holds no variable, so micro does not rebuild it as a slot list. On the type inference of the Church numeral 400 these steps took the prototype from 463 ms to 330 ms (plain?), 311 ms (the top skip) and 254 ms (atom?); the merged tree takes 210 ms (Section 14.3.5).

Pitfall (The first ∀° switches the check on for good). The first fast path is about the whole branch, not the current scope: once a ∀° has run, levels exist and every binding below top is checked, even after the ∀° has exited. First-order search that follows a ∀° pays for it, measured on the merged tree at +125%+125\% on append° backwards and +122%+122\% on open append°. Skipping the check at depth 0 would be unsound against host escapes; the fix planned is to spare the scope check where micro spares its occurs check (Section 14.5.1).

12.3.7Wake-up and termination

When =° binds something and EE is not empty, μkanren-settle retries every suspended item, oldest first (μkanren-wake). An item is retried by its kind:

  • an equation u≐vu\doteq v: if one side is now an unbound variable XX and the other no variable, XX is bound only once its check passes (μkanren-retry/bind); otherwise the equation is unified again, which may solve it, fail, or suspend it again;
  • a type on a flexible term: decided if the head is now known, else suspended again;
  • an absento: decided, kept, or dropped when levels entail it (Section 12.5).

The new bindings of a round are checked like those of =°, and rounds repeat while a round binds. A constraint still undecided is suspended again without binding anything.

Proposition 12.10 (Wake-up terminates). Suppose every hnf computed during the wake-up terminates. Then the loop of μkanren-settle terminates.

Argument (a sketch, not a mechanised proof). A round that binds nothing ends the loop, so it suffices that only finitely many rounds bind. A round that binds does so for good: the only binding ever taken back is the one that Check has just examined, and a retried X≐tX \doteq t binds XX only after its check passed, so the retry does not bind and unbind the same variable forever. The variables a round may create come from lowering (case (4)), whose new variable has a strictly smaller level than the one it replaces, and from pruning (cases (6b) and (6c)), whose new variable either has a strictly smaller level (when GG is lowered, possibly with extra arguments) or the same level and strictly fewer arguments (FF-same likewise creates HH at the level of FF with fewer arguments). So every new variable replaces exactly one variable that is bound for good, and is below it in the lexicographic order on (level, number of arguments), which is well founded. A chain of replacements (a variable, the one that replaces it, the one that replaces that, …) is therefore finite; with finitely many variables at the start, finitely many variables are ever created, each is bound at most once, and only finitely many rounds can bind. This is the decreasing measure the design relies on. One point a full proof would have to settle: the number of arguments is that of the occurrence being pruned, which an untyped term does not fix once and for all. □

The hypothesis on hnf is not a formality: @ gives full β, and on untyped meta-terms full β may diverge (Chapter 14). On pattern problems no such reduction happens (every contraction is a β0\beta_0 renaming), and the rules are Miller’s and Nipkow’s algorithm with the prefix erased into levels: it terminates, fails only when there is no unifier, and otherwise computes a most general one Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, Thm 7.1, Prop. 7.3, 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, Thm 2. The suite checks the book’s mgus verbatim: U=λx y. g (V′ y)U = \lambda x\,y.\,g\,(V'\,y) and V=λy w. V′ yV = \lambda y\,w.\,V'\,y for Example 7.23, U=λx. f (V′ x)U = \lambda x.\,f\,(V'\,x) for Example 7.31, and G,H:=λw. TG, H := \lambda w.\,T for λx λy. G x=λx λy. H y\lambda x\,\lambda y.\,G\,x = \lambda x\,\lambda y.\,H\,y (Example 7.2).

Pitfall (Suspended is not solved). Non-patterns are suspended, never enumerated: there is no Huet search [MN p. 213]. An answer may therefore be conditional on residual equations that are jointly unsatisfiable. F a=bF\,a = b and F a=cF\,a = c (aa a constant, so no pattern) are both suspended, and the answer is printed with the two residuals; only a binding of FF reveals the conflict:

(°->list #f (fresh° (q F) (=° q F) (=° (@ F 'a) 'b) (=° (@ F 'a) 'c)))
(°->list/datum (fresh° (q F) (=° q F) (=° (@ F 'a) 'b) (=° (@ F 'a) 'c)
                        (=° F (ƛ (z) 'b))))
((λ (α) (assert (≐ (@ α 'a) 'b)) (assert (≐ (@ α 'a) 'c)) α))
()

This is floundering reported, not detected. The residuals are the honest output: they say exactly which equations the search did not decide.

12.3.8Worked traces

Each trace below poses a problem, follows the rules, and ends with the module’s actual output. The probe used here prints the depth, the levels of the given variables and EE:

(define ((probe label . vars) s)
  (display label) (display ": depth ") (display (μkanren-λ-depth s))
  (display ", levels ") (write (map (λ (v) (μkanren-λ-level v s)) vars))
  (display ", E ") (write (μkanren-λ-delayed s)) (newline)
  (✓° s))

Example 12.11 (Warm-up: flexible–rigid, and ξ). Two equations that touch no pruning or lowering: ∃q ∀x ∀y. q x y=g y x\exists q\,\forall x\,\forall y.\ q\,x\,y = g\,y\,x, and ∃q. λx. (g x)=λy. (g (q y))\exists q.\ \lambda x.\,(g\ x) = \lambda y.\,(g\ (q\,y)), where both (g … )(g\ \dots) are Scheme lists.

(°->list/datum (fresh° (q) (∀° (x y) (=° (@ q x y) `(g ,y ,x)))))
(°->list/datum (fresh° (q) (=° (ƛ (x) `(g ,x)) (ƛ (y) `(g ,(@ q y))))))
((ƛ (x y) (g y x)))
((ƛ (x) x))

Trace of the first. ℓ(q)=0\ell(q)=0, ℓ(x)=1\ell(x)=1, ℓ(y)=2\ell(y)=2. The left side is flexible and ⟨x,y⟩\langle x,y\rangle is a pattern for qq; the right side is the list (g y x), rigid: FR. Elim walks the list in context firm: g is an atom and stays; yy is a2a_2 and becomes the bound variable of the second binder; xx is a1a_1 and becomes that of the first (case (1)). Nothing was bound on the way, and q:=λx y. (g y x)q := \lambda x\,y.\,(g\ y\ x), the binders named after the eigenvariables.

Trace of the second. Both sides are abstractions: ξ opens them with one new eigenvariable cc of level ∞\infty (hint x), leaving (g c) ≐\doteq (g (@ q c)). These are lists, so micro decomposes them and hands c≐q cc \doteq q\,c back to the hook. ⟨c⟩\langle c\rangle is a pattern for qq (∞>0\infty > 0), and Elim turns cc into the bound variable: q:=λx. xq := \lambda x.\,x, a projection. The binding was made under ξ, so μkanren-scoped checks it at once; it holds no eigenvariable and passes.

Example 12.12 (Pruning: problem 8.H [MN p. 223–224]). The problem (Example 7.23) is

∃U ∃V ∀w ∀x ∀y. f (U x y)=f (g (V y w)). \exists U\,\exists V\,\forall w\,\forall x\,\forall y.\ f\,(U\,x\,y) = f\,(g\,(V\,y\,w)).
(°->list/datum (fresh° (q u v) (=° q (list u v))
  (∀° (w x y) (probe "before" u v)
              (=° `(f ,(@ u x y)) `(f (g ,(@ v y w))))
              (probe "after" u v))))
before: depth 3, levels (0 0), E ()
after: depth 3, levels (0 0), E ()
(((ƛ (x y) (g (@ α y))) (ƛ (y w) (@ α y))))

Trace. UU, VV have level 0 and w,x,yw,x,y levels 1, 2, 3. Both sides are lists, so micro decomposes them: f against f, then U x y≐g (V y w)U\,x\,y \doteq g\,(V\,y\,w) with a λ-record on the left, handed to the hook. The left side is a pattern (xx, yy distinct, levels 2,3>02,3>0) and the right is rigid: FR, Elim(0,U,⟨x,y⟩,g (V y w))\mathrm{Elim}(0, U, \langle x,y\rangle, g\,(V\,y\,w)). The root is the list (g ...): case (5), context firm. Inside, V y wV\,y\,w is flexible with a pattern for VV (levels 3,1>03,1>0): case (6b). Keep yy (it is in a¯\bar a, it becomes the bound variable of yy); drop ww (not local, not in a¯\bar a, and ℓ(w)=1>0\ell(w)=1>0); extra\mathit{extra} is empty since ℓ(V)=0\ell(V)=0 is not above ℓ=0\ell=0. Something was dropped, so prune: V:=λy w. V′ yV := \lambda y\,w.\,V'\,y, ℓ(V′)=0\ell(V')=0, and the body of UU is g (V′ y)g\,(V'\,y). Finally U:=λx y. g (V′ y)U := \lambda x\,y.\,g\,(V'\,y). Both are the book’s mgu, with α for V′V'. The binders of VV are named after the eigenvariables yy, ww it was applied to.

Example 12.13 (Flexible–flexible). Different heads, ∀x ∀y. F x y=G y x\forall x\,\forall y.\ F\,x\,y = G\,y\,x, and the same head, ∀x ∀y. F x y=F y x\forall x\,\forall y.\ F\,x\,y = F\,y\,x:

(°->list #f (fresh° (q f g) (=° q (list f g)) (∀° (x y) (=° (@ f x y) (@ g y x)))))
(°->list #f (fresh° (q) (∀° (x y) (=° (@ q x y) (@ q y x)))))
((λ (α) (cons (ƛ (x y) (@ α y x)) (cons α '()))))
((λ (α) (ƛ (x y) α)))

Trace. In the first, both sides are patterns with different heads: FR on FF. In Elim, G y xG\,y\,x is case (6b) with both arguments in a¯\bar a, kept; ℓ(G)=0\ell(G)=0 is not above ℓ(F)=0\ell(F)=0, so nothing is pruned or lowered and GG stays unbound: F:=λx y. G y xF := \lambda x\,y.\,G\,y\,x. That is the book’s mgu for different heads [MN p. 222] with the common variables listed as y,xy,x: F:=λx λy. H y xF := \lambda x\,\lambda y.\,H\,y\,x and G:=λy λx. H y xG := \lambda y\,\lambda x.\,H\,y\,x, which is HH by η, up to the name of HH. In the second, FF-same: the positions where x yx\,y and y xy\,x agree are none, so F:=λx y. HF := \lambda x\,y.\,H with HH new.

Example 12.14 (A non-pattern, suspended and woken). ∃F ∀x. F (g x)=h (g x)\exists F\,\forall x.\ F\,(g\,x) = h\,(g\,x) is not in LλL_\lambda: the argument g xg\,x is not an eigenvariable. It has two solutions, F:=λz. h zF := \lambda z.\,h\,z and F:=λz. h (g x)F := \lambda z.\,h\,(g\,x), but the second is illegal here because FF is quantified outside xx. The module neither guesses nor fails:

(°->list #f (fresh° (q) (∀° (x) (=° (@ q `(g ,x)) `(h (g ,x))) (probe "inside" q))
                        (probe "after ∀" q)))
(°->list/datum (fresh° (q) (∀° (x) (=° (@ q `(g ,x)) `(h (g ,x))))
                           (probe "before F :=" q)
                           (=° q (ƛ (z) `(h ,z)))
                           (probe "after F :=" q)))
(°->list/datum (fresh° (q) (∀° (x) (=° (@ q `(g ,x)) `(h (g ,x))))
                           (=° q (ƛ (z) 'k))))
(°->list/datum (fresh° (q) (=° q (ƛ (z) `(h ,z)))
                           (∀° (x) (=° (@ q `(g ,x)) `(h (g ,x))))))
inside: depth 1, levels (0), E ((= (@ _0 (g (eigen x))) (h (g (eigen x)))))
after ∀: depth 0, levels (0), E ((= (ƛ (x) (@ _0 (g x))) (ƛ (x) (h (g x)))))
((λ (α)
    (assert
      (≐ (ƛ (x) (@ α (cons 'g (cons x '()))))
         (ƛ (x) (cons 'h (cons (cons 'g (cons x '())) '())))))
    α))
before F :=: depth 0, levels (0), E ((= (ƛ (x) (@ _0 (g x))) (ƛ (x) (h (g x)))))
after F :=: depth 0, levels (0), E ()
((ƛ (z) (h z)))
()
((ƛ (z) (h z)))

Trace. Inside the scope the left side is flexible but no pattern and the right is rigid: Delay, and EE holds the equation, with the eigenvariable xx in it. At the exit of ∀° (x) the equation mentions xx, so it is discharged (Section 12.4.2): no variable in it has a level ≥ℓ(x)=1\ge\ell(x)=1, so nothing is raised, and the equation is closed into λx. F (g x)≐λx. h (g x)\lambda x.\,F\,(g\,x) \doteq \lambda x.\,h\,(g\,x), equivalent by ξ. It is retried at once, opens xx again as an ∞\infty-level name, is still no pattern, and is suspended again. The run ends with it, and the answer carries it as a residual (assert (≐ ...)). In the second run the binding F:=λz. h zF := \lambda z.\,h\,z wakes it: ξ, then β turns the left side into h (g c)h\,(g\,c), which equals the right side, and EE is empty. In the third run F:=λz. kF := \lambda z.\,k makes the retry compare kk with h (g c)h\,(g\,c): a clash, so =° fails and there is no answer. In the fourth run the binding comes first and the equation is a plain β-redex, solved with no suspension. The answer is the same in both goal orders.

Example 12.15 (A binding taken back). ∃q ∃G ∃H ∀y. q=G (H y)\exists q\,\exists G\,\exists H\,\forall y.\ q = G\,(H\,y). micro binds q:=G (H y)q := G\,(H\,y) at once, as Var. Check at level ℓ(q)=0\ell(q)=0 then meets G (H y)G\,(H\,y), a flexible term whose argument H yH\,y is no eigenvariable: case (6c), walking H yH\,y in a soft context. There yy (level 1, not allowed for a level-0 variable) sits below the flexible head HH, a weak context: trouble, not ⊥\bot, since HH may drop yy, and GG may drop all of H yH\,y. So the check suspends, the binding is taken back, and q≐G (H y)q \doteq G\,(H\,y) waits in EE:

(°->list #f (fresh° (q G H) (∀° (y) (=° q (@ G (@ H y))) (probe "inside" q G H))))
(°->list/datum (fresh° (q G H) (∀° (y) (=° q (@ G (@ H y)))) (=° G (ƛ (a) 'k))))
inside: depth 1, levels (0 0 0), E ((= _0 (@ _1 (@ _2 (eigen y)))))
((λ (α β γ) (assert (≐ (ƛ (y) α) (ƛ (y) (@ β (@ γ y))))) α))
(k)

At the exit of the scope the equation is closed over yy and reported, qq unbound, which is all one can say. With G:=λa. kG := \lambda a.\,k the retry binds q:=kq := k, a plain term, and the residual is gone. The same happens in every order of the goals.

Example 12.16 (Occurs and scope failures, and a soft occurrence).

(°->list #f (fresh° (q) (=° q `(f ,q))))                              ; X = f X
(°->list #f (fresh° (q) (∀° (w x y) (=° (@ q x y) `(g ,(@ q y w))))))  ; 8.I
(°->list #f (fresh° (q) (∀° (w x y) (=° (@ q x y) `(g ,w)))))          ; 8.J
(°->list #f (fresh° (F) (=° F (ƛ (x) `(g ,(@ F x))))))         ; F = λx.g (F x)
(°->list #f (fresh° (q F G) (=° q (list F G))
              (∀° (x) (=° (@ F x) (@ G (@ F x))))))
()
()
()
()
((λ (α β) (assert (≐ α (ƛ (x) (@ β (@ α x))))) (cons α (cons β '()))))

The first is micro’s occurs check, unchanged. In 8.I, U y wU\,y\,w occurs below the list (g ...), a firm context, and its arguments are rigid: case (6a), ⊥\bot (Example 7.24); it also has as many arguments as U x yU\,x\,y, so the count alone would fail it. In 8.J, ww has level 1, is not an argument of UU, and UU has level 0: case (1), ⊥\bot by scope (Example 7.25). The fourth fails micro’s occurs check, the occurs hook passes it to Elim with no arguments, and F xF\,x below g is case (6a) again. The last is the soft occurs check: F xF\,x occurs inside the argument of GG, which may be λz.z\lambda z.z, so the equation is suspended (and is closed over xx at the exit of the scope) instead of failing.

Example 12.17 (An argument that may be an abstraction). ∃q ∀x ∃G. q=G (λw. k)∧G=λy. y x\exists q\,\forall x\,\exists G.\ q = G\,(\lambda w.\,k) \wedge G = \lambda y.\,y\,x in both orders:

(°->list/datum (fresh° (q) (∀° (x) (fresh° (G) (=° q (@ G (ƛ (w) 'k)))
                                               (=° G (ƛ (y) (@ y x)))))))
(°->list/datum (fresh° (q) (∀° (x) (fresh° (G) (=° G (ƛ (y) (@ y x)))
                                               (=° q (@ G (ƛ (w) 'k)))))))
(k)
(k)

In the first order, Check of q:=G (λw.k)q := G\,(\lambda w.k) at level 0 finds GG of level 1, which must be lowered; but its argument is an abstraction that GG may apply to xx and so drop GG’s own xx. Lowering GG would not be strict, so case (6c) suspends. Then G:=λy. y xG := \lambda y.\,y\,x wakes the equation, β gives (λw.k) x=k(\lambda w.k)\,x = k, and q:=kq := k. In the other order β happens at once. A version that lowered GG here lost the answer in the first order.Third adversarial review.

12.4∀° and ⊃°

The book’s goal-directed search for hereditary Harrop formulas consists of the rules and, or, instan, generic, augment and backchain [MN p. 77], [MN p. 82], [MN p. 124] (Rules 3.6; the names are those of Rules A.6). Uniform proofs are complete for intuitionistic provability of these formulas Dale Miller, Gopalan Nadathur, Frank Pfenning, and Andre Scedrov. Uniform proofs as a foundation for logic programming. Annals of Pure and Applied Logic, 51:125–157, 1991 (Theorem 3.12), so implementing the rules faithfully is the semantics. and, or and ∃\exists are micro’s and°, or° (interleaving) and fresh°. This section gives the other three as the module implements them.

12.4.1generic

Σ∪{c};𝒫⟶G[c/x]Σ;𝒫⟶∀x. G  (generic)(c∉Σ) \dfrac{\Sigma\cup\{c\}; \mathcal{P} \longrightarrow G[c/x]}{\Sigma; \mathcal{P} \longrightarrow \forall x.\,G}\;(\text{generic})\quad(c\notin\Sigma)

(∀° (x) g ...) expands into (∀ª 'x (λ (x) (and° g ...))), and (∀° (x y) g ...) into one ∀ª per name, nested, so (∀° (w x y) ...) gives w,x,yw,x,y the levels d+1d+1, d+2d+2, d+3d+3. The Scheme variable x is bound to the eigenvariable, as ƛ binds its placeholder. ∀ª takes a state ss whose λ record has depth dd and does the following.

  1. Record the level dd of every variable created so far (pad LL up to the variable count).
  2. Run the body (f c) for a new eigenvariable cc of level d+1d+1, in the state with depth d+1d+1 and top:=max⁡(top,d+1)\mathit{top} := \max(\mathit{top}, d+1).
  3. For each answer state s1s_1 of the body: record the level d+1d+1 of the variables created inside (pad LL again), set the depth back to dd, and discharge the constraints on cc (Section 12.4.2); if discharge fails, drop the answer.
(define ((∀ª name f) s)
  (let* ((x  (μkanren-hh s))
         (d  (μkanren-hh-depth x))
         (x* (μkanren-hh-with (μkanren-hh-pad x (μkanren-state-vars-count s))
                              depth: (add1 d) top: (max (add1 d) (μkanren-hh-top x))))
         (c  (μkanren-eigen* name (add1 d))))
    (append-map§
      (λ (s1)
        (let1 (s2 (μkanren-with s1
                    (μkanren-hh-with (μkanren-hh-pad (μkanren-hh s1)
                                                     (μkanren-state-vars-count s1))
                                     depth: d)))
          (match/first (μkanren-discharge s2 c d)
            (#f (✗° s2))
            (,s3 (✓° s3)))))
      (δ ((f c) (μkanren-with s x*))))))

The shape is that of micro’s andª (Chapter 10): the body’s stream is delayed with δ, and append-map§ post-processes it answer by answer, so the restoring step runs on every answer, however late the stream produces it. Steps 1 and 3 pad LL because a variable’s level is implicit (the current depth) until LL is extended past it: padding fixes it before the depth changes.

The signature Σ\Sigma is not carried. What carries the quantifier structure is the level of each variable: a variable created at depth dd stands for an ∃\exists after the first dd universals of its branch (Miller’s mixed 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, linearised by creation), and Check forbids exactly the substitutions that would violate that prefix. NJK prove this tagging sound and complete (Proposition A.35, 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, Prop. 4.1).

Tutorial (Why the depth must be restored on every answer). A creation timestamp would tell a variable created before cc from one created after it, and one might think that suffices: older variables may not see cc. But a variable created after the ∀° has exited may not see cc either. With the depth restored on every answer, such a variable gets level d<ℓ(c)d < \ell(c), so it cannot take cc. This is λProlog’s universe register 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 two classic cases, [MN p. 85]:

(list (°->list #f (fresh° (q) (∀° (x) (=° q x))))         ; ∃Y∀x. Y = x
      (°->list #f (fresh° (q) (∀° (x) (fresh° (y) (=° y x)))
                              (=° q 'ok))))                ; ∀x∃Y. Y = x
(() ((λ () 'ok)))

In the first, qq has level 0 and xx level 1: Check fails by case (1). In the second, yy is created inside, at level 1, and may take xx.

Example 12.18 (Lowering, seen from the state). A variable created inside the scope and placed inside the value of an outer one must forget the scope:

(define ((probe . vars) s)
  (for-each (λ (v) (let1 (w (μkanren-state-find v s))
                     (write v) (display " ↦ ") (write w)
                     (when (μkanren-var? w)
                       (display " level ") (display (μkanren-λ-level w s)))
                     (display "; ")))
            vars)
  (newline) (✓° s))
(°->list #f (fresh° (A) (∀° (x) (fresh° (B) (probe A B)
                                             (=° A `(arr ,B c))
                                             (probe A B)))))
_0 ↦ _0 level 0; _1 ↦ _1 level 1;
_0 ↦ (arr _1 c); _1 ↦ _2 level 0;
((λ (α) (cons 'arr (cons α (cons 'c '())))))

AA (_0) has level 0 and BB (_1) level 1. Binding A:=(𝚊𝚛𝚛 B c)A := (\mathtt{arr}\ B\ c) triggers Check at level 0, which meets the unbound BB of level 1>01>0: case (4), lower. A new variable _2 of level 0 is created and B:=_𝟸B := \mathtt{\_2}; Check eliminates no head and has no arguments a¯\bar a to raise over, so the raising part is empty. This is NJK’s “change to ii the tags of the variables in tt whose tag is >i>i”, done by a binding instead of a mutation, so that it is undone by backtracking for free.

12.4.2Discharge at the exit of a scope

When ∀° exits, some constraints may still mention cc: suspended equations, generic disequalities of N, absentos of micro’s T. A residual that mentions cc outside its scope would be meaningless, and the printer must never show an eigenvariable free. μkanren-discharge closes them, back at depth dd:

  1. Raise. Every unbound variable YY of the equations and disequalities to be closed with ℓ(Y)≥ℓ(c)\ell(Y)\ge\ell(c) is raised: Y:=Y′ cY := Y'\,c with ℓ(Y′)=d\ell(Y')=d. Inside the scope YY could depend on cc; Y′Y' lives outside it, so the dependency becomes an explicit argument: ∀c ∃Y\forall c\,\exists Y is turned into ∃Y′ ∀c\exists Y'\,\forall c with Y=Y′ cY = Y'\,c. This is Miller’s raising [MN p. 107] (Proposition 4.14), a bijection on solutions.
  2. Close. A suspended equation u≐vu \doteq v that mentions cc stands for ∀c (u=v)\forall c\,(u = v) and becomes λc.u≐λc.v\lambda c.u \doteq \lambda c.v, equivalent by ξ. A generic disequality is closed the same way, under generic’s reading of cc as a new name. An absento of T whose term mentions cc is closed too, since absence in λc.u\lambda c.u is absence in uu. An absento whose datum mentions cc moves to EE as (absent d u), unless the levels entail it: if uu does not hold cc and all its variables have levels below ℓ(c)\ell(c), no instance of uu can ever hold cc, and the constraint is dropped.
  3. Retry. The raise bindings go through μkanren-post-unify, which wakes EE, so the closed constraints are retried. With no raise, the closed equations are retried anyway.
  4. Repeat. A raise may bring cc into more constraints (an absento of T on a raised YY now watches Y′ cY'\,c; a prefix of D on YY moves to N holding cc). Discharge repeats until no raise is left.

The constraints that cannot be closed by an abstraction (a type on F xF\,x; an absento whose datum is cc on a term that may still hold cc) keep cc and print under a ∀ (Section 12.6).

Example 12.19 (Discharge: raising, closing, retrying).

(define ((probe label . vars) s)   ; prints values and the levels of unbound variables
  (display label) (display ": depth ") (display (μkanren-λ-depth s))
  (for-each (λ (v) (display ", ") (write v) (display " ↦ ")
                   (write (μkanren-state-find/value v s))
                   (let1 (w (μkanren-state-find v s))
                     (when (μkanren-var? w)
                       (display " level ") (display (μkanren-λ-level w s)))))
            vars)
  (display ", E ") (write (μkanren-λ-delayed s)) (newline)
  (✓° s))
(°->list #f (fresh° (q) (∀° (a) (fresh° (f) (=° (@ f a) `(g ,a ,a))
                                             (probe "inside" f)))
                        (=° q 'ok)))
(°->list #f (fresh° (q) (∀° (x) (=° (@ q x) `(g ,q)) (probe "inside" q))))
inside: depth 1, _1 ↦ _1 level 1, E ((= (@ _1 (eigen a)) (g (eigen a) (eigen a))))
((λ (α)
    (assert (≐ (ƛ (a) (@ α a a)) (ƛ (a) (cons 'g (cons a (cons a '()))))))
    'ok))
inside: depth 1, _0 ↦ _0 level 0, E ((= (@ _0 (eigen x)) (g _0)))
()

In the first, ff is created inside the scope of aa (level 1), so f af\,a is no pattern (the book’s 8.A, four unifiers and no mgu, [MN p. 213]) and is suspended. At the exit, ff has level 1≥ℓ(a)1\ge\ell(a): it is raised, f:=f′ af := f'\,a with ℓ(f′)=0\ell(f')=0, and the equation closes into λa. f′ a a≐λa. g a a\lambda a.\,f'\,a\,a \doteq \lambda a.\,g\,a\,a. That is still no pattern (the argument aa is repeated), so it is reported. In the second, F x≐g FF\,x \doteq g\,F is a pattern equation, but FF itself occurs with no argument in its own body, case (4) with a¯≠⟨⟩\bar a \neq \langle\rangle: suspend. At the exit nothing needs raising (ℓ(F)=0\ell(F)=0), the equation closes into λx. F x≐λx. g F\lambda x.\,F\,x \doteq \lambda x.\,g\,F, which by η is F≐λx. g FF \doteq \lambda x.\,g\,F, and the retry fails the occurs check: no answer, as it must be.

12.4.3augment

Σ;𝒫∪{D}⟶GΣ;𝒫⟶D⊃G  (augment) \dfrac{\Sigma; \mathcal{P}\cup\{D\} \longrightarrow G}{\Sigma; \mathcal{P} \longrightarrow D\supset G}\;(\text{augment})

(⊃° (D ...) g ...) expands into ⊃ª, which pushes the clauses on Γ for the body and gives the old Γ back to every answer of the body:

(define ((⊃ª clauses g) s)
  (let* ((x (μkanren-hh s))
         (Γ (μkanren-hh-Γ x))
         (Γ* (fold-right
               (λ (c Γ*)
                 (let1 (old (cond ((assq (car c) Γ*) => cdr) (else '())))
                   (cons (cons (car c) (cons (cdr c) old))
                         (if (null? old) Γ* (alist-delete (car c) Γ* eq?)))))
               Γ clauses)))
    (append-map§
      (λ (s1) (✓° (μkanren-with s1 (μkanren-hh-with (μkanren-hh s1) Γ: Γ))))
      (δ (g (μkanren-with s (μkanren-hh-with x Γ: Γ*)))))))

A clause is a pair (relation . procedure): the relation is the dynamic relation’s own procedure, used as an eq? key, and the procedure maps the list of a call’s arguments to the goal that the clause makes of them. Since Γ lives in the state, or° branches cannot interfere, and restoring it on every answer is the stack discipline of the book [MN p. 78], [MN p. 83]. Assuming a clause for a relation already in Γ replaces that relation’s entry by one with the new clause in front of the old ones, so a lookup costs the number of distinct assumed relations, not the number of clauses. The fold-right puts the first clause of a list on top.

12.4.4backchain and define-dynamic-relation

In λProlog every predicate can be extended by an assumption. Here only relations made by define-dynamic-relation can:

(define-syntax define-dynamic-relation
  (syntax-rules ()
    ((_ (name arg ...))
     (define name
       (μkanren-dynamic
         (λ (arg ...) (λ (s) (δ ((μkanren-hyps° name (list arg ...) #f) s)))))))
    ((_ (name arg ...) g ...)
     (define name
       (μkanren-dynamic
         (λ (arg ...)
           (λ (s) (δ ((μkanren-hyps° name (list arg ...) (and° g ...)) s)))))))))

(define ((μkanren-hyps° key args static) s)
  (let* ((gs (map (λ (c) (c args))
                  (cond ((assq key (μkanren-hh-Γ (μkanren-hh s))) => cdr) (else '()))))
         (gs (if static (append gs (list static)) gs)))
    (if (null? gs) '() ((reduce-right orª #f gs) s))))

A call disjoins, in one flat or°, the assumed clauses for the relation, most recent first, and then the static body. If C1,…,CmC_1,\dots,C_m are the clauses assumed for rr in the current Γ, in the order they were assumed, and BrB_r is the static body of rr (absent when it has none), then

r t¯  ⇝  Cm(t¯)  ∨  …  ∨  C1(t¯)  ∨  Br(t¯), r\,\bar t \;\rightsquigarrow\; C_m(\bar t) \;\vee\; \dots \;\vee\; C_1(\bar t) \;\vee\; B_r(\bar t),

where Ci(t¯)C_i(\bar t) unifies t¯\bar t with the head of CiC_i, its own ∀ variables renamed and its free variables shared (see the clause syntax below), and runs its body. This is backchain (Rules 3.6) with the choice of clause made by or° instead of by a selection rule; a relation with neither hypotheses nor static body fails. When every clause answers at once, the answers come in λProlog’s order; otherwise interleaving decides. The relation is tagged with CHICKEN’s extend-procedure, so μkanren-dynamic? is an O(1)O(1) test and no global registry is needed. Assuming a clause for a relation that is not dynamic is an error, not a silent no-op:

(define-dynamic-relation (n° x) (=° x 1))
(list (°->list/datum (fresh° (q) (⊃° ((n° 2)) (⊃° ((n° 3)) (n° q)))))
      (°->list/datum (fresh° (q) (⊃° ((n° 2) (n° 3)) (n° q)))))
(define (error-message thunk)     ; the message of the error `thunk` raises
  (handle-exceptions exn ((condition-property-accessor 'exn 'message #f) exn)
    (begin (thunk) #f)))
(define-relation (r° x) (=° x 1))
(error-message (λ () (°->list #f (fresh° (q) (⊃° ((r° 2)) (r° q))))))
((3 2 1) (2 3 1))
"not a dynamic relation, see define-dynamic-relation"

The two orders are the book’s [MN p. 78]: p 2 => p 3 => p X gives 3, 2, 1, and (p 2 & p 3) => p X gives 2, 3, 1. In the first query the inner ⊃° runs last, so Γ maps n° to the clauses for 3 and 2, in this order, and the call disjoins q=3q=3, q=2q=2 and the static q=1q=1. In the second, fold-right puts the first clause of the list on top, so the clause for 2 comes before the one for 3.

12.4.5Clause syntax

clause DDmeaning and expansion
(rel t ...)a fact; (λ (args) (fresh° (v ...) (=° args (list t ...))))
((rel t ...) ← g ...)a rule, infix
(← (rel t ...) g ...)the same rule, prefix; rewritten to the infix form
(∀ (w ...) D)DD with its own variables w ..., accumulated into the fresh° of the expansion

A rule expands to (μkanren-clause* rel (λ (args) (fresh° (v ...) (=° args (list t ...)) g ...))), and μkanren-clause* raises the error above when rel is not dynamic. Two kinds of variables appear in a clause, as in the book [MN p. 86–88]:

  • its free logic variables are those of the closure: shared with the context, and among all uses of the clause;
  • its own ∀ variables are made by the fresh° inside the procedure, so they are renamed at each use, at the current level. That is NJK’s “new tagged instance” of a clause 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, p. 14.
(define-dynamic-relation (h° x))
(list (°->list/datum (fresh° (q y) (⊃° ((h° `(,y ,y))) (h° '(1 1)) (h° '(2 2)))))
      (°->list/datum (fresh° (q) (⊃° ((∀ (z) (h° `(,z ,z)))) (h° '(1 1)) (h° '(2 2)))
                                 (=° q 'ok))))
(() (ok))

With the shared yy, the first use binds y:=1y:=1 and the second use cannot match (2 2); with the clause’s own zz, each use gets a new zz.

Example 12.20 (Levels reach into clauses, 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 With the program ∀z (q z⊃p (d z))\forall z\,(q\,z \supset p\,(d\,z)), the goal ∃x ∀y (q y⊃p x)\exists x\,\forall y\,(q\,y \supset p\,x) must fail and ∀y ∃x (q y⊃p x)\forall y\,\exists x\,(q\,y \supset p\,x) must succeed (Example A.36):

(define-dynamic-relation (q° z))
(define-dynamic-relation (p° x) (fresh° (z) (=° x `(d ,z)) (q° z)))
(list (°->list #f (fresh° (x) (∀° (y) (⊃° ((q° y)) (p° x)))))
      (°->list #f (fresh° (r) (∀° (y) (fresh° (x) (⊃° ((q° y)) (p° x)))) (=° r 'ok))))
(() ((λ () 'ok)))

In the first goal, xx has level 0. Backchaining on p° creates the clause variable zz inside the scope of yy (level 1) and binds x:=(d z)x := (d\ z); Check lowers zz to level 0. The hypothesis (q° y) then asks z=yz = y, a level-0 variable against a level-1 eigenvariable: scope failure. Without lowering, zz would keep level 1 and take yy, and x=(d y)x = (d\ y) would leak yy out of its scope.

12.4.6Worked example: type inference

The book’s type inference for untyped λ-terms (Section 6.5.4, [MN p. 190–191]) uses all three rules at once:

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.

In the module’s syntax (src/test/microkanren-lambda-programs.scm):

(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 object term abs x\ M is `(abs ,(ƛ (x) M)); (M x) is (@ R x), a β-redex once RR is bound. The answers for S, I and λx. x x\lambda x.\,x\,x (from the prototype’s examples.out, which its examples.scm prints byte for byte on the merged tree):

(((arr (arr α (arr β γ)) (arr (arr α β) (arr α γ)))) ((arr α α)) ())

To see the rules at work, here is the same program with a trace goal that prints the depth and the walked arguments, with the level of each unbound variable after @. The trace in the static body runs only when the static clauses are tried, after the hypotheses:

(define ((trace label . ts) s)
  (display label) (display " [depth ") (display (μkanren-λ-depth s)) (display "]")
  (for-each (λ (t) (display " ") (write (μkanren-state-find/value t s))
                   (let1 (w (μkanren-state-find t s))
                     (when (μkanren-var? w)
                       (display "@") (display (μkanren-λ-level w s)))))
            ts)
  (newline) (✓° s))
(define-dynamic-relation (typeof° m t)
  (trace "static typeof°" m t)
  (cond°
    ((fresh° (M N B) (=° m `(app ,M ,N)) (trace " app" M N B)
       (typeof° M `(arr ,B ,t)) (typeof° N B)))
    ((fresh° (R A B) (=° m `(abs ,R)) (=° t `(arr ,A ,B)) (trace " abs" R A B)
       (∀° (x) (⊃° ((typeof° x A)) (typeof° (@ R x) B)))))))
(°->list/datum (fresh° (q) (typeof° `(abs ,(ƛ (x) `(abs ,(ƛ (y) x)))) q)))
(°->list/datum (fresh° (q) (typeof° `(abs ,(ƛ (x) `(app ,x ,x))) q)))
static typeof° [depth 0] (abs (ƛ (x) (abs (ƛ (y) x)))) _0@0
 abs [depth 0] (ƛ (x) (abs (ƛ (y) x))) _2@0 _3@0
static typeof° [depth 1] (abs (ƛ (y) (eigen x))) _3@0
 abs [depth 1] (ƛ (y) (eigen x)) _7@0 _8@0
static typeof° [depth 2] (eigen x) _8@0
((arr α (arr β α)))
static typeof° [depth 0] (abs (ƛ (x) (app x x))) _0@0
 abs [depth 0] (ƛ (x) (app x x)) _2@0 _3@0
static typeof° [depth 1] (app (eigen x) (eigen x)) _3@0
 app [depth 1] (eigen x) (eigen x) _6@1
static typeof° [depth 1] (eigen x) (arr _6 _3)
static typeof° [depth 1] (eigen x) _7@0
()

Tutorial (λx.λy.x, step by step).

  1. Depth 0, Γ empty. The query TT is _0. No hypothesis for typeof°, so the static body runs. The abs clause creates R,A,BR,A,B (_1, _2, _3, level 0), binds R:=λx. 𝚊𝚋𝚜 (λy. x)R := \lambda x.\,\mathtt{abs}\,(\lambda y.\,x) and T:=(𝚊𝚛𝚛 A B)T := (\mathtt{arr}\ A\ B).
  2. generic. ∀° (x) records levels, raises the depth to 1 and makes the eigenvariable xx of level 1.
  3. augment. ⊃° pushes ⟨typeof∘,λargs. args≐(x A)⟩\langle\texttt{typeof}^{\circ}, \lambda\mathit{args}.\ \mathit{args} \doteq (x\ A)\rangle on Γ.
  4. β. The goal is (typeof° (@ R x) B); @ reduces the redex to 𝚊𝚋𝚜 (λy. x)\mathtt{abs}\,(\lambda y.\,x), with xx now the eigenvariable, printed (eigen x).
  5. backchain, depth 1. The hypothesis is tried first: (𝚊𝚋𝚜 … )≐x(\mathtt{abs}\ \dots) \doteq x clashes. Then the static body: the abs clause creates R′,A′,B′R',A',B' at level 1 and binds B:=(𝚊𝚛𝚛 A′ B′)B := (\mathtt{arr}\ A'\ B'). Here Check runs: BB has level 0, A′A' and B′B' level 1, so both are lowered, to new variables _7, _8 of level 0 (the trace shows _7@0 _8@0, the walked values). This is right: the type of the inner abstraction is part of the outer type, which lives outside the scope of xx.
  6. generic, augment again. Depth 2, eigenvariable yy of level 2, Γ now holds two clauses for typeof°, (y A′)(y\ A') on top of (x A)(x\ A).
  7. backchain, depth 2. The goal is (typeof° x B'). The most recent hypothesis gives x≐yx \doteq y, a clash of two eigenvariables. The older one gives B′≐AB' \doteq A: a level-0 variable bound to another, fine. The static body is tried as well (the last trace line) and fails, since xx is neither an application nor an abstraction.
  8. Exits. Each ∀° gives its answers back their depth and discharges nothing (no constraint mentions xx or yy); each ⊃° gives Γ back. The answer is T=𝚊𝚛𝚛 A (𝚊𝚛𝚛 A′ A)T = \mathtt{arr}\ A\ (\mathtt{arr}\ A'\ A), printed (arr α (arr β α)).

Tutorial (λx.x x fails by the occurs check). At depth 1, with the hypothesis 𝚝𝚢𝚙𝚎𝚘𝚏 x A\mathtt{typeof}\ x\ A, the goal is 𝚝𝚢𝚙𝚎𝚘𝚏 (𝚊𝚙𝚙 x x) B\mathtt{typeof}\ (\mathtt{app}\ x\ x)\ B. The app clause binds M,N:=xM,N := x and creates its B′′B'' (_6) at level 1. The first subgoal 𝚝𝚢𝚙𝚎𝚘𝚏 x (𝚊𝚛𝚛 B′′ B)\mathtt{typeof}\ x\ (\mathtt{arr}\ B''\ B) uses the hypothesis: A:=(𝚊𝚛𝚛 B′′ B)A := (\mathtt{arr}\ B''\ B), and since ℓ(A)=0\ell(A)=0, Check lowers B′′B'' to the level-0 _7. The second subgoal 𝚝𝚢𝚙𝚎𝚘𝚏 x B′′\mathtt{typeof}\ x\ B'' (printed with B′′B'' walked to _7) asks _𝟽≐A=(𝚊𝚛𝚛 _𝟽 B)\mathtt{\_7} \doteq A = (\mathtt{arr}\ \mathtt{\_7}\ B): micro’s occurs check fails, and since the term holds no λ-term, the occurs hook does not intervene. The static attempts fail too, and there is no answer, the book’s “no” [MN p. 191].

12.5micro’s stores on λ-terms

λProlog has no disequality, no absento and no type constraints such as symbol° (its types are static). (aux kanren micro) has all three (Section 10.5), and every relation built on them must keep working when its arguments are λ-terms. The readings adopted here extend micro’s semantics over λProlog’s term model: equality is αβη\alpha\beta\eta-equality, a flexible term is undecided until its head is known, and an eigenvariable is, by default, a new name.

12.5.1Disequality: the diseq hook and the store N

Definition 12.21 (Trial). The module claims a disequality u≠vu \neq v when either side, walked, holds a λ-record or an eigenvariable, and also, under the extensional reading once a ∀° has run, a first-order one (in D an absento of T could absorb it, and absence reads eigenvariables generically). Its trial unifies u≐vu \doteq v in the current state, with Check, and classifies the result (μkanren-trial):

  • unsat
    no unifier: the disequality holds for good and is dropped;
  • entailed
    a unifier that binds no variable older than the trial (or binds older variables only to distinct variables the trial itself created) and suspends nothing: u=vu=v already holds, and ≠° fails;
  • kept
    otherwise: the pair is stored in N as (reading u . v) and re-tried after every =°.

The variables a trial creates (by pruning, by FF-same, by lowering) are existential inside the negation: λx y. F x≠λx y. G y\lambda x\,y.\,F\,x \neq \lambda x\,y.\,G\,y means ¬∃H. F=λx.H∧G=λy.H\neg\exists H.\ F = \lambda x.H \wedge G = \lambda y.H. A prefix of micro’s D would wrongly store them as free variables, which is one reason N is a separate store.

(°->list #f (fresh° (q) (=° q (ƛ (x) x)) (≠° q (ƛ (y) y))))     ; entailed mod α
(°->list #f (fresh° (q) (≠° (@ (ƛ (x) `(g ,x)) 'a) '(g a))))    ; entailed mod β
(°->list #f (fresh° (q) (≠° (ƛ (x) x) (ƛ (x) 'k)) (=° q 'ok)))  ; holds for good
(°->list/datum (fresh° (q F) (=° q F) (≠° (@ F 'a) 'a)
                        (=° F (ƛ (z) z))))                 ; woken, violated
(°->list/datum (fresh° (q F) (=° q F) (≠° (@ F 'a) 'a)
                        (=° F (ƛ (z) 'b))))                ; woken, holds
(°->list #f (fresh° (q f g) (=° q (list f g))
              (≠° (ƛ (x y) (@ f x)) (ƛ (x y) (@ g y)))))
()
()
((λ () 'ok))
()
((ƛ (z) b))
((λ (α β)
    (begin (deny (∃ (_3) (and (equal? α (ƛ (x) _3)) (equal? β (ƛ (y) _3))))))
    (cons α (cons β '()))))

Line by line: the first trial succeeds under ξ binding nothing, so it is entailed and ≠° fails; the second never reaches the module, since @ has already β-reduced its left side to the list (g a) and micro’s own ≠° fails on two equal terms; the third trial clashes (xx against kk under ξ), so the disequality is unsat and dropped. In the fourth and fifth the trial F a≐aF\,a \doteq a is no pattern (aa is a constant) and suspends, so the pair is kept in N; the binding of FF retries it, and it is violated by λz.z\lambda z.z and holds for good with λz.b\lambda z.b. In the last, the trial is the flexible–flexible problem of Example 12.13 under two binders: it binds the older FF and GG to λx.H\lambda x.H and λy.H\lambda y.H with a new HH, so the pair is kept, and the answer denies exactly that mgu, with HH (_3) existential inside the deny.

Migration from D to N. A prefix of D born first-order may come to hold a λ-term or an eigenvariable later, at any depth below its variables. The post hook moves it to N, as the tuple disequality it stands for, before micro posts it again (E4 of Definition 11.13). So D never holds a λ-term, and micro’s plain trial never decides a λ-equation without the scope check and the reading. The probe prints N, D and E:

(define ((probe label) s)
  (display label) (display ": N ") (write (μkanren-λ-disequalities s))
  (display ", D ") (write (μkanren-state-D s))
  (display ", E ") (write (μkanren-λ-delayed s))
  (newline) (✓° s))
(°->list #f (fresh° (q Y) (≠° q (list Y)) (probe "before")
                          (=° Y (ƛ (z) z)) (probe "after")))
before: N (), D (((_0 _1))), E ()
after: N ((generic (_0) (_1))), D (), E ()
((λ (α) (begin (deny (equal? α (cons (ƛ (z) z) '())))) α))

The hook finds such prefixes from the new bindings, never by walking D (μkanren-migrate, aux.kanren.lambda.scm:895–944). D held no λ-term before the binding, and every binding is in the assocs the hook receives (E2), so a prefix holds one after the binding exactly when the value of a binding that reaches it does. A prefix reaches a bound variable in one of two ways: micro’s records list it under the variable, as a side of one of its pairs (μkanren-state-prefix-ids), or the variable lies below a compound side of the prefix, or below a value bound since, and then W lists it, which micro’s watch hook fills for every new prefix (μkanren-λ-watch). For each bound variable that either lists, the hook walks the bound value once. If the value holds no λ-term, the variables it reaches go to W under the ids of the prefixes that W listed and that are still live; if it holds one, each listed prefix is walked once and moves. A first look of at most 64 nodes (μkanren-new-terms?) tells most first-order bindings at once that they hold no λ-term, and then only the W-listed prefixes are looked at, since micro posts the record-listed ones again anyway; with W empty the hook does nothing. Walking the prefixes themselves at every binding, as the prototype did, made a store of nn disequalities cost n2n^2 walks.Section 14.3 has the measurements.

Subsumption by A. A trial that binds a variable typed in A to a rigid λ-term or an eigenvariable of which the type’s predicate is false has no solution; symbol° and number° hold of neither. So the disequality is dropped, as micro drops (≠° q 5) under (symbol° q):

(°->list #f (fresh° (q) (symbol° q) (≠° q (ƛ (x) x))))
((λ (α) (assert (every (μ v (symbol? v)) (list α))) α))

Two readings of ∀. What does ∀x. q≠x\forall x.\ q \neq x mean? λProlog has no ≠\neq, but it has pi x\ not (q = x), which succeeds: xx is a new name, distinct from everything. The parameter μkanren-λ-reading chooses, and each disequality keeps the reading in force when it was posted.

  • 'generic (the default) reads an eigenvariable as generic’s new name, ∇-like, as αKanren’s noms 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. At the exit of the scope the constraint is closed: ∀x. F x≠x\forall x.\ F\,x \neq x becomes F≠λx.xF \neq \lambda x.x, consistently whichever comes first, the binding or the ≠\neq.
  • 'extensional reads an eigenvariable as any term of its universe, as in the miniKanren work on universal quantification 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. The trial replaces each eigenvariable by a new variable of its level, after raising the variables that may depend on it, and counts as entailed when it binds older variables only to distinct such variables. Then ∀x. q≠x\forall x.\ q \neq x fails, since xx could be qq.
(°->list #f (fresh° (q) (∀° (x) (≠° q x))))
(°->list #f (fresh° (q F) (=° q F) (∀° (x) (≠° (@ F x) x))))
(°->list #f (fresh° (q F) (=° q F) (∀° (x) (≠° (@ F x) x)) (=° F (ƛ (z) z))))
(°->list #f (fresh° (q F) (=° q F) (∀° (x) (≠° (@ F x) x)) (=° F (ƛ (z) 'c))))
(parameterize ((μkanren-λ-reading 'extensional))
  (list (°->list #f (fresh° (q) (∀° (x) (≠° q x))))
        (°->list #f (fresh° (q F) (=° q F) (∀° (x) (≠° (@ F x) x))))
        (°->list #f (fresh° (q F) (=° q F) (∀° (x) (≠° (@ F x) x))
                                (=° F (ƛ (z) 'c))))))
((λ (α) α))
((λ (α) (begin (deny (equal? α (ƛ (x) x)))) α))
()
((λ () (ƛ (z) 'c)))
(() ((λ (α) (∀ (x) (begin (deny (≐ (@ α x) x)))) α)) ())

Under the generic reading, ∀x. F x≠x\forall x.\ F\,x\neq x is the disequality F≠λx.xF \neq \lambda x.x: violated by F:=λz.zF := \lambda z.z, satisfied by F:=λz.cF:=\lambda z.c. Under the extensional reading it says that F t≠tF\,t \neq t for every tt of the universe, so F:=λz.cF := \lambda z.c violates it (t=ct = c); since it cannot be closed by an abstraction, it is printed under a ∀.

Projection. micro drops a disequality over a variable that is out of the answer, since such a variable can always be chosen to keep the sides apart. That fails for a variable inside an argument of a flexible term: ∃Y. G≠F Y\exists Y.\ G \neq F\,Y is F≠λz.GF \neq \lambda z.G, since FF may ignore its argument. Such an entry is kept, and its variable prints as a working variable, read existentially:

(°->pretty (fresh° (q) (fresh° (F G Y) (=° q (list F G)) (≠° G (@ F Y)))))
(((α β) : (≠ β (@ α _3))))

12.5.2Absence: the parts hook

absent° looks for its datum in the parts of a λ-term (μkanren-λ-parts), never in binder names or indices. A flexible term has no parts yet: it is 'stuck and watched whole, like a variable, and decided once its head is known. Below a binder, the parts that mention the binder stay closed (λx.(a . b)\lambda x.(a\,.\,b) is looked into as λx.a\lambda x.a and λx.b\lambda x.b), so a watched term never has a loose index.

(°->list #f (fresh° (q F) (=° q F) (absent° 'c (@ F 'c))))
(°->list/datum (fresh° (q F) (=° q F) (absent° 'c (@ F 'c)) (=° F (ƛ (z) 'b))))
(°->list #f (fresh° (q) (absent° 'x (ƛ (x) `(g ,x))) (=° q 'ok)))
(°->list #f (fresh° (q F) (=° q F) (absent° 'c (ƛ (x) `(,(@ F x) c)))))
(°->list #f (fresh° (q F) (=° q F) (∀° (x) (absent° x (@ F x)))))
(°->list #f (fresh° (q) (∀° (x) (absent° x q))))
((λ (α) (assert (absent? 'c (@ α 'c))) α))
((ƛ (z) b))
((λ () 'ok))
()
((λ (α) (∀ (x) (assert (absent? x (@ α x)))) α))
((λ (α) α))

In order: c∉F cc \notin F\,c waits; F:=λz.bF := \lambda z.b drops the argument, so it holds; the binder name x is not the symbol 'x; cc is found at once outside the flexible part; an absento of an eigenvariable on a term that may still hold it keeps xx and prints under ∀; and ∀x. x∉q\forall x.\ x \notin q is entailed by the levels (qq has level 0<10<1, so no instance of qq can hold xx) and dropped. The datum may itself be a λ-term, or reduce to an atom ((@ G 'b) is a once G:=λz.aG := \lambda z.a): it is then unified, modulo βη, as micro unifies a compound datum.

12.5.3Types: the tag hook

A type on a flexible term waits in E as (tag tag u); the post hook does the same for a variable of A just bound to one. A rigid λ-term or an eigenvariable is decided by the type’s predicate: abstractions and eigenvariables are neither symbols nor numbers, while a type of the user’s made with define-μkanren-tag may hold of them. micro’s types are disjoint, so two different types on the same flexible term fail at once:

(°->list #f (fresh° (q F) (=° q (@ F 'a)) (symbol° q)))
(°->list/datum (fresh° (q F) (=° q (@ F 'a)) (symbol° q) (=° F (ƛ (z) z))))
(°->list #f (fresh° (q F) (=° q (@ F 'a)) (symbol° q) (number° q)))
(°->list #f (fresh° (q) (∀° (x) (symbol° x))))
(°->list #f (fresh° (q F) (=° q F) (∀° (x) (symbol° (@ F x)))))
((λ (α) (assert (every (μ v (symbol? v)) (list (@ α 'a)))) (@ α 'a)))
(a)
()
()
((λ (α) (∀ (x) (assert (every (μ v (symbol? v)) (list (@ α x))))) α))

Pitfall (Readings are per constraint, and only for ≠). The extensional reading applies to ≠° only; absent° and the types always read an eigenvariable as generic does. A disequality keeps the reading in force when it was posted; a first-order disequality that migrates from D to N later takes the reading in force when it migrates, since D records none. The two can differ only if the program changes μkanren-λ-reading between the two goals.

12.6Reification

micro reifies an answer as a λ-expression whose parameters name the answer’s variables and whose body lists the constraints and ends with the value (Section 10.7). The module plugs into that through the hooks value, repr, terms, forms and environment (Chapter 11).

Values. Deep values are β-normal and η-short (μkanren-λ-value). They are used by answers, by D, A and T, by project° and by aggregation.

Binders. An abstraction prints as (ƛ (x y) body), nested binders merged. A binder is named after its hint, renamed apart from the binders around it, from every symbol of its body, and from the operators of the rebuilding code (cons, quote, vector, make-record-instance, ƛ, @, eigen, bvar). So neither capture nor shadowing can mislead the reader (Ma and Friedman’s “true = false”, Section 9.2.3), and a ground answer evaluates back to the same term:

(°->list/datum (fresh° (q) (=° q (ƛ (a) (ƛ (a) a)))))
(μkanren-datum (μkanren-abstract 'cons (λ (c) `(a ,c))))
((ƛ (a a1) a1))
(ƛ (cons1) (a cons1))

Applications print as (@ h a ...), so a flexible application (@ α x) cannot be mistaken for the list (α x).

Residual forms. The constraints of the λ layer print as Scheme forms that can be evaluated:

constraintform in the answer
suspended equation (E)(assert (≐ u v))
type on a flexible term (E)(assert (every (μ v (symbol? v)) (list u)))
absento with a pending term (E, T)(assert (absent? d u))
disequality whose trial binds (N)(begin (deny (equal? α t))), with (∃ (_3) ...) inside deny when the trial creates variables
disequality whose trial only suspends (N)(begin (deny (≐ u v)))
any of them still holding an eigenvariablewrapped in (∀ (x) form)

The forms of E and of N are sorted by their printed form, as micro sorts D and T, and a form that says what an earlier one says, up to the names of the binders of ƛ, ∀ and ∃, is kept once (μkanren-sort-forms, μkanren-form-α-key; both came with the merge, commit 5be5f35). So the printed answer depends far less on the order of the goals that posted its constraints, and the same disequality posted as q≠λx. xq\ne\lambda x.\, x and, through q=Fq=F, as F≠λy. yF\ne\lambda y.\, y prints once:

(°->list #f (fresh° (q F) (=° q F) (≠° q (ƛ (x) x)) (≠° F (ƛ (y) y))))
(°->list #f (fresh° (q F) (=° q F) (≠° (@ F 'b) 'a) (≠° (@ F 'a) 'b)))
(°->list #f (fresh° (q F) (=° q F) (≠° (@ F 'a) 'b) (≠° (@ F 'b) 'a)))
((λ (α) (begin (deny (equal? α (ƛ (x) x)))) α))
((λ (α) (begin (deny (≐ (@ α 'a) 'b))) (begin (deny (≐ (@ α 'b) 'a))) α))
((λ (α) (begin (deny (≐ (@ α 'a) 'b))) (begin (deny (≐ (@ α 'b) 'a))) α))

On 12,000 random λ programs, each run in its order, reversed and shuffled, the printed answers of 578 depended on the order of the goals in the prototype, and of 165 on the merged tree; 161 of those have a residual ≐ in some order, the limit of Section 14.2.3. ≐ is exported: it decides αβη-equality of closed terms by unifying them in the empty state, so the forms evaluate. Through the terms hook, the variables of residual equations are reified after those of the answer, so they are named α, β, … rather than _2 (Example 12.15). micro’s show module gives the αKanren-style view °->pretty:

(°->pretty (fresh° (q) (∀° (x) (=° (@ q `(g ,x)) `(h (g ,x))))))
(°->pretty (fresh° (q) (∀° (x) (=° (@ q x x) x))))
((α : (= (ƛ (x) (@ α (g x))) (ƛ (x) (h (g x))))))
((α : (= (ƛ (x) (@ α x x)) (ƛ (x) x))))

No free eigenvariable. Every constraint that holds an eigenvariable past its scope is closed, by ƛ or by ∀, so no eigenvariable ever appears free in an answer. The one value that could hold one is the answer itself, when the variable that °->list reifies is created inside a ∀°. λProlog reports no binding for a variable quantified inside pi x\ , and this answer cannot be told without xx, so reifying it is an error:

(error-message (λ () (°->list #f (∀° (x) (fresh° (q) (=° q x))))))
"the answer holds the eigenvariable of a ∀° it was created in: create the variable it reifies outside every ∀°"

Live ground answers. ƛ, @ and ≐ are bound in the module’s environment, which the environment hook hands to °->list/ground. A ground answer is therefore a λ-term one can apply:

(@ (car (°->list/ground (fresh° (q) (=° q (ƛ (x y) `(g ,x ,y)))))) 'b 'b)
(g b b)

°->list/datum answers plain data instead, comparable with equal? against quoted book answers; that is what the suite uses, and μkanren-repr->datum of (aux kanren micro show) turns micro’s rebuilding code into such data.

Pitfall (Hints are not part of equality). equal? sees hints, the unifier does not. (ƛ (x) x) and (ƛ (y) y) unify and are μkanren-α=?, but they are not equal?: equal? compares records slot by slot, hint included, and the hint is kept in the record so that answers print the user’s binder names. When comparing λ-terms in host code, use μkanren-α=? or ≐. A related trap is Scheme’s own: (ƛ (quote) 'a) shadows quote while the body is built; terms built through μkanren-abstract with such a hint print and evaluate correctly.

12.7API reference

namemeaning
Terms
(ƛ (x ...) body)λ-abstraction over Scheme binders, η-short
(@ f a ...)application; β at once on an abstraction, nested applications flattened
(≐ u v)αβη-equality of closed terms, for residual forms
(μkanren-abstract name f)the abstraction of the term (f p), p a placeholder; binder hinted name
(μkanren-apply f args)@ on a list of arguments
(μkanren-hnorm t s)head normal form of t in state s (Definition 12.3)
(μkanren-α=? u v)α-equivalence of deep values, hints ignored
(μkanren-datum t)a term as data, printed without a state
μkanren-lam? μkanren-app? μkanren-eigen? μkanren-bvar? μkanren-λ-term?record predicates; the last is their union
μkanren-lam-hint μkanren-eigen-name μkanren-eigen-levelaccessors
Goals
(∀° (x ...) g ...)generic; (∀ª name f) its procedural form, f taking the eigenvariable
(⊃° (D ...) g ...)augment; (⊃ª clauses g) its procedural form
(define-dynamic-relation (r a ...) g ...)a relation that hypotheses can extend; with no g, no static clauses
(μkanren-dynamic f) (μkanren-dynamic? f)tag a procedure as dynamic, test the tag
μkanren-hyps° μkanren-clause μkanren-clause/vars μkanren-clause*what the macros expand to
Clauses DD
(r t ...) ((r t ...) ← g ...) (← (r t ...) g ...) (∀ (v ...) D)fact, rule (infix and prefix), own variables
Answers
(°->list/datum g)the answers of g as plain data, constraints dropped
μkanren-λ-show-extensionhow the show module reads the module’s answers, registered at load time
Engine
μkanren-λ-readingparameter, 'generic (default) or 'extensional
(μkanren-λ-depth s)the current universe level
(μkanren-λ-level α s)the level of variable α
(μkanren-λ-delayed s)the suspended constraints E
(μkanren-λ-disequalities s)the λ-disequalities N
μkanren-λ-extensionthe registered extension record
In (aux kanren micro show)
(°->pretty g) μkanren-answer->prettyαKanren-style answers, (value : constraint ...)
(μkanren-repr->datum r)micro’s rebuilding code as data; no longer exported by the module, where it clashed with this one

12.8Summary

  • Terms. Four records, locally nameless: μkanren-lam (interned hint, body), μkanren-app, μkanren-eigen (name, level, uninterned id), μkanren-bvar. ƛ uses Scheme binders and builds η-short; @ β-reduces at once. Terms built alike are equal?; α-equality is μkanren-α=? and ≐. Lists remain data: (@ 'g 'a) is not '(g a).
  • State. One immutable record in micro’s slot X: depth, top, the levels LL/LnL_n (an sbral, lazily padded), Γ (one entry per relation), E (suspended constraints), N (λ-disequalities), W (the prefixes of D that reach each variable). ∀° and ⊃° restore depth and Γ on every answer; branches never share it.
  • Unification. micro does the first-order part; the hook applies ξ, η, Rigid, FF-same, FR/FF-diff by variable elimination, and suspends non-patterns: the rules of Rules A.30 with the prefix erased into levels. Patterns are read off levels. Elim prunes and lowers only strict occurrences, fails an occurrence of FF only by Nipkow’s size argument, and suspends whatever a later binding could decide.
  • Check. Every binding is scope-checked at its variable’s level (NJK’s binding rule with pruning), or taken back into E when a non-pattern decides it. Fast paths skip it before any ∀°, on plain terms and for top-level variables. Wake-up retries E in rounds while a round binds, and terminates when hnf does.
  • ∀° and ⊃°. generic runs its body one universe deeper with a new eigenvariable and discharges the residuals on exit (raise, close by ξ, retry, repeat). augment pushes closures on Γ. Dynamic relations backchain on hypotheses first, most recent first, then on their static body; a clause’s free variables are shared, its ∀ variables renamed per use.
  • Stores. ≠° on λ-terms goes to N with a trial whose new variables are existential; D never holds a λ-term, and the prefixes a binding brings one into move to N, found per binding; two readings of ∀\forall, generic (default) and extensional. absent° looks into parts and watches flexible terms; types wait on flexible terms and are decided by their predicate.
  • Answers. β-normal, η-short, binders renamed apart; residual forms sorted, each kept once up to α; residuals as (assert (≐ u v)), (deny ...), (absent? ...), closed with ∀ when they keep an eigenvariable; never a free eigenvariable; ground answers are live terms.