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 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 Kanren. 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.
- The λProlog original, copied from the book, with its printed page
[MN p. n].The “p.N” in the labels of
examples.scmare PDF pages; the prose uses printed pages (see Section 1.5). - 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 atf84cf9c.The merge moved the programs, unchanged, tosrc/test/microkanren-lambda-programs.scm(Section 14.4). - The answers, pasted verbatim from
examples.out, the actual output of the script. Run on the merged tree (masteratc0ff08c), 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. - 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 withequal?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 valueok. 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 of a logic variable is the number of
∀°goals around the point where it was created. The level of an eigenvariable is the depth of the∀°that created it, counting that∀°. The names that the unifier opens below binders have level . A variable of level may be bound only to a term whose eigenvariables have level : it stands for an placed after the first universals of its branch. - A pattern for is a list of arguments that reduce to distinct eigenvariables, each of level greater than . This is Miller’s condition “quantified inside the scope of ”, read off the levels (Section 7.5, Section A.10 and Definition 12.5).
For instance, in (fresh° (q) (∀° (x) (fresh° (y) ...))) we have , and
: the list is a pattern for but not for , and may be bound to while
may not.
| rule | fires on | effect |
|---|---|---|
| Var, Check | , unbound | micro binds after its occurs check. Then the scope check fails on an eigenvariable of level , lowers the younger variables of to , and prunes flexible subterms. A non-pattern it cannot decide turns the binding back into a suspended equation. |
| ξ | open both bodies with one new name (level ), unify them, and Check the bindings made under it | |
| η | , no abstraction | unify with , new (level ); only when one side is an abstraction |
| Rigid | same head and arity: unify the arguments; otherwise fail | |
| FF-same | , both patterns | : success; arities differ: fail; else , |
| FR | , a pattern, rigid or flexible with another head (the case “FF-diff”) | . In : each becomes the -th bound variable (projection); constants, and eigenvariables of level , are kept (imitation); an eigenvariable out of reach fails (8.J); a flexible pattern loses the arguments may not see (pruning, 8.H); a younger variable is lowered to and raised over the it may see (8.K); an occurrence of fails when no instance can make it smaller (8.I), and otherwise suspends |
| FF-one | , only a pattern | FR on |
| Delay | no side a pattern | unless the sides are α-equal, suspend in the store E (: the names opened so far); every later binding retries it; at the end it prints as (assert (≐ u v)) |
| Occurs | with inside a λ-term of | succeed if reduces to , else eliminate with no arguments |
| generic | (∀° (x) g) | a new eigenvariable at depth; runs one level deeper; every answer gets the depth back |
| discharge | leaving ∀° (back to depth ) with residuals on | raise , , for each variable of the residual with ; close the residual into ; retry it; repeat while a raise brings into more constraints (Section 12.4.2) |
| augment | (⊃° (D ...) g ...) | push the clauses on Γ for only; every answer gets Γ back |
| backchain | a call of a dynamic relation | one 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).
(ƛ (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 namesx,ysurvive only as printing hints.=°bindsqto 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.(=° (ƛ (a) a) (ƛ (b) b))is decided by ξ: both bodies are opened with the same new name , and holds. Nothing is bound, soqstays 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.(@ f 'a)receives the logic variablef, not its value:@is a Scheme procedure and does not consult the state. So it builds the flexible application . Oncefis bound to , the reifier’s deep walk contracts the β-redex, and the answer is(g a a), as(x\ g x x) ais in λProlog.- λa.λa.a is the term λa.λb.b: the inner binder shadows the outer one, because the inner Scheme
ashadows the outera. 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 for levels. In each query q is created by the outer fresh°, at depth 0, so
.
- . generic creates the eigenvariable with
and runs
(=° q x)at depth 1. micro binds , then theposthook runs Check: is an eigenvariable with , so the binding fails. The query has no answer:(). - . Now
yis created inside the∀°, so and 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 ofyis not part of the answer, which is what λProlog does for a variable quantified insidepi x\. - The alias.
yhas level 1 again. The first goal binds . Check of this binding finds the younger variable inside a term bound to the older , and lowers it: with . This is condition (3) of Nadathur, Jayaraman and Kwon’s binding rule, quoted in Section 3.4.3: the variables of take the level of . The second goal walks to and binds , which Check now rejects, since . Without lowering, would escape into through . The suite checks both orders of the two goals (A1/alias). - micro’s
cons°.cons°is an ordinary relation of micro, defined with=°. Since the check runs in=°’sposthook, 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 , the goal must fail, while 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 and . backchain on (p° x) runs the static
body, which creates the clause’s own z at depth 1, so . The binding puts
the younger inside the older , and Check lowers it: with . The call
(q° z') then finds the hypothesis (q° y), and fails, since .
In the second query is created inside the ∀°, so ; is not lowered, and
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 , add to the program and prove
. 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).
(define-dynamic-relation (p° x) (=° x 1))makesp°a dynamic relation whose static body is(=° x 1), the clausep 1.- First query. The outer
⊃°setsp°. The inner one puts its clause in front:p°. - The call
(p° q)is backchain: one flat disjunction , 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). - Second query. One
⊃°assumes both clauses, which are kept in the order written:p°, 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).
(false°)runs its body:xis new, and(fact° `(finished ,x 210))is a backchain on Γ first. The hypothesis unifies(finished dana q)with(finished x 210): , .(fact° '(finished dana 250))succeeds from the static body.- The static clauses also prove
(finished x 210), with . 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).
(sterile° q): . generic creates the eigenvariable , , and the depth becomes 1.- Two augments:
in°,bug°. The clause(in° x j)closes over thejofsterile°, which isq. (dead° x)has no hypothesis, so backchain runs its static body. It createsj'at depth 1, and(heated° j')binds .(in° x j')backchains on the hypothesis: it unifies with , so . Check accepts it: the constantjcontains no eigenvariable.(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 are the two hypotheses. Had a step tried to bind q to something containing ,
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 .
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: and 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 , take a new constant , assume that it has type , 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.
noThese 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).
(typeof° m q)with(abs ,(ƛ (x) x)). backchain: Γ has no hypothesis yet, so only the staticcond°runs. Theappbranch fails on(=° m `(app ,M ,N)).- The
absbranch binds and ; , , have level 0. - generic: an eigenvariable
x, call it , with . augment:typeof°. - The goal
(typeof° (@ R x) B). As in the previous example,(@ R x)receives the logic variable , not its value, so it is the flexible term . Since is bound, every walk reduces it to . - backchain on Γ first: the hypothesis unifies with , so
, a variable–variable binding with no eigenvariable in it (micro binds the older
variable to the newer one). Then the static clauses fail: is neither
an
appnor anabslist. - The
∀°exits: depth 0, Γ empty. The answer is , printed(arr α α).
For the hypothesis is used twice: once for the head, giving ,
once for the argument, giving , 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 and for .
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 with unknown: a pattern, solved by FR with the
projection . 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:
. When the second call (cbn° (@ R N) v) unifies its first
argument with `(abs ,R'), the walk of contracts the redex to (abs ,(ƛ (w) w)). The
argument 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 #
The one-line subst R N (R N) is the book’s example of a clause outside 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 in either order of the goals. This query is the suite’s case A4/beta, run separately,
with 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 to the flexible term . 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 , and the reifier’s deep walk contracts the
redex. Had the first binding involved an eigenvariable that only the value of could keep or drop,
Check would have turned it into a suspended equation (Delay), retried when 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 and [MN p. 199]. In the module:
- The
absclause binds and . generic gives at level 1, augment assumes(copy° c c), and the goal iscopy°. - The
absclause again. The equation is a pattern for : FR binds . was created at level 1, inside the first∀°, so it is lowered and raised over : (the 8.K step of Section 13.10). The book’s is our . - A second generic gives at level 2, and
(copy° d d)is assumed. The goal iscopy°. Theappclause binds by FR, and the hypotheses give , , by projection. - Each
∀°exits with no residual. The answer is , the book’sabs v\abs u\app u vup 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 (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).
substform°creates the eigenvariable (level 1), assumes(copyterm° x '(f a)), and callscopyform°on , a flexible pattern, against the formula.- The first
copyform°clause matches(op B C)on the left: is solved by FR. The variables , , were created at level 1, so elimination lowers them and raises them over : . The next goal unifies the formula(and ...)with(op D E), so gives by imitation, and theor°then acceptsand. The two halves are copied in turn. - For the first half, the
pclause gives and then(copyterm° (X' x) '(f a)). backchain tries the hypothesis first: gives by projection, which is the answer . Then the static clauses: and(copyterm° (X'' x) 'a), where only the constantaclause applies, and by imitation: the answer . - The second half does the same for . The occurrence of
ahas only the static answer, since the hypothesis copies to , not to .
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.
| goal | depth | Γ for depth° (most recent first) |
|---|---|---|
trans 1 (abs x\ abs y\ abs z\ y) P | 0 | — |
trans 2 (abs y\ abs z\ y) P1 | 1 | |
trans 3 (abs z\ c2) P2 | 2 | |
trans 4 c2 P3 | 3 |
(We write for the three eigenvariables, all hinted c.) In the last goal only the
third clause applies, since is neither an abs nor an app list. (depth° n c2)
backchains on Γ, most recent first: and fail on and ,
while gives , and project° computes . 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 with unknown, a pattern.
The app clause solves by FR, lowering and
raising them over . The deb clause then meets (depth° n (M1' c)): the hypothesis
(depth° 1 c) gives , 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, , 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::xThis is the program and the session of [MN p. 142–143]. The third clause is outside : 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.
- micro unifies the two lists
(fdl ...)cell by cell, and hands the two abstractions to the hook. ξ opens them with one name (level ): . - The pairs are unified cell by cell: , and . The right side applies 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 : .
- The recursive call
(palindrome° `(fdl ,F))binds in each of its branches. Each binding retries the suspended equation, which has become a pattern equation for , or a failure. The second clause, for instance, binds . The equation becomes , so and , and FR gives : the first answer, the lista::b::a.
The first clause, , fails on ; 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:
- , and the second argument of
phi°, the variableuof the clause, is bound to`(abs ,(ƛ (k) `(abs ,(ƛ (x) `(app ,(@ P x) ,k))))). Here(@ P x)is built insideƛ, withxthe placeholder of an object binder: it is the flexible term applied to a bound variable. - generic twice: eigenvariables , . augment: the clause
(ftrans° x `(abs ,(ƛ (k) `(app ,k ,y)))). - The goal
(ftrans° (@ M x) (@ P y)), that is,ftrans°, since reduces to . backchain on Γ first: is a pattern, . FR projects and imitates the rest: . The static clauses fail on , which is neither anabsnor anapplist. - Once is bound, the subterm of
u, under the object binder , reduces to(abs (ƛ (k3) (app k3 x))), the book’sabs (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 , an eigenvariable is a . So
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).
- : the left side is a pattern (), the right side is rigid. FR replaces each by the bound variable: .
- : two patterns with different heads, so FR on (the case FF-diff). Elimination of
keeps with both its arguments, since both are among ’s, and nothing needs pruning:
, and stays free. The book’s is our , printed
α. - : FF-same. The arguments agree in no position, so : 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 and , , . Here f is the
symbol 'f at the head of a list, a constant of the signature. The book quantifies and
universally at the front of the prefix, before and ; an eigenvariable that every variable may
see behaves like a constant, so nothing is lost.
- micro unifies the two lists
(f ...):fagainstf, then the hook gets . The left side is a pattern, so FR runs . - The walk keeps the constant
g. It meets the pattern : is among ’s arguments and is kept; is not, and , so it must go. Pruning binds , with . - The result is abstracted over ’s arguments: .
The answer is the book’s mgu, with α for . The binders of ’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 and is created after three ∀°, so . Elimination of over the
pattern meets , a variable younger than . It is lowered to ’s level and
raised over those arguments of that may see: , so
with , and . No raising over and 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, , is first-order: micro’s own occurs check rejects it.
- 8.I, (Example 7.24): elimination of meets below the rigid constant , with as many rigid arguments as has. No instance of 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, (Example 7.25): is not among ’s arguments and . 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.
- is the first query of Section 13.3 again, while is a pattern problem with the projection as its answer. The first variable cannot be , 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, , has the two solutions and [MN p. 208]. Example 8.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 , 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).
- repeats , so it is no pattern: Delay stores it in E. When the
∀°exits, discharge closes it over , since a residual that mentions stands for . It is then retried, and stays suspended. The answer is unconstrained except for this equation, printed as(= (ƛ (x) (@ α x x)) (ƛ (x) x)): no eigenvariable appears free in an answer. - In the second query
'ais a constant, not an eigenvariable, so is no pattern either. This is 8.A withain the signature, and it is reported as it stands. - In the third query the suspended 8.M equation is woken by the binding : reduces to , and the equation holds. The answer is the value of , 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 universal and 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 is created inside the scope of , so , and is no pattern for it ( is
not younger than ). At the exit of ∀°, discharge raises with
, Miller’s raising (Section 4.5), and closes the equation into
, over , which prints as α.
13.10.6Occurrences that must not be pruned#
The subtle part of dynamic 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 , , have level 0, and .
- micro binds , and Check looks at the bound term. is no pattern: its argument is a flexible term, not an eigenvariable. Inside that argument is , which may not see. Pruning ’s argument () would be a guess: if ignores its argument, disappears with no pruning at all, so pruning would lose solutions. The occurrence of 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).
- So Check takes the binding back (
μkanren-state-forget) and suspends the equation . At the exit of∀°it is closed over , and prints as . - In the second query wakes it: , so , and the
answer is
(k).
The equation is similar. It holds for every constant function , so failing it as an
occurs error, or pruning, would be wrong. Only the right side is a pattern, so FF-one
runs FR on it, with the sides swapped; elimination meets itself below binders only, and
suspends. At the exit the equation is closed over into , whose left
side η-contracts to : that is the printed (= α (ƛ (y) (@ α a))). satisfies it; would need , 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 Kanren. 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 = 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 under generic, solved by projection, exactly as the paper says: “the == operator recognizes β-equivalence” (p. 7). E8, , is the paper’s second “false positive” of binder-merging (p. 4). Here it fails, as it must: the right side is , and Rigid meets against , 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).
- (E3–E5, p. 2–3). The paper answers
(d0). Here ξ opens both sides with a new name and leaves , which Check rejects: was opened below a binder that is outside of. Read with quantifiers, the equation is , the first query of Section 13.3 and Example 8.J with no arguments, which is false: no single equals every ([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). - The conjunction with (E6, p. 3). The paper again answers
(d0), by the same grafting. Both conjuncts fail here. - (counter-example 2). With static closures, would be bound to a level that is not available where lives. Here it fails like item 1. Under the quantifier reading the variables have no positions to refer to, so this problem cannot arise.
- (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 , which is false, into true. Here
the inner
ashadows 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. - Example 3, (p. 6). The paper needs a
context, a postponed equation between closures, because and might refer to the
binders by position. Here neither may depend on the binders, so the equation is simply
, solved by Var:
((α α)), with no postponed part. 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 dynamiceq°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 , 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.
| example | book | Part I | order of the answers against λProlog |
|---|---|---|---|
| ∃∀ / ∀∃, aliases | [MN p. 85] | Section 3.4.3 | failure/success as in the book |
| clause order | [MN p. 78] | Section 3.2 | same: (3 2 1), (2 3 1) |
| courses | [MN p. 80–81] | Section 3.3.2 | same answers; all proofs listed, the book shows the first |
| jars | [MN p. 83] | Section 3.4 | same |
| reverse | [MN p. 87] | Section 3.5 | same; one answer backwards |
| typeof | [MN p. 190–191] | Section 6.5.4 | same; backwards finds terms where DFS loops |
| cbn | [MN p. 183] | Section 6.3.2 | same |
| copy, subst | [MN p. 199–200] | Section 6.7 | same |
| existential generalisation | [MN p. 202] | Section 6.7 | same four, same order |
| de Bruijn | [MN p. 193–194] | Section 6.5.5 | same terms, both directions |
| prenex | [MN p. 196–197] | Section 6.6.3 | same five, in the order 1 3 2 4 5 |
| mappred | [MN p. 129] | Example 5.8 | same |
| palindromes | [MN p. 142–143] | Section 5.7.2 | same nine, same order |
| CPS | [MN p. 257] | Section 8.2.5 | same term |
| 8.H, 8.K | [MN p. 223–225] | Example 7.23 and Example 7.31 | the book’s mgus |
| 8.G, 8.I, 8.J | [MN p. 222,224] | Example 7.24 and Example 7.25 | failures |
| 8.M, 8.A | [MN p. 208,213] | Example 7.5 | suspended 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 = xfails,∀x∃Y. Y = xsucceeds, 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, asrev nil Kandfact (finished dana X)need. Their own∀variables are renamed at each use. - β is applied on demand:
(@ R N)built withRunknown reduces as soon asRis bound. Call-by-name evaluation works, andsubst R N (R N)works withRbound 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.bfails), and on the order of the answers ofassume.