Chapter 10

Anatomy of (aux kanren micro)

What and why

The chapters so far studied what a higher-order logic programming language is: the uniform proofs of hereditary Harrop formulas (Chapter 3), λ-terms as data (Chapter 4 and Chapter 6), higher-order pattern unification (Chapter 7), and, in Chapter 9, how λKanren grafts these features onto a miniKanren Weixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2021; and Weixi Ma, Kuang-Chen Lu, and Daniel P. Friedman. Higher-order logic programming with λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2020. This chapter opens the proposal part of the document. Before deciding how (aux kanren micro) should grow, we need an exact picture of the engine: what a variable is, what a state contains, how unification and the constraint stores interact, how the search interleaves, and how answers are printed. The point is not to explain the code to its author but to put next to each other the facts that matter when the engine is extended: which invariants a new feature must preserve, which parts can be reused from outside, and which parts are closed.

The engine is a μKanren in the sense of Hemann and Friedman Jason Hemann and Daniel P. Friedman. μ\muKanren: A minimal functional core for relational programming. In Proceedings of the 2013 Workshop on Scheme and Functional Programming (Scheme ’13), 2013 (a goal maps a state to a stream of states) with a cKanren-like constraint store holding disequalities, disjoint type tags and absento constraints, in the style of The Reasoned Schemer Daniel P. Friedman, William E. Byrd, Oleg Kiselyov, and Jason Hemann. The Reasoned Schemer. MIT Press, 2nd edition, 2018, kept by variable as faster-miniKanren keeps them. The chapter describes the engine on the master branch of aux after the merge of (aux kanren lambda) (Section 14.4). All references :N are line numbers of src/aux.kanren.micro.scm (1410 lines) at commit c0ff08c. That engine carries the extension protocol of Chapter 11, which commit 26b4708 added; this chapter is about its first-order core and leaves the protocol to Chapter 11. Every Scheme snippet in this chapter was run on that engine with no extension loaded; its output is pasted verbatim below it. The snippets import (aux base), (aux stream), (aux fds sbral) and (aux kanren micro).

Table 10.1: A map of aux.kanren.micro.scm.
linescontentsection
3–33module header, export list, imports
35–74sentinel, tags, variablesSection 10.1
76–176the state record and its invariantsSection 10.2
178–309the extension protocolSection 11.4
311–410records of the variables, viewsSection 10.2 and Section 10.3
412–551the binding site, walks, unificationSection 10.3 and Section 10.4
553–781reification, sorting and projectionSection 10.7
783–1158the stores: posting, handing onSection 10.5
1160–1295goals, combinators, constraint goalsSection 10.6
1297–1381aggregationSection 10.8
1383–1410define-relation, runnersSection 10.6 and Section 10.7

10.1Terms and variables

There is no term datatype: a term is any Scheme value, and the engine gives structure to some of them.

