Chapter 13

The book’s examples in (aux kanren lambda)

Chapter 12 presented the module (aux kanren lambda) rule by rule: the terms ƛ and @, the levels that police the scope of eigenvariables, the unifier for LλL_\lambda with its delayed equations, and the goals ∀° and ⊃°. This chapter runs that machinery on the programs of Part I. Each example was introduced in an earlier chapter, where we explained what it means in λProlog. Here we ask a narrower question: what does the module do with it? Which rule fires, why does the answer have the shape it has, and does it come out in the order λProlog gives?

The examples follow the book’s progression. We start with the terms themselves (α, β, shadowing), go on to the two new goals (∀°, then ⊃°, then both together in type inference), then to programs over λ-tree syntax (substitution, de Bruijn indices, prenex forms), higher-order programming (mappred, functional difference lists, Fischer’s CPS transformation), and finally to the unification problems of the book’s Chapter 8 one by one. The last section takes the queries of Ma and Friedman’s 2021 paperWeixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2021 and answers them as λProlog would, explaining each point where the answers differ.

13.1How to read the examples

Every example has four parts.

  1. The λProlog original, copied from the book, with its printed page [MN p. n].The “p.N” in the labels of examples.scm are PDF pages; the prose uses printed pages (see Section 1.5).
  2. The Scheme version, copied verbatim from the curated script examples.scm, or from the programs it includes, test/programs.scm. Both live in the prototype’s directory, doc/hol-kanren/prototype/, frozen at f84cf9c.The merge moved the programs, unchanged, to src/test/microkanren-lambda-programs.scm (Section 14.4).
  3. The answers, pasted verbatim from examples.out, the actual output of the script. Run on the merged tree (master at c0ff08c), the script prints that file byte for byte. A few examples that the script does not contain were run separately with the same imports, on the merged tree; each of them says so.
  4. A walk-through: the rules of Chapter 12 that fire, the state changes they make, and how the order of the answers compares with λProlog.

13.1.1The dictionary

The header of examples.scm gives the translation that every example uses:

;;; The dictionary, λProlog → here:
;;;   x\ t                 (ƛ (x) t)               object binder by a Scheme binder (λ-tree syntax)
;;;   (F t)                (@ F t)                 application of a variable or an abstraction
;;;   pi x\ G              (∀° (x) G)              GENERIC
;;;   D => G               (⊃° (D) G)              AUGMENT, for a relation made by define-dynamic-relation
;;;   pi X\ H :- B         (∀ (X) (H ← B))         a hypothetical clause with its own variables
;;;   sigma X\ G           (fresh° (X) G)
;;;   G1, G2   G1 ; G2     (and° G1 G2)  (or° G1 G2)
;;; Object-level syntax is Scheme data: `abs M` is `(abs ,M), `app M N` is `(app ,M ,N).

Object-level syntax stays first-order Scheme data, as everywhere in (aux kanren micro). Only the binders are meta-level: abs x\ app x x becomes `(abs ,(ƛ (x) `(app ,x ,x))), a list whose second element is a λ-term. Inside the body of ƛ, the Scheme variable x is bound to a placeholder, so Scheme scoping gives the object binders, shadowing included (Section 6.2).

13.1.2Three ways to print an answer

The script prints each query with a small macro, its label first:

(define-syntax show
  (syntax-rules ()
    ((_ label e) (begin (display ";; ") (display label) (newline) (pretty-print e) (newline)))))

and uses three runners.

  • (°->list/datum g) gives each answer as plain data, comparable with equal? against the book’s answers. Abstractions print as (ƛ (x y) body), with nested binders merged and renamed apart. Applications whose head is not an abstraction print as (@ h a ...). Unbound logic variables print as α, β, γ, …, in order of first occurrence.
  • (°->list #f g) gives micro’s own answer form, a closed expression (λ (α ...) constraint ... term) (Section 10.7). The empty list () means that the query failed. ((λ () 'ok)) means one answer, with the ground value ok. A residual equation prints as (assert (≐ u v)).
  • (°->pretty g), from (aux kanren micro show), gives the αKanren-style view (α : constraint ...), which is the most readable one for suspended equations.

Many queries end in (=° q 'ok) or (=° q 'solved). A query whose interesting part is a success or a failure has no answer variable of its own, so these goals give it one to print.

13.1.3The rules, in one table

The walk-throughs name the rules of Chapter 12: the unification rules of Rules 12.6, variable elimination (Definition 12.7), the scope check Check (Definition 12.8), and the three search rules of Section 12.4. We recall them here in one line each. Two notions are needed first.

  • The level ℓ(X)\ell(X) of a logic variable is the number of ∀° goals around the point where it was created. The level ℓ(c)\ell(c) of an eigenvariable is the depth of the ∀° that created it, counting that ∀°. The names that the unifier opens below binders have level ∞\infty. A variable of level ℓ\ell may be bound only to a term whose eigenvariables have level ≤ℓ\le\ell: it stands for an ∃\exists placed after the first ℓ\ell universals of its branch.
  • A pattern for FF is a list of arguments that reduce to distinct eigenvariables, each of level greater than ℓ(F)\ell(F). This is Miller’s condition “quantified inside the scope of FF”, read off the levels (Section 7.5, Section A.10 and Definition 12.5).

For instance, in (fresh° (q) (∀° (x) (fresh° (y) ...))) we have ℓ(q)=0\ell(q)=0, ℓ(x)=1\ell(x)=1 and ℓ(y)=1\ell(y)=1: the list (x)(x) is a pattern for qq but not for yy, and yy may be bound to xx while qq may not.

rulefires oneffect
Var, CheckX≐tX\doteq t, XX unboundmicro binds X:=tX:=t after its occurs check. Then the scope check Elim(ℓ(X),−,⟨⟩,t)\mathrm{Elim}(\ell(X),-,\langle\rangle,t) fails on an eigenvariable of level >ℓ(X)>\ell(X), lowers the younger variables of tt to ℓ(X)\ell(X), and prunes flexible subterms. A non-pattern it cannot decide turns the binding back into a suspended equation.
ξλ.b≐λ.b′\lambda.b\doteq\lambda.b'open both bodies with one new name cc (level ∞\infty), unify them, and Check the bindings made under it
ηλ.b≐t\lambda.b\doteq t, tt no abstractionunify b[c/0]b[c/0] with (t c)(t\ c), cc new (level ∞\infty); only when one side is an abstraction
Rigidh u¯≐h′ v¯h\,\bar u\doteq h'\,\bar vsame head and arity: unify the arguments; otherwise fail
FF-sameF a¯≐F b¯F\,\bar a\doteq F\,\bar b, both patternsa¯=b¯\bar a=\bar b: success; arities differ: fail; else F:=λx¯. H ⟨xi∣ai=bi⟩F:=\lambda\bar x.\,H\,\langle x_i\mid a_i=b_i\rangle, ℓ(H)=ℓ(F)\ell(H)=\ell(F)
FRF a¯≐tF\,\bar a\doteq t, a¯\bar a a pattern, tt rigid or flexible with another head (the case “FF-diff”)F:=λx¯. Elim(ℓ(F),F,a¯,t)F:=\lambda\bar x.\,\mathrm{Elim}(\ell(F),F,\bar a,t). In tt: each aia_i becomes the ii-th bound variable (projection); constants, and eigenvariables of level ≤ℓ(F)\le\ell(F), are kept (imitation); an eigenvariable out of reach fails (8.J); a flexible pattern G b¯G\,\bar b loses the arguments FF may not see (pruning, 8.H); a younger variable is lowered to ℓ(F)\ell(F) and raised over the aia_i it may see (8.K); an occurrence of FF fails when no instance can make it smaller (8.I), and otherwise suspends
FF-oneF a¯≐G b¯F\,\bar a\doteq G\,\bar b, only b¯\bar b a patternFR on GG
Delayno side a patternunless the sides are α-equal, suspend λL.u≐λL.v\lambda L.u\doteq\lambda L.v in the store E (LL: the names opened so far); every later binding retries it; at the end it prints as (assert (≐ u v))
OccursX≐tX\doteq t with XX inside a λ-term of ttsucceed if tt reduces to XX, else eliminate XX with no arguments
generic(∀° (x) g)a new eigenvariable at depth+1{}+1; gg runs one level deeper; every answer gets the depth back
dischargeleaving ∀° (back to depth dd) with residuals on ccraise Y:=Y′ cY:=Y'\,c, ℓ(Y′)=d\ell(Y')=d, for each variable YY of the residual with ℓ(Y)≥ℓ(c)\ell(Y)\ge\ell(c); close the residual into λc.u≐λc.v\lambda c.u\doteq\lambda c.v; retry it; repeat while a raise brings cc into more constraints (Section 12.4.2)
augment(⊃° (D ...) g ...)push the clauses on Γ for gg only; every answer gets Γ back
backchaina call of a dynamic relationone flat or°: the hypotheses, most recent first, then the static body

13.2λ-tree syntax: α, β and shadowing

The first examples involve no search at all. They check that the terms behave as the book’s λ-terms do: equal up to the names of bound variables (Section 4.2), with β as part of equality, and with binders that obey lexical scope (Section 6.2.3).

(show "λx.λy.(x . y), as data and as micro's rebuilding code"
      (list (°->list/datum (fresh° (q) (=° q (ƛ (x y) (cons x y)))))
            (°->list #f (fresh° (q) (=° q (ƛ (x y) (cons x y)))))))

(show "α-equivalence: λa.a = λb.b, and the β-redex (λx.g x x) a"
      (list (°->list #f (fresh° (q) (=° (ƛ (a) a) (ƛ (b) b))))
            (°->list/datum (fresh° (q f) (=° f (ƛ (x) `(g ,x ,x))) (=° q (@ f 'a))))))

(show "shadowing, λa.λa.a, printed λa.λa1.a1 (Ma–Friedman's \"true = false\" hazard)"
      (°->list/datum (fresh° (q) (=° q (ƛ (a) (ƛ (a) a))))))
;; λx.λy.(x . y), as data and as micro's rebuilding code
(((ƛ (x y) (x . y))) ((λ () (ƛ (x y) (cons x y)))))

;; α-equivalence: λa.a = λb.b, and the β-redex (λx.g x x) a
(((λ (α) α)) ((g a a)))

;; shadowing, λa.λa.a, printed λa.λa1.a1 (Ma–Friedman's "true = false" hazard)
((ƛ (a a1) a1))

Tutorial (what happens).

  1. (ƛ (x y) (cons x y)) is built at once, before any goal runs. The body is a pair whose two cells hold the de Bruijn indices 1 and 0, and the names x, y survive only as printing hints. =° binds q to it by Var: no eigenvariable is involved, so Check has nothing to do. The rebuilding code (λ () (ƛ (x y) (cons x y))) is an expression that rebuilds the same term when evaluated, since ƛ is bound in the module.
  2. (=° (ƛ (a) a) (ƛ (b) b)) is decided by ξ: both bodies are opened with the same new name cc, and c≐cc\doteq c holds. Nothing is bound, so q stays free and prints as α. In fact the two terms are already the same record up to the hint: locally nameless terms make α-equivalence a structural fact.
  3. (@ f 'a) receives the logic variable f, not its value: @ is a Scheme procedure and does not consult the state. So it builds the flexible application f af\,a. Once f is bound to λx. g x x\lambda x.\, g\,x\,x, the reifier’s deep walk contracts the β-redex, and the answer is (g a a), as (x\ g x x) a is in λProlog.
  4. λa.λa.a is the term λa.λb.b: the inner binder shadows the outer one, because the inner Scheme a shadows the outer a. The printer renames apart, so the answer reads (ƛ (a a1) a1): Church’s false, not true. Section 13.11 returns to this.

13.3Universal goals and the scope of eigenvariables

Section 3.4.3 introduced the simplest example of quantifier scope: sigma x\ pi y\ x = y is not provable, while pi y\ sigma x\ x = y is. In the book’s words:

?- sigma x\ pi y\ x = y.

“This query is not provable because (pi y\ t = y) is not provable for any term t in which y does not appear” [MN p. 85]. examples.scm writes the two queries with an answer variable:

;; ?- pi x\ (Y = x).        no                ∃Y∀x. Y = x
;; ?- pi x\ sigma Y\ Y = x.  yes               ∀x∃Y. Y = x
(show "∃Y∀x. Y = x  and  ∀x∃Y. Y = x"
      (list (°->list #f (fresh° (q) (∀° (x) (=° q x))))
            (°->list #f (fresh° (q) (∀° (x) (fresh° (y) (=° y x))) (=° q 'ok)))))

(show "escape through an alias (q = (y), y = x), and through micro's cons°: both fail"
      (list (°->list #f (fresh° (q) (∀° (x) (fresh° (y) (=° q (list y)) (=° y x)))))
            (°->list #f (fresh° (q) (∀° (x) (cons° x '() q))))))
;; ∃Y∀x. Y = x  and  ∀x∃Y. Y = x
(() ((λ () 'ok)))

;; escape through an alias (q = (y), y = x), and through micro's cons°: both fail
(() ())

Tutorial (the levels at work). Write ℓ\ell for levels. In each query q is created by the outer fresh°, at depth 0, so ℓ(q)=0\ell(q)=0.

  1. ∃Y∀x. Y=x\exists Y\forall x.\,Y=x. generic creates the eigenvariable xx with ℓ(x)=1\ell(x)=1 and runs (=° q x) at depth 1. micro binds q:=xq:=x, then the post hook runs Check: xx is an eigenvariable with ℓ(x)=1>ℓ(q)=0\ell(x)=1>\ell(q)=0, so the binding fails. The query has no answer: ().
  2. ∀x∃Y. Y=x\forall x\exists Y.\,Y=x. Now y is created inside the ∀°, so ℓ(y)=1\ell(y)=1 and y:=xy:=x passes Check. When the ∀° exits, the depth is set back to 0 for the rest of the query, and (=° q 'ok) gives the answer. The binding of y is not part of the answer, which is what λProlog does for a variable quantified inside pi x\.
  3. The alias. y has level 1 again. The first goal binds q:=(y)q:=(y). Check of this binding finds the younger variable yy inside a term bound to the older qq, and lowers it: y:=y′y:=y' with ℓ(y′)=0\ell(y')=0. This is condition (3) of Nadathur, Jayaraman and Kwon’s binding rule, quoted in Section 3.4.3: the variables of tt take the level of XX. The second goal walks yy to y′y' and binds y′:=xy':=x, which Check now rejects, since ℓ(x)=1>0\ell(x)=1>0. Without lowering, xx would escape into qq through yy. The suite checks both orders of the two goals (A1/alias).
  4. micro’s cons°. cons° is an ordinary relation of micro, defined with =°. Since the check runs in =°’s post hook, every relation built on =° inherits it. Of the three prototypes, the one with its own unifier failed exactly here (Section 11.3.1).

The same check applies to logic variables that reach a clause. Section 3.5 quoted Nadathur, Jayaraman and Kwon’s example: with the clause ∀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, while ∀y ∃x (q y⊃p x)\forall y\,\exists x\,(q\,y\supset p\,x) succeedsGopalan 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. This is the suite’s case A1/levels-reach-clauses, shown in Example 12.20 as well; we ran it separately:

(show "∃x∀y(q y ⊃ p x) with ∀z(q z ⊃ p (d z))"
      (let ()
        (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° (q) (∀° (y) (fresh° (x) (⊃° ((q° y)) (p° x)))) (=° q 'ok))))))
;; ∃x∀y(q y ⊃ p x) with ∀z(q z ⊃ p (d z))
(() ((λ () 'ok)))

In the first query ℓ(x)=0\ell(x)=0 and ℓ(y)=1\ell(y)=1. backchain on (p° x) runs the static body, which creates the clause’s own z at depth 1, so ℓ(z)=1\ell(z)=1. The binding x:=(d z)x:=(d\,z) puts the younger zz inside the older xx, and Check lowers it: z:=z′z:=z' with ℓ(z′)=0\ell(z')=0. The call (q° z') then finds the hypothesis (q° y), and z′≐yz'\doteq y fails, since ℓ(y)=1>0\ell(y)=1>0. In the second query xx is created inside the ∀°, so ℓ(x)=1\ell(x)=1; zz is not lowered, and z≐yz\doteq y succeeds. This is NJK’s “new tagged instance” of a clause: its own variables are created at the current level, at each use, and then obey the binding rule like any other variable.

13.4Hypothetical goals and the program context

Chapter 3 introduced augment: to prove D⊃GD\supset G, add DD to the program and prove GG. In the module the program context Γ is a field of the state. ⊃° extends it for the extent of its body and gives every answer the old Γ back. Only relations made by define-dynamic-relation read Γ (Section 14.2.1); assuming a clause for any other relation raises an error.

13.4.1Clause order under augmentation

“λProlog uses the rule that when an implicational goal augments the current program, it does so by adding the new clauses at the front of the program” [MN p. 78]. With the program p 1:

?- p 2 => p 3 => p X.
X = 3;
X = 2;
X = 1
?- (p 2 & p 3) => p X.
X = 2;
X = 3;
X = 1
;; p 1.
;; ?- p 2 => p 3 => p X.          X = 3; X = 2; X = 1
;; ?- (p 2 & p 3) => p X.         X = 2; X = 3; X = 1
(define-dynamic-relation (p° x) (=° x 1))
(show "clause order under augmentation (p.94)"
      (list (°->list/datum (fresh° (q) (⊃° ((p° 2)) (⊃° ((p° 3)) (p° q)))))
            (°->list/datum (fresh° (q) (⊃° ((p° 2) (p° 3)) (p° q))))))
;; clause order under augmentation (p.94)
((3 2 1) (2 3 1))

Tutorial (the state of Γ, step by step).

  1. (define-dynamic-relation (p° x) (=° x 1)) makes p° a dynamic relation whose static body is (=° x 1), the clause p 1.
  2. First query. The outer ⊃° sets Γ=[\Gamma=[p°↦(p 2)]{}\mapsto(p\,2)]. The inner one puts its clause in front: Γ=[\Gamma=[p°↦(p 3, p 2)]{}\mapsto(p\,3,\ p\,2)].
  3. The call (p° q) is backchain: one flat disjunction (q≐3)∨(q≐2)∨(q≐1)(q\doteq3)\vee(q\doteq2)\vee(q\doteq1), the hypotheses most recent first, then the static body. Each disjunct succeeds at once, so micro’s interleaving delivers them in order: (3 2 1).
  4. Second query. One ⊃° assumes both clauses, which are kept in the order written: Γ=[\Gamma=[p°↦(p 2, p 3)]{}\mapsto(p\,2,\ p\,3)], and the answers are (2 3 1).

Both orders agree with the book. The agreement is not an accident of the search: the dynamic relation is built as one flat or°, so when every clause answers immediately, the answers come in clause order. When the clauses do more work before answering, interleaving decides the order instead (Section 13.7.2).

13.4.2The course database (book Fig. 3.1)

Section 3.3.2 presented the database and its four hypothetical queries:

fact (finished kim 102) & fact (finished dana 101).
fact (finished kim 210) & fact (finished dana 250).
fact (cs_major X) :-
   (fact (finished X 101); fact (finished X 102)),
   fact (finished X 250), fact (finished X 301).
fact (graduates X) :-
   (fact (finished X 101); fact (finished X 102)),
   (fact (finished X 210); fact (finished X 250)),
   fact (finished X 301).
false :- fact (finished X 210), fact (finished X 250).

?- fact (finished dana X) => false.
X = 210;
no
?- fact (finished X Y) => (fact (graduates X), fact (cs_major X)).
X = dana
Y = 301;
no
?- fact (finished kim X) => fact (finished kim Y) =>
   (fact (graduates kim), fact (cs_major kim)).
X = 250
Y = 301
?- fact (finished kim 250) => fact (finished kim 301) => false.
solved

(Figure 3.1 without its type declarations, and the four sessions, [MN p. 80–81].) In test/programs.scm the program is one dynamic relation fact°, since every query assumes fact clauses:

(define-dynamic-relation (fact° e)
  (fresh° (x)
    (cond°
      ((=° e '(finished kim 102))) ((=° e '(finished dana 101)))
      ((=° e '(finished kim 210))) ((=° e '(finished dana 250)))
      ((=° e `(cs_major ,x))
       (or° (fact° `(finished ,x 101)) (fact° `(finished ,x 102)))
       (fact° `(finished ,x 250))
       (fact° `(finished ,x 301)))
      ((=° e `(graduates ,x))
       (or° (fact° `(finished ,x 101)) (fact° `(finished ,x 102)))
       (or° (fact° `(finished ,x 210)) (fact° `(finished ,x 250)))
       (fact° `(finished ,x 301))))))

(define-dynamic-relation (false°) (fresh° (x) (fact° `(finished ,x 210)) (fact° `(finished ,x 250))))

and the queries are

(show "courses: which course would make Dana's record inconsistent"
      (°->list/datum (fresh° (q) (⊃° ((fact° `(finished dana ,q))) (false°)))))
(show "courses: who graduates in CS after one more course, and which"
      (°->list/datum (fresh° (q x y) (=° q (list x y)) (⊃° ((fact° `(finished ,x ,y))) (fact° `(graduates ,x)) (fact° `(cs_major ,x))))))
(show "courses: Kim's two courses (each order is a proof, each found twice; the book shows the first)"
      (sorted (°->list/datum (fresh° (q x y) (=° q (list x y))
                               (⊃° ((fact° `(finished kim ,x))) (⊃° ((fact° `(finished kim ,y))) (fact° '(graduates kim)) (fact° '(cs_major kim))))))))
(show "courses: no consistent way for Kim"
      (°->list/datum (fresh° (q) (⊃° ((fact° '(finished kim 250))) (⊃° ((fact° '(finished kim 301))) (false°))) (=° q 'solved))))
;; courses: which course would make Dana's record inconsistent
(210)

;; courses: who graduates in CS after one more course, and which
((dana 301))

;; courses: Kim's two courses (each order is a proof, each found twice; the book shows the first)
((250 301) (250 301) (301 250) (301 250))

;; courses: no consistent way for Kim
(solved)

Tutorial (a logic variable inside a hypothesis). Take the first query. q is created before ⊃° runs, so the assumed clause (fact° `(finished dana ,q)) is one still unknown fact, not a schema: q is a free variable of the clause’s closure, shared with the query ([MN p. 86–88]; backchain in Section 12.4).

  1. (false°) runs its body: x is new, and (fact° `(finished ,x 210)) is a backchain on Γ first. The hypothesis unifies (finished dana q) with (finished x 210): x:=𝖽𝖺𝗇𝖺x:=\mathsf{dana}, q:=210q:=210.
  2. (fact° '(finished dana 250)) succeeds from the static body.
  3. The static clauses also prove (finished x 210), with x:=𝗄𝗂𝗆x:=\mathsf{kim}. But then (finished kim 250) must hold, and it is neither a fact nor an instance of the hypothesis, which is about Dana. So the only answer is (210), as in the book.

In the third query there are four answers instead of the book’s one: the book shows only the first answer. They are proofs of the same goal. The symmetric pair appears because either hypothesis can supply either course. Each answer appears twice because the disjunct (or° (fact° `(finished ,x 210)) (fact° `(finished ,x 250))) in graduates has two proofs once 250 is assumed: from Kim’s static 210, and from the hypothesis. The script sorts them, since the order among them is the interleaving’s. Section 3.3.2 reached the same count with the throwaway interpreter of Section 3.8.3.

13.4.3Jars and bugs

The example of Section 3.4 combines generic and augment:

sterile J :- pi x\ bug x => in x J => dead x.
dead B    :- heated J, in B J, bug B.
heated j.

This is the program of [MN p. 83]; its signature has no constant of type bug. In Scheme:

;; p.98-99:  sterile J :- pi x\ bug x => in x J => dead x.
;;           dead B :- heated J, in B J, bug B.        heated j.
(define-dynamic-relation (bug° b))
(define-dynamic-relation (in° b j))
(define-relation (heated° j) (=° j 'j))
(define-dynamic-relation (dead° b) (fresh° (j) (heated° j) (in° b j) (bug° b)))
(define-relation (sterile° j) (∀° (x) (⊃° ((bug° x)) (⊃° ((in° x j)) (dead° x)))))
(show "jars and bugs: ?- sterile Q." (°->list/datum (fresh° (q) (sterile° q))))
;; jars and bugs: ?- sterile Q.
(j)

Tutorial (trace of sterile Q).

  1. (sterile° q): ℓ(q)=0\ell(q)=0. generic creates the eigenvariable xx, ℓ(x)=1\ell(x)=1, and the depth becomes 1.
  2. Two augments: Γ=[\Gamma=[in°↦(𝗂𝗇 x q){}\mapsto(\mathsf{in}\,x\,q), bug°↦(𝖻𝗎𝗀 x)]{}\mapsto(\mathsf{bug}\,x)]. The clause (in° x j) closes over the j of sterile°, which is q.
  3. (dead° x) has no hypothesis, so backchain runs its static body. It creates j' at depth 1, and (heated° j') binds j′:=𝗃j':=\mathsf{j}.
  4. (in° x j') backchains on the hypothesis: it unifies (x 𝗃)(x\ \mathsf{j}) with (x q)(x\ q), so q:=𝗃q:=\mathsf{j}. Check accepts it: the constant j contains no eigenvariable.
  5. (bug° x) succeeds from the hypothesis. The ∀° exits: depth 0 and the old Γ come back, and there is no residual to discharge. The answer is (j).

The proof is about an arbitrary bug: bug° and in° have no static clauses at all, and the only facts about xx are the two hypotheses. Had a step tried to bind q to something containing xx, Check would have rejected it.

13.4.4Reverse with assumed clauses (book Fig. 3.4)

Section 3.5 showed how an assumed clause can “tie” a variable of the goal:

reverse L K :-
   (rev nil K &
    (pi X\ pi L\ pi K\ rev (X::L) K :- rev L (X::K)))
        => rev L nil.

(Figure 3.4, [MN p. 87]). The first clause mentions the K of reverse, the second has its own universally quantified X, L, K. The Scheme version says the same with ∀:

;; Figure 3.4 (p.104):
;; reverse L K :- (rev nil K & (pi X\ pi L\ pi K\ rev (X::L) K :- rev L (X::K))) => rev L nil.
;; the free K of `rev nil K` is the caller's, the clause's own X, L, K are renamed at each use.
(define-dynamic-relation (rev° l k))
(define-relation (reverse° l k)
  (⊃° ((rev° '() k) (∀ (X L K) ((rev° `(,X . ,L) K) ← (rev° L `(,X . ,K))))) (rev° l '())))
(show "reverse with assumed clauses, forwards and backwards"
      (list (°->list/datum (fresh° (q) (reverse° '(1 2 3) q)))
            (°->list/datum (take° 1 (fresh° (q) (reverse° q '(1 2 3)))))))
;; reverse with assumed clauses, forwards and backwards
(((3 2 1)) ((3 2 1)))

Tutorial (two kinds of clause variables). ⊃° expands each clause into a pair (rev° . procedure), the procedure taking the list of arguments of a call. For (rev° '() k) the procedure is (=° args (list '() k)): k is a free variable of the closure, the caller’s q. For the ∀ clause the procedure is (fresh° (X L K) (=° args ...) (rev° L ...)): its variables are created anew at each call, which is how λProlog renames a clause’s own variables (Section 12.4).

Forwards, (rev° '(1 2 3) '()) uses the second clause three times, building the accumulator (3 2 1), and then (rev° '() '(3 2 1)) uses the first one, which binds k:=(3 2 1)k:=(3\,2\,1). Backwards, k is (1 2 3) and l is unknown. The second clause guesses longer and longer lists, and the first clause succeeds only when the accumulator equals (1 2 3), after three steps. That is the only answer, but nothing tells the search so. In a separate run, (take° 2 (fresh° (q) (reverse° q '(1 2 3)))) had not returned after 20 seconds, so the script takes one answer.

13.5Type inference: ∀\forall and ⊃\supset together

Type inference (Section 6.5.4 and Section 8.2.1) is the book’s standard example of a universal goal and a hypothesis working together. To type λx. M\lambda x.\, M, take a new constant xx, assume that it has type AA, and type the body:

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.

?- typeof (abs x\ abs y\ abs z\ app (app x z) (app y z)) Ty.
Ty = arr (arr T1 (arr T2 T3)) (arr (arr T1 T2) (arr T1 T3))
?- typeof (abs x\x) Ty.
Ty = arr T1 T1
?- typeof (abs x\ app x x) Ty.
no

These are the clauses and the session of [MN p. 190–191]. In test/programs.scm:

; §7.4.3, type inference:  typeof (abs M) (arr A B) :- pi x\ typeof x A => typeof (M x) B.
(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)))))))

and the queries:

(show "typeof S, I and λx.x x"
      (list (°->list/datum (fresh° (q) (typeof° `(abs ,(ƛ (x) `(abs ,(ƛ (y) `(abs ,(ƛ (z) `(app (app ,x ,z) (app ,y ,z)))))))) q)))
            (°->list/datum (fresh° (q) (typeof° `(abs ,(ƛ (x) x)) q)))
            (°->list/datum (fresh° (q) (typeof° `(abs ,(ƛ (x) `(app ,x ,x))) q)))))
(show "typeof backwards: the first terms of type i → i (interleaving finds them where DFS loops)"
      (°->list/datum (take° 3 (fresh° (q) (typeof° q '(arr i i))))))
;; typeof S, I and λx.x x
(((arr (arr α (arr β γ)) (arr (arr α β) (arr α γ)))) ((arr α α)) ())

;; typeof backwards: the first terms of type i → i (interleaving finds them where DFS loops)
((abs (ƛ (x) x))
 (abs (ƛ (x) (app (abs (ƛ (x1) x1)) x)))
 (abs (ƛ (x) (app (abs (ƛ (x1) x)) x))))

Tutorial (typing abs x\x, state by state).

  1. (typeof° m q) with m=m={}(abs ,(ƛ (x) x)). backchain: Γ has no hypothesis yet, so only the static cond° runs. The app branch fails on (=° m `(app ,M ,N)).
  2. The abs branch binds R:=λx. xR:=\lambda x.\, x and q:=(𝖺𝗋𝗋 A B)q:=(\mathsf{arr}\ A\ B); RR, AA, BB have level 0.
  3. generic: an eigenvariable x, call it cc, with ℓ(c)=1\ell(c)=1. augment: Γ=[\Gamma=[typeof°↦(𝗍𝗒𝗉𝖾𝗈𝖿 c A)]{}\mapsto(\mathsf{typeof}\ c\ A)].
  4. The goal (typeof° (@ R x) B). As in the previous example, (@ R x) receives the logic variable RR, not its value, so it is the flexible term R cR\,c. Since RR is bound, every walk reduces it to cc.
  5. backchain on Γ first: the hypothesis unifies (c B)(c\ B) with (c A)(c\ A), so A≐BA\doteq B, a variable–variable binding with no eigenvariable in it (micro binds the older variable to the newer one). Then the static clauses fail: cc is neither an app nor an abs list.
  6. The ∀° exits: depth 0, Γ empty. The answer is q=(𝖺𝗋𝗋 A A)q=(\mathsf{arr}\ A\ A), printed (arr α α).

For λx. x x\lambda x.\, x\,x the hypothesis is used twice: once for the head, giving A:=(𝖺𝗋𝗋 B′ B)A:=(\mathsf{arr}\ B'\ B), once for the argument, giving B′≐(𝖺𝗋𝗋 B′ B)B'\doteq(\mathsf{arr}\ B'\ B), which fails micro’s ordinary occurs check. For S, three nested ∀° goals put three hypotheses in Γ, all for typeof°, most recent first. The answer has the book’s shape, with α, β, γ in place of T1, T2, T3. Section 12.4.6 prints the same steps with a probe, for λx. λy. x\lambda x.\, \lambda y.\, x and for λx. x x\lambda x.\, x\,x.

Kanren angle (running type inference backwards). The book never asks typeof Ty (arr i i) with the term unknown, and for a good reason: depth-first search tries the app clause first, which asks again for a term of unknown type, forever. micro’s interleaving search alternates between the branches, so it finds terms of a given type, and even (term, type) pairs. We ran the suite’s case A3/backwards separately:

(show "typeof backwards: (term type) pairs"
      (°->list/datum (take° 4 (fresh° (q m t) (=° q (list m t)) (typeof° m t)))))
;; typeof backwards: (term type) pairs
(((abs (ƛ (x) x)) (arr α α))
 ((abs (ƛ (x) (abs (ƛ (x1) x1)))) (arr α (arr β β)))
 ((abs (ƛ (x) (abs (ƛ (x1) x)))) (arr α (arr β α)))
 ((app (abs (ƛ (x) x)) (abs (ƛ (x) x))) (arr α α)))

The interesting step is R c≐cR\,c\doteq c with RR unknown: a pattern, solved by FR with the projection R:=λx. xR:=\lambda x.\, x. The binder of the answer is named x after the eigenvariable of the ∀°, the name the clause gave it. This is one of the places where the module finds answers that λProlog misses (Section 14.2.4).

13.6Object-level substitution

Section 6.3 explained the central idea of λ-tree syntax: object-level substitution is meta-level β. Section 6.7 gave the alternative that avoids β altogether, copy clauses assumed under pi. Both run here.

13.6.1Call-by-name evaluation

cbn (abs R) (abs R).
cbn (app M N) V :- cbn M (abs R), cbn (R N) V.

?- cbn (app (abs x\ abs w\w) (app (abs x\ app x x) (abs x\ app x x))) V.

gives V = abs w\w, while call-by-value loops (Figure 7.3, [MN p. 182–183]).

; Figure 7.3, call-by-name evaluation: β of the object language is β of the meta-language.
(define-relation (cbn° m v)
  (cond°
    ((fresh° (R) (=° m `(abs ,R)) (=° v m)))
    ((fresh° (M N R) (=° m `(app ,M ,N)) (cbn° M `(abs ,R)) (cbn° (@ R N) v)))))
(show "call by name: (λx.λw.w) Ω"
      (let* ((ω `(abs ,(ƛ (x) `(app ,x ,x)))) (Ω `(app ,ω ,ω)))
        (°->list/datum (fresh° (q) (cbn° `(app (abs ,(ƛ (x) `(abs ,(ƛ (w) w)))) ,Ω) q)))))
;; call by name: (λx.λw.w) Ω
((abs (ƛ (w) w)))

Tutorial (β on demand). In the app branch, (@ R N) is built from the logic variable R, as in the type-inference trace: it is a flexible application. (cbn° M `(abs ,R)) evaluates the operator (abs ,(ƛ (x) ...)), which is already a value: R:=λx. 𝖺𝖻𝗌 (λw. w)R:=\lambda x.\, \mathsf{abs}\,(\lambda w.\, w). When the second call (cbn° (@ R N) v) unifies its first argument with `(abs ,R'), the walk of R NR\,N contracts the redex to (abs ,(ƛ (w) w)). The argument N=ΩN=\Omega is dropped by that β step and never evaluated, so the search terminates, as call-by-name should. No rule of the unifier is needed beyond β: every step is a pattern-free, first-order unification on a reduced term.

13.6.2subst R N (R N): dynamic LλL_\lambda

The one-line subst R N (R N) is the book’s example of a clause outside LλL_\lambda that is “meant only to compute the effect of substitution through reduction” [MN p. 225–226], since R is expected to be known when the clause is used (Section 7.9.1). The module accepts the non-pattern R NR\,N in either order of the goals. This query is the suite’s case A4/beta, run separately, with RR bound after the equation:

(show "subst R N (R N): R bound after"
      (°->list/datum (fresh° (q r) (=° q (@ r `(abs ,(ƛ (y) y)))) (=° r (ƛ (x) `(app ,x ,x))))))
;; subst R N (R N): R bound after
((app (abs (ƛ (y) y)) (abs (ƛ (y) y))))

The first goal binds qq to the flexible term r (𝖺𝖻𝗌…)r\,(\mathsf{abs}\ldots). The argument is a list, not an eigenvariable, so this is no pattern, but no ∀° has run, so Check has nothing to forbid and the binding stands. The second goal binds rr, and the reifier’s deep walk contracts the redex. Had the first binding involved an eigenvariable that only the value of rr could keep or drop, Check would have turned it into a suspended equation (Delay), retried when rr is bound (Section 13.10.5 and Example 12.15).

13.6.3Copy and substitution without β (book Fig. 7.10)

copy (app M N) (app P Q) :- copy M P, copy N Q.
copy (abs M) (abs N) :- pi x\ copy x x => copy (M x) (N x).
subst M T S :- pi x\ copy x T => copy (M x) S.

?- copy (abs x\ abs y\ app y x) M.

“Solving for all the variables yields the unique answer substitution” M = abs v\abs u\app u v (Figure 7.10 and the trace, [MN p. 199–200]).

; Figure 7.10, copy and subst on untyped λ-terms.
(define-dynamic-relation (copy° m n)
  (cond°
    ((fresh° (M N P Q) (=° m `(app ,M ,N)) (=° n `(app ,P ,Q)) (copy° M P) (copy° N Q)))
    ((fresh° (M N) (=° m `(abs ,M)) (=° n `(abs ,N))
       (∀° (x) (⊃° ((copy° x x)) (copy° (@ M x) (@ N x))))))))
(define-relation (subst° m t s) (∀° (x) (⊃° ((copy° x t)) (copy° (@ m x) s))))
(show "copy (p.215), and subst (x\\ app x x) (abs y\\ y)"
      (list (°->list/datum (fresh° (q) (copy° `(abs ,(ƛ (x) `(abs ,(ƛ (y) `(app ,y ,x))))) q)))
            (°->list/datum (fresh° (q) (subst° (ƛ (x) `(app ,x ,x)) `(abs ,(ƛ (y) y)) q)))))
;; copy (p.215), and subst (x\ app x x) (abs y\ y)
(((abs (ƛ (x) (abs (ƛ (x1) (app x1 x))))))
 ((app (abs (ƛ (y) y)) (abs (ƛ (y) y)))))

Tutorial (the book’s trace, replayed). The book traces this query with the eigenvariables cc and dd [MN p. 199]. In the module:

  1. The abs clause binds M0:=λx. 𝖺𝖻𝗌 (λy. 𝖺𝗉𝗉 y x)M_0:=\lambda x.\, \mathsf{abs}\,(\lambda y.\, \mathsf{app}\ y\ x) and q:=(𝖺𝖻𝗌 N0)q:=(\mathsf{abs}\ N_0). generic gives cc at level 1, augment assumes (copy° c c), and the goal is copy° (𝖺𝖻𝗌 (λy. 𝖺𝗉𝗉 y c)) (N0 c)(\mathsf{abs}\,(\lambda y.\, \mathsf{app}\ y\ c))\ (N_0\,c).
  2. The abs clause again. The equation N0 c≐(𝖺𝖻𝗌 N1)N_0\,c\doteq(\mathsf{abs}\ N_1) is a pattern for N0N_0: FR binds N0:=λx. 𝖺𝖻𝗌 (N1′ x)N_0:=\lambda x.\, \mathsf{abs}\,(N_1'\,x). N1N_1 was created at level 1, inside the first ∀°, so it is lowered and raised over cc: N1:=N1′ cN_1:=N_1'\,c (the 8.K step of Section 13.10). The book’s M1M_1 is our N0N_0.
  3. A second generic gives dd at level 2, and (copy° d d) is assumed. The goal is copy° (𝖺𝗉𝗉 d c) (N1′ c d)(\mathsf{app}\ d\ c)\ (N_1'\,c\,d). The app clause binds N1′ c d≐(𝖺𝗉𝗉 P Q)N_1'\,c\,d\doteq(\mathsf{app}\ P\ Q) by FR, and the hypotheses give P=dP=d, Q=cQ=c, by projection.
  4. Each ∀° exits with no residual. The answer is 𝖺𝖻𝗌 (λx. 𝖺𝖻𝗌 (λx1. 𝖺𝗉𝗉 x1 x))\mathsf{abs}\,(\lambda x.\, \mathsf{abs}\,(\lambda x_1.\, \mathsf{app}\ x_1\ x)), the book’s abs v\abs u\app u v up to the names.

The binders are named x and x1: the unifier names the abstractions it builds after the eigenvariables they abstract, and both eigenvariables come from the clause’s (∀° (x) ...). The printer renames the second one apart.

13.6.4Existential generalisation (book Fig. 7.11)

Figure 7.11 specifies substitution into first-order formulas with copyterm and copyform clauses [MN p. 201]. Because subst is a relation, it can run backwards and abstract a term out of a formula: “given a term T and a formula S, it is possible to compute an abstraction M such that (subst M T S) is derivable” [MN p. 202]:

?- subst M (f a) ((p (f a)) && (q a (f a))).
M = x\ (p x) && (q a x)
M = x\ (p x) && (q a (f a))
M = x\ (p (f a)) && (q a x)
M = x\ (p (f a)) && (q a (f a))

These are the four existential generalisations of the formula on f af\,a (Section 6.7). test/programs.scm has the clauses for the constants used here:

; Figure 7.11, copy and subst on first-order formulas.
(define-dynamic-relation (copyterm° t s)
  (cond°
    ((=° t 'a) (=° s 'a))
    ((fresh° (x u) (=° t `(f ,x)) (=° s `(f ,u)) (copyterm° x u)))
    ((fresh° (x y u v) (=° t `(g ,x ,y)) (=° s `(g ,u ,v)) (copyterm° x u) (copyterm° y v)))))
(define-relation (copyform° b d)
  (cond°
    ((fresh° (B C D E op) (=° b `(,op ,B ,C)) (=° d `(,op ,D ,E)) (or° (=° op 'and) (=° op 'or) (=° op 'imp))
       (copyform° B D) (copyform° C E)))
    ((fresh° (B D op) (=° b `(,op ,B)) (=° d `(,op ,D)) (or° (=° op 'all) (=° op 'some))
       (∀° (y) (⊃° ((copyterm° y y)) (copyform° (@ B y) (@ D y))))))
    ((fresh° (x u) (=° b `(p ,x)) (=° d `(p ,u)) (copyterm° x u)))
    ((fresh° (x y u v) (=° b `(q ,x ,y)) (=° d `(q ,u ,v)) (copyterm° x u) (copyterm° y v)))))
(define-relation (substform° m t n) (∀° (x) (⊃° ((copyterm° x t)) (copyform° (@ m x) n))))
(show "existential generalization: the book's four answers, in its order"
      (°->list/datum (fresh° (q) (substform° q '(f a) '(and (p (f a)) (q a (f a)))))))
;; existential generalization: the book's four answers, in its order
((ƛ (x) (and (p x) (q a x)))
 (ƛ (x) (and (p x) (q a (f a))))
 (ƛ (x) (and (p (f a)) (q a x)))
 (ƛ (x) (and (p (f a)) (q a (f a)))))

Tutorial (how an unknown abstraction is built, piece by piece).

  1. substform° creates the eigenvariable xx (level 1), assumes (copyterm° x '(f a)), and calls copyform° on q xq\,x, a flexible pattern, against the formula.
  2. The first copyform° clause matches (op B C) on the left: q x≐(𝗈𝗉 B C)q\,x\doteq(\mathsf{op}\ B\ C) is solved by FR. The variables 𝗈𝗉\mathsf{op}, BB, CC were created at level 1, so elimination lowers them and raises them over xx: q:=λx. (𝗈𝗉′ x  B′ x  C′ x)q:=\lambda x.\, (\mathsf{op}'\,x\ \ B'\,x\ \ C'\,x). The next goal unifies the formula (and ...) with (op D E), so 𝗈𝗉′ x≐𝖺𝗇𝖽\mathsf{op}'\,x\doteq\mathsf{and} gives 𝗈𝗉′:=λx. 𝖺𝗇𝖽\mathsf{op}':=\lambda x.\, \mathsf{and} by imitation, and the or° then accepts and. The two halves are copied in turn.
  3. For the first half, the p clause gives B′ x≐(𝗉 X)B'\,x\doteq(\mathsf{p}\ X) and then (copyterm° (X' x) '(f a)). backchain tries the hypothesis first: X′ x≐xX'\,x\doteq x gives X′:=λx. xX':=\lambda x.\, x by projection, which is the answer p xp\,x. Then the static clauses: X′ x≐(𝖿 X′′)X'\,x\doteq(\mathsf{f}\ X'') and (copyterm° (X'' x) 'a), where only the constant a clause applies, and X′′:=λx. aX'':=\lambda x.\, a by imitation: the answer p (f a)p\,(f\,a).
  4. The second half does the same for q a (f a)q\,a\,(f\,a). The occurrence of a has only the static answer, since the hypothesis copies xx to f af\,a, not to aa.

The order is the book’s: the hypothesis comes first for each occurrence, and the first occurrence varies slowest.

13.7Recursion over binders: de Bruijn terms and prenex forms

13.7.1Translating to and from de Bruijn syntax

Section 6.5.5 translated λ-tree syntax into de Bruijn’s nameless terms by assuming, for each binder crossed, the depth at which it was crossed:

trans D (abs M) (ab P) :- pi c\ depth D c => (E is D + 1, trans E (M c) P).
trans D (app M N) (ap P Q) :- trans D M P, trans D N Q.
trans D X (deb E) :- depth N X, E is (D - N).

?- trans 1 (abs x\ app x (abs y\ app x (abs w\ app w x))) D.
D = ab (ap (deb 1) (ab (ap (deb 2) (ab (ap (deb 1) (deb 3))))))
?- trans 1 P (ab (ap (deb 1) (ab (ap (deb 2) (ab (ap (deb 1) (deb 3))))))).
P = abs W1\ app W1 (abs W2\ app W1 (abs W3\ app W3 W1))

These are the clauses and the session of [MN p. 193]. micro has no is, so the Scheme version computes with project°:

; §7.4.4, translation to and from de Bruijn syntax, with the `depth` assumptions.
(define-dynamic-relation (depth° n x))
(define-relation (trans° d t b)
  (cond°
    ((fresh° (M P) (=° t `(abs ,M)) (=° b `(ab ,P))
       (∀° (c) (⊃° ((depth° d c)) (fresh° (e) (project° ((d* d)) (=° e (+ d* 1))) (trans° e (@ M c) P))))))
    ((fresh° (M N P R) (=° t `(app ,M ,N)) (=° b `(ap ,P ,R)) (trans° d M P) (trans° d N R)))
    ((fresh° (n e) (=° b `(deb ,e)) (depth° n t) (project° ((d* d) (n* n)) (=° e (- d* n*)))))))
(show "de Bruijn, both directions"
      (list (°->list/datum (fresh° (q) (trans° 1 `(abs ,(ƛ (x) `(app ,x (abs ,(ƛ (y) `(app ,x (abs ,(ƛ (w) `(app ,w ,x))))))))) q)))
            (°->list/datum (fresh° (q) (trans° 1 q '(ab (ap (deb 1) (ab (ap (deb 2) (ab (ap (deb 1) (deb 3))))))))))))
;; de Bruijn, both directions
(((ab (ap (deb 1) (ab (ap (deb 2) (ab (ap (deb 1) (deb 3))))))))
 ((abs (ƛ (c) (app c (abs (ƛ (c1) (app c (abs (ƛ (c2) (app c2 c)))))))))))

Both answers are the book’s terms. The backward one is abs W1\ app W1 (abs W2\ app W1 (abs W3\ app W3 W1)) with c, c1, c2 for W1, W2, W3: the unifier named the abstractions after the eigenvariable c of the clause.

The book traces a smaller query step by step, trans 1 (abs x\ abs y\ abs z\ y) P, and ends with “the instantiation of P with (ab (ab (ab (deb 2))))” [MN p. 193–194]. We ran it separately:

(define t3 `(abs ,(ƛ (x) `(abs ,(ƛ (y) `(abs ,(ƛ (z) y)))))))
(show "trans 1 (abs x\\ abs y\\ abs z\\ y) P"
      (°->list/datum (fresh° (q) (trans° 1 t3 q))))
;; trans 1 (abs x\ abs y\ abs z\ y) P
((ab (ab (ab (deb 2)))))

Tutorial (the book’s trace as state changes). Read depth for the level of the ∀°, and Γ for the depth° hypotheses.

goaldepthΓ for depth° (most recent first)
trans 1 (abs x\ abs y\ abs z\ y) P0—
trans 2 (abs y\ abs z\ y) P11(1 c1)(1\ c_1)
trans 3 (abs z\ c2) P22(2 c2), (1 c1)(2\ c_2),\ (1\ c_1)
trans 4 c2 P33(3 c3), (2 c2), (1 c1)(3\ c_3),\ (2\ c_2),\ (1\ c_1)

(We write c1,c2,c3c_1,c_2,c_3 for the three eigenvariables, all hinted c.) In the last goal only the third clause applies, since c2c_2 is neither an abs nor an app list. (depth° n c2) backchains on Γ, most recent first: (3 c3)(3\ c_3) and (1 c1)(1\ c_1) fail on c3≠c2c_3\neq c_2 and c1≠c2c_1\neq c_2, while (2 c2)(2\ c_2) gives n=2n=2, and project° computes e=4−2=2e=4-2=2. Each ∀° then exits, restoring the depth and Γ. The book’s depth c 1 is the same fact with its arguments in the order of the trace; the clause and our code write depth D c.

In the backward direction the first argument of trans° is M cM\,c with MM unknown, a pattern. The app clause solves M c≐(𝖺𝗉𝗉 M1 N1)M\,c\doteq(\mathsf{app}\ M_1\ N_1) by FR, lowering M1,N1M_1,N_1 and raising them over cc. The deb clause then meets (depth° n (M1' c)): the hypothesis (depth° 1 c) gives M1′ c≐cM_1'\,c\doteq c, a projection. Every equation in this program is a pattern.

13.7.2Prenex normal forms (book Fig. 7.8)

Section 6.6.3 showed that prenex is a relation, not a function:

?- prenex ((all x\ q x x) && (all z\ all y\ q z y)) P.

“will generate the following five answer substitutions for P” [MN p. 197]:

all z\ all y\ (q z z) && (q z y)
all x\ all z\ all y\ (q x x) && (q z y)
all z\ all x\ (q x x) && (q z x)
all z\ all x\ all y\ (q x x) && (q z y)
all z\ all y\ all x\ (q x x) && (q z y)

The program of test/programs.scm transcribes Figure 7.8 in the book’s order, one cond° branch per clause, except that clauses differing only in their connective or quantifier (such as prenex (B && C) D and prenex (B !! C) D) share one branch through an or°. We show the main relation and the first two of the seven merge° branches:

(define-relation (prenex° b d)
  (cond°
    ((atom° b) (=° d b))
    ((fresh° (a) (=° b `(neg ,a)) (atom° a) (=° d b)))
    ((fresh° (op B C U V) (=° b `(,op ,B ,C)) (or° (=° op 'and) (=° op 'or)) (prenex° B U) (prenex° C V) (merge° `(,op ,U ,V) d)))
    ((fresh° (q B D) (=° b `(,q ,B)) (=° d `(,q ,D)) (or° (=° q 'all) (=° q 'some)) (∀° (x) (prenex° (@ B x) (@ D x)))))))
(define-relation (merge° b d)
  (cond°
    ((fresh° (B C D) (=° b `(and (all ,B) (all ,C))) (=° d `(all ,D))
       (∀° (x) (merge° `(and ,(@ B x) ,(@ C x)) (@ D x)))))
    ((fresh° (q B C D) (=° b `(and (,q ,B) ,C)) (=° d `(,q ,D)) (or° (=° q 'all) (=° q 'some))
       (∀° (x) (merge° `(and ,(@ B x) ,C) (@ D x)))))
(show "prenex is a relation: the book's five answers (here in the order 1 3 2 4 5)"
      (°->list/datum (fresh° (q) (prenex° `(and (all ,(ƛ (x) `(q ,x ,x))) (all ,(ƛ (z) `(all ,(ƛ (y) `(q ,z ,y)))))) q))))
;; prenex is a relation: the book's five answers (here in the order 1 3 2 4 5)
((all (ƛ (x) (all (ƛ (x1) (and (q x x) (q x x1))))))
 (all (ƛ (x) (all (ƛ (x1) (and (q x1 x1) (q x x1))))))
 (all (ƛ (x) (all (ƛ (x1) (all (ƛ (x2) (and (q x x) (q x1 x2))))))))
 (all (ƛ (x) (all (ƛ (x1) (all (ƛ (x2) (and (q x1 x1) (q x x2))))))))
 (all (ƛ (x) (all (ƛ (x1) (all (ƛ (x2) (and (q x2 x2) (q x x1)))))))))

Tutorial (matching the answers to the book’s). Rename the binders: our second answer, ∀x∀x1. (q x1 x1)∧(q x x1)\forall x\forall x_1.\,(q\,x_1\,x_1)\wedge(q\,x\,x_1), is the book’s third, all z\ all x\ (q x x) && (q z x); our third is the book’s second. The other three are in the book’s position. So all five forms are found, in the order 1 3 2 4 5.

Why the difference? merge° has three clauses that apply to a conjunction of two universals: the one that merges both quantifiers into one ((all B) && (all C)), and the two that pull out only the left or only the right one. λProlog tries them depth first, so all the answers of the first clause come before those of the second. micro interleaves the branches of cond°, so an answer that a later branch reaches in fewer steps can come first (Section 2.12.1 and Section 10.6). The set of answers is the book’s, and each answer is found once. The unique prenex form of the book’s first example [MN p. 196] comes out unique too (we ran it separately):

(define f1 `(or (all ,(ƛ (x) `(and (and (p ,x) (all ,(ƛ (y) `(q ,x ,y)))) (p (f ,x))))) (p a)))
(show "prenex: the book's formula with a unique prenex form"
      (°->list/datum (fresh° (q) (prenex° f1 q))))
;; prenex: the book's formula with a unique prenex form
((all (ƛ (x) (all (ƛ (x1) (or (and (and (p x) (q x x1)) (p (f x))) (p a)))))))

(We read the book’s && as left-associative.) The answer is the book’s all x\ all y\ ((p x) && (q x y) && (p (f x))) !! (p a). Every equation in this program is a pattern: (@ B x) and (@ D x) apply a variable to the eigenvariable of the enclosing ∀°.

13.8Higher-order programming

13.8.1mappred

Example 5.8 introduced mappred (Figures 5.3–5.4):

mappred P nil nil.
mappred P (X::L) (Y::K) :- P X Y, mappred P L K.
age bob 23 & age sue 24 & age ned 23.

?- mappred (x\y\ age x y) (ned::bob::sue::nil) L.
L = (23::23::24::nil)
?- mappred (x\y\ age y x) (23::24::nil) K.
K = (bob::sue::nil);
K = (ned::sue::nil)

These are the clauses of [MN p. 127] and the session of [MN p. 129]. A predicate argument is a Scheme procedure here: age° itself for x\y\ age x y, which is η-equal to age, and a Scheme closure for the swapped version.

; §5.3, Figures 5.3-5.4 (p.143): mappred with a relation argument, a Scheme closure here.
(define-relation (age° n a) (cond° ((=° n 'bob) (=° a 23)) ((=° n 'sue) (=° a 24)) ((=° n 'ned) (=° a 23))))
(define-relation (mappred° p l k)
  (cond°
    ((null° l) (null° k))
    ((fresh° (x xs y ys) (=° l `(,x . ,xs)) (=° k `(,y . ,ys)) (p x y) (mappred° p xs ys)))))
(show "mappred (p.143, p.145)"
      (list (°->list/datum (fresh° (q) (mappred° age° '(ned bob sue) q)))
            (°->list/datum (fresh° (q) (mappred° (λ (x y) (age° y x)) '(23 24) q)))))
;; mappred (p.143, p.145)
(((23 23 24)) ((bob sue) (ned sue)))

Both answers, and their order, are the book’s. Nothing of the λ layer is involved: this is the higher-order programming that any Scheme-hosted miniKanren has for free (Section 5.11). The price is the one stated in Section 14.2.1: a predicate is a closure, not a term, so a program cannot unify predicates, quantify over them (pi rev\), or assume clauses for a predicate variable.

13.8.2Palindromes with functional difference lists (book Fig. 5.11)

Section 5.7.2 represented a list by an abstraction over its tail, so that both ends can be reached in one unification step:

palindrome (fdl x\x).
palindrome (fdl x\ Y::x).
palindrome (fdl x\ Y::(F (Y::x))) :- palindrome (fdl F).

?- palindrome (fdl x\ a::b::c::b::a::x).
solved
?- palindrome (fdl x\ a::b::a::(F x)).
F = x\ x;
F = x\ b::a::x;
F = x\ a::b::a::x;
F = x\ Y::a::b::a::x;
F = x\ Z::Z::a::b::a::x;
F = x\ Y::Z::Y::a::b::a::x;
F = x\ Y::Z::Z::Y::a::b::a::x;
F = x\ Y::Z::U::Z::Y::a::b::a::x;
F = x\ Y::Z::U::U::Z::Y::a::b::a::x

This is the program and the session of [MN p. 142–143]. The third clause is outside LλL_\lambda: FF is applied to Y::x, which is not an eigenvariable.

; §5.8.2, Figure 5.11 (p.158): a functional difference list is an abstraction over its tail, and the
; palindrome clauses destructure one by unification, `x\ Y::(F (Y::x))` being no pattern: it waits.
(define-relation (palindrome° f)
  (cond°
    ((=° f `(fdl ,(ƛ (x) x))))
    ((fresh° (Y) (=° f `(fdl ,(ƛ (x) `(,Y . ,x))))))
    ((fresh° (Y F) (=° f `(fdl ,(ƛ (x) `(,Y . ,(@ F `(,Y . ,x)))))) (palindrome° `(fdl ,F))))))
(show "functional difference lists: palindromes (p.158), the book's first nine answers in its order"
      (list (°->list/datum (fresh° (q) (palindrome° `(fdl ,(ƛ (x) `(a b c b a . ,x)))) (=° q 'solved)))
            (°->list/datum (take° 9 (fresh° (q) (palindrome° `(fdl ,(ƛ (x) `(a b a . ,(@ q x))))))))))
;; functional difference lists: palindromes (p.158), the book's first nine answers in its order
((solved)
 ((ƛ (x) x)
  (ƛ (x) (b a . x))
  (ƛ (x) (a b a . x))
  (ƛ (x) (α a b a . x))
  (ƛ (x) (α α a b a . x))
  (ƛ (x) (α β α a b a . x))
  (ƛ (x) (α β β α a b a . x))
  (ƛ (x) (α β γ β α a b a . x))
  (ƛ (x) (α β γ γ β α a b a . x))))

Tutorial (a non-pattern that waits for the recursive call). Follow the third clause on the query fdl x\ a::b::a::(F x), our q.

  1. micro unifies the two lists (fdl ...) cell by cell, and hands the two abstractions to the hook. ξ opens them with one name cc (level ∞\infty): a::b::a::(q c)≐Y::(F (Y::c))a\mathbin{::}b\mathbin{::}a\mathbin{::}(q\,c)\doteq Y\mathbin{::}(F\,(Y\mathbin{::}c)).
  2. The pairs are unified cell by cell: Y:=aY:=a, and b::a::(q c)≐F (a::c)b\mathbin{::}a\mathbin{::}(q\,c)\doteq F\,(a\mathbin{::}c). The right side applies FF to a list, so it is no pattern; the left side is rigid. No side is a pattern, so FR cannot fire, and Delay suspends the equation, closed over the opened name cc: λc. b::a::(q c)≐λc. F (a::c)\lambda c.\, b\mathbin{::}a\mathbin{::}(q\,c)\doteq\lambda c.\, F\,(a\mathbin{::}c).
  3. The recursive call (palindrome° `(fdl ,F)) binds FF in each of its branches. Each binding retries the suspended equation, which has become a pattern equation for qq, or a failure. The second clause, for instance, binds F:=λx. Y′::xF:=\lambda x.\, Y'\mathbin{::}x. The equation becomes b::a::(q c)≐Y′::a::cb\mathbin{::}a\mathbin{::}(q\,c)\doteq Y'\mathbin{::}a\mathbin{::}c, so Y′:=bY':=b and q c≐cq\,c\doteq c, and FR gives q:=λx. xq:=\lambda x.\, x: the first answer, the list a::b::a.

The first clause, F:=λx. xF:=\lambda x.\, x, fails on b≐ab\doteq a; deeper recursions give the longer answers. The answers are the book’s nine, in the book’s order, with α, β, γ for the book’s variables in order of first occurrence (so the fifth answer’s α is the book’s Z). A procedure that rejected non-patterns, as ELPI does by default, would lose this program (Section 11.2).

13.9Fischer’s CPS transformation (book Fig. 10.6)

Section 8.2.5 presented the book’s relational CPS transformation. It has no clause for variables: going under a binder, phi assumes how the bound variable translates.

ftrans (abs V) (abs k\ k @ U) :- phi (abs V) U.
ftrans (M @ N) (abs k\ P @ (abs m\ Q @ (abs n\ m @ k @ n))) :-
   ftrans M P, ftrans N Q.
phi (abs M) (abs k\ abs x\ (P x) @ k) :-
   pi x\ pi y\ ftrans x (abs k\ k @ y) => ftrans (M x) (P y).

?- ftrans ((abs u\u) @ (abs u\u)) F.
F = (abs W1\ (abs (W2\ W2 @ abs W3\ abs W4\ abs (W5\ W5 @ W4) @ W3)) @
     (abs W2\ (abs (W3\ W3 @ abs W4\ abs W5\ abs (W6\ W6 @ W5) @ W4)) @
     (abs W3\ W2 @ W1 @ W3))).

This is Figure 10.6 and the session of [MN p. 257]. The object application M @ N is the list (app M N):

; §10.3.2, Figure 10.6 (p.273): Fischer's CPS transformation; object application `M @ N` is `(app M N)`.
; There is no clause for variables: going under a binder assumes ftrans x (abs k\ k @ y).
(define-dynamic-relation (ftrans° m f)
  (cond°
    ((fresh° (V U) (=° m `(abs ,V)) (=° f `(abs ,(ƛ (k) `(app ,k ,U)))) (phi° m U)))
    ((fresh° (M N P Q) (=° m `(app ,M ,N)) (ftrans° M P) (ftrans° N Q)
       (=° f `(abs ,(ƛ (k) `(app ,P (abs ,(ƛ (m) `(app ,Q (abs ,(ƛ (n) `(app (app ,m ,k) ,n))))))))))))))
(define-relation (phi° m u)
  (fresh° (M P) (=° m `(abs ,M)) (=° u `(abs ,(ƛ (k) `(abs ,(ƛ (x) `(app ,(@ P x) ,k))))))
    (∀° (x y) (⊃° ((ftrans° x `(abs ,(ƛ (k) `(app ,k ,y))))) (ftrans° (@ M x) (@ P y))))))
(show "ftrans ((abs u\\u) @ (abs u\\u)) F" (°->list/datum (fresh° (q) (ftrans° `(app (abs ,(ƛ (u) u)) (abs ,(ƛ (u) u))) q))))
;; ftrans ((abs u\u) @ (abs u\u)) F
((abs (ƛ (k)
         (app (abs (ƛ (k1)
                      (app k1
                           (abs (ƛ (k2)
                                   (abs (ƛ (x) (app (abs (ƛ (k3) (app k3 x))) k2))))))))
              (abs (ƛ (m)
                      (app (abs (ƛ (k1)
                                   (app k1
                                        (abs (ƛ (k2)
                                                (abs (ƛ (x) (app (abs (ƛ (k3) (app k3 x))) k2))))))))
                           (abs (ƛ (n) (app (app m k) n))))))))))

Tutorial (reading the answer against the book’s term). Map k to W1 and m to the outer W2. The operator part (abs (ƛ (k1) (app k1 (abs (ƛ (k2) (abs (ƛ (x) (app (abs (ƛ (k3) (app k3 x))) k2)))))))) is the book’s abs (W2\ W2 @ abs W3\ abs W4\ abs (W5\ W5 @ W4) @ W3) with k1, k2, x, k3 for W2, W3, W4, W5. The final continuation (abs (ƛ (n) (app (app m k) n))) is abs W3\ W2 @ W1 @ W3. So the answer is exactly the book’s term up to α. The suite compares it with equal? against this datum (A7/cps).

The steps that involve the λ layer are in phi°, called on abs u\u:

  1. M:=λu. uM:=\lambda u.\, u, and the second argument of phi°, the variable u of the clause, is bound to `(abs ,(ƛ (k) `(abs ,(ƛ (x) `(app ,(@ P x) ,k))))). Here (@ P x) is built inside ƛ, with x the placeholder of an object binder: it is the flexible term PP applied to a bound variable.
  2. generic twice: eigenvariables xx, yy. augment: the clause (ftrans° x `(abs ,(ƛ (k) `(app ,k ,y)))).
  3. The goal (ftrans° (@ M x) (@ P y)), that is, ftrans° x (P y)x\ (P\,y), since M xM\,x reduces to xx. backchain on Γ first: P y≐𝖺𝖻𝗌 (λk. 𝖺𝗉𝗉 k y)P\,y\doteq\mathsf{abs}\,(\lambda k.\, \mathsf{app}\ k\ y) is a pattern, ℓ(y)=2>ℓ(P)\ell(y)=2>\ell(P). FR projects yy and imitates the rest: P:=λy. 𝖺𝖻𝗌 (λk. 𝖺𝗉𝗉 k y)P:=\lambda y.\, \mathsf{abs}\,(\lambda k.\, \mathsf{app}\ k\ y). The static clauses fail on xx, which is neither an abs nor an app list.
  4. Once PP is bound, the subterm P xP\,x of u, under the object binder xx, reduces to (abs (ƛ (k3) (app k3 x))), the book’s abs (W5\ W5 @ W4).

13.10Higher-order pattern unification

The book’s Chapter 8 develops pattern unification on small problems with explicit quantifier prefixes (Chapter 7). In the module a prefix is written with goals: a variable created by fresh° outside a ∀° is an outer ∃\exists, an eigenvariable is a ∀\forall. So ∃F ∀x ∀y [… ]\exists F\,\forall x\,\forall y\,[\dots] is (fresh° (F) (∀° (x y) ...)). We use q for the first variable, since it is the one the runners print. The labels 8.A–8.M are those of Section 7.7.

13.10.1Flex-rigid and flex-flex

;; ?- pi x\ F x = g x x.                     F = x\ g x x
;; ?- pi x\ pi y\ F x y = G y x.             F = x\ y\ H y x,  G = H
;; ?- pi x\ pi y\ F x y = F y x.             F = x\ y\ H
(show "flex-rigid and flex-flex"
      (list (°->list/datum (fresh° (q) (∀° (x) (=° (@ q x) `(g ,x ,x)))))
            (°->list/datum (fresh° (q f g) (=° q (list f g)) (∀° (x y) (=° (@ f x y) (@ g y x)))))
            (°->list/datum (fresh° (q) (∀° (x y) (=° (@ q x y) (@ q y x)))))))
;; flex-rigid and flex-flex
(((ƛ (x) (g x x))) (((ƛ (x y) (@ α y x)) α)) ((ƛ (x y) α)))

Tutorial (three rules, three answers).

  1. q x≐g x xq\,x\doteq g\,x\,x: the left side is a pattern (ℓ(x)=1>ℓ(q)=0\ell(x)=1>\ell(q)=0), the right side is rigid. FR replaces each xx by the bound variable: q:=λx. g x xq:=\lambda x.\, g\,x\,x.
  2. f x y≐g y xf\,x\,y\doteq g\,y\,x: two patterns with different heads, so FR on ff (the case FF-diff). Elimination of ff keeps gg with both its arguments, since both are among ff’s, and nothing needs pruning: f:=λx y. g y xf:=\lambda x\,y.\, g\,y\,x, and gg stays free. The book’s HH is our gg, printed α.
  3. q x y≐q y xq\,x\,y\doteq q\,y\,x: FF-same. The arguments agree in no position, so q:=λx y. Hq:=\lambda x\,y.\, H: a constant function ([MN p. 222]; Section 7.5.2).

13.10.2Example 8.H: pruning

∀f ∀g ∃U ∃V ∀w ∀x ∀y [(f (U x y)) = (f (g (V y w)))]

“variable elimination becomes applicable. Using it first generates the pruning substitution λy λw (V′ y) for V and subsequently the substitution λx λy (g (V′ y)) for U” [MN p. 223–224]. We solved it by hand in Example 7.23.

;; Example 8.H (p.239-240): ?- pi w\ pi x\ pi y\ f (U x y) = f (g (V y w)).
;; U = x\ y\ g (V' y),  V = y\ w\ V' y
(show "Example 8.H, pruning: (U V)" (°->list/datum (fresh° (q u v) (=° q (list u v)) (∀° (w x y) (=° `(f ,(@ u x y)) `(f (g ,(@ v y w))))))))
;; Example 8.H, pruning: (U V)
(((ƛ (x y) (g (@ α y))) (ƛ (y w) (@ α y))))

Tutorial (8.H with levels). The prefix gives ℓ(u)=ℓ(v)=0\ell(u)=\ell(v)=0 and ℓ(w)=1\ell(w)=1, ℓ(x)=2\ell(x)=2, ℓ(y)=3\ell(y)=3. Here f is the symbol 'f at the head of a list, a constant of the signature. The book quantifies ff and gg universally at the front of the prefix, before UU and VV; an eigenvariable that every variable may see behaves like a constant, so nothing is lost.

  1. micro unifies the two lists (f ...): f against f, then the hook gets u x y≐g (v y w)u\,x\,y\doteq g\,(v\,y\,w). The left side is a pattern, so FR runs Elim(0,u,(x,y), g (v y w))\mathrm{Elim}(0,u,(x,y),\,g\,(v\,y\,w)).
  2. The walk keeps the constant g. It meets the pattern v y wv\,y\,w: yy is among uu’s arguments and is kept; ww is not, and ℓ(w)=1>0\ell(w)=1>0, so it must go. Pruning binds v:=λy w. v′ yv:=\lambda y\,w.\, v'\,y, with ℓ(v′)=0\ell(v')=0.
  3. The result g (v′ y)g\,(v'\,y) is abstracted over uu’s arguments: u:=λx y. g (v′ y)u:=\lambda x\,y.\, g\,(v'\,y).

The answer is the book’s mgu, with α for V′V'. The binders of vv’s value are named y and w, after the eigenvariables of the query.

13.10.3Example 8.K: delayed raising

∀f ∃U ∀x ∀y ∀z ∃V [(U x) = (f V)]

“we would replace V with the term (V′ x), where V′ is a new variable quantified at the same place in the prefix as U and would produce the unifying substitution λx (f (V′ x)) for U” [MN p. 225]; see Example 7.31.

;; Example 8.K (p.240-241): ?- pi x\ pi y\ pi z\ sigma V\ U x = f V.      U = x\ f (V' x)
(show "Example 8.K, delayed raising" (°->list/datum (fresh° (q) (∀° (x y z) (fresh° (v) (=° (@ q x) `(f ,v)))))))
;; Example 8.K, delayed raising
((ƛ (x) (f (@ α x))))

Here ℓ(q)=0\ell(q)=0 and vv is created after three ∀°, so ℓ(v)=3\ell(v)=3. Elimination of qq over the pattern (x)(x) meets vv, a variable younger than qq. It is lowered to qq’s level and raised over those arguments of qq that vv may see: ℓ(x)=1≤ℓ(v)\ell(x)=1\le\ell(v), so v:=v′ xv:=v'\,x with ℓ(v′)=0\ell(v')=0, and q:=λx. f (v′ x)q:=\lambda x.\, f\,(v'\,x). No raising over yy and zz ever happens: the levels record the information that the book proposes to keep “with each existentially quantified variable”, and elimination reads it only when it is needed.

13.10.4Failures: occurs check, scope (8.G, 8.I, 8.J)

;; Examples 8.G, 8.I, 8.J: X = f X;  U x y = g (U y w);  U x y = g w.      no, no, no
(show "Examples 8.G (occurs), 8.I (occurs under a flexible head), 8.J (scope)"
      (list (°->list #f (fresh° (q) (=° q `(f ,q))))
            (°->list #f (fresh° (q) (∀° (w x y) (=° (@ q x y) `(g ,(@ q y w))))))
            (°->list #f (fresh° (q) (∀° (w x y) (=° (@ q x y) `(g ,w)))))))

;; ∃F∀x. F = x fails; ∃F∀x. F x = x gives F = λz.z.
(show "scope: F = x versus F x = x"
      (list (°->list #f (fresh° (q) (∀° (x) (=° q x))))
            (°->list/datum (fresh° (q) (∀° (x) (=° (@ q x) x))))))
;; Examples 8.G (occurs), 8.I (occurs under a flexible head), 8.J (scope)
(() () ())

;; scope: F = x versus F x = x
(() ((ƛ (x) x)))
  • 8.G, X≐f XX\doteq f\,X, is first-order: micro’s own occurs check rejects it.
  • 8.I, U x y≐g (U y w)U\,x\,y\doteq g\,(U\,y\,w) (Example 7.24): elimination of UU meets U y wU\,y\,w below the rigid constant gg, with as many rigid arguments as U x yU\,x\,y has. No instance of UU can make the right side as small as the left, so this is an occurs failure (Nipkow’s size argument, case (6a) of Definition 12.7).
  • 8.J, U x y≐g wU\,x\,y\doteq g\,w (Example 7.25): ww is not among UU’s arguments and ℓ(w)=1>ℓ(U)=0\ell(w)=1>\ell(U)=0. It appears “in a position that is not the argument of a flexible term” [MN p. 224], so no pruning can remove it: a scope failure.
  • ∃F∀x. F=x\exists F\forall x.\,F=x is the first query of Section 13.3 again, while ∃F∀x. F x=x\exists F\forall x.\,F\,x=x is a pattern problem with the projection F:=λx. xF:=\lambda x.\, x as its answer. The first variable cannot be xx, but it can be a function that returns it.

13.10.5Non-patterns: suspended, reported, woken

Two of the book’s problems have no most general unifier. Example 8.M, ∀x (F x x=x)\forall x\,(F\,x\,x=x), has the two solutions λu v. u\lambda u\,v.\, u and λu v. v\lambda u\,v.\, v [MN p. 208]. Example 8.A, ∀a ∀g ∃F [(F a)=(g a a)]\forall a\,\forall g\,\exists F\,[(F\,a)=(g\,a\,a)], has four [MN p. 213] (Example 7.5). Without Huet’s procedure the module cannot enumerate them, as Teyjus 1 does. It does what Teyjus 2 does: it suspends the equation and reports it (dynamic LλL_\lambda, Section 7.9.1).

;; Example 8.M (p.224): pi x\ F x x = x has two incomparable unifiers: it waits, and is reported.
;; Example 8.A (p.229): F a = g a a, four unifiers: likewise (no Huet enumeration).
(show "non-patterns: 8.M and 8.A, suspended; 8.M woken by F := λa.λb.b"
      (list (°->pretty (fresh° (q) (∀° (x) (=° (@ q x x) x))))
            (°->pretty (fresh° (q) (=° (@ q 'a) '(g a a))))
            (°->list/datum (fresh° (q) (∀° (x) (=° (@ q x x) x)) (=° q (ƛ (a b) b))))))
;; non-patterns: 8.M and 8.A, suspended; 8.M woken by F := λa.λb.b
(((α : (= (ƛ (x) (@ α x x)) (ƛ (x) x))))
 ((α : (= (@ α a) (g a a))))
 ((ƛ (a b) b)))

Tutorial (from suspension to answer).

  1. q x x≐xq\,x\,x\doteq x repeats xx, so it is no pattern: Delay stores it in E. When the ∀° exits, discharge closes it over xx, since a residual that mentions xx stands for ∀x (u=v)\forall x\,(u=v). It is then retried, and stays suspended. The answer is qq unconstrained except for this equation, printed as (= (ƛ (x) (@ α x x)) (ƛ (x) x)): no eigenvariable appears free in an answer.
  2. In the second query 'a is a constant, not an eigenvariable, so q aq\,a is no pattern either. This is 8.A with a in the signature, and it is reported as it stands.
  3. In the third query the suspended 8.M equation is woken by the binding q:=λa b. bq:=\lambda a\,b.\, b: (λa b. b) x x(\lambda a\,b.\, b)\,x\,x reduces to xx, and the equation holds. The answer is the value of qq, with no residual left.

A program can thus solve a non-pattern problem by generating candidates for the unknown function with ordinary goals. The suspended equation then acts as a test. The book’s form of 8.A, with aa universal and FF inside its scope, shows discharge at work. This is the suite’s case A5/non-pattern, run separately:

(show "8.A under ∀ a, raised at exit"
      (°->list #f (fresh° (q) (∀° (a) (fresh° (f) (=° (@ f a) `(g ,a ,a)))) (=° q 'ok))))
;; 8.A under ∀ a, raised at exit
((λ (α)
    (assert (≐ (ƛ (a) (@ α a a)) (ƛ (a) (cons 'g (cons a (cons a '()))))))
    'ok))

Here ff is created inside the scope of aa, so ℓ(f)=1\ell(f)=1, and f af\,a is no pattern for it (aa is not younger than ff). At the exit of ∀°, discharge raises f:=f′ af:=f'\,a with ℓ(f′)=0\ell(f')=0, Miller’s raising (Section 4.5), and closes the equation into λa. f′ a a≐λa. g a a\lambda a.\, f'\,a\,a\doteq\lambda a.\, g\,a\,a, over f′f', which prints as α.

13.10.6Occurrences that must not be pruned

The subtle part of dynamic LλL_\lambda is what elimination may do inside the arguments of a non-pattern. The book’s advice is to “defer further consideration of this equation until such time that substitutions resulting from solving other parts of the problem have altered its status” [MN p. 226]. Two examples of examples.scm show why deferring is necessary.

;; Dynamic L_λ (p.241-242): G may drop its argument, so nothing inside it is pruned or lowered. The
;; equation ∃q∃G∃H∀y. q = G (H y) waits, closed over y at ∀ exit, and is solved by G := λa.k. Likewise
;; pi y\ F a = F y holds with any constant F: it waits, then F := λz.c solves it, and F := λz.z does not.
(show "non-strict occurrences: q = G (H y), and F a = F y"
      (list (°->pretty (fresh° (q G H) (∀° (y) (=° q (@ G (@ H y))))))
            (°->list/datum (fresh° (q G H) (∀° (y) (=° q (@ G (@ H y)))) (=° G (ƛ (a) 'k))))
            (°->pretty (fresh° (q) (∀° (y) (=° (@ q 'a) (@ q y)))))
            (°->list/datum (fresh° (q) (∀° (y) (=° (@ q 'a) (@ q y))) (=° q (ƛ (z) 'c))))
            (°->list/datum (fresh° (q) (∀° (y) (=° (@ q 'a) (@ q y))) (=° q (ƛ (z) z))))))
;; non-strict occurrences: q = G (H y), and F a = F y
(((α : (= (ƛ (y) α) (ƛ (y) (@ β (@ γ y))))))
 (k)
 ((α : (= α (ƛ (y) (@ α a)))))
 ((ƛ (z) c))
 ())

Tutorial (why q = G (H y) must wait). All of qq, GG, HH have level 0, and ℓ(y)=1\ell(y)=1.

  1. micro binds q:=G (H y)q:=G\,(H\,y), and Check looks at the bound term. G (H y)G\,(H\,y) is no pattern: its argument is a flexible term, not an eigenvariable. Inside that argument is yy, which qq may not see. Pruning HH’s argument (H:=λz. H′H:=\lambda z.\, H') would be a guess: if GG ignores its argument, yy disappears with no pruning at all, so pruning would lose solutions. The occurrence of yy is not strict (Definition 12.7 and the tutorial after it, after Dowek, Hardin, Kirchner and PfenningGilles 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).
  2. So Check takes the binding back (μkanren-state-forget) and suspends the equation q≐G (H y)q\doteq G\,(H\,y). At the exit of ∀° it is closed over yy, and prints as λy. q≐λy. G (H y)\lambda y.\, q\doteq\lambda y.\, G\,(H\,y).
  3. In the second query G:=λa. kG:=\lambda a.\, k wakes it: λy. q≐λy. k\lambda y.\, q\doteq\lambda y.\, k, so q:=kq:=k, and the answer is (k).

The equation q a≐q yq\,a\doteq q\,y is similar. It holds for every constant function qq, so failing it as an occurs error, or pruning, would be wrong. Only the right side q yq\,y is a pattern, so FF-one runs FR on it, with the sides swapped; elimination meets qq itself below binders only, and suspends. At the exit the equation is closed over yy into λy. q y≐λy. q a\lambda y.\, q\,y\doteq\lambda y.\, q\,a, whose left side η-contracts to qq: that is the printed (= α (ƛ (y) (@ α a))). q:=λz. cq:=\lambda z.\, c satisfies it; q:=λz. zq:=\lambda z.\, z would need a=ya=y, and fails.

Pitfall (a residual is a condition, not a proof). An answer with a suspended equation means: this is a solution if the residual has one. The module does not decide that, since general higher-order unification is undecidable (Section 4.9). Several residuals may even be jointly unsatisfiable, and the answer would still be printed (Section 14.2.3, the case limits/no-huet). Treat (assert (≐ ...)) in an answer as a question returned to the program. Generating candidates, as in the 8.M query above, is one way to answer it.

13.11Ma and Friedman 2021, answered by λProlog’s semantics

Section 9.2 described Ma and Friedman’s proposalWeixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2021. Their unifier treats a logic variable under binders as a static closure that may refer to the binders by position, so that (== (λ (a) X) (λ (b) b)) succeeds with XX = d0, the level of the binder. Section 9.3.1 gave three counter-examples that compare this reading with pattern unification and with nominal unification. The module takes the other side: a logic variable outside a binder cannot depend on it, as in λProlog. This section runs the paper’s queries and states each difference. All the outputs below are from examples.out, except the ones marked as run separately.

The paper does not number its code boxes. We call them E1–E12 in their order of appearance, with the paper’s page; “Example 1–3” are the paper’s own numbered examples of its Section 4.

13.11.1Where the answers agree

The paper’s E2 (p. 2) and E12 (p. 7):

> (run 1 X
    (== (λ (a) a) (λ (b) b)))
'(_0)
>(run 1 F
   (all (A)
     (== A (F A))))
'((lambda (_0) _0))

(the paper’s transcripts). In the module, run separately (the second query is also in examples.out):

(show "E2: λa.a = λb.b;  E8: λx.λy.x y = λa.λa.a a"
      (list (°->list #f (fresh° (q) (=° (ƛ (a) a) (ƛ (b) b))))
            (°->list #f (fresh° (q) (=° (ƛ (x y) (@ x y)) (ƛ (a a) (@ a a)))))))
(show "E12: (run 1 F (all (A) (== A (F A))))"
      (°->list/datum (fresh° (q) (∀° (a) (=° a (@ q a))))))
;; E2: λa.a = λb.b;  E8: λx.λy.x y = λa.λa.a a
(((λ (α) α)) ())

;; E12: (run 1 F (all (A) (== A (F A))))
((ƛ (a) a))

E2 is α-equivalence of closed terms, decided by ξ. E12 is the pattern F a≐aF\,a\doteq a under generic, solved by projection, exactly as the paper says: “the == operator recognizes β-equivalence” (p. 7). E8, λx. λy. x y≐λa. λa. a a\lambda x.\, \lambda y.\, x\,y\doteq\lambda a.\, \lambda a.\, a\,a, is the paper’s second “false positive” of binder-merging (p. 4). Here it fails, as it must: the right side is λa. λb. b b\lambda a.\, \lambda b.\, b\,b, and Rigid meets xx against bb, two different opened names.

13.11.2Where the answers differ

(show "λa.X = λb.b fails (the paper: X = d0); λa.λa.X = λc.λd.c fails; ∀A. A = F A gives F = λA.A"
      (list (°->list #f (fresh° (q) (=° (ƛ (a) q) (ƛ (b) b))))
            (°->list #f (fresh° (q) (=° (ƛ (a) (ƛ (a) q)) (ƛ (c) (ƛ (d) c)))))
            (°->list/datum (fresh° (q) (∀° (a) (=° a (@ q a)))))))
;; λa.X = λb.b fails (the paper: X = d0); λa.λa.X = λc.λd.c fails; ∀A. A = F A gives F = λA.A
(() () ((ƛ (a) a)))

and, run separately, the paper’s Example 3, the three counter-examples of Section 9.3.1 (the first is the paper’s conjunction, the third is shown again with two ground variants), and the paper’s assume query:

(show "their Example 3: λa.λb.X = λc.λd.Y"
      (°->list/datum (fresh° (q X Y) (=° q (list X Y)) (=° (ƛ (a b) X) (ƛ (c d) Y)))))
(show "counter-example 1: λa.X = λb.b ∧ λc.X = λd.d"
      (°->list #f (fresh° (q) (=° (ƛ (a) q) (ƛ (b) b)) (=° (ƛ (c) q) (ƛ (d) d)))))
(show "counter-example 2: Q = X ∧ λa.X = λb.b"
      (°->list #f (fresh° (q x) (=° q x) (=° (ƛ (a) x) (ƛ (b) b)))))
(show "counter-example 3 and its variants"
      (list (°->list #f (fresh° (q) (=° (ƛ (a) (ƛ (a) q)) (ƛ (c) (ƛ (d) c)))))
            (°->list #f (fresh° (q) (=° (ƛ (a) (ƛ (a) a)) (ƛ (c) (ƛ (d) c)))))
            (°->list #f (fresh° (q) (=° (ƛ (a) (ƛ (a) a)) (ƛ (c) (ƛ (d) d))) (=° q 'ok)))))
(define-dynamic-relation (eq° a b) (=° a b))
(show "(assume (== apple orange) (== apple X)) with a dynamic eq°"
      (°->list/datum (fresh° (q) (⊃° ((eq° 'apple 'orange)) (eq° 'apple q)))))
;; their Example 3: λa.λb.X = λc.λd.Y
((α α))

;; counter-example 1: λa.X = λb.b ∧ λc.X = λd.d
()

;; counter-example 2: Q = X ∧ λa.X = λb.b
()

;; counter-example 3 and its variants
(() () ((λ () 'ok)))

;; (assume (== apple orange) (== apple X)) with a dynamic eq°
(orange apple)

For comparison, the paper’s transcripts of E5, E6 (p. 3) and E11 (p. 7):

> (run 1 X
    (== (λ (a) X) (λ (b) b)))
'(d0)
> (run 1 X
    (== (λ (a) X) (λ (b) b))
    (== (λ (c) X) (λ (d) d)))
'(d0)
>(run 2 X
   (assume (== 'apple 'orange)
     (== 'apple X)))
'(apple orange)

Tutorial (each difference, and the reason for it).

  1. λa. X≐λb. b\lambda a.\, X\doteq\lambda b.\, b (E3–E5, p. 2–3). The paper answers (d0). Here ξ opens both sides with a new name cc and leaves X≐cX\doteq c, which Check rejects: cc was opened below a binder that XX is outside of. Read with quantifiers, the equation is ∃X ∀c. X=c\exists X\,\forall c.\,X=c, the first query of Section 13.3 and Example 8.J with no arguments, which is false: no single XX equals every cc ([MN p. 85]; Example 7.25). The paper itself grants that this failure is what every existing algorithm answers: “Under any existing higher-order unification algorithm, X and a cannot be unified due to the scope restrictions” (p. 2). It then calls the failure “counter-intuitive” (p. 3).
  2. The conjunction with λc. X≐λd. d\lambda c.\, X\doteq\lambda d.\, d (E6, p. 3). The paper again answers (d0), by the same grafting. Both conjuncts fail here.
  3. Q=X∧λa. X≐λb. bQ=X\wedge\lambda a.\, X\doteq\lambda b.\, b (counter-example 2). With static closures, QQ would be bound to a level that is not available where QQ lives. Here it fails like item 1. Under the quantifier reading the variables have no positions to refer to, so this problem cannot arise.
  4. λa. λa. X≐λc. λd. c\lambda a.\, \lambda a.\, X\doteq\lambda c.\, \lambda d.\, c (E7, p. 4). It fails, in the paper’s algorithm too (their Example 2). The paper’s warning is about binder-merging implementations that turn the ground term λa. λa. a\lambda a.\, \lambda a.\, a, which is false, into true. Here the inner a shadows the outer one by Scheme’s scoping, and the printer renames apart (Section 13.2). So false = true fails, and false = false succeeds: the second and third answers.
  5. Example 3, λa. λb. X≐λc. λd. Y\lambda a.\, \lambda b.\, X\doteq\lambda c.\, \lambda d.\, Y (p. 6). The paper needs a context, a postponed equation between closures, because XX and YY might refer to the binders by position. Here neither may depend on the binders, so the equation is simply X≐YX\doteq Y, solved by Var: ((α α)), with no postponed part.
  6. assume (E11, p. 7). The paper’s query, shown above, gives '(apple orange). The paper gives no operational account; the natural reading is ordinary unification first, then the hypothesis. λProlog cannot write this query, since = is not a predicate one can assume clauses for. With a dynamic eq° whose static body is =°, the hypothesis comes first, by the rule of [MN p. 78] (Section 13.4.1): (orange apple).

Kanren angle (what the comparison shows). The two systems agree wherever the problem is about closed terms or about patterns under ∀: α, the “true = false” hazard of ground terms, and E12. On unification they differ exactly where a logic variable occurs under an object binder that it is not applied to (the order of the assume answers is a separate matter, of clause order). There, Ma and Friedman give the variable access to the binders by position. The module keeps the quantifier reading: a variable outside a binder cannot see it, and a variable that should depend on a binder must be applied to it. We ran

(show "λa.F a = λb.b: a variable applied to the binder"
      (°->list/datum (fresh° (q) (=° (ƛ (a) (@ q a)) (ƛ (b) b)))))
;; λa.F a = λb.b: a variable applied to the binder
((ƛ (b) b))

Read with quantifiers this is ∃q ∀a. q a=a\exists q\,\forall a.\,q\,a=a, a pattern problem whose answer is the projection. The design options are compared in Section 9.8, and the choice is argued in Chapter 11.

13.12The examples at a glance

One row per example: the book’s page, the place in Part I where the example was introduced, and how the module’s answers compare with λProlog’s. “Same” means the same answers in the same order.

examplebookPart Iorder of the answers against λProlog
∃∀ / ∀∃, aliases[MN p. 85]Section 3.4.3failure/success as in the book
clause order[MN p. 78]Section 3.2same: (3 2 1), (2 3 1)
courses[MN p. 80–81]Section 3.3.2same answers; all proofs listed, the book shows the first
jars[MN p. 83]Section 3.4same
reverse[MN p. 87]Section 3.5same; one answer backwards
typeof[MN p. 190–191]Section 6.5.4same; backwards finds terms where DFS loops
cbn[MN p. 183]Section 6.3.2same
copy, subst[MN p. 199–200]Section 6.7same
existential generalisation[MN p. 202]Section 6.7same four, same order
de Bruijn[MN p. 193–194]Section 6.5.5same terms, both directions
prenex[MN p. 196–197]Section 6.6.3same five, in the order 1 3 2 4 5
mappred[MN p. 129]Example 5.8same
palindromes[MN p. 142–143]Section 5.7.2same nine, same order
CPS[MN p. 257]Section 8.2.5same term
8.H, 8.K[MN p. 223–225]Example 7.23 and Example 7.31the book’s mgus
8.G, 8.I, 8.J[MN p. 222,224]Example 7.24 and Example 7.25failures
8.M, 8.A[MN p. 208,213]Example 7.5suspended and reported (no enumeration)
Ma–Friedman—Section 9.3.1λProlog’s answers; differences above

13.13Summary

  • Every core example of the book runs in (aux kanren lambda) with the book’s answers: the hypothetical queries of Chapter 3, type inference, substitution, the de Bruijn translation, prenex forms, palindromes and the CPS transformation, and the unification problems of Chapter 8 (the two without a most general unifier are reported, not solved).
  • The answer order is the book’s in every example except prenex normal forms (1 3 2 4 5) and the courses query, whose duplicate proofs come in the interleaving’s order. Answers come in clause order when every clause answers at once, because a dynamic relation is one flat disjunction: hypotheses most recent first, then the static body.
  • Scope is enforced by levels at every binding. ∃Y∀x. Y = x fails, ∀x∃Y. Y = x succeeds, and an eigenvariable cannot escape through an alias, through a relation built on =°, or through the variables of a clause: lowering gives each such variable the level of the variable it is bound into.
  • Clauses assumed with ⊃° share their free variables with the context, as rev nil K and fact (finished dana X) need. Their own ∀ variables are renamed at each use.
  • β is applied on demand: (@ R N) built with R unknown reduces as soon as R is bound. Call-by-name evaluation works, and subst R N (R N) works with R bound before or after the equation.
  • Pattern problems give the book’s most general unifiers, read off the levels: projection, imitation, pruning (8.H), lowering with delayed raising (8.K), and the occurs and scope failures (8.I, 8.J).
  • Non-patterns are suspended, closed over the eigenvariables that leave their scope, retried at every binding, and reported as (assert (≐ ...)). That is enough for the palindrome program and for generate-and-test over 8.M, but not for enumerating the unifiers of 8.M or 8.A.
  • Against Ma and Friedman 2021 the module gives λProlog’s answers. It agrees on α, on the “true = false” hazard and on E12. It disagrees where a variable occurs under a binder it is not applied to (λa.X = λb.b fails), and on the order of the answers of assume.