Definition 10.1 (Terms of (aux kanren micro)). A term is one of: a logic variable; an atom (symbol, boolean, '(), character, number, string, or any other Scheme object); a pair (t . u) of terms; a vector of terms; an instance of a CHICKEN record type (define-record) whose slots are terms. Vectors and record instances together are the structures (μkanren-structure?, :392).

A logic variable is a record with a single integer slot (:52, :59):

(define-record μkanren-var index)
(define (μkanren-var-working? α) (and (μkanren-var? α) (<= 0 (μkanren-var-index α))))

The sign of the index separates two kinds of variable:

  • a working variable has index i≥0i \ge 0; it lives during the search, its index is its slot in the substitution, and it prints as _i;
  • a reified variable has index −1,−2,…-1,-2,\dots; it exists only in answers, is created only by reification (Section 10.7), and prints as a Greek letter α, β, …, ω, then α1, …, leaving out λ and μ, which an answer uses as its binder and in its type assertions (:63–74, commit 8046761).

The helper μkanren-var-index>=0 (:61) maps both kinds onto ℕ\mathbb{N}: i↦ii\mapsto i for working variables, −1↦0-1\mapsto 0, −2↦1-2\mapsto 1, … for reified ones.

(write (map make-μkanren-var '(0 1 7 -1 -2 -11 -12 -22 -23))) (newline)
(_0 _1 _7 α β ν ξ ω α1)

The eleventh and twelfth reified variables are ν and ξ, since λ and μ are skipped, and the 22 letters left run out at ω.

Indices are allocated by freshª from a counter in the state (Section 10.6), so along one branch of the search they increase monotonically: the index of a variable is its age, lower meaning older. This fact, invisible to a user, is the most useful one for the λProlog extension.

Pitfall (A variable is a record). A μkanren-var is itself a record-instance?. Every structural walker of the engine therefore tests μkanren-var? before the generic record case (e.g. :438 before :441 in the occurs check, and the explicit (not (μkanren-var? w*)) at :531). Any new walker, such as a scope check, must do the same, or it will descend into a variable as if it were a two-slot structure.

Kanren angle (Indices as levels). λProlog’s GENERIC rule reduces Σ;𝒫⟶∀x G\Sigma; \mathcal{P} \longrightarrow \forall x\,G to c:τ,Σ;𝒫⟶G[c/x]c{:}\tau,\Sigma; \mathcal{P} \longrightarrow G[c/x] for a token cc not in Σ\Sigma [MN p. 39], and the query sigma x\ pi y\ x = y must fail [MN p. 85–86]: with logic variables, a variable created before cc must never be bound to a term containing it. Implementations enforce this with universe indices or levels attached to variables and constants Gopalan Nadathur, Bharat Jayaraman, and Keehang Kwon. Scoping constructs in logic programming: implementation problems and their solution. Journal of Logic Programming, 25(2):119–161, 1995. In (aux kanren micro) the monotone index already is a level boundary: if the eigenvariable is created when the counter is nn, then “created before cc” is exactly “index <n< n”. The prototype of Section 10.9.3 uses precisely this. Index order alone is not enough, though: a variable created after the ∀\forall has exited must not see cc either, and lowering changes a variable’s level after its creation. (aux kanren lambda) therefore keeps a level per variable, in an sbral indexed like S and padded only when the depth changes or the unifier creates a variable of another level (Definition 11.1, Definition 12.4, Section 12.2).

10.2The state

Definition 10.2 (State). A state is a record of nine fields (:128–132):

(define-record-type μkanren-state
  (make-μkanren-state/C vars-count S M C P Tc tags raw X)
  μkanren-state? ...)
(define μkanren-state-empty (make-μkanren-state/C 0 empty/sbral μkanren-M-none empty/sbral empty/sbral '() '() #f '()))
fieldcontentwritten by / read by
vars-countthe next fresh index, i.e. the number of variables introduced on this branchwritten and read by freshª (:1167–1172), and by the aggregations (:1335–1339)
Sthe substitution: a skew-binary random-access list (sbral) of terms or of the sentinel *μkanren-unbound*bound only by μkanren-state-update (:428–454), unbound again only by μkanren-state-forget (:399–402); read by every walk
Mwhich unbound variables the values of S may hold: a pair (m . X), every such variable having an index ≤m\le m or listed in X, at most four of them (:81–84)written with S; read by the binding site, to spare its occurs check (:419–426)
Cthe records of the variables, an sbral indexed like S: for each variable its type tag (A), its absento tags (T), the ids of the prefixes that list it (D), a mark t, and the list W of the variables whose absentos’ data hold it (:86–92)written by the goals that post a constraint and by =°, which empties the record of a variable it binds
Pthe prefixes of the disequality store, an sbral by id; a dropped prefix leaves #f≠°, μkanren-add-prefix (:927–936); =°
Tcthe absento entries keyed on a compound term, (u . tag)absent°; =° when a marked variable is bound
tagstags asserted through Awritten at :1158, read by nobody in the engine (a dead field)
raw#f, or the list (D A T) of stores given as lists from outsidemake-μkanren-state, μkanren-state-with, μkanren-state-unify; the next goal indexes them (:1145–1152)
Xthe slot of the extensionsnever read by the engine (Section 11.4.1)

The three stores of earlier versions, D, A and T, are no longer fields. Since commit 2d2fb4e the constraints are kept by variable, as faster-miniKanren keeps them, and the views μkanren-state-D, μkanren-state-A and μkanren-state-T (:362–389) read the three stores back as lists: D as its prefixes, newest first, A as (var . tag) pairs, T as (term . tag) pairs. Only S, C and P are real sbrals. States are immutable and copied by functional update with keyword arguments (:159–176),

(μkanren-state-with s D: (append D* D))          ; a copy of s with a new D

except at the two hottest sites, μkanren-state-update and freshª, which call the internal μkanren-state-with/S (:144–146) on the substitution and M alone. A copy that replaces S or a store is raw: its stores are kept as the lists given, since they may no longer hold, and the next goal verifies and indexes them as a whole. A copy that replaces only vars-count, tags or X keeps the stores indexed. The positional constructor make-μkanren-state keeps its six-argument signature, (vars-count S D A T tags) with X optional (:137–138), and builds a raw state; the destructuring macro μkanren-state-match (:322–329) binds the views and is no longer used by micro itself.

To see states, we use a small printer (not part of the engine) and run goals on the empty state:

(define (dump s)   ; the fields of a state on one line; a tag is shown by its name
  (for-each (λ (k v) (display k) (display " ") (write v) (display "  "))
            '(vars-count S D A T)
            (list (μkanren-state-vars-count s)
                  (sbral->list (μkanren-state-S s))
                  (μkanren-state-D s)
                  (map (λ (p) (cons (car p) (μkanren-tag-name (cdr p)))) (μkanren-state-A s))
                  (map (λ (p) (cons (car p) (μkanren-tag-name (cdr p)))) (μkanren-state-T s))))
  (newline))
(define (states g) (§->list (g μkanren-state-empty)))   ; every answer state of g

(for-each dump (states (fresh° (q x y) (=° q (list x y)) (≠° x 1) (symbol° y) (absent° 'k x))))
vars-count 3  S ((_1 _2))  D (((_1 . 1)))  A ((_2 . μkanren-tag/sym87))  T ((_1 . k))

The three variables q, x, y are _0, _1, _2; S holds one binding (_0 is bound to the list (_1 _2)); each store holds one constraint, read from the records of _1 and _2. The numeric suffix of a tag name such as μkanren-tag/sym87 is a gensym counter (:44–45): it identifies the tag but its value depends on the program that loaded the module, so the same tag may print with another number in another script.

Proposition 10.3 (The eq?-invariant). States are compared by identity: (define (μkanren-state-equal? s s*) (eq? s s*)) (:152). Unification returns the very same state object when it adds no binding, and a freshly allocated one otherwise (by inspection of :487–515: the non-binding cases call return, which closes over the input state, and only μkanren-state-update allocates).

This is not an optimisation but semantics: every entailment test of the engine reads “unification gave back s” as “the two terms are already equal”. The users are ≠° (:1191: the terms are already equal, so the disequality fails), =° (:1178: nothing new, so nothing to hand on), the re-posting of one prefix (:1099, :1116), the absento test μkanren-tag-unify (:859) and subsumption (:733).

Pitfall (Preserving the eq?-invariant). Any extension that runs inside unification, or after it, must return the input state itself when it changes nothing. A hook that rebuilds the state with μkanren-state-with, which always allocates, on a no-op unification would make (≠° 1 1) look satisfiable. The protocol states this as its invariant E1 (:109).

How the record has grown. The state record was widened in place several times: from (substitution counter) to (S D A T) (commit 61bb868), then vars-count (1e7994e), then tags (d118ddd), then, in October 2026, the records of the variables in place of the lists D, A, T, with raw for the stores given from outside (2d2fb4e), and M (d5b6f34). Each step edited micro, and the early ones the positional state constructions of test/microkanren.scm. No sibling module (arith, date, show, unionfind) ever builds a state: every store so far was added inside micro. This is the precedent the proposal of Chapter 11 had to reckon with; its slot X (26b4708) is the last field added, and the first that micro never reads.

10.3The substitution and the walk

S as an sbral. (aux fds sbral) implements Okasaki’s skew-binary random-access lists: cons/sbral, car/sbral, cdr/sbral in O(1)O(1), sbral-ref and update/sbral in O(log⁡n)O(\log n), length/sbral in O(log⁡n)O(\log n). S stores the most recent variable first: the slot of the working variable of index ii sits at position ℓ−1−i\ell-1-i, where ℓ\ell is the length of S (μkanren-var-index/sbral, :312). Extending S at the front with cons/sbral therefore keeps the positions of older variables valid when counted from the end.

Lazy extension. freshª does not touch S. Binding the variable of index ii first pads S with the sentinel *μkanren-unbound* until it has a slot ii (μkanren-var-extend/sbral, :315–320). Hence ℓ=1+max⁡{bound index}\ell = 1+\max\{\text{bound index}\}, and a variable whose index is ≥ℓ\ge \ell is unbound without having a slot.

(for-each dump (states (fresh° (a b c d) (=° c 5))))
vars-count 4  S (5 #<aux.kanren.micro#μkanren-unbound> #<aux.kanren.micro#μkanren-unbound>)  D ()  A ()  T ()

Four variables were introduced but S has three slots: c (index 2) is bound to 5 at the front, a and b hold the sentinel, d (index 3) lies beyond S.

Definition 10.4 (Walk). Let ℓ\ell be the length of S. The walk of a term tt (μkanren-state-find/SL, :459–465) is computed by the loop F(β0,β)F(\beta_0,\beta), started with β0=β=t\beta_0=\beta=t:

  1. if β\beta is a variable with idx(β)≥ℓ\mathit{idx}(\beta) \ge \ell (with idx\mathit{idx} == μkanren-var-index>=0), answer β\beta (unbound, no slot);
  2. if β\beta is a working variable, continue with F(β,S[ℓ−1−i])F(\beta, S[\ell-1-i]);
  3. if β\beta is the sentinel, answer β0\beta_0, the last variable visited;
  4. otherwise answer β\beta.

Case 4 catches non-variables but also reified variables, which are not working: to the walk a reified variable is a constant. Bindings are triangular (S maps a variable to a term that may contain bound variables) and the walk never compresses paths. The variant with explicit S and l hoists the O(log⁡n)O(\log n) length/sbral out of deep traversals; μkanren-state-find (:467–468) computes it once.

Deep walks. Three exported procedures resolve a term completely:

  • μkanren-state-find/value (:524–535) returns a Scheme value, rebuilding pairs with cons, vectors with list->vector and records with (apply make-record-instance slots), or through the value hook for a record of an extension (Section 11.4.3); unbound variables stay μkanren-var records;
  • μkanren-state-find/values (:1298) maps it over a list (the key of an aggregation group);
  • μkanren-state-find/repr (:537–551) returns an expression that rebuilds the value: a variable becomes its symbol, a symbol 'sym, a pair (cons a d), a vector (vector ...), a record (make-record-instance 'type ...).

Pitfall (Deep walks rebuild records). Because find/value rebuilds every record, the value it returns is equal? but not eq? to the record that was unified. Here a record c of the type eigen of Section 10.9.3 is bound to q and read back:

(let* ((c (make-eigen 99)) (r (car (§->list ((fresh° (q) (=° q c)) μkanren-state-empty))))
       (v (μkanren-state-find/value (make-μkanren-var 0) r)))
  (pretty-print (list (eq? v c) (equal? v c) (eigen? v))))
(#f #t #t)

Constructed terms must be compared with predicates and equal? (or by an id slot), never with eq?; Section 10.9.3 shows a scope check that goes wrong exactly this way.

10.4Unification

10.4.1Binding and the occurs check

Exactly one procedure creates a binding (:428–454, abridged):

(define (μkanren-state-update α v s assocs #!optional held)
  (define (walk M) ...)   ; M admitting the walk of v too, or #f if α occurs in it
  (let* ((M (μkanren-state-M s))
         (M* (if (and held (not (μkanren-M-admits? M (μkanren-var-index α)))) M (walk M))))
    (cond
      (M* (let* ((S* (μkanren-update/sbral α v (μkanren-state-S s)))
                 (s* (μkanren-state-with/S s (μkanren-state-vars-count s) S* M*))
                 (assocs* (cons `(,α . ,v) assocs)))
            `(,s* ,assocs*)))
      ; an occurrence inside an extension's term may be only apparent: the extension decides.
      ((pair? μkanren-extensions) (μkanren-extension/occurs α v s assocs))
      (else #f))))

It answers #f if α\alpha occurs in vv (the occurs check walks vv, its pairs and its structures through S), otherwise the pair (s* assocs*). The list assocs accumulates the bindings made by the current unification as (var . term) pairs: this is cKanren’s “prefix”.

The occurs check is not always run. M records which unbound variables the values of S may hold (:81–84): every such variable has an index at most mm or is one of the at most four indices of the window X (μkanren-M-admit, :419–426). When vv is held, a part of a value already in S as every walked term that differs from its source is, and M does not admit α\alpha, then α\alpha cannot occur in vv, and the walk is spared (commit d5b6f34). Otherwise the walk looks for α\alpha and makes M admit the unbound variables it meets, which the binding writes into S. On append° backwards, whose bindings take the tails of a ground list already in S, this spares a walk of the tail at every step. The last clause is the protocol’s: with an extension registered, a failed occurs check is handed to its occurs hook (Section 11.4.3).

The procedure is not exported; it is the only place where a binding can be refused before it enters the state, e.g. for violating a scope; a check run right after each =°, before the next goal, works as well (the route the protocol takes, Section 11.4.3).

10.4.2The unification algorithm

Definition 10.5 (Unification, :483–515). (μkanren-unify u v s assocs) walks both sides to u∗u^*, v∗v^* and tries these cases in order:

  1. u∗eq?v∗u^* \mathrel{\texttt{eq?}} v^*: success, nothing bound;
  2. two strings that are string=?: success;
  3. two numbers that are μkanren-number-eqv? (:473–478: eqv?, but two NaN flonums are equal and non-real numbers are compared part by part): success;
  4. two working variables of indices i,ji, j: if i=ji=j success; if i<ji<j bind u∗:=v∗u^* := v^*, else v∗:=u∗v^* := u^*, i.e. the older variable is bound to the newer one;
  5. one working variable: bind it to the other side;
  6. two structures: unify the lists of their slots (μkanren-structure->list, :393), where record->vector puts the record’s type name first, unless an extension owns one of them;
  7. two pairs: unify the cars, then the cdrs in the resulting state;
  8. an extension’s term against a pair or an atom: the extension’s unify hook;
  9. otherwise fail with #f.

The result is (s* assocs*) or #f. With assocs == '(), the second component is exactly the list of new bindings. The cases are those of μkanren-unify/held (:487–515), which also passes down whether each side is held, for the binding site. With no extension registered, cases 6 and 8 cost a test of the empty registry.

Two procedures give this algorithm to the outside. μkanren-unify (:483) answers a state whose stores are as they were: the bindings it reports must go through μkanren-post-unify (Section 10.5.4), as =° does, unless the answer is a trial thrown away; it is exported for the hooks of extensions. The older export μkanren-state-unify (:519–522) answers a raw state instead, whose stores are lists that the next goal verifies and indexes as a whole.

Read as rules, the algorithm is the standard first-order syntactic one with occurs check; what is specific to (aux kanren micro) is (a) the orientation of variable–variable bindings, (b) structures, (c) the treatment of atoms. The exported μkanren-state-unify can be called by hand:

(define q (make-μkanren-var 0))
; a state where _0 exists
(define s0 (μkanren-state-with μkanren-state-empty vars-count: 1))

(define r (μkanren-state-unify q '(1 2) s0 '()))
(pretty-print (cadr r))                                         ; the new bindings
(define r2 (μkanren-state-unify q '(1 2) (car r) '()))
; nothing new: the very same state
(pretty-print (list (eq? (car r2) (car r)) (cadr r2)))
(pretty-print (μkanren-state-unify q (list 1 q) s0 '()))        ; occurs check
((_0 1 2))
(#t ())
#f

The first line is the one-element prefix ((_0 . (1 2))), printed as Scheme prints it; the second shows Proposition 10.3 at work; the third is the occurs check.

Orientation. Unifying two fresh variables binds the older to the newer:

(for-each dump (states (fresh° (a b) (=° a b))))
vars-count 2  S (_1)  D ()  A ()  T ()

S has one slot, the one of _0, and it holds _1. A level discipline in the style of λProlog would prefer the opposite orientation for a variable–variable pair (bind the younger variable to the older one, so that such a binding never moves a variable out of its scope). Flipping the orientation would not be enough, though: in sigma X\ pi y\ sigma Z\ (X = f Z, Z = y) the binding X:=f ZX := f\,Z makes the young ZZ reachable from the old XX, so a real level discipline must also lower the level of every variable of a term bound to an older variable (this is the shape of the fourth query of Section 10.9.3, with list for ff). With the orientation of (aux kanren micro) an old variable can moreover be aliased to a young one, and a scope check must look through such chains (Section 10.9.3).

Structures and atoms. Records unify as the list of their slots, so any define-record is a new term constructor for free; but a record and a vector with the same slot list unify too. Numbers are compared with eqv?, so an exact and an inexact number never unify.

(define-record dbi n)
(pretty-print (record->vector (make-dbi 3)))
(pretty-print (°->list #f (fresh° (q) (=° (make-dbi q) (vector 'dbi 7)))))
(pretty-print (°->list #f (fresh° (q) (=° (vector 1 q) '(1 2)))))
(pretty-print (°->list #f (fresh° (q) (=° (/ 0. 0.) (/ 0. 0.)) (=° "ab" (string #\a #\b)) (=° q 'ok))))
(pretty-print (°->list #f (fresh° (q) (=° 1 1.0) (=° q 'ok))))
#(dbi 3)
((λ () 7))
()
((λ () 'ok))
()

In order: the slot list of a record starts with its type name; a dbi record unifies with the vector #(dbi 7); a vector never unifies with a list; NaN equals NaN and equal strings unify although they are distinct objects; 1 and 1.0 do not unify. Anything else (procedures, bytevectors, …) unifies only with itself under eq?.

Pitfall (Procedures are opaque). A Scheme closure is an atom compared with eq?. Higher-order abstract syntax with real Scheme procedures (the λProlog abs x\ ... rendered as (λ (x) ...)) cannot be unified, walked, constrained or reified. λ-terms must be first-order data, e.g. de Bruijn records such as dbi above (Chapter 6).

Kanren angle (Where higher-order unification would go). Without its cases 6 and 8 the cond of Definition 10.5 is closed: no dispatch table, no hook, which is how it stood before commit 26b4708. A new term kind with syntactic equality needs nothing (it is a record); a term kind with a different equality, such as LλL_\lambda flexible terms F x1…xnF\,x_1\dots x_n solved by pattern unification (Chapter 7) or nominal terms with suspended swappings William E. Byrd and Daniel P. Friedman. α\alphaKanren: A fresh name in nominal logic programming. In Proceedings of the 2007 Workshop on Scheme and Functional Programming, Université Laval Technical Report DIUL-RT-0701, pages 79–90, 2007; and Christian Urban, Andrew M. Pitts, and Murdoch J. Gabbay. Nominal unification. Theoretical Computer Science, 323(1–3):473–497, 2004, needs either a new clause here (before case 6) or a goal that solves the problem outside and emits ordinary bindings (Section 10.9.2). The choice between them is made in Chapter 11; cases 6 and 8 are the clauses it chose.

10.5The constraint stores and their re-verification

Unification only binds; the three stores keep negative and type information, and must be re-checked whenever a binding is made. They are kept by variable: a constraint is filed in the record of the variables it waits on, and a binding hands on the constraints of the variable it binds, and those only. The records keep six invariants, I1–I6, stated in the comment of the state record (:98–106); the first is that a variable with a record is unbound.

10.5.1D: disequalities

Definition 10.6 (Prefix). A prefix is a list d=((x1.t1)…(xk.tk))d = ((x_1 . t_1) \dots (x_k . t_k)) of variable–term pairs; it denotes the constraint ¬(x1=t1∧⋯∧xk=tk)\neg(x_1 = t_1 \wedge \dots \wedge x_k = t_k). The store D is the list of prefixes of P that are not dropped, newest first (μkanren-state-D, :362–365), read as their conjunction.

The goal (≠° u v) (:1185–1192) runs a trial unification of uu and vv with an empty assocs and reads the result:

  • #f: uu and vv can never be equal, so the constraint is dropped and the goal succeeds with the state unchanged;
  • the very same state (Proposition 10.3): uu and vv are already equal, so the goal fails;
  • a new state with bindings dd: the goal succeeds with the old state extended by the prefix dd (μkanren-add-prefix, :927–936), unless a type tag or an absento in the record of a left side makes dd vacuous (subsumption, below). The new prefix gets the next id of P, and the records of its left sides, and of its right sides that are variables, list that id.

A tuple disequality gives one prefix with several pairs. When =° binds a variable, the prefixes that its record lists are posted again (μkanren-repost-prefixes, :1105–1117) by a trial unification of their pairs: if the trial fails the prefix is satisfied forever and dropped; if it adds nothing the prefix is violated and the =° fails; otherwise the prefix is replaced by its normalised version, the new trial bindings, under a new id.

Tutorial (The life of a tuple disequality). We assert (x,y)≠(1,2)(x,y) \ne (1,2) and then bind xx, watching D.

(for-each dump (states (fresh° (q x y) (=° q (list x y)) (≠° (list x y) '(1 2)))))
(for-each dump (states (fresh° (q x y) (=° q (list x y)) (≠° (list x y) '(1 2)) (=° x 1))))
(for-each dump (states (fresh° (q x y) (=° q (list x y)) (≠° (list x y) '(1 2)) (=° x 3))))
(write (states (fresh° (q x y) (=° q (list x y)) (≠° (list x y) '(1 2)) (=° x 1) (=° y 2)))) (newline)
vars-count 3  S ((_1 _2))  D (((_2 . 2) (_1 . 1)))  A ()  T ()
vars-count 3  S (1 (_1 _2))  D (((_2 . 2)))  A ()  T ()
vars-count 3  S (3 (_1 _2))  D ()  A ()  T ()
()
  1. The trial unification of (_1 _2) with (1 2) would bind both variables, so D holds the single prefix ((_2 . 2) (_1 . 1)): “not both”. The records of _1 and _2 list it.
  2. After (=° x 1), the record of _1 hands the prefix on; the trial now binds only _2, and the prefix is normalised to ((_2 . 2)): the constraint has become y≠2y \ne 2.
  3. After (=° x 3) the trial fails: the prefix can never be violated and disappears.
  4. After (=° x 1) and (=° y 2) the trial binds nothing: the prefix is violated and the goal has no answer state.

Incremental re-verification. After an =°, only the prefixes listed in the records of the variables just bound are posted again (μkanren-repost, :1129–1141); the assocs returned by unification is exactly the list needed to find them, and a variable without a record costs its lookup. An unlisted prefix cannot have become violated: its left sides are unbound (I2), and since none of them was just bound, its trial unification would still bind its first left side. It may, however, have become satisfied through the occurs check deep in its terms; projection runs one last full μkanren-verify-D to drop those (:771).

10.5.2A: disjoint type tags

A tag is a record (name def pred) (:38): an identity, the quoted source of a predicate (printed in answers), and the predicate itself. Type tags are made with define-μkanren-tag (:44–45), whose comment asks that a tag hold atoms only, infinitely many of them, and none that another tag holds (:40–43). They are turned into goals by μkanren-make-tag-A (:1154–1158); the built-in ones are (:1259–1270)

(define-μkanren-tag (μkanren-tag/sym v) (symbol? v))
(define-μkanren-tag (μkanren-tag/num v) (number? v))
(define symbol° (μkanren-make-tag-A μkanren-tag/sym))
(define number° (μkanren-make-tag-A μkanren-tag/num))

On a bound term the goal just tests the predicate (μkanren-post-type, :985–991); on an unbound variable it writes the tag into the variable’s record. Tags are mutually exclusive: μkanren-post-A (:976–981) answers #f when the variable already carries a different tag. Adding a tag also drops the prefixes of the variable that it makes vacuous (μkanren-subsume-prefixes, :947–950: a pair (α . u) whose α\alpha is tagged by a predicate rejecting uu; this is I4).

(for-each dump (states (fresh° (q) (≠° q 'a) (number° q))))
(write (states (fresh° (q) (number° q) (symbol° q)))) (newline)
vars-count 1  S ()  D ()  A ((_0 . μkanren-tag/num88))  T ()
()

A number can never be the symbol a, so the disequality is gone; and no term is both a number and a symbol.

10.5.3T: absento

(absent° datum term) (:1286–1290; note the argument order) states that datum, which may be any Scheme value, atomic or compound, ground or not, does not occur in term. A ground datum makes an ad-hoc tag whose name is the datum itself (μkanren-absento+, :1008–1030): the tag is filed in the record of a variable term, or, for a compound that could still become the datum, in Tc, where the compound is “watched whole” and decomposed only when it no longer can (:1034–1042). A datum with variables is posted as faster-miniKanren posts it, as disequalities with the nodes of the term until its walk is ground (μkanren-absento/term+, :1050–1070, commit 9cecddf). When a watched variable is bound, the constraint moves to the parts:

(for-each dump (states (fresh° (q x y) (absent° 'k q) (=° q (list x y)))))
(write (states (fresh° (q x y) (absent° 'k q) (=° q (list x y)) (=° y 'k)))) (newline)
vars-count 3  S ((_1 _2))  D ()  A ()  T ((_2 . k) (_1 . k))
()

When a variable carrying an absento gets a type tag, the absento is converted into a disequality (e.g. symbol° α plus absent° 'closure α becomes the prefix ((α . closure))), by μkanren-convert-T and μkanren-ext-D (:953–972); this is I3. The conversion happens for any tag, but μkanren-add-prefix does not take a prefix that the tag makes vacuous:

(for-each dump (states (fresh° (q) (absent° 'closure q) (symbol° q))))
(for-each dump (states (fresh° (q) (absent° 'closure q) (number° q))))
(pretty-print (°->list #f (fresh° (q) (absent° 'closure q) (number° q))))
vars-count 1  S ()  D (((_0 . closure)))  A ((_0 . μkanren-tag/sym87))  T ()
vars-count 1  S ()  D ()  A ((_0 . μkanren-tag/num88))  T ()
((λ (α) (assert (every (μ v (number? v)) (list α))) α))

For a symbol the prefix is meaningful (q≠𝖼𝗅𝗈𝗌𝗎𝗋𝖾q \ne \mathsf{closure}); for a number it is vacuous, and D does not hold it. (In the micro of f53bdcb, before the records, the vacuous prefix stayed in D until projection dropped it.)

10.5.4The post-unification chain

The goal =° (:1174–1183) is where everything meets:

(define ((=° u v) s)
  (define post°
    (λ1-match/first
      ((,s* ,assocs)  (cond
                        ((μkanren-state-equal? s s*) (✓° s*))      ; nothing bound: done
                        ((μkanren-post-unify s* assocs) => ✓°)    ; hand the constraints on
                        (else (✗° s*))))))
  (cond
    ((μkanren-unify u v s '()) => post°)
    (else (✗° s))))

After a unification that binds something, μkanren-post-unify (:261–269) runs the post hooks of the registered extensions, none in this chapter, then μkanren-repost (:1129–1141), or indexes the stores of a raw state. μkanren-repost takes the bound variables in turn, and for each one that has a record:

its record is emptied (I1) →\to its prefixes are posted again →\to its type tag is posted again on its walk →\to its absento tags likewise →\to the absentos whose datum holds it are posted again on their keys (I6),

and, if one of them was marked as reachable from a compound key of Tc, the entries of Tc are verified again at the end (I5). Nothing else is looked at: a store is no longer re-verified in full after a binding, as A and T were before the records. The whole chain is skipped when nothing was bound (Proposition 10.3).

Kanren angle (A new store had nowhere to plug in). In micro alone there is no list of verifiers to which a new store could append itself: the chain is a fixed sequence of procedures wired for D, A and T. λProlog features that need state of their own all hit this wall: a dynamic program for AUGMENT [MN p. 39], scope information for GENERIC, a store of postponed non-pattern equations that must be woken after each binding (Chapter 7). What such a store requires of the engine is (i) a place in the state that every goal copies forward, (ii) a call after each binding with the new assocs, (iii) a say in reification. Section 10.9.2 shows how far one gets without (ii) and (iii); Chapter 11 gives the protocol that provides all three, the slot X, the post hook that μkanren-post-unify runs, and the hooks of reification.

10.6.1Streams and goals

Definition 10.7 (Streams and goals). A stream ((aux stream)) is '(), a mature pair (state . stream), or an immature CHICKEN promise made with δ (delay, memoising). A goal is a procedure from a state to a stream of states. A relation is a procedure from terms to a goal.

The primitives (:1160–1253; an excerpt, comments ours) are few:

; succeed once with the given state
(define ✓° list)
(define ✗° (K '()))                                    ; fail
(define ((freshª f) s)
  (let* ((vc  (μkanren-state-vars-count s))
         (α   (make-μkanren-var vc))
         (g   (f α))                                   ; the body is built only now
         (s*  (μkanren-state-with/S s (add1 vc) (μkanren-state-S s) (μkanren-state-M s))))
    (δ (g s*))))                                       ; and suspended
(define ((orª f g) s) (append§/interleaved/2 (δ (f s)) (δ (g s))))

((andª f g) s) is (append-map§ g (δ (f s))), but it is not written so. In a chain nested to the left, as and° builds it, each bind would wrap again every promise of the binds inside it, so a chain of nn binds would cost n2n^2. Since commit d5b6f34 a goal made by andª keeps the innermost goal and the others of its chain as its procedure data, and runs them in one fold (:1195–1218):

(define (andª f g)
  (let1 (c (procedure-data f))
    (if (μkanren-binds? c)                             ; f is a chain: extend it
        (let* ((c* (make-μkanren-binds (μkanren-binds-goal c) (cons g (μkanren-binds-gs c))))
               (gs (δ (reverse (μkanren-binds-gs c*)))))
          (extend-procedure (λ (s) (μkanren-and/fold (μkanren-binds-goal c*) (force gs) s)) c*))
        (extend-procedure (λ (s) (append-map§ g (δ (f s)))) (make-μkanren-binds f (list g))))))

μkanren-and/fold makes the promises the nested binds would make and then folds the goals over the stream with append-map§/fold of (aux stream), so the answers and their order are those of the nested binds; a chain of nn bindings costs nn, up to the first answer that reaches a bind with a promise pending behind it (the comment at :1195–1203 gives the limits). The suffix ª marks the applicative procedure behind a macro; ° marks a goal, a goal-making macro or a relation. Interleaving lives in (aux stream) (aux.stream.scm:87–92):

(define append§/interleaved/2
  (λ (s1 s2)
    (cond
      ((null? s1) s2)
      ; SWAP on suspension
      ((promise? s1) (δ (append§/interleaved/2 s2 (force s1))))
      (else (cons§ (car s1) (append§/interleaved/2 (cdr s1) s2))))))

When the left stream is suspended, the two streams swap places; this is what makes disjunction complete, and every δ is a point where control can pass to another branch.

The macros (:1223–1241, :1295). (fresh° (x y) g ...) nests one freshª per variable, each suspending once; (fresh° q ← (a b) g ...) also binds q to (list a b). and° is left-nested, (and° g1 g2 g3) == (andª (andª g1 g2) g3); or° is right-nested, (or° g1 g2 g3) == (orª g1 (orª g2 g3)). cond° is conde: (or° (and° g ...) ...), with no else. null°, boolean°, cons° are one-liners over =° and or°.

Tutorial (Fairness, and its shape). Two infinite generators in a disjunction share the answers:

(define-relation (nat° n) (or° (=° n 'z) (fresh° (m) (=° n `(s ,m)) (nat° m))))
(write (°->list/ground (take° 6 (fresh° (q) (or° (fresh° (n) (nat° n) (=° q `(left ,n)))
                                                (fresh° (n) (nat° n) (=° q `(right ,n)))))))) (newline)
((left z) (right z) (left (s z)) (right (s z)) (left (s (s z))) (right (s (s z))))

The interleaving is fair between two branches, but or° nests to the right, so with three branches the first one competes against the pair of the other two:

(define-relation (numb° n k) (or° (=° n k) (numb° n (+ k 1))))
(write (°->list/ground (take° 12 (fresh° (q) (fresh° (n)
          (or° (and° (numb° n 0) (=° q (list 'a n)))
               (and° (numb° n 0) (=° q (list 'b n)))
               (and° (numb° n 0) (=° q (list 'c n))))))))) (newline)
((a 0) (a 1) (b 0) (a 2) (c 0) (a 3) (b 1) (a 4) (c 1) (a 5) (b 2) (a 6))

In the long run branch a gets half of the answers, b and c a quarter each (here 7, 3 and 2 of the first 12). Conjunction, on the other hand, is not fair: (and° generator failing-test) diverges, so as in every miniKanren generators go before tests and recursive calls last. For instance, the append° of Section 10.7 with its recursive call placed before (cons° a c rs) still finds the four splits of (1 2 3), but then searches forever for a fifth one under an unbounded run, while the order shown there terminates.

10.6.2define-relation and the inverse-η delay

Because and° and or° expand into procedure calls of andª and orª, their goal arguments are evaluated when the goal tree is built, before any state exists. A recursive relation written with plain define whose recursive call is not under a fresh° therefore builds an infinite tree:

(define (ones° x) (or° (=° x 1) (ones° x)))          ; plain define: no delay
(write (°->list/ground (take° 3 (fresh° (q) (ones° q))))) (newline)

Run under timeout 10, this prints nothing and is killed (exit=124). The macro of :1387 applies an inverse-η expansion and a suspension:

(define-syntax-rule (define-relation (name arg ...) g ...) (define (name arg ...) (λ (s) (δ ((and° g ...) s)))))

so the body is built only when the goal meets a state, and then suspended:

(define-relation (ones° x) (or° (=° x 1) (ones° x)))
(write (°->list/ground (take° 3 (fresh° (q) (ones° q))))) (newline)
(1 1 1)

Plain define remains fine when every recursive call sits under a fresh°, whose body is under λ (α); the relational interpreter of test/microkanren-untagged.scm is written that way.

Pitfall (Answer order is observable). Each fresh° variable and each relation call adds a suspension, or° adds two. The test suites pin the raw answers, including their order. A new goal that adds or removes a single δ (for example a new =°-like goal) can permute the answers of existing suites.

10.6.3Soft cut, bounded runs, escape to Scheme

(if° g? gt gf) (:1244–1250) is LogicT’s ifte, i.e. miniKanren’s conda for one clause: if g? has at least one answer, all its answers are continued with gt; otherwise gf runs on the original state. (take° n g) (:1253) keeps the first nn answers of g (all of them if n<0n<0); (take° 1 g) is once. With gt == ✗° and gf == ✓°, if° is negation as failure:

(write (°->list/ground (fresh° (q) (if° (or° (=° q 1) (=° q 2)) ✓° (=° q 3)))))
(newline)
(write (°->list/ground (fresh° (q) (if° ✗° ✓° (=° q 3))))) (newline)
(write (list (°->list/ground (fresh° (q) (=° q 1) (if° (=° q 2) ✗° ✓°)))
             (°->list/ground (fresh° (q) (=° q 2) (if° (=° q 2) ✗° ✓°)))
             (°->list/ground (fresh° (q) (if° (=° q 2) ✗° ✓°))))) (newline)
(write (°->list/ground (fresh° (q) (take° 2 (nat° q))))) (newline)
(1 2)
(3)
((1) () ())
(z (s z))

The third line exhibits the classic unsoundness: with q unbound, “q is not 2” fails, because the test succeeds by binding q.

λProlog’s if and not are defined with the cut [MN p. 137]:

type if   o -> o -> o -> o.
if P Q R :- P, !, Q.
if P Q R :- R.

type not  o -> o.
not P :- P, !, fail.
not P.

and the book’s example of their non-logical character, “?- X = 2, not (1 = X). succeeds, whereas ?- not (1 = X), X = 2. fails” [MN p. 137–138], behaves the same way with if°. There is one difference: the cut keeps only the first proof of P, while if° keeps all the answers of its test, so λProlog’s if P Q R is (if° (take° 1 P) Q R):

; X = 2, not (1 = X)
(write (list (°->list/ground (fresh° (q) (=° q 2) (if° (=° 1 q) ✗° ✓°)))
             ; the converse
             (°->list/ground (fresh° (q) (if° (=° 1 q) ✗° ✓°) (=° q 2)))))
(newline)
(write (list (°->list/ground (fresh° (q) (if° (or° (=° q 1) (=° q 2)) ✓° ✗°)))
             (°->list/ground
               (fresh° (q) (if° (take° 1 (or° (=° q 1) (=° q 2))) ✓° ✗°)))))
(newline)
((2) ())
((1 2) (1))

(project° ((x* x) ...) g ...) (:1292–1293) binds Scheme variables to the deep-walked values of logic terms and runs g ...: the non-relational escape hatch. An unbound variable is seen as a μkanren-var record.

(write (°->list/ground (fresh° (q x) (=° x 20) (project° ((x* x)) (=° q (* 2 x*)))))) (newline)
(pretty-print (°->list #f (fresh° (q x) (project° ((x* x)) (=° q (list (μkanren-var? x*) (μkanren-var-index x*)))))))
(40)
((λ () (cons #t (cons 1 '()))))

Kanren angle (AUGMENT and GENERIC as goals). A goal sees the whole state and returns a stream of states, so it can do more than =° does: it can change the state on entry and post-process every answer state on exit. That is the shape that both D⊃GD\supset G (add DD, solve GG, then restore the program on every answer of GG) and ∀x G\forall x\,G (create cc, solve GG, then check that cc did not escape) require [MN p. 39]. The two prototypes of Section 10.9.2 are written exactly this way, with append-map§ over the answers of GG, and so are the ∀° and ⊃° of (aux kanren lambda) (Section 12.4).

10.7Reification and the runners

10.7.1From a state to a λ-expression

An answer is not a substitution but a closed Scheme expression

(λ (α β ...) constraint-form ... term)

which, applied to values for the free variables, re-checks the constraints with assert and deny and returns the term. It is built by μkanren-project (:762–781) in six steps:

  1. deep-walk the query term;
  2. name its free variables in order of first occurrence (left to right, car before cdr) by binding each of them to a fresh reified variable −1,−2,…-1,-2,\dots in a scratch state (μkanren-state-reify, :554–569), then those of the residual constraints of the extensions;
  3. re-verify D in full;
  4. purify: drop every constraint that mentions a variable unreachable from the answer (still working in the scratch state, μkanren-anyvar?, :679–686); this is sound for disequalities, since such a variable can always be chosen to satisfy them (commit f569f8d applies it to every disequality that reaches such a variable), and T is projected part by part (:688–705);
  5. drop the prefixes subsumed by others or made vacuous by a tag (:757–760, :821–828);
  6. render with μkanren-form (:590–600), sorting the pairs of each prefix, the prefixes and T by their printed forms (:602–626), so that an answer does not depend on the order in which the stores were filled (commits c52c365, aaa50d0); the extensions’ forms follow micro’s.
storeform in the answer
D, prefix of one pair(begin (deny (equal? α <repr>)))
D, prefix of nn pairs(begin (deny (and (equal? α ...) (equal? β ...))))
A, grouped by tag(assert (every (μ v (symbol? v)) (list α γ)))
T(assert (absent? '<datum> <repr>))
(pretty-print (°->list #f (fresh° (q x y) (=° q (list x y)) (≠° x 'a) (symbol° x) (absent° 'z y))))
(pretty-print (°->list #f (fresh° (q x y) (=° q (list x y)) (≠° (list x y) '(1 2)))))
(pretty-print (°->list #f (fresh° (q) (fresh° (h) (≠° h 3) (=° q 7)))))
(pretty-print (°->list/ground (fresh° (q x) (=° q (list x 1)) (≠° x 2))))
((λ (α β)
    (begin (deny (equal? α 'a)))
    (assert (every (μ v (symbol? v)) (list α)))
    (assert (absent? 'z β))
    (cons α (cons β '()))))
((λ (α β)
    (begin (deny (and (equal? α 1) (equal? β 2))))
    (cons α (cons β '()))))
((λ () 7))
((α 1))

The third answer shows purification: the disequality on the unreachable h is gone. The fourth shows grounding: °->list/ground evaluates only (lambda vars term), dropping the constraints, and applies it to the variable symbols themselves, so the free variable reads back as the symbol α. The show module (aux kanren micro show) parses the answer forms back without eval (aux.kanren.micro.show.scm:73–106), so a new kind of constraint in answers needs a case there too, or, since commit e97f7ef, a show extension that reads it (Section 11.4.8).

10.7.2Running

The runners are at :1383–1410:

(define (°->§ g)
  (let* ((§ (δ (g μkanren-state-empty)))
         (P (μkanren-project (make-μkanren-var 0))))
    (map§ P §)))
(define-syntax-rule (μkanren-run (v n grounded) g ...) (°->list grounded (take° n (fresh° (v) g ...))))

(°->list grounded g) forces °->§ and, if grounded, evals each answer in micro’s own module environment, or in the one an extension names; °->list/ground is (°->list #t g). μkanren-run is the TRS-like run, with n<0n<0 meaning “all”. The query variable is always the variable of index 0, i.e. the first one the goal introduces. With the usual append°:

(define-relation (append° r s rs)
  (cond°
    ((null° r) (=° s rs))
    ((fresh° (a d c) (cons° a d r) (cons° a c rs) (append° d s c)))))
(pretty-print (μkanren-run (q -1 #t) (fresh° (x y) (append° x y '(1 2 3)) (=° q (list x y)))))
(pretty-print (μkanren-run (q 3 #f) (fresh° (x y z) (append° x y z) (=° q (list x y z)))))
((() (1 2 3)) ((1) (2 3)) ((1 2) (3)) ((1 2 3) ()))
((λ (α) (cons '() (cons α (cons α '()))))
 (λ (α β) (cons (cons α '()) (cons β (cons (cons α β) '()))))
 (λ (α β γ)
    (cons (cons α (cons β '())) (cons γ (cons (cons α (cons β γ)) '())))))

Pitfall (The query variable is index 0). °->§ hard-wires the empty initial state and projects variable 0. An extension that reserves indices (for eigenvariables, registers, …) before the first fresh° shifts the query variable; a module that needs a richer initial state needs its own runner, which is easy since make-μkanren-var and μkanren-project are exported.

Kanren angle (What answers will have to show). Eigenvariables and a dynamic program never appear in micro’s own answers. If a ≠° mentioning an eigenvariable survives its scope, or a postponed higher-order equation is left at the end, reification must either drop it or print it; purification (step 4) does not know about scopes. See Section 10.9.3 for an example, Chapter 11 for the hooks that let an extension print its constraints, and Section 12.6 for how (aux kanren lambda) uses them.

10.8Aggregation

Four SQL-like goals (:1297–1381) consume the whole answer stream of a sub-goal with a fold and turn it into Scheme data, so the sub-goal must be finite and the goals are non-relational (findall/bagof-like). groupby° groups the answers of g by the values of the keys and runs the continuation once per group on the original state, with the aggregate and the key names bound as Scheme variables; window° is OVER (PARTITION BY ...) and runs the continuation on each answer state of g; set° folds per key; enumerate° numbers the answers in stream order. Three recent commits fixed details that matter to an extension: each aggregated column keeps values of its own (f8f28b7); the groups of set° and groupby° come in the order of their first state (a0382e3, :1300–1308), not in the order of a hash table’s buckets; and the bodies of set°, groupby° and enumerate°, which run on the outer state, count the variables of the from goal as introduced (5f406fd, μkanren-key-of/counting, :1331–1339), so a fresh° in a body cannot reuse their indices.

(pretty-print (°->list/ground (fresh° (q) (fresh° (k v)
   (groupby° (((vs (λ (l) l)) v)) over (k) from
             (or° (and° (=° k 'a) (=° v 1)) (and° (=° k 'b) (=° v 2)) (and° (=° k 'a) (=° v 3)))
             => (=° q (list k vs)))))))
((a (1 3)) (b (2)))

The group of a, whose first state comes first, answers first. They are the precedent for goals that run a sub-search to completion, the mechanism a findall-style predicate would use.

10.9Extension points

10.9.1Open versus closed

Table 10.2 sorts the parts of micro’s first-order core by whether an importing module can use or extend them without editing aux.kanren.micro.scm. It is the inventory that the design of Chapter 11 started from, read on the core of commit c0ff08c: the right column is what an edit of micro was needed for, and the protocol of commit 26b4708 is that edit (Table 11.6 maps each closed entry to the hook that opens it).

open (usable from outside)closed (needs an edit of micro)
Goals are plain procedures state →\to stream; the accessors of vars-count, S, tags and X and of the views D, A, T, and μkanren-state-with, are exported.The field list of the state (:128–132), its constructors (:137–150, :170–176, :1148–1149), the records of the variables (:336–348).
Raw unification μkanren-state-unify returns the new state and the exact new bindings (its stores as lists, which the next goal verifies).The unification cond (:487–515): no clause of its own for a term kind with non-syntactic equality.
Walks μkanren-state-find, /value, /values, /repr.The binding site with occurs check, μkanren-state-update, unexported: the only place to refuse a binding before it enters the state (a check right after each =° works as well, Section 11.4.3).
Variables: make-μkanren-var, μkanren-var-index, …; a fresh unique integer by bumping vars-count.The post-=° chain (μkanren-repost, :1129–1141), wired for D/A/T, its pieces unexported.
New first-order constructors: any define-record unifies, reifies, works with ≠° and absent°.Reification (:762–781, :590–600): knows only D/A/T; purification and subsumption are store-specific.
New disjoint types: define-μkanren-tag with μkanren-make-tag-A.°->§: fixed empty initial state, fixed query index 0.
Projection μkanren-project; the combinators freshª, andª, orª, if°, take°, project°; all of (aux stream); define-relation.
Table 10.2: The inventory of (aux kanren micro)’s core for an extension.

Two of the open entries in action: a user-defined disjoint type, and a goal written as a bare lambda that reads the state.

(define-μkanren-tag (tag/str v) (string? v))
(define string° (μkanren-make-tag-A tag/str))
(pretty-print (°->list #f (fresh° (q) (string° q))))
(pretty-print (map (λ (g) (°->list #f g))
                   (list (fresh° (q) (string° q) (=° q "hi"))
                         (fresh° (q) (string° q) (=° q 3))
                         (fresh° (q) (string° q) (symbol° q))
                         (fresh° (q) (string° q) (≠° q 3)))))
(pretty-print (°->list/ground (fresh° (q x y) (λ (s) ((=° q (μkanren-state-vars-count s)) s)))))
((λ (α) (assert (every (μ v (string? v)) (list α))) α))
(((λ () "hi")) () () ((λ (α) (assert (every (μ v (string? v)) (list α))) α)))
(3)

The new tag is printed in answers, is disjoint from symbol°, and subsumes (≠° q 3). The last goal sees vars-count =3=3.

A CHICKEN rule constrains every new module: a macro exported from a module whose expansion refers to an unexported binding fails at the use site. This is why freshª, andª, orª, ✓°, ✗°, =°, μkanren-fold/key§, μkanren-group§ and μkanren-key-of/counting are exported (:4–21); macros such as the ∀° and ⊃° of (aux kanren lambda) follow the same discipline.

10.9.2Three tricks that need no edit, and their limits

Trick 1: wrapper goals that emit =°. A solver written outside the engine (say, higher-order pattern unification computing a most general unifier {F↦t1,… }\{F\mapsto t_1,\dots\}) should express its result as ordinary =° goals, (and° (=° F t1) ...), so that each binding runs the D/A/T chain. The tempting shortcut, calling the exported raw unification and returning its state, silently bypasses the stores:

; WRONG: bypasses the D/A/T re-verification
(define ((bind/raw x t) s)
  (let1 (r (μkanren-state-unify x t s '())) (if r (✓° (car r)) (✗° s))))
; right: the result is expressed as an ordinary =°
(define ((bind/emit x t) s) ((=° x t) s))

(define raw (§->list ((fresh° (q) (≠° q 'a) (bind/raw q 'a)) μkanren-state-empty)))
; q = a and q ≠ a!
(pretty-print (map (λ (s) (list (sbral->list (μkanren-state-S s)) (μkanren-state-D s))) raw))
(pretty-print (handle-exceptions e (list 'error ((condition-property-accessor 'exn 'message) e))
                (°->list #f (fresh° (q) (≠° q 'a) (bind/raw q 'a)))))
(pretty-print (°->list #f (fresh° (q) (≠° q 'a) (bind/emit q 'a))))
(((a) (((_0 . a)))))
(error "bad argument type - not a list")
()

The raw version produces a state where S says q=𝖺q=\mathsf{a} and D says q≠𝖺q\ne\mathsf{a}; reification then re-verifies D, gets #f for “violated”, and crashes. The emitting version fails, as it should. Since the records of 2d2fb4e the state that μkanren-state-unify answers is raw, so the next goal that reads the stores verifies them as a whole and catches the violation; a goal after bind/raw that ends the query does not:

(pretty-print (°->list #f (fresh° (q) (≠° q 'a) (bind/raw q 'a) (≠° 1 2))))
(pretty-print (°->list #f (fresh° (q) (≠° q 'a) (bind/raw q 'b) (≠° 1 2))))
()
((λ () 'b))

The answer still depends on whether some goal happens to come after the raw binding. Limits: extra suspensions and repeated verification; and plain =° applied by a user to terms that need the special solver would still unify them syntactically, so a module must forbid that or shadow =°.

Trick 2: S-registers. Without the protocol’s slot X there is no way to add a field from outside: every goal of micro builds its states with micro’s own constructors, so a wrapper record would be lost at the next =°. Dynamic scoping (parameterize) fails too, because promises are forced outside its extent, and so does a side table keyed by the state, because a new state is allocated at every binding. But S itself is copied forward by every goal and is persistent and branch-local. So: reserve a fresh index nn (bump vars-count), bind variable nn by raw unification to an opaque record carrying the data, and find the current value as the register of highest index. Raw unification is harmless here because the register variable is fresh and unconstrained, and registers are never reachable from the query variable, so they are never reified. Here the data is a λProlog-style program context, giving a prototype of AUGMENT:

; a register: an opaque record bound in S
(define-record ctx clauses)
; reserve index n, bind var n (raw unify) to a ctx record
(define (ctx-push s Γ)
  (let* ((n (μkanren-state-vars-count s))
         (s1 (μkanren-state-with s vars-count: (add1 n))))
    (car (μkanren-state-unify (make-μkanren-var n) (make-ctx Γ) s1 '()))))
; the most recent register, by a shallow walk downwards
(define (ctx-current s)
  (let loop ((i (sub1 (μkanren-state-vars-count s))))
    (cond ((< i 0) '())
          (else (let1 (v (μkanren-state-find (make-μkanren-var i) s))
                  (if (ctx? v) (ctx-clauses v) (loop (sub1 i))))))))
; D ⊃ G, D a list of clause procedures (λ (x) goal)
(define ((⊃ª D g) s)
  (let1 (Γ (ctx-current s))
    (append-map§ (λ (s2) (✓° (ctx-push s2 Γ))) (δ (g (ctx-push s (append D Γ)))))))
; a dynamic predicate: try every clause of the context
(define ((hyp° x) s)
  (let1 (Γ (ctx-current s)) ((fold-right (λ (c g) (orª (c x) g)) ✗° Γ) s)))

(define (is° v) (λ (x) (=° x v)))            ; the clause  hyp X :- X = v
(for-each (λ (g) (write (°->list/ground g)) (newline))
  (list (fresh° (q) (⊃ª (list (is° 'a)) (hyp° q)))
        (fresh° (q) (⊃ª (list (is° 'a)) ✓°) (hyp° q))
        (fresh° (q) (⊃ª (list (is° 'a)) (⊃ª (list (is° 'b)) (hyp° q))))
        (fresh° (q) (or° (⊃ª (list (is° 'a)) (hyp° q)) (hyp° q)))
        (fresh° (q) (fresh° (y) (⊃ª (list (λ (x) (=° x y))) (fresh° (u) (hyp° u) (=° u 7))) (=° q y)))))
(a)
()
(b a)
(a)
(7)

In order: the assumed clause is used; outside its scope it is gone; nested assumptions stack, newest first; two branches of a disjunction do not see each other’s assumptions; and a free logic variable y of an assumed clause is shared with the context, not renamed, as in λProlog [MN p. 86–88]. Limits: the lookup scans the indices, O(vars-count⋅log⁡)O(\texttt{vars-count}\cdot\log) per call; registers must be allocated after the query variable; it is a library convention, not an engine guarantee.

10.9.3Trick 3: a ∀ prototype with a post-filter scope check

The eigenvariable is a record whose id is a reserved index, hence unique; distinct eigenvariables never unify (their id slots differ). The scope check is a post-filter on each answer state of the body: every variable of index <n< n, i.e. older than the eigenvariable, is deep-walked and must not contain it.

(define-record eigen id)
(define (contains? c t)
  (cond
    ; find/value REBUILDS records: compare ids, not identity
    ((eigen? t) (= (eigen-id t) (eigen-id c)))
    ((pair? t) (or (contains? c (car t)) (contains? c (cdr t))))
    ((vector? t) (any (λ (u) (contains? c u)) (vector->list t)))
    ((and (record-instance? t) (not (μkanren-var? t)))
     (any (λ (u) (contains? c u)) (vector->list (record->vector t))))
    (else #f)))
(define ((∀ª f) s)
  (let* ((n (μkanren-state-vars-count s))
         (c (make-eigen n))                        ; unique: index n is reserved
         (s* (μkanren-state-with s vars-count: (add1 n)))
         (escapes? (λ (s1) (let loop ((i 0))
                             (and (< i n)
                                  (or (contains? c (μkanren-state-find/value (make-μkanren-var i) s1))
                                      (loop (add1 i))))))))
    (append-map§ (λ (s1) (if (escapes? s1) '() (✓° s1))) (δ ((f c) s*)))))
(define-syntax-rule (∀° (x) g ...) (∀ª (λ (x) (and° g ...))))

(for-each (λ (g) (pretty-print (°->list #f g)))
  (list (fresh° (q) (∀° (x) (=° q x)))                              ; 1. ∃Q ∀x. Q = x
        (fresh° (q) (∀° (x) (fresh° (y) (=° y x))) (=° q 'ok))      ; 2. ∀x ∃Y. Y = x
        (fresh° (q) (∀° (x) (∀° (y) (=° x y))))                     ; 3. ∀x ∀y. x = y
        (fresh° (q) (∀° (x) (fresh° (y) (=° q (list y)) (=° y x)))) ; 4. alias
        (fresh° (q) (∀° (x) (fresh° (z) (=° q (list 'f z)))))       ; 5.
        (fresh° (q) (∀° (x) (≠° q x)))))                            ; 6. ≠ survives
()
((λ () 'ok))
()
()
((λ (α) (cons 'f (cons α '()))))
((λ (α) (begin (deny (equal? α (make-record-instance 'eigen 1)))) α))

Tutorial (Reading the six answers).

  1. ∃Q ∀x. Q=x\exists Q\,\forall x.\,Q=x is the book’s sigma x\ pi y\ x = y, “not provable” [MN p. 85]. Here q is _0; ∀° reserves index 1 and makes c == (eigen 1); the body binds _0 := c; the post-filter walks _0, finds c, and discards the state.
  2. ∀x ∃Y. Y=x\forall x\,\exists Y.\,Y=x succeeds: y has index 2 ≥n=1\ge n=1, so it is inside the scope.
  3. Two eigenvariables (eigen 1) and (eigen 2) differ in their id slot: unification fails.
  4. The escape is indirect: _0 := (list _2) and _2 := c. Because the check deep-walks the old variable, it sees (list c) and rejects the state. This is the chain created by the older-to-newer orientation of Section 10.4.
  5. A younger variable left unbound is harmless and is reified as α.
  6. A disequality mentioning c survives in D and is reified with the eigenvariable in it: the check filters bindings, not constraints.

Why is checking at the end of the body enough for soundness? After the scope closes, c is lexically unreachable and, by the check, no term reachable from an older variable contains it, so no later goal can bring it back.This argument is informal; the prototype was tested, not proved. What is lost is early pruning: a bad binding is detected only when the body has produced an answer, at a cost of O(n⋅∣term∣)O(n\cdot|\text{term}|) per answer. Eager checking needs the scope test at the binding site (closed), or a post-unification hook with a level map, or a module-level =° that shadows micro’s and checks its bindings against the open scopes kept in an S-register; the last option covers only goals written with the new module’s =°. (aux kanren lambda) takes the second: the protocol’s post hook, and levels kept in X (Section 12.3).

Pitfall (The scope check must not use eq?). With the first line of contains? written as ((eigen? t) (eq? t c)), the same query as answer 1 wrongly succeeds, because find/value rebuilt the record (Section 10.3):

(pretty-print (°->list #f (fresh° (q) (∀° (x) (=° q x)))))
((λ () (make-record-instance 'eigen 1)))

Kanren angle (What the tricks leave open). The three tricks show that the shape of AUGMENT and GENERIC fits micro’s core as it is: a goal that changes the state on entry and filters or restores it on every answer. What they cannot provide is what only the engine can do: a named place in the state (instead of a register scan), a call after every binding (for eager scope checks and for waking postponed equations), and a say in reification (to drop out-of-scope constraints and print new ones). These are the requirements Chapter 11 turns into a proposal, and Chapter 12 into a module.

10.10Summary

  • Terms are Scheme data; logic variables are records with an integer index, working (≥0\ge 0, printed _i) or reified (<0<0, printed α, β, …, without λ and μ). Indices grow monotonically along a branch, so an index is an age and doubles as a level boundary.
  • A state has nine fields: vars-count, S, M, the records C of the variables, the prefixes P, Tc, tags (dead), raw and the extensions’ slot X; D, A and T are views read from C, P and Tc. States are compared by eq?: unification returns the same state iff it binds nothing, and every entailment test relies on this.
  • S is an sbral, most recent variable first, extended lazily; the walk follows triangular bindings and treats reified variables as constants; deep walks rebuild records, losing their identity.
  • Unification is first-order with occurs check, spared by M when the bound value is already part of S; the only binding site is μkanren-state-update; the older variable is bound to the newer; vectors and records unify as slot lists (so records and same-shaped vectors unify); numbers by a NaN-reflexive eqv?; closures only by eq?.
  • D holds prefixes (negated conjunctions of bindings), A disjoint type tags, T absento constraints, all filed in the records of the variables they wait on; a binding hands on the constraints of the variables it binds, and those only; in micro alone the chain after =° has no slot for a new store.
  • Goals are state →\to stream; orª interleaves by swapping on suspensions (or° nests right, so three branches get 12,14,14\frac12,\frac14,\frac14); conjunction is not fair; a left-nested chain of andª runs as one fold; define-relation delays recursive relations; if° is conda (it keeps every answer of its test, so λProlog’s cut-based if is if° on a (take° 1 ...) test), take° bounds a run, project° escapes to Scheme; answer order is pinned by the tests.
  • Answers are closed expressions (λ (vars) constraints ... term), purified of unreachable variables, their forms sorted; grounding drops the constraints; the query variable is index 0; aggregations answer their groups in the order of their first state.
  • Open to extension: goals as procedures, raw unification, walks, records as constructors, user type tags, projection, the combinators. Closed in the core: the state’s fields, the unification cond, the binding site, the post-=° chain, reification, the runner; the protocol of Chapter 11 (commit 26b4708) opens each of them with a hook.
  • Without editing micro one can: emit =° from external solvers (never return raw-unified states), carry branch-local data in S-registers (a working AUGMENT prototype), and check eigenvariable scope by post-filtering the answers of a ∀ body (a working GENERIC prototype). Their limits — scans, late pruning, constraints outliving scopes — are the requirements of Chapter 11.