Chapter 12
The module (aux kanren lambda)
What and why#
Chapter 10 took (aux kanren micro) apart and ended, in Section 10.9, with the list of points an extension
cannot reach from outside: the state has no free slot, and the unifier, the walkers and the reifier are closed.
Chapter 11 opened exactly those points with a small, λ-agnostic protocol of hooks and explained why the
proposal is a client module of that protocol rather than a native engine. This chapter is about the client
itself: the module (aux kanren lambda), which brings into (aux kanren micro) the three ingredients of Part I,
- λ-tree syntax (Chapter 6): object-level binders are meta-level abstractions;
- higher-order pattern unification, (Chapter 7), with universe levels in place of the mixed prefix and with non-patterns suspended (“dynamic ”);
- universal and hypothetical goals, generic and augment, over hereditary Harrop formulas (Chapter 3).
The chapter is the formal heart of the proposal. It states what the terms are (Section 12.1),
what the module keeps in the state (Section 12.2), the unification rules with their side
conditions and the termination argument (Section 12.3), the rules for ∀° and ⊃° and
why levels make them sound (Section 12.4), how micro’s disequality, absence and type constraints
read λ-terms (Section 12.5), how answers are printed (Section 12.6), and, as a
reference, the exported API (Section 12.7). The curated book examples are the subject of
Chapter 13; the known limits, the costs and the merge are in Chapter 14.
The module is src/aux.kanren.lambda.scm, 1427 lines, 984 of them neither blank nor
comment, on master since the commits of Section 14.4. Its suites are
src/test/microkanren-lambda.scm (93 cases, 421 assertions) and
src/test/microkanren-lambda-limits.scm (6 cases), with the book’s
programs in src/test/microkanren-lambda-programs.scm; the prototype it was
ported from stays in doc/hol-kanren/prototype/, frozen at
f84cf9c. Every Scheme snippet below was run on the merged tree, master at
c0ff08c; its output is pasted verbatim under it. The snippets import
(import scheme (chicken base) (chicken pretty-print)
(chicken condition) (chicken memory representation)
(aux base) (aux stream) (aux kanren micro) (aux kanren micro show)
(aux kanren lambda))Several of them use a probe: a goal that prints part of the state and succeeds. A goal of (aux kanren micro) is a
procedure from a state to a stream of states (Definition 10.7), so a probe is three lines; each snippet
shows the one it uses.
12.1Terms#
12.1.1Four records#
First-order structure stays Scheme data, exactly as in (aux kanren micro): pairs, vectors, foreign records and atoms
(Definition 10.1). The module adds four record types, defined at the top of the file:
(define-record μkanren-lam hint body) ; λ.body, locally nameless
(define-record μkanren-app head args) ; head applied to a list of arguments
(define-record μkanren-eigen name level id) ; a scoped constant of GENERIC
(define-record μkanren-bvar index) ; a de Bruijn index, only inside bodiesDefinition 12.1 (λ-terms of the module). Extend the terms of (aux kanren micro) (Definition 10.1) with
where is an eigenvariable of level (μkanren-eigen), a
bound variable with de Bruijn index (μkanren-bvar), an abstraction whose binder
carries the printing hint , a symbol (μkanren-lam), and an application with
(μkanren-app). A term is locally closed when every in it lies below at least
abstractions. Only locally closed terms are ever bound to variables or stored in constraints.
The representation is locally nameless Arthur Charguéraud. The locally nameless representation. Journal of Automated Reasoning, 49(3):363–408, 2012: bound variables are de Bruijn indices N. G. de Bruijn. Lambda calculus notation with nameless dummies, a tool for automatic formula manipulation, with application to the Church–Rosser theorem. Indagationes Mathematicae, 34(5):381–392, 1972, free ones are names (logic variables and eigenvariables). Three design choices follow from it.
- The hint is only for printing, and it is an interned symbol. The binder’s identity is
its position. Two terms built alike are therefore
equal?, so λ-terms can be grouped bygroupby°and compared by the host. - An eigenvariable’s identity is its
id, an uninterned symbol, compared witheq?. Itsnameis a hint and itslevelis the universe it lives in (Section 12.2). Level (+inf.0) marks the names that the unifier opens when it descends under binders and the placeholders thatƛuses while building a body. - The first 64 bound variables are preallocated in a vector, so the common indices allocate nothing.
The de Bruijn operations (shift, instantiate, close) never walk the substitution: a term bound to a variable is locally closed, so a binding never contributes a loose index. Instantiation shifts the substituted term only when it has loose indices itself, which is decided once per instantiation.
12.1.2The constructors ƛ and @#
The user never builds these records by hand. Two constructors give the surface syntax of λ-tree terms:
(define-syntax ƛ
(syntax-rules ()
((_ () body) body)
((_ (x y ...) body) (μkanren-abstract 'x (λ (x) (ƛ (y ...) body))))))
; λ.(f p), with the placeholder p closed into #0
(define (μkanren-abstract name f)
(let1 (p (μkanren-eigen* name +inf.0))
(μkanren-lam/η name (μkanren-close (f p) p))))
(define (@ f . args) (μkanren-beta f args)) ; β at once on an abstraction(ƛ (x) body) binds the Scheme variable x to a fresh placeholder eigenvariable while
body is evaluated, then closes that placeholder into the index #0. The object binder is thus a Scheme
binder: shadowing, lexical scope and quasiquotation all behave as a Scheme programmer expects, which is the
point of λ-tree syntax [MN p. 177]. Two invariants are enforced at construction.
- η-short.
μkanren-lam/ηbuilds as when is not free in . The unifier builds its abstractions the same way. This matters because micro’s own occurs check runs before any hook can see an equation: holds by η, but in η-long form micro would see inside the value it binds to and fail; built η-short, the left side is and the equation is trivial. - β at construction.
@applied to an abstraction β-reduces at once, and nested applications are flattened:(@ (@ f a) b)is(@ f a b).
Example 12.2 (Construction and printing). Every record has a printer that shows its term as data. The raw record of shows the hint
x and the index in the body:
(ƛ (x y) (cons x y))
(record->vector (ƛ (x) `(f ,x))) ; from (chicken memory representation)
(equal? (ƛ (x) `(f ,x)) (ƛ (x) `(f ,x)))
(equal? (ƛ (x) x) (ƛ (y) y))
(μkanren-α=? (ƛ (x) x) (ƛ (y) y))
(@ (ƛ (x) `(g ,x ,x)) 'a)
(ƛ (x) (@ 'g x))
(ƛ (x) `(g ,x))
(@ 'g 'a)
(equal? (@ 'g 'a) '(g a))
(ƛ (a) (ƛ (a) a)) => (ƛ (x y) (x . y))
=> #(aux.kanren.lambda#μkanren-lam x (f #<aux.kanren.lambda#μkanren-bvar>))
=> #t
=> #f
=> #t
=> (g a a)
=> g
=> (ƛ (x) (g x))
=> (@ g a)
=> #f
=> (ƛ (a a1) a1)Line by line: nested binders print merged, (ƛ (x y) ...); the body of a μkanren-lam holds an
index, not the name; terms built alike are equal?; α-variants with different hints are not
equal? but are α-equal; @ reduced the redex; written with @ is the
η-redex of and was built as g; written with a quasiquoted list it is no η-redex (the list
(g x) is data, not an application), so it stays an abstraction; the λ-tree application of a constant
prints with @ and is not the list (g a); shadowing is lexical, and the printer renames the
inner binder apart (Section 12.6).
12.1.3Three kinds of application#
An application is classified by its head after walking it in the current substitution:
Definition 12.3 (Flexible, β-redex, rigid; head normal form). An application is flexible if walks to an unbound logic variable, a
β-redex if walks to an abstraction, and rigid otherwise (a constant, an eigenvariable, a
bound variable). The head normal form (μkanren-hnorm) walks , flattens
nested applications, contracts head β-redexes, and contracts an abstraction whose body has become an
η-redex through a binding (e.g. once ).
Under the restriction every contraction hnf performs is a renaming
(Definition 6.13). On instantiated heads @ gives full β, which is what the book calls
dynamic [MN p. 225–226].
(μkanren-hnorm (@ (ƛ (x) (@ x 'b)) (ƛ (y) `(g ,y ,y))) μkanren-state-empty)
(°->list #f (fresh° (q F) (=° q (@ F 'a))))
(°->list/datum (fresh° (q F) (=° q (list F (@ F 'a))) (=° F (ƛ (z) `(h ,z)))))(g b b)
((λ (α) (@ α 'a)))
(((ƛ (z) (h z)) (h a)))The second answer is a flexible term, printed as (@ α 'a); once is bound (third line) the same
term is a β-redex and its value is (h a).
12.1.4Scheme lists versus λ-tree application#
The object language of the book’s programs is written with Scheme lists, as (aux kanren micro) always did:
is `(abs ,M), is `(app ,M ,N), with a meta-level
abstraction for a binder. The λ-tree application (@ 'g 'a) and the list '(g a) are distinct terms
and never unify:
(°->list #f (fresh° (q) (=° (@ 'g 'a) '(g a)))) => ()This is deliberate. One of the three prototypes identified the two (a spine notation for lists) and lost
commutativity of conjunction: with η, the same pair of goals gave different answers in the two orders. Keeping
lists as data and @ as the only application keeps (aux kanren micro)’s first-order unification untouched for lists,
and confines the higher-order rules to terms that contain a λ-record.
Pitfall (What is and is not an η-redex). η-contraction applies to λ-tree applications only. (ƛ (x) (@ 'g x)) is g, but
(ƛ (x) `(g ,x)) is an abstraction over a two-element list, and stays one. The module is untyped, so it
cannot η-expand a term against its type: η-expansion happens only on demand, when one side of an
equation is an abstraction (rule η below), as in Miller’s untyped treatment
Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, §9.3. A rigid list such as '(g a) therefore equals an abstraction only when the
abstraction’s body equals the λ-tree application (@ '(g a) x) of the list to the bound variable (and
ƛ already builds such an η-redex as the list itself); never when the body is a list such as
`(g a ,x).
12.2The extension’s state#
12.2.1The record in X#
The protocol gives (aux kanren micro)’s state a slot X that micro copies but never reads
(Chapter 11). The module keeps one record in it (aux.kanren.lambda.scm:231–240):
(define-record μkanren-hh depth top L Ln Γ E N W)
(define μkanren-hh0 (make-μkanren-hh 0 0 empty/sbral 0 '() '() '() empty/sbral))
(define (μkanren-hh s) (let1 (x (μkanren-state-X s)) (if (null? x) μkanren-hh0 x)))X = '(), the value in μkanren-state-empty, reads as “everything empty”, so the
initial state of every runner works unchanged.
Definition 12.4 (The λ state). The record holds:
(
depth)
the current universe level, raised by∀°for the extent of its body;
the highest level reached so far in this branch;
the levels of the logic variables: is a skew-binary random-access list (aux’ssbral) indexed like the substitution , holding the levels of the variables with index . The level of variable isso a variable created since was last extended has the current depth. is padded with exactly when the depth changes and whenever the unifier creates a variable of another level; lookup is ;
the assumed clauses: an alist from a relation to its clauses, most recent first, one entry per distinct relation;
the suspended constraints: equations(= u v)outside (or bindings whose scope check a non-pattern decides), types(tag tag u)on flexible terms, and absentos(absent d u)whose datum outlived its eigenvariable’s scope;
the disequalities that involve λ-terms or eigenvariables, as(reading u . v). micro’s D never holds one (Section 12.5);
an sbral indexed like : for each variable, the ids of the prefixes of D that reach it where micro’s records do not list them, below a compound side or through a binding. It lets theposthook find the prefixes a binding reaches without walking D (Section 12.5).
Levels are the module’s whole account of quantifier order. A logic variable created at depth stands for
an placed after the first universals of its branch; an eigenvariable created by the -th
∀° has level . The binding conditions of Nadathur, Jayaraman and Kwon Gopalan Nadathur, Bharat Jayaraman, and Keehang Kwon. Scoping constructs in logic programming: implementation problems and their solution. Journal of Logic Programming, 25(2):119–161, 1995
(Definition A.34 and Definition 9.15) are then stated on levels: a variable of level may be bound
only to a term whose eigenvariables have level , and the variables of level in that term are
lowered to .
12.2.2Copied, never mutated#
The record is immutable. Every change builds a new one with μkanren-hh-with, a keyword-argument copy, and
installs it with (μkanren-state-with s X: x). Since a state is a value and or° gives each branch the
state it was given, two branches can never see each other’s depth, Γ or suspended constraints. What needs
care is the end of a scope: ∀° and ⊃° change the record for their body only, and each
answer of the body must give the change back. Both do so on every answer state (Section 12.4). The
following probe shows depth and levels through two nested ∀°:
(define ((probe label . vars) s)
(display label) (display ": depth ") (display (μkanren-λ-depth s))
(display ", levels ") (write (map (λ (v) (μkanren-λ-level v s)) vars))
(display ", E ") (write (μkanren-λ-delayed s))
(display ", N ") (write (μkanren-λ-disequalities s)) (newline)
(✓° s))
(°->list #f
(fresh° (q)
(probe "start" q)
(∀° (x)
(fresh° (Y)
(probe "inside ∀x" q Y)
(∀° (z) (fresh° (W) (probe "inside ∀x∀z" q Y W)))
(probe "back in ∀x" q Y)
(=° (@ q x) (@ Y x x))
(probe "after q x = Y x x" q Y)))
(probe "after ∀x" q)))
(°->list #f (fresh° (q) (or° (∀° (x) (probe "branch 1" q) (=° q 1))
(and° (probe "branch 2" q) (=° q 2)))))start: depth 0, levels (0), E (), N ()
inside ∀x: depth 1, levels (0 1), E (), N ()
inside ∀x∀z: depth 2, levels (0 1 2), E (), N ()
back in ∀x: depth 1, levels (0 1), E (), N ()
after q x = Y x x: depth 1, levels (0 1), E (), N ()
after ∀x: depth 0, levels (0), E (), N ()
((λ (α) (ƛ (x) (@ α x x x))))
branch 1: depth 1, levels (0), E (), N ()
branch 2: depth 0, levels (0), E (), N ()
((λ () 1) (λ () 2))Tutorial (Reading the probe). is created at depth 0, inside ∀° (x) at depth 1, at depth 2; after each ∀° the depth
is back where it was. Written as a mixed prefix, the goal is ,
and each level is the number of universals to the left of the quantifier: , , , ,
. The equation is solved inside the scope, and its answer shows the
levels at work. has level 0 and its argument (level 1) is a pattern for it, so the unifier eliminates
: where is with turned into the bound variable. But has
level 1 and level 0: ’s value may not mention a variable that could see unless is passed
explicitly. is no pattern ( is repeated), but both its arguments are ’s own argument ,
so none of them has to be dropped. is therefore lowered and raised at once, with
, and . The answer (ƛ (x) (@ α x x x)) is that binding; the
rules responsible are FR and case (6c) of variable elimination, Definition 12.7. The last
two lines show the branches: ∀° raised the depth in branch 1 only.
The module’s hooks keep the protocol invariants E1–E6 of Definition 11.13; in particular, every
function of the module that may leave the state unchanged is written to return it eq? (E1).
12.3Unification#
12.3.1Where the rules run#
(aux kanren micro)’s unifier μkanren-state-unify still does all first-order work: variables, pairs, vectors, foreign
records and atoms. Through the protocol’s unify hook it hands any pair with a walked λ-record on one
side, neither side a variable, to μkanren-λ-unify, which applies the rules of Rules 12.6.
The rules call back into μkanren-state-unify for subterms, so the two unifiers interleave freely. After
=° has made its bindings, the post hook μkanren-λ-post runs before micro verifies D, A
and T:
- settle: the scope check Check of every new binding, then the wake-up of , in rounds while a round binds (Section 12.3.7);
- migrate: the prefixes of D that a new binding has brought a λ-term or an eigenvariable into move
to N, found from the bound variables, and the types of A on variables just bound to λ-terms go to the
taghook when micro hands them on (Section 12.5); - verify N: every λ-disequality is tried again.
12.3.2Notation#
Write for the level of a logic variable and for that of an eigenvariable; the names the unifier opens under binders have . A name is an eigenvariable or, inside variable elimination, a bound variable of the term being walked.
Definition 12.5 (Pattern, read off levels). A list of arguments is a pattern for a variable if every
is an eigenvariable, the are pairwise distinct, and for every
(μkanren-pattern?). A flexible term is a pattern when is a pattern for .
For example, inside (∀° (x y) ...) with , , , the lists
and are patterns for , while (repeated), (a
constant) and (a variable) are not. The same definition, with a bound variable of the
term being walked counted as an eigenvariable of level , is used inside variable elimination (case (6b)
below).
This is Miller’s condition (Definition 7.15): the arguments are distinct variables
“quantified inside the scope of ”. With a prefix, “inside the scope” means “to the
right of ”; with levels it means “of a level above ‘s”, which is how Nadathur and Linnell read the
condition without a prefix Gopalan Nadathur and Natalie Linnell. Practical higher-order pattern unification with on-the-fly raising. In ICLP 2005: 21st International Logic Programming Conference, volume 3668 of LNCS, pages 371–386, Sitges, Spain, 2006. Springer, §4. An eigenvariable could already see is not a
pattern argument: in the term is no pattern, since may use
directly and the equation has several incomparable solutions.
Throughout, is an abstraction with body , its body with #0 instantiated to , an application, and logic variables. Both sides are put in hnf before a rule is chosen.
12.3.3The rules#
The rules of Rules 12.6 are transformations, read top-down as in Rules A.22 and Rules A.30: the equation above the line is replaced by the equations, bindings or suspension below it. They are the rules of Rules A.30 with the prefix erased into levels; Section 7.6 gives the same rules under other names, recalled in parentheses. ξ is abs (Abs), η is eta (Eta), Rigid is rr-dec and rr-clash (Dec and Clash), FF-same is ff-same (the same-head case of FlexFlex), Delay is delay. FR covers elim (Elim) with its pruning, occurs and scope, and also ff-diff (FlexFlex with distinct heads): instead of binding both heads to a new , it eliminates and prunes only where needed, which gives the same mgu up to the name of (Example 12.13). Var and Occurs are elim and occurs for a variable with no arguments, a case that micro’s first-order unifier meets first, and they are where the eager scope check, Check, enters; FF-one orients a flexible–flexible pair as swap orients a flexible–rigid one.
Rules 12.6 (Unification rules of μkanren-λ-unify).
The unification rules of μkanren-λ-unify, applied after hnf of both sides; above the line
the equation, below what is done with it. In ξ and η, is a new eigenvariable of level
. In FF-same and FR, are new binders, one per argument , and Elim
replaces each in by the bound variable of . Variable elimination, Elim, is
Definition 12.7; Check is Definition 12.8. Each rule may also answer or suspend,
as its side conditions say.
The side conditions, in the order the code tests them (μkanren-λ-unify and the functions it calls):
- Var
One side is an unbound variable. micro binds it, with its occurs check; the scope check Check runs afterwards, in theposthook. Variable–variable pairs are micro’s as well. - ξ
Both sides are abstractions. is a new eigenvariable of level , so no variable can capture it except through its own pattern arguments. Because is local to this very unification, the bindings made under it are checked at once (μkanren-scoped), not at the end of=°. - η
One side is an abstraction and the other is not. The other side is applied to the new . This is the only η-expansion the module performs. - Rigid
Both sides are rigid applications with the same number of arguments: heads and argument lists are unified by micro. Two eigenvariables unify iff they are the same (eq?ids), two bound variables iff their indices agree. Any other pair with a λ-term on one side fails: different rigid heads, different arities (untyped), a λ-record against a pair or an atom. - FF-same
Same head on both sides, both argument lists patterns. Equal lists: success with no binding. Different lengths: . Otherwise keeps the positions where the arguments agree, with a new of level [MN p. 222]. If is no pattern, Delay. - FR
One side is a pattern ; the other side is rigid, or flexible with another head (“FF-diff”: variable elimination prunes as needed [MN p. 222]). If Elim fails the rule fails; if Elim suspends, Delay. The binding is built η-short, its binders named after the eigenvariables . - FF-one
Two flexible terms, only the right one a pattern: FR on . - Delay
No side is a usable pattern. The equation is pushed on , closed over the names that the unifier had opened so far (, so no -level name escapes the unification that created it), unless and are already α-equal, in which case it is dropped. - Occurs
Not a rule ofμkanren-λ-unifybut of the protocol’soccurshook: micro’s occurs check failed on and holds a λ-term. If is itself the equation holds ( with ); otherwise is eliminated with no arguments, which may fail, succeed, or suspend ( holds with ). A first-order cycle, , holds no λ-term and fails in micro as before.
12.3.4Variable elimination#
FR is the book’s variable elimination [MN p. 223] (Definition 7.21) with levels in place of the prefix. It walks the right-hand side once and builds the body of ’s binding, pruning, lowering and raising the variables it meets on the way. Compared with Definition 7.21, three things are added: lowering with delayed raising (case (4)), where Definition 7.21 assumes a prefix already raised into form (the eager raising of Example 7.31); the treatment of non-patterns inside the right-hand side (cases (6c) and (7)), which the book never meets since it stays in ; and a finer occurs test (case (6a)), since an occurrence of is fatal only when no instance can make it smaller. The contexts below exist to decide these three cases.
Definition 12.7 (Variable elimination). , with a pattern for and (or absent and
empty, for Check), walks at a local depth (the binders crossed inside
) and in a context: strict (top: below binders only; rigid: below a first rigid
constructor that is an application headed by a bound variable or by an ; firm: below a first rigid
constructor that is a constant, an eigenvariable not in , a pair, a vector or a record, a root no instance
of can project onto) or soft (inside an argument of a flexible term that is no pattern, or
weak: below a flexible head inside such an argument). It answers a term with new bindings,
, or suspend. By cases on the walked subterm:
- Eigenvariable : if , the bound variable of ; else if , itself; else (scope failure, Example 7.25). In a weak context the last case is trouble, not .
- Bound variable: itself.
- Abstraction : at depth .
- Unbound variable : if , when is empty (the first-order occurs check) and suspend otherwise; if , ; in a soft context, trouble; otherwise lower and raise: with and , the arguments of that could see; the result is applied to their bound variables (“delayed raising”, Example 7.31).
- Rigid application, pair, vector, record: homomorphic. A
topcontext becomesrigidbelow an application whose head is a bound variable or in , andfirmbelow any other head, a pair, a vector or a record; any other context is passed on unchanged. - Flexible in a strict context:
- (a) if : (occurs failure) when the context is not
top, no is functional (an abstraction, a variable or a flexible term, which may become an abstraction), and either the context isfirmor , with the binders on top of ; otherwise suspend; - (b) if is a pattern for (each a local bound variable or an eigenvariable of level , pairwise distinct): keep iff it is local, or in , or ; let if , else empty. If every is kept, is empty and , is unchanged. Otherwise prune: with , and the result is applied to the images of the kept arguments and of (Example 7.23);
- (c) if is no pattern: each is walked on its own in a soft context, binding nothing; it is kept, as the walk rebuilt it (its turned into bound variables), if the walk succeeds, dropped if it fails by scope on a rigid path (it holds a forbidden eigenvariable that every instance keeps), and any other trouble suspends the whole equation. Then, if nothing was dropped and needs no lowering, stays as it is; otherwise, if some is functional, suspend; else prune and lower as in (b).
- (a) if : (occurs failure) when the context is not
- Flexible in a soft context: or is trouble; otherwise the arguments are walked in a weak context and kept as they are. Inside an argument, the application of a variable bound inside that argument is treated as flexible too.
Inside an argument of a non-pattern, case (6c) reinterprets every failure: a scope failure of case (1) in a soft, non-weak context drops the argument, and any other or trouble suspends the equation.
Tutorial (Reading the contexts). The context answers one question about the subterm being walked: will every instance of the right-hand
side still contain it? At top and below rigid constructors (rigid, firm) the answer is
yes, because no substitution can remove a rigid constructor; so a forbidden eigenvariable there is a definite
failure, and a variable there can be lowered or pruned without losing solutions. Inside an argument of a
non-pattern the answer is “not necessarily”, since may become a function that ignores
that argument; so nothing is bound there and doubts turn into a suspension. firm and rigid
differ only in the occurs test (6a): below a constant, an eigenvariable outside or a pair, ’s instance
cannot be a projection, so an inner with rigid arguments is fatal whatever their number; below a
bound variable or an at the head, the number matters. The next two tutorials give the reasons in detail.
Tutorial (Strict and non-strict occurrences). Pruning removes an argument from a variable; lowering makes a variable forget the eigenvariables it could see. Both are sound only on strict occurrences, those not inside an argument of a flexible term that is no pattern (Dowek, Hardin, Kirchner and Pfenning Gilles Dowek, Thérèse Hardin, Claude Kirchner, and Frank Pfenning. Unification via explicit substitutions: the case of higher-order patterns. In M. Maher, editor, Joint International Conference and Symposium on Logic Programming (JICSLP), pages 259–273. MIT Press, 1996). The reason is that the flexible head may later turn out to drop that argument. Take : it has the solution . If elimination of lowered inside the argument of , the later would fail by scope and the answer would be lost in that goal order, which breaks the commutativity of conjunction. So nothing is bound inside such an argument: a variable to lower (case (4)) or a flexible term to prune (case (7)) is trouble there, and trouble suspends the equation. The exception of case (6c) is the one pruning that is strict: an argument that holds, on a rigid path, an eigenvariable that may not see is held by every instance of that argument, so must drop it. This makes solvable as , . Even that pruning waits when an argument is, or may become, an abstraction: could apply it to another argument and drop that one (Section 12.3.8 shows , solved in both orders).
Tutorial (When an occurrence of F is fatal). Case (6a) is Nipkow’s size argument Tobias Nipkow. Functional unification of higher-order patterns. In M. Vardi, editor, 8th Symposium on Logic in Computer Science, pages 64–74, New York, 1993. IEEE: inside the body of makes the
equation unsolvable only if no instance of can be smaller than the instance of . That
holds when the are rigid (no substitution makes them reduce) and are as many as plus the
binders on top ( is by η), as in
and Example 7.24. The count does not matter when the root of the body is a
constant, an eigenvariable not in or a pair (context firm): no instance of
can then be a projection, so has that root and sits strictly inside it. So the η-short
fails as Miller and Nipkow fail it. Otherwise the instance may shrink and the
equation is outside : it is suspended. For instance holds
with , and holds with .
12.3.5The eager scope check#
Definition 12.8 (Check). For a binding that micro has just made, is with no head to eliminate (μkanren-enforce). If it answers , =° fails.
If it suspends, the binding is taken back: μkanren-state-forget unbinds and the equation
is pushed on . Otherwise its own bindings (lowerings, prunings) are kept.
Check is NJK’s binding rule with its lowering (Definition A.34): “ contains no constant with tag ; change to the tags of the variables in whose tag is ” Gopalan Nadathur, Bharat Jayaraman, and Keehang Kwon. Scoping constructs in logic programming: implementation problems and their solution. Journal of Logic Programming, 25(2):119–161, 1995, p. 16, extended from variables to flexible terms by pruning. Taking a binding back is what Teyjus does with a binding whose check depends on a non-pattern. Its effect is an invariant:
Proposition 12.9 (No captured eigenvariable). After every =°, no binding in the substitution has an eigenvariable of level in the
value of .
Argument. Every binding made by micro goes through Check unless the fast paths of
Section 12.3.6 prove it unnecessary; Check either fails, or rewrites the variables of so
that it holds, or unbinds . The bindings that Check itself makes are lowerings and prunings,
which by construction respect the levels. The remaining gap is host code (project° and set!),
discussed in Chapter 14. □
12.3.6Fast paths#
Check on every binding would be costly on first-order search, so three cheap tests come first.
- No
∀°yet. While no∀°has run, the depth is 0 and is empty (μkanren-levels?is false): every level is 0, no check can fail, none runs. - Plain terms.
μkanren-plain?is an allocation-free walk, like micro’s occurs check. It accepts when holds no eigenvariable or variable of a level above and no application with a variable or abstraction head (which Elim might prune, lower or reduce). Only otherwise does Elim run. - Top-level variables. A variable of level , the highest level reached, can see
every eigenvariable and every variable there is, so its bindings are skipped. The bindings made under
ξ or η are checked anyway, by
μkanren-scoped.
The protocol’s atom? hook belongs here as well: it tells micro’s occurs check that an eigenvariable or
a bound variable holds no variable, so micro does not rebuild it as a slot list. On the type inference of the
Church numeral 400 these steps took the prototype from 463 ms to 330 ms (plain?), 311 ms (the
top skip) and 254 ms (atom?); the merged tree takes 210 ms (Section 14.3.5).
Pitfall (The first ∀° switches the check on for good). The first fast path is about the whole branch, not the current scope: once a ∀° has run, levels exist
and every binding below top is checked, even after the ∀° has exited. First-order search that
follows a ∀° pays for it, measured on the merged tree at on append° backwards and
on open append°. Skipping the check at depth 0 would be unsound against host escapes; the
fix planned is to spare the scope check where micro spares its occurs check (Section 14.5.1).
12.3.7Wake-up and termination#
When =° binds something and is not empty, μkanren-settle retries every suspended item, oldest
first (μkanren-wake). An item is retried by its kind:
- an equation : if one side is now an unbound variable and the other no variable, is
bound only once its check passes (
μkanren-retry/bind); otherwise the equation is unified again, which may solve it, fail, or suspend it again; - a type on a flexible term: decided if the head is now known, else suspended again;
- an absento: decided, kept, or dropped when levels entail it (Section 12.5).
The new bindings of a round are checked like those of =°, and rounds repeat while a round binds. A
constraint still undecided is suspended again without binding anything.
Proposition 12.10 (Wake-up terminates). Suppose every hnf computed during the wake-up terminates. Then the loop of μkanren-settle terminates.
Argument (a sketch, not a mechanised proof). A round that binds nothing ends the loop, so it suffices that only finitely many rounds bind. A round that binds does so for good: the only binding ever taken back is the one that Check has just examined, and a retried binds only after its check passed, so the retry does not bind and unbind the same variable forever. The variables a round may create come from lowering (case (4)), whose new variable has a strictly smaller level than the one it replaces, and from pruning (cases (6b) and (6c)), whose new variable either has a strictly smaller level (when is lowered, possibly with extra arguments) or the same level and strictly fewer arguments (FF-same likewise creates at the level of with fewer arguments). So every new variable replaces exactly one variable that is bound for good, and is below it in the lexicographic order on (level, number of arguments), which is well founded. A chain of replacements (a variable, the one that replaces it, the one that replaces that, …) is therefore finite; with finitely many variables at the start, finitely many variables are ever created, each is bound at most once, and only finitely many rounds can bind. This is the decreasing measure the design relies on. One point a full proof would have to settle: the number of arguments is that of the occurrence being pruned, which an untyped term does not fix once and for all. □
The hypothesis on hnf is not a formality: @ gives full β, and on untyped meta-terms full β may diverge
(Chapter 14). On pattern problems no such reduction happens (every contraction is a renaming),
and the rules are Miller’s and Nipkow’s algorithm with the prefix erased into levels: it terminates, fails only
when there is no unifier, and otherwise computes a most general one Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, Thm 7.1, Prop. 7.3,
Gopalan Nadathur and Natalie Linnell. Practical higher-order pattern unification with on-the-fly raising. In ICLP 2005: 21st International Logic Programming Conference, volume 3668 of LNCS, pages 371–386, Sitges, Spain, 2006. Springer, Thm 2. The suite checks the book’s mgus verbatim: and
for Example 7.23, for Example 7.31, and
for (Example 7.2).
Pitfall (Suspended is not solved). Non-patterns are suspended, never enumerated: there is no Huet search [MN p. 213]. An answer may therefore be conditional on residual equations that are jointly unsatisfiable. and ( a constant, so no pattern) are both suspended, and the answer is printed with the two residuals; only a binding of reveals the conflict:
(°->list #f (fresh° (q F) (=° q F) (=° (@ F 'a) 'b) (=° (@ F 'a) 'c)))
(°->list/datum (fresh° (q F) (=° q F) (=° (@ F 'a) 'b) (=° (@ F 'a) 'c)
(=° F (ƛ (z) 'b))))((λ (α) (assert (≐ (@ α 'a) 'b)) (assert (≐ (@ α 'a) 'c)) α))
()This is floundering reported, not detected. The residuals are the honest output: they say exactly which equations the search did not decide.
12.3.8Worked traces#
Each trace below poses a problem, follows the rules, and ends with the module’s actual output. The probe used here prints the depth, the levels of the given variables and :
(define ((probe label . vars) s)
(display label) (display ": depth ") (display (μkanren-λ-depth s))
(display ", levels ") (write (map (λ (v) (μkanren-λ-level v s)) vars))
(display ", E ") (write (μkanren-λ-delayed s)) (newline)
(✓° s))Example 12.11 (Warm-up: flexible–rigid, and ξ). Two equations that touch no pruning or lowering: , and , where both are Scheme lists.
(°->list/datum (fresh° (q) (∀° (x y) (=° (@ q x y) `(g ,y ,x)))))
(°->list/datum (fresh° (q) (=° (ƛ (x) `(g ,x)) (ƛ (y) `(g ,(@ q y))))))((ƛ (x y) (g y x)))
((ƛ (x) x))Trace of the first. , , . The left side is flexible and
is a pattern for ; the right side is the list (g y x), rigid: FR. Elim walks the list in
context firm: g is an atom and stays; is and becomes the bound variable of the second
binder; is and becomes that of the first (case (1)). Nothing was bound on the way, and
, the binders named after the eigenvariables.
Trace of the second. Both sides are abstractions: ξ opens them with one new eigenvariable
of level (hint x), leaving (g c) (g (@ q c)). These are lists, so micro
decomposes them and hands back to the hook. is a pattern for
(), and Elim turns into the bound variable: , a projection. The binding
was made under ξ, so μkanren-scoped checks it at once; it holds no eigenvariable and passes.
Example 12.12 (Pruning: problem 8.H [MN p. 223–224]). The problem (Example 7.23) is
(°->list/datum (fresh° (q u v) (=° q (list u v))
(∀° (w x y) (probe "before" u v)
(=° `(f ,(@ u x y)) `(f (g ,(@ v y w))))
(probe "after" u v))))before: depth 3, levels (0 0), E ()
after: depth 3, levels (0 0), E ()
(((ƛ (x y) (g (@ α y))) (ƛ (y w) (@ α y))))Trace. , have level 0 and levels 1, 2, 3. Both sides are lists, so micro decomposes
them: f against f, then with a λ-record on the left, handed to the
hook. The left side is a pattern (, distinct, levels ) and the right is rigid: FR,
. The root is the list (g ...): case (5),
context firm. Inside, is flexible with a pattern for (levels ): case (6b). Keep
(it is in , it becomes the bound variable of ); drop (not local, not in , and
); is empty since is not above . Something was dropped, so
prune: , , and the body of is . Finally
. Both are the book’s mgu, with α for . The binders of are
named after the eigenvariables , it was applied to.
Example 12.13 (Flexible–flexible). Different heads, , and the same head, :
(°->list #f (fresh° (q f g) (=° q (list f g)) (∀° (x y) (=° (@ f x y) (@ g y x)))))
(°->list #f (fresh° (q) (∀° (x y) (=° (@ q x y) (@ q y x)))))((λ (α) (cons (ƛ (x y) (@ α y x)) (cons α '()))))
((λ (α) (ƛ (x y) α)))Trace. In the first, both sides are patterns with different heads: FR on . In Elim, is case (6b) with both arguments in , kept; is not above , so nothing is pruned or lowered and stays unbound: . That is the book’s mgu for different heads [MN p. 222] with the common variables listed as : and , which is by η, up to the name of . In the second, FF-same: the positions where and agree are none, so with new.
Example 12.14 (A non-pattern, suspended and woken). is not in : the argument is not an eigenvariable. It has two solutions, and , but the second is illegal here because is quantified outside . The module neither guesses nor fails:
(°->list #f (fresh° (q) (∀° (x) (=° (@ q `(g ,x)) `(h (g ,x))) (probe "inside" q))
(probe "after ∀" q)))
(°->list/datum (fresh° (q) (∀° (x) (=° (@ q `(g ,x)) `(h (g ,x))))
(probe "before F :=" q)
(=° q (ƛ (z) `(h ,z)))
(probe "after F :=" q)))
(°->list/datum (fresh° (q) (∀° (x) (=° (@ q `(g ,x)) `(h (g ,x))))
(=° q (ƛ (z) 'k))))
(°->list/datum (fresh° (q) (=° q (ƛ (z) `(h ,z)))
(∀° (x) (=° (@ q `(g ,x)) `(h (g ,x))))))inside: depth 1, levels (0), E ((= (@ _0 (g (eigen x))) (h (g (eigen x)))))
after ∀: depth 0, levels (0), E ((= (ƛ (x) (@ _0 (g x))) (ƛ (x) (h (g x)))))
((λ (α)
(assert
(≐ (ƛ (x) (@ α (cons 'g (cons x '()))))
(ƛ (x) (cons 'h (cons (cons 'g (cons x '())) '())))))
α))
before F :=: depth 0, levels (0), E ((= (ƛ (x) (@ _0 (g x))) (ƛ (x) (h (g x)))))
after F :=: depth 0, levels (0), E ()
((ƛ (z) (h z)))
()
((ƛ (z) (h z)))Trace. Inside the scope the left side is flexible but no pattern and the right is rigid:
Delay, and holds the equation, with the eigenvariable in it. At the exit of ∀° (x)
the equation mentions , so it is discharged (Section 12.4.2): no variable in it has a
level , so nothing is raised, and the equation is closed into
, equivalent by ξ. It is retried at once, opens
again as an -level name, is still no pattern, and is suspended again. The run ends with it, and
the answer carries it as a residual (assert (≐ ...)). In the second run the binding
wakes it: ξ, then β turns the left side into , which equals the right side, and is
empty. In the third run makes the retry compare with : a clash, so =°
fails and there is no answer. In the fourth run the binding comes first and the equation is a plain β-redex,
solved with no suspension. The answer is the same in both goal orders.
Example 12.15 (A binding taken back). . micro binds at once, as Var. Check at level then meets , a flexible term whose argument is no eigenvariable: case (6c), walking in a soft context. There (level 1, not allowed for a level-0 variable) sits below the flexible head , a weak context: trouble, not , since may drop , and may drop all of . So the check suspends, the binding is taken back, and waits in :
(°->list #f (fresh° (q G H) (∀° (y) (=° q (@ G (@ H y))) (probe "inside" q G H))))
(°->list/datum (fresh° (q G H) (∀° (y) (=° q (@ G (@ H y)))) (=° G (ƛ (a) 'k))))inside: depth 1, levels (0 0 0), E ((= _0 (@ _1 (@ _2 (eigen y)))))
((λ (α β γ) (assert (≐ (ƛ (y) α) (ƛ (y) (@ β (@ γ y))))) α))
(k)At the exit of the scope the equation is closed over and reported, unbound, which is all one can say. With the retry binds , a plain term, and the residual is gone. The same happens in every order of the goals.
Example 12.16 (Occurs and scope failures, and a soft occurrence).
(°->list #f (fresh° (q) (=° q `(f ,q)))) ; X = f X
(°->list #f (fresh° (q) (∀° (w x y) (=° (@ q x y) `(g ,(@ q y w)))))) ; 8.I
(°->list #f (fresh° (q) (∀° (w x y) (=° (@ q x y) `(g ,w))))) ; 8.J
(°->list #f (fresh° (F) (=° F (ƛ (x) `(g ,(@ F x)))))) ; F = λx.g (F x)
(°->list #f (fresh° (q F G) (=° q (list F G))
(∀° (x) (=° (@ F x) (@ G (@ F x))))))()
()
()
()
((λ (α β) (assert (≐ α (ƛ (x) (@ β (@ α x))))) (cons α (cons β '()))))The first is micro’s occurs check, unchanged. In 8.I, occurs below the list (g ...), a
firm context, and its arguments are rigid: case (6a), (Example 7.24); it also has as
many arguments as , so the count alone would fail it. In 8.J, has level 1, is not
an argument of , and has level 0: case (1), by scope (Example 7.25). The fourth fails
micro’s occurs check, the occurs hook passes it to Elim with no arguments, and below g
is case (6a) again. The last is the soft occurs check: occurs inside the argument of , which may
be , so the equation is suspended (and is closed over at the exit of the scope) instead of
failing.
Example 12.17 (An argument that may be an abstraction). in both orders:
(°->list/datum (fresh° (q) (∀° (x) (fresh° (G) (=° q (@ G (ƛ (w) 'k)))
(=° G (ƛ (y) (@ y x)))))))
(°->list/datum (fresh° (q) (∀° (x) (fresh° (G) (=° G (ƛ (y) (@ y x)))
(=° q (@ G (ƛ (w) 'k)))))))(k)
(k)In the first order, Check of at level 0 finds of level 1, which must be lowered; but its argument is an abstraction that may apply to and so drop ’s own . Lowering would not be strict, so case (6c) suspends. Then wakes the equation, β gives , and . In the other order β happens at once. A version that lowered here lost the answer in the first order.Third adversarial review.
12.4∀° and ⊃°#
The book’s goal-directed search for hereditary Harrop formulas consists of the rules and, or, instan,
generic, augment and backchain [MN p. 77], [MN p. 82], [MN p. 124] (Rules 3.6; the names are those of Rules A.6). Uniform proofs are
complete for intuitionistic provability of these formulas Dale Miller, Gopalan Nadathur, Frank Pfenning, and Andre Scedrov. Uniform proofs as a foundation for logic programming. Annals of Pure and Applied Logic, 51:125–157, 1991
(Theorem 3.12), so implementing the rules faithfully is the semantics. and, or and
are micro’s and°, or° (interleaving) and fresh°. This section gives the other
three as the module implements them.
12.4.1generic#
(∀° (x) g ...) expands into (∀ª 'x (λ (x) (and° g ...))), and (∀° (x y) g ...) into one
∀ª per name, nested, so (∀° (w x y) ...) gives the levels , , . The Scheme
variable x is bound to the eigenvariable, as ƛ binds its placeholder. ∀ª takes a state
whose λ record has depth and does the following.
- Record the level of every variable created so far (pad up to the variable count).
- Run the body
(f c)for a new eigenvariable of level , in the state with depth and . - For each answer state of the body: record the level of the variables created inside (pad again), set the depth back to , and discharge the constraints on (Section 12.4.2); if discharge fails, drop the answer.
(define ((∀ª name f) s)
(let* ((x (μkanren-hh s))
(d (μkanren-hh-depth x))
(x* (μkanren-hh-with (μkanren-hh-pad x (μkanren-state-vars-count s))
depth: (add1 d) top: (max (add1 d) (μkanren-hh-top x))))
(c (μkanren-eigen* name (add1 d))))
(append-map§
(λ (s1)
(let1 (s2 (μkanren-with s1
(μkanren-hh-with (μkanren-hh-pad (μkanren-hh s1)
(μkanren-state-vars-count s1))
depth: d)))
(match/first (μkanren-discharge s2 c d)
(#f (✗° s2))
(,s3 (✓° s3)))))
(δ ((f c) (μkanren-with s x*))))))The shape is that of micro’s andª (Chapter 10): the body’s stream is delayed with δ, and
append-map§ post-processes it answer by answer, so the restoring step runs on every answer, however
late the stream produces it. Steps 1 and 3 pad because a variable’s level is implicit (the current
depth) until is extended past it: padding fixes it before the depth changes.
The signature is not carried. What carries the quantifier structure is the level of each variable: a variable created at depth stands for an after the first universals of its branch (Miller’s mixed prefix Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, linearised by creation), and Check forbids exactly the substitutions that would violate that prefix. NJK prove this tagging sound and complete (Proposition A.35, Gopalan Nadathur, Bharat Jayaraman, and Keehang Kwon. Scoping constructs in logic programming: implementation problems and their solution. Journal of Logic Programming, 25(2):119–161, 1995, Prop. 4.1).
Tutorial (Why the depth must be restored on every answer). A creation timestamp would tell a variable created before from one created after it, and one might think
that suffices: older variables may not see . But a variable created after the ∀° has exited
may not see either. With the depth restored on every answer, such a variable gets level , so
it cannot take . This is λProlog’s universe register Gopalan Nadathur, Bharat Jayaraman, and Keehang Kwon. Scoping constructs in logic programming: implementation problems and their solution. Journal of Logic Programming, 25(2):119–161, 1995. The two classic
cases, [MN p. 85]:
(list (°->list #f (fresh° (q) (∀° (x) (=° q x)))) ; ∃Y∀x. Y = x
(°->list #f (fresh° (q) (∀° (x) (fresh° (y) (=° y x)))
(=° q 'ok)))) ; ∀x∃Y. Y = x(() ((λ () 'ok)))In the first, has level 0 and level 1: Check fails by case (1). In the second, is created inside, at level 1, and may take .
Example 12.18 (Lowering, seen from the state). A variable created inside the scope and placed inside the value of an outer one must forget the scope:
(define ((probe . vars) s)
(for-each (λ (v) (let1 (w (μkanren-state-find v s))
(write v) (display " ↦ ") (write w)
(when (μkanren-var? w)
(display " level ") (display (μkanren-λ-level w s)))
(display "; ")))
vars)
(newline) (✓° s))
(°->list #f (fresh° (A) (∀° (x) (fresh° (B) (probe A B)
(=° A `(arr ,B c))
(probe A B)))))_0 ↦ _0 level 0; _1 ↦ _1 level 1;
_0 ↦ (arr _1 c); _1 ↦ _2 level 0;
((λ (α) (cons 'arr (cons α (cons 'c '()))))) (_0) has level 0 and (_1) level 1. Binding triggers
Check at level 0, which meets the unbound of level : case (4), lower. A new variable
_2 of level 0 is created and ; Check eliminates no head and has no
arguments to raise over, so the raising part is empty. This is NJK’s “change to the tags of the variables in whose tag is ”, done by a
binding instead of a mutation, so that it is undone by backtracking for free.
12.4.2Discharge at the exit of a scope#
When ∀° exits, some constraints may still mention : suspended equations, generic disequalities of N,
absentos of micro’s T. A residual that mentions outside its scope would be meaningless, and the printer
must never show an eigenvariable free. μkanren-discharge closes them, back at depth :
- Raise. Every unbound variable of the equations and disequalities to be closed with is raised: with . Inside the scope could depend on ; lives outside it, so the dependency becomes an explicit argument: is turned into with . This is Miller’s raising [MN p. 107] (Proposition 4.14), a bijection on solutions.
- Close. A suspended equation that mentions stands for
and becomes , equivalent by ξ. A generic
disequality is closed the same way, under generic’s reading of as a new name. An absento of T whose
term mentions is closed too, since absence in is absence in . An absento whose
datum mentions moves to as
(absent d u), unless the levels entail it: if does not hold and all its variables have levels below , no instance of can ever hold , and the constraint is dropped. - Retry. The raise bindings go through
μkanren-post-unify, which wakes , so the closed constraints are retried. With no raise, the closed equations are retried anyway. - Repeat. A raise may bring into more constraints (an absento of T on a raised now watches ; a prefix of D on moves to N holding ). Discharge repeats until no raise is left.
The constraints that cannot be closed by an abstraction (a type on ; an absento whose datum is on a
term that may still hold ) keep and print under a ∀ (Section 12.6).
Example 12.19 (Discharge: raising, closing, retrying).
(define ((probe label . vars) s) ; prints values and the levels of unbound variables
(display label) (display ": depth ") (display (μkanren-λ-depth s))
(for-each (λ (v) (display ", ") (write v) (display " ↦ ")
(write (μkanren-state-find/value v s))
(let1 (w (μkanren-state-find v s))
(when (μkanren-var? w)
(display " level ") (display (μkanren-λ-level w s)))))
vars)
(display ", E ") (write (μkanren-λ-delayed s)) (newline)
(✓° s))
(°->list #f (fresh° (q) (∀° (a) (fresh° (f) (=° (@ f a) `(g ,a ,a))
(probe "inside" f)))
(=° q 'ok)))
(°->list #f (fresh° (q) (∀° (x) (=° (@ q x) `(g ,q)) (probe "inside" q))))inside: depth 1, _1 ↦ _1 level 1, E ((= (@ _1 (eigen a)) (g (eigen a) (eigen a))))
((λ (α)
(assert (≐ (ƛ (a) (@ α a a)) (ƛ (a) (cons 'g (cons a (cons a '()))))))
'ok))
inside: depth 1, _0 ↦ _0 level 0, E ((= (@ _0 (eigen x)) (g _0)))
()In the first, is created inside the scope of (level 1), so is no pattern (the book’s 8.A, four unifiers and no mgu, [MN p. 213]) and is suspended. At the exit, has level : it is raised, with , and the equation closes into . That is still no pattern (the argument is repeated), so it is reported. In the second, is a pattern equation, but itself occurs with no argument in its own body, case (4) with : suspend. At the exit nothing needs raising (), the equation closes into , which by η is , and the retry fails the occurs check: no answer, as it must be.
12.4.3augment#
(⊃° (D ...) g ...) expands into ⊃ª, which pushes the clauses on Γ for the body and gives the old Γ
back to every answer of the body:
(define ((⊃ª clauses g) s)
(let* ((x (μkanren-hh s))
(Γ (μkanren-hh-Γ x))
(Γ* (fold-right
(λ (c Γ*)
(let1 (old (cond ((assq (car c) Γ*) => cdr) (else '())))
(cons (cons (car c) (cons (cdr c) old))
(if (null? old) Γ* (alist-delete (car c) Γ* eq?)))))
Γ clauses)))
(append-map§
(λ (s1) (✓° (μkanren-with s1 (μkanren-hh-with (μkanren-hh s1) Γ: Γ))))
(δ (g (μkanren-with s (μkanren-hh-with x Γ: Γ*)))))))A clause is a pair (relation . procedure): the relation is the dynamic relation’s own procedure, used
as an eq? key, and the procedure maps the list of a call’s arguments to the goal that the clause makes of
them. Since Γ lives in the state, or° branches cannot interfere, and restoring it on every answer is the
stack discipline of the book [MN p. 78], [MN p. 83]. Assuming a clause for a relation already in Γ replaces that
relation’s entry by one with the new clause in front of the old ones, so a lookup costs the number of distinct
assumed relations, not the number of clauses. The fold-right puts the first clause of a list on top.
12.4.4backchain and define-dynamic-relation#
In λProlog every predicate can be extended by an assumption. Here only relations made by
define-dynamic-relation can:
(define-syntax define-dynamic-relation
(syntax-rules ()
((_ (name arg ...))
(define name
(μkanren-dynamic
(λ (arg ...) (λ (s) (δ ((μkanren-hyps° name (list arg ...) #f) s)))))))
((_ (name arg ...) g ...)
(define name
(μkanren-dynamic
(λ (arg ...)
(λ (s) (δ ((μkanren-hyps° name (list arg ...) (and° g ...)) s)))))))))
(define ((μkanren-hyps° key args static) s)
(let* ((gs (map (λ (c) (c args))
(cond ((assq key (μkanren-hh-Γ (μkanren-hh s))) => cdr) (else '()))))
(gs (if static (append gs (list static)) gs)))
(if (null? gs) '() ((reduce-right orª #f gs) s))))A call disjoins, in one flat or°, the assumed clauses for the relation, most recent first, and then
the static body. If are the clauses assumed for in the current Γ, in the order they were
assumed, and is the static body of (absent when it has none), then
where unifies with the head of , its own ∀ variables renamed and its free
variables shared (see the clause syntax below), and runs its body. This is
backchain (Rules 3.6) with the choice of clause made by or° instead of by a selection rule; a
relation with neither hypotheses nor static body fails. When every clause answers at once, the answers come in λProlog’s order; otherwise
interleaving decides. The relation is tagged with CHICKEN’s extend-procedure, so μkanren-dynamic?
is an test and no global registry is needed. Assuming a clause for a relation that is not dynamic is an
error, not a silent no-op:
(define-dynamic-relation (n° x) (=° x 1))
(list (°->list/datum (fresh° (q) (⊃° ((n° 2)) (⊃° ((n° 3)) (n° q)))))
(°->list/datum (fresh° (q) (⊃° ((n° 2) (n° 3)) (n° q)))))
(define (error-message thunk) ; the message of the error `thunk` raises
(handle-exceptions exn ((condition-property-accessor 'exn 'message #f) exn)
(begin (thunk) #f)))
(define-relation (r° x) (=° x 1))
(error-message (λ () (°->list #f (fresh° (q) (⊃° ((r° 2)) (r° q))))))((3 2 1) (2 3 1))
"not a dynamic relation, see define-dynamic-relation"The two orders are the book’s [MN p. 78]: p 2 => p 3 => p X gives 3, 2, 1, and
(p 2 & p 3) => p X gives 2, 3, 1. In the first query the inner ⊃° runs last, so Γ maps n° to
the clauses for 3 and 2, in this order, and the call disjoins , and the static . In the second,
fold-right puts the first clause of the list on top, so the clause for 2 comes before the one for 3.
12.4.5Clause syntax#
| clause | meaning and expansion |
|---|---|
(rel t ...) | a fact; (λ (args) (fresh° (v ...) (=° args (list t ...)))) |
((rel t ...) ← g ...) | a rule, infix |
(← (rel t ...) g ...) | the same rule, prefix; rewritten to the infix form |
(∀ (w ...) D) | with its own variables w ..., accumulated into the fresh° of the expansion |
A rule expands to (μkanren-clause* rel (λ (args) (fresh° (v ...) (=° args (list t ...)) g ...))),
and μkanren-clause* raises the error above when rel is not dynamic. Two kinds of variables appear
in a clause, as in the book [MN p. 86–88]:
- its free logic variables are those of the closure: shared with the context, and among all uses of the clause;
- its own
∀variables are made by thefresh°inside the procedure, so they are renamed at each use, at the current level. That is NJK’s “new tagged instance” of a clause Gopalan Nadathur, Bharat Jayaraman, and Keehang Kwon. Scoping constructs in logic programming: implementation problems and their solution. Journal of Logic Programming, 25(2):119–161, 1995, p. 14.
(define-dynamic-relation (h° x))
(list (°->list/datum (fresh° (q y) (⊃° ((h° `(,y ,y))) (h° '(1 1)) (h° '(2 2)))))
(°->list/datum (fresh° (q) (⊃° ((∀ (z) (h° `(,z ,z)))) (h° '(1 1)) (h° '(2 2)))
(=° q 'ok))))(() (ok))With the shared , the first use binds and the second use cannot match (2 2); with the clause’s
own , each use gets a new .
Example 12.20 (Levels reach into clauses, p. 16).Gopalan Nadathur, Bharat Jayaraman, and Keehang Kwon. Scoping constructs in logic programming: implementation problems and their solution. Journal of Logic Programming, 25(2):119–161, 1995 With the program , the goal must fail and must succeed (Example A.36):
(define-dynamic-relation (q° z))
(define-dynamic-relation (p° x) (fresh° (z) (=° x `(d ,z)) (q° z)))
(list (°->list #f (fresh° (x) (∀° (y) (⊃° ((q° y)) (p° x)))))
(°->list #f (fresh° (r) (∀° (y) (fresh° (x) (⊃° ((q° y)) (p° x)))) (=° r 'ok))))(() ((λ () 'ok)))In the first goal, has level 0. Backchaining on p° creates the clause variable inside the scope of
(level 1) and binds ; Check lowers to level 0. The hypothesis (q° y) then
asks , a level-0 variable against a level-1 eigenvariable: scope failure. Without lowering, would
keep level 1 and take , and would leak out of its scope.
12.4.6Worked example: type inference#
The book’s type inference for untyped λ-terms (Section 6.5.4, [MN p. 190–191]) uses all three rules at once:
typeof (app M N) A :- typeof M (arr B A), typeof N B.
typeof (abs M) (arr A B) :- pi x\ typeof x A => typeof (M x) B.In the module’s syntax (src/test/microkanren-lambda-programs.scm):
(define-dynamic-relation (typeof° m t)
(cond°
((fresh° (M N B) (=° m `(app ,M ,N)) (typeof° M `(arr ,B ,t)) (typeof° N B)))
((fresh° (R A B) (=° m `(abs ,R)) (=° t `(arr ,A ,B))
(∀° (x) (⊃° ((typeof° x A)) (typeof° (@ R x) B)))))))The object term abs x\ M is `(abs ,(ƛ (x) M)); (M x) is (@ R x), a β-redex once is
bound. The answers for S, I and (from the prototype’s examples.out, which its
examples.scm prints byte for byte on the merged tree):
(((arr (arr α (arr β γ)) (arr (arr α β) (arr α γ)))) ((arr α α)) ())To see the rules at work, here is the same program with a trace goal that prints the depth and the walked
arguments, with the level of each unbound variable after @. The trace in the static body runs only
when the static clauses are tried, after the hypotheses:
(define ((trace label . ts) s)
(display label) (display " [depth ") (display (μkanren-λ-depth s)) (display "]")
(for-each (λ (t) (display " ") (write (μkanren-state-find/value t s))
(let1 (w (μkanren-state-find t s))
(when (μkanren-var? w)
(display "@") (display (μkanren-λ-level w s)))))
ts)
(newline) (✓° s))
(define-dynamic-relation (typeof° m t)
(trace "static typeof°" m t)
(cond°
((fresh° (M N B) (=° m `(app ,M ,N)) (trace " app" M N B)
(typeof° M `(arr ,B ,t)) (typeof° N B)))
((fresh° (R A B) (=° m `(abs ,R)) (=° t `(arr ,A ,B)) (trace " abs" R A B)
(∀° (x) (⊃° ((typeof° x A)) (typeof° (@ R x) B)))))))
(°->list/datum (fresh° (q) (typeof° `(abs ,(ƛ (x) `(abs ,(ƛ (y) x)))) q)))
(°->list/datum (fresh° (q) (typeof° `(abs ,(ƛ (x) `(app ,x ,x))) q)))static typeof° [depth 0] (abs (ƛ (x) (abs (ƛ (y) x)))) _0@0
abs [depth 0] (ƛ (x) (abs (ƛ (y) x))) _2@0 _3@0
static typeof° [depth 1] (abs (ƛ (y) (eigen x))) _3@0
abs [depth 1] (ƛ (y) (eigen x)) _7@0 _8@0
static typeof° [depth 2] (eigen x) _8@0
((arr α (arr β α)))
static typeof° [depth 0] (abs (ƛ (x) (app x x))) _0@0
abs [depth 0] (ƛ (x) (app x x)) _2@0 _3@0
static typeof° [depth 1] (app (eigen x) (eigen x)) _3@0
app [depth 1] (eigen x) (eigen x) _6@1
static typeof° [depth 1] (eigen x) (arr _6 _3)
static typeof° [depth 1] (eigen x) _7@0
()Tutorial (λx.λy.x, step by step).
- Depth 0, Γ empty. The query is
_0. No hypothesis fortypeof°, so the static body runs. Theabsclause creates (_1,_2,_3, level 0), binds and . - generic.
∀° (x)records levels, raises the depth to 1 and makes the eigenvariable of level 1. - augment.
⊃°pushes on Γ. - β. The goal is
(typeof° (@ R x) B);@reduces the redex to , with now the eigenvariable, printed(eigen x). - backchain, depth 1. The hypothesis is tried first: clashes.
Then the static body: the
absclause creates at level 1 and binds . Here Check runs: has level 0, and level 1, so both are lowered, to new variables_7,_8of level 0 (the trace shows_7@0 _8@0, the walked values). This is right: the type of the inner abstraction is part of the outer type, which lives outside the scope of . - generic, augment again. Depth 2, eigenvariable of level 2, Γ now holds two clauses for
typeof°, on top of . - backchain, depth 2. The goal is
(typeof° x B'). The most recent hypothesis gives , a clash of two eigenvariables. The older one gives : a level-0 variable bound to another, fine. The static body is tried as well (the last trace line) and fails, since is neither an application nor an abstraction. - Exits. Each
∀°gives its answers back their depth and discharges nothing (no constraint mentions or ); each⊃°gives Γ back. The answer is , printed(arr α (arr β α)).
Tutorial (λx.x x fails by the occurs check). At depth 1, with the hypothesis , the goal is
. The app clause binds and creates its
(_6) at level 1. The first subgoal uses the hypothesis:
, and since , Check lowers to the level-0
_7. The second subgoal (printed with walked to _7) asks
: micro’s occurs check fails, and since the term holds
no λ-term, the occurs hook does not intervene. The static attempts fail too, and there is no answer,
the book’s “no” [MN p. 191].
12.5micro’s stores on λ-terms#
λProlog has no disequality, no absento and no type constraints such as symbol° (its types are
static). (aux kanren micro) has all three (Section 10.5), and
every relation built on them must keep working when its arguments are λ-terms. The readings adopted here extend
micro’s semantics over λProlog’s term model: equality is -equality, a flexible term is
undecided until its head is known, and an eigenvariable is, by default, a new name.
12.5.1Disequality: the diseq hook and the store N#
Definition 12.21 (Trial). The module claims a disequality when either side, walked, holds a λ-record or an
eigenvariable, and also, under the extensional reading once a ∀° has run, a first-order one (in D an
absento of T could absorb it, and absence reads eigenvariables generically). Its trial unifies in the current state, with Check, and classifies
the result (μkanren-trial):
unsat
no unifier: the disequality holds for good and is dropped;entailed
a unifier that binds no variable older than the trial (or binds older variables only to distinct variables the trial itself created) and suspends nothing: already holds, and≠°fails;- kept
otherwise: the pair is stored in N as(reading u . v)and re-tried after every=°.
The variables a trial creates (by pruning, by FF-same, by lowering) are existential inside the negation: means . A prefix of micro’s D would wrongly store them as free variables, which is one reason N is a separate store.
(°->list #f (fresh° (q) (=° q (ƛ (x) x)) (≠° q (ƛ (y) y)))) ; entailed mod α
(°->list #f (fresh° (q) (≠° (@ (ƛ (x) `(g ,x)) 'a) '(g a)))) ; entailed mod β
(°->list #f (fresh° (q) (≠° (ƛ (x) x) (ƛ (x) 'k)) (=° q 'ok))) ; holds for good
(°->list/datum (fresh° (q F) (=° q F) (≠° (@ F 'a) 'a)
(=° F (ƛ (z) z)))) ; woken, violated
(°->list/datum (fresh° (q F) (=° q F) (≠° (@ F 'a) 'a)
(=° F (ƛ (z) 'b)))) ; woken, holds
(°->list #f (fresh° (q f g) (=° q (list f g))
(≠° (ƛ (x y) (@ f x)) (ƛ (x y) (@ g y)))))()
()
((λ () 'ok))
()
((ƛ (z) b))
((λ (α β)
(begin (deny (∃ (_3) (and (equal? α (ƛ (x) _3)) (equal? β (ƛ (y) _3))))))
(cons α (cons β '()))))Line by line: the first trial succeeds under ξ binding nothing, so it is entailed and
≠° fails; the second never reaches the module, since @ has already β-reduced its left side to the
list (g a) and micro’s own ≠° fails on two equal terms; the third trial clashes ( against under ξ), so the disequality is unsat and
dropped. In the fourth and fifth the trial is no pattern ( is a constant) and suspends, so the
pair is kept in N; the binding of retries it, and it is violated by and holds for good
with . In the last, the trial is the flexible–flexible problem of Example 12.13 under two
binders: it binds the older and to and with a new , so the pair is kept,
and the answer denies exactly that mgu, with (_3) existential inside the deny.
Migration from D to N. A prefix of D born first-order may come to hold a λ-term or an eigenvariable
later, at any depth below its variables. The post hook moves it to N, as the tuple disequality it
stands for, before micro posts it again (E4 of Definition 11.13). So D never holds a λ-term,
and micro’s plain trial never decides a λ-equation without the scope check and the reading. The probe prints
N, D and E:
(define ((probe label) s)
(display label) (display ": N ") (write (μkanren-λ-disequalities s))
(display ", D ") (write (μkanren-state-D s))
(display ", E ") (write (μkanren-λ-delayed s))
(newline) (✓° s))
(°->list #f (fresh° (q Y) (≠° q (list Y)) (probe "before")
(=° Y (ƛ (z) z)) (probe "after")))before: N (), D (((_0 _1))), E ()
after: N ((generic (_0) (_1))), D (), E ()
((λ (α) (begin (deny (equal? α (cons (ƛ (z) z) '())))) α))The hook finds such prefixes from the new bindings, never by walking D (μkanren-migrate,
aux.kanren.lambda.scm:895–944). D held no λ-term before the binding, and every binding is in the
assocs the hook receives (E2), so a prefix holds one after the binding exactly when the value of a
binding that reaches it does. A prefix reaches a bound variable in one of two ways: micro’s records list it
under the variable, as a side of one of its pairs (μkanren-state-prefix-ids), or the variable lies below
a compound side of the prefix, or below a value bound since, and then W lists it, which micro’s watch
hook fills for every new prefix (μkanren-λ-watch). For each bound variable that either lists, the hook
walks the bound value once. If the value holds no λ-term, the variables it reaches go to W under the ids of
the prefixes that W listed and that are still live; if it holds one, each listed prefix is walked once and
moves. A first look of at most 64 nodes (μkanren-new-terms?) tells most first-order bindings at once
that they hold no λ-term, and then only the W-listed prefixes are looked at, since micro posts the
record-listed ones again anyway; with W empty the hook does nothing. Walking the prefixes themselves at every
binding, as the prototype did, made a store of disequalities cost walks.Section 14.3
has the measurements.
Subsumption by A. A trial that binds a variable typed in A to a rigid λ-term or an eigenvariable
of which the type’s predicate is false has no solution; symbol° and number° hold of neither. So the disequality is dropped, as micro
drops (≠° q 5) under (symbol° q):
(°->list #f (fresh° (q) (symbol° q) (≠° q (ƛ (x) x))))((λ (α) (assert (every (μ v (symbol? v)) (list α))) α))Two readings of ∀. What does mean? λProlog has no , but it has
pi x\ not (q = x), which succeeds: is a new name, distinct from everything. The parameter
μkanren-λ-reading chooses, and each disequality keeps the reading in force when it was posted.
'generic(the default) reads an eigenvariable as generic’s new name, ∇-like, as αKanren’s noms William E. Byrd and Daniel P. Friedman. Kanren: A fresh name in nominal logic programming. In Proceedings of the 2007 Workshop on Scheme and Functional Programming, Université Laval Technical Report DIUL-RT-0701, pages 79–90, 2007. At the exit of the scope the constraint is closed: becomes , consistently whichever comes first, the binding or the .'extensionalreads an eigenvariable as any term of its universe, as in the miniKanren work on universal quantification Evgenii Moiseenko. Constructive negation for miniKanren. In miniKanren and Relational Programming Workshop, 2019; and Ende Jin, Gregory Rosenblatt, Matthew Might, and Lisa Zhang. Universal quantification and implication in miniKanren. In miniKanren and Relational Programming Workshop, 2021. The trial replaces each eigenvariable by a new variable of its level, after raising the variables that may depend on it, and counts as entailed when it binds older variables only to distinct such variables. Then fails, since could be .
(°->list #f (fresh° (q) (∀° (x) (≠° q x))))
(°->list #f (fresh° (q F) (=° q F) (∀° (x) (≠° (@ F x) x))))
(°->list #f (fresh° (q F) (=° q F) (∀° (x) (≠° (@ F x) x)) (=° F (ƛ (z) z))))
(°->list #f (fresh° (q F) (=° q F) (∀° (x) (≠° (@ F x) x)) (=° F (ƛ (z) 'c))))
(parameterize ((μkanren-λ-reading 'extensional))
(list (°->list #f (fresh° (q) (∀° (x) (≠° q x))))
(°->list #f (fresh° (q F) (=° q F) (∀° (x) (≠° (@ F x) x))))
(°->list #f (fresh° (q F) (=° q F) (∀° (x) (≠° (@ F x) x))
(=° F (ƛ (z) 'c))))))((λ (α) α))
((λ (α) (begin (deny (equal? α (ƛ (x) x)))) α))
()
((λ () (ƛ (z) 'c)))
(() ((λ (α) (∀ (x) (begin (deny (≐ (@ α x) x)))) α)) ())Under the generic reading,
is the disequality : violated by , satisfied by
. Under the extensional reading it says that for every of the
universe, so violates it (); since it cannot be closed by an abstraction, it is printed
under a ∀.
Projection. micro drops a disequality over a variable that is out of the answer, since such a variable can always be chosen to keep the sides apart. That fails for a variable inside an argument of a flexible term: is , since may ignore its argument. Such an entry is kept, and its variable prints as a working variable, read existentially:
(°->pretty (fresh° (q) (fresh° (F G Y) (=° q (list F G)) (≠° G (@ F Y)))))(((α β) : (≠ β (@ α _3))))12.5.2Absence: the parts hook#
absent° looks for its datum in the parts of a λ-term (μkanren-λ-parts), never in binder names
or indices. A flexible term has no parts yet: it is 'stuck and watched whole, like a variable, and decided
once its head is known. Below a binder, the parts that mention the binder stay closed ( is
looked into as and ), so a watched term never has a loose index.
(°->list #f (fresh° (q F) (=° q F) (absent° 'c (@ F 'c))))
(°->list/datum (fresh° (q F) (=° q F) (absent° 'c (@ F 'c)) (=° F (ƛ (z) 'b))))
(°->list #f (fresh° (q) (absent° 'x (ƛ (x) `(g ,x))) (=° q 'ok)))
(°->list #f (fresh° (q F) (=° q F) (absent° 'c (ƛ (x) `(,(@ F x) c)))))
(°->list #f (fresh° (q F) (=° q F) (∀° (x) (absent° x (@ F x)))))
(°->list #f (fresh° (q) (∀° (x) (absent° x q))))((λ (α) (assert (absent? 'c (@ α 'c))) α))
((ƛ (z) b))
((λ () 'ok))
()
((λ (α) (∀ (x) (assert (absent? x (@ α x)))) α))
((λ (α) α))In order: waits; drops the argument, so it holds; the binder name x
is not the symbol 'x; is found at once outside the flexible part; an absento of an eigenvariable on a
term that may still hold it keeps and prints under ∀; and is entailed by the
levels ( has level , so no instance of can hold ) and dropped. The datum may itself be a λ-term,
or reduce to an atom ((@ G 'b) is a once ): it is then unified, modulo βη, as micro
unifies a compound datum.
12.5.3Types: the tag hook#
A type on a flexible term waits in E as (tag tag u); the post hook does the same for a variable of
A just bound to one. A rigid λ-term or an eigenvariable is decided by the type’s predicate: abstractions and
eigenvariables are neither symbols nor numbers, while a type of the user’s made with define-μkanren-tag
may hold of them. micro’s types are disjoint, so two different types on the same flexible term fail at once:
(°->list #f (fresh° (q F) (=° q (@ F 'a)) (symbol° q)))
(°->list/datum (fresh° (q F) (=° q (@ F 'a)) (symbol° q) (=° F (ƛ (z) z))))
(°->list #f (fresh° (q F) (=° q (@ F 'a)) (symbol° q) (number° q)))
(°->list #f (fresh° (q) (∀° (x) (symbol° x))))
(°->list #f (fresh° (q F) (=° q F) (∀° (x) (symbol° (@ F x)))))((λ (α) (assert (every (μ v (symbol? v)) (list (@ α 'a)))) (@ α 'a)))
(a)
()
()
((λ (α) (∀ (x) (assert (every (μ v (symbol? v)) (list (@ α x))))) α))Pitfall (Readings are per constraint, and only for ≠). The extensional reading applies to ≠° only; absent° and the types always read an eigenvariable as
generic does. A disequality keeps the reading in force when it was posted; a first-order disequality that
migrates from D to N later takes the reading in force when it migrates, since D records none. The two can differ
only if the program changes μkanren-λ-reading between the two goals.
12.6Reification#
micro reifies an answer as a λ-expression whose parameters name the answer’s variables and whose body lists the
constraints and ends with the value (Section 10.7). The module plugs into that through the hooks
value, repr, terms, forms and environment (Chapter 11).
Values. Deep values are β-normal and η-short (μkanren-λ-value). They are used by answers, by
D, A and T, by project° and by aggregation.
Binders. An abstraction prints as (ƛ (x y) body), nested binders merged. A binder is named
after its hint, renamed apart from the binders around it, from every symbol of its body, and from the operators
of the rebuilding code (cons, quote, vector, make-record-instance, ƛ, @,
eigen, bvar). So neither capture nor shadowing can mislead the reader (Ma and Friedman’s
“true = false”, Section 9.2.3), and a ground answer evaluates back to the same term:
(°->list/datum (fresh° (q) (=° q (ƛ (a) (ƛ (a) a)))))
(μkanren-datum (μkanren-abstract 'cons (λ (c) `(a ,c))))((ƛ (a a1) a1))
(ƛ (cons1) (a cons1))Applications print as (@ h a ...), so a flexible application (@ α x) cannot be mistaken
for the list (α x).
Residual forms. The constraints of the λ layer print as Scheme forms that can be evaluated:
| constraint | form in the answer |
|---|---|
| suspended equation (E) | (assert (≐ u v)) |
| type on a flexible term (E) | (assert (every (μ v (symbol? v)) (list u))) |
| absento with a pending term (E, T) | (assert (absent? d u)) |
| disequality whose trial binds (N) | (begin (deny (equal? α t))), with (∃ (_3) ...) inside deny when the trial creates variables |
| disequality whose trial only suspends (N) | (begin (deny (≐ u v))) |
| any of them still holding an eigenvariable | wrapped in (∀ (x) form) |
The forms of E and of N are sorted by their printed form, as micro sorts D and T, and a form that says what
an earlier one says, up to the names of the binders of ƛ, ∀ and ∃, is kept once
(μkanren-sort-forms, μkanren-form-α-key; both came with the merge, commit 5be5f35). So
the printed answer depends far less on the order of the goals that posted its constraints, and the same
disequality posted as and, through , as prints once:
(°->list #f (fresh° (q F) (=° q F) (≠° q (ƛ (x) x)) (≠° F (ƛ (y) y))))
(°->list #f (fresh° (q F) (=° q F) (≠° (@ F 'b) 'a) (≠° (@ F 'a) 'b)))
(°->list #f (fresh° (q F) (=° q F) (≠° (@ F 'a) 'b) (≠° (@ F 'b) 'a)))((λ (α) (begin (deny (equal? α (ƛ (x) x)))) α))
((λ (α) (begin (deny (≐ (@ α 'a) 'b))) (begin (deny (≐ (@ α 'b) 'a))) α))
((λ (α) (begin (deny (≐ (@ α 'a) 'b))) (begin (deny (≐ (@ α 'b) 'a))) α))On 12,000 random λ programs, each run in its order, reversed and shuffled, the printed answers of 578
depended on the order of the goals in the prototype, and of 165 on the merged tree; 161 of those have a
residual ≐ in some order, the limit of Section 14.2.3.
≐ is exported: it decides αβη-equality of closed terms by unifying them in the empty state, so the forms
evaluate. Through the terms hook, the variables of residual equations are reified after those of
the answer, so they are named α, β, … rather than _2
(Example 12.15). micro’s show module gives the αKanren-style view °->pretty:
(°->pretty (fresh° (q) (∀° (x) (=° (@ q `(g ,x)) `(h (g ,x))))))
(°->pretty (fresh° (q) (∀° (x) (=° (@ q x x) x))))((α : (= (ƛ (x) (@ α (g x))) (ƛ (x) (h (g x))))))
((α : (= (ƛ (x) (@ α x x)) (ƛ (x) x))))No free eigenvariable. Every constraint that holds an eigenvariable past its scope is closed, by
ƛ or by ∀, so no eigenvariable ever appears free in an answer. The one value that could hold one is the
answer itself, when the variable that °->list reifies is created inside a ∀°. λProlog reports no binding
for a variable quantified inside pi x\ , and this answer cannot be told without , so reifying it is an error:
(error-message (λ () (°->list #f (∀° (x) (fresh° (q) (=° q x))))))"the answer holds the eigenvariable of a ∀° it was created in: create the variable it reifies outside every ∀°"Live ground answers. ƛ, @ and ≐ are bound in the module’s environment, which the
environment hook hands to °->list/ground. A ground answer is therefore a λ-term one can apply:
(@ (car (°->list/ground (fresh° (q) (=° q (ƛ (x y) `(g ,x ,y)))))) 'b 'b)(g b b)°->list/datum answers plain data instead, comparable with equal? against quoted book answers; that is what
the suite uses, and μkanren-repr->datum of (aux kanren micro show) turns micro’s rebuilding code
into such data.
Pitfall (Hints are not part of equality). equal? sees hints, the unifier does not. (ƛ (x) x) and (ƛ (y) y) unify and are μkanren-α=?,
but they are not equal?: equal? compares records slot by slot, hint included, and the hint is
kept in the record so that answers print the user’s binder names. When comparing λ-terms in host code, use μkanren-α=? or ≐.
A related trap is Scheme’s own: (ƛ (quote) 'a) shadows quote while the body is built; terms built through
μkanren-abstract with such a hint print and evaluate correctly.
12.7API reference#
| name | meaning |
|---|---|
| Terms | |
(ƛ (x ...) body) | λ-abstraction over Scheme binders, η-short |
(@ f a ...) | application; β at once on an abstraction, nested applications flattened |
(≐ u v) | αβη-equality of closed terms, for residual forms |
(μkanren-abstract name f) | the abstraction of the term (f p), p a placeholder; binder hinted name |
(μkanren-apply f args) | @ on a list of arguments |
(μkanren-hnorm t s) | head normal form of t in state s (Definition 12.3) |
(μkanren-α=? u v) | α-equivalence of deep values, hints ignored |
(μkanren-datum t) | a term as data, printed without a state |
μkanren-lam? μkanren-app? μkanren-eigen? μkanren-bvar? μkanren-λ-term? | record predicates; the last is their union |
μkanren-lam-hint μkanren-eigen-name μkanren-eigen-level | accessors |
| Goals | |
(∀° (x ...) g ...) | generic; (∀ª name f) its procedural form, f taking the eigenvariable |
(⊃° (D ...) g ...) | augment; (⊃ª clauses g) its procedural form |
(define-dynamic-relation (r a ...) g ...) | a relation that hypotheses can extend; with no g, no static clauses |
(μkanren-dynamic f) (μkanren-dynamic? f) | tag a procedure as dynamic, test the tag |
μkanren-hyps° μkanren-clause μkanren-clause/vars μkanren-clause* | what the macros expand to |
| Clauses | |
(r t ...) ((r t ...) ← g ...) (← (r t ...) g ...) (∀ (v ...) D) | fact, rule (infix and prefix), own variables |
| Answers | |
(°->list/datum g) | the answers of g as plain data, constraints dropped |
μkanren-λ-show-extension | how the show module reads the module’s answers, registered at load time |
| Engine | |
μkanren-λ-reading | parameter, 'generic (default) or 'extensional |
(μkanren-λ-depth s) | the current universe level |
(μkanren-λ-level α s) | the level of variable α |
(μkanren-λ-delayed s) | the suspended constraints E |
(μkanren-λ-disequalities s) | the λ-disequalities N |
μkanren-λ-extension | the registered extension record |
In (aux kanren micro show) | |
(°->pretty g) μkanren-answer->pretty | αKanren-style answers, (value : constraint ...) |
(μkanren-repr->datum r) | micro’s rebuilding code as data; no longer exported by the module, where it clashed with this one |
12.8Summary#
- Terms. Four records, locally nameless:
μkanren-lam(interned hint, body),μkanren-app,μkanren-eigen(name, level, uninterned id),μkanren-bvar.ƛuses Scheme binders and builds η-short;@β-reduces at once. Terms built alike areequal?; α-equality isμkanren-α=?and≐. Lists remain data:(@ 'g 'a)is not'(g a). - State. One immutable record in micro’s slot
X: depth, top, the levels / (an sbral, lazily padded), Γ (one entry per relation), E (suspended constraints), N (λ-disequalities), W (the prefixes of D that reach each variable).∀°and⊃°restore depth and Γ on every answer; branches never share it. - Unification. micro does the first-order part; the hook applies ξ, η, Rigid, FF-same, FR/FF-diff by variable elimination, and suspends non-patterns: the rules of Rules A.30 with the prefix erased into levels. Patterns are read off levels. Elim prunes and lowers only strict occurrences, fails an occurrence of only by Nipkow’s size argument, and suspends whatever a later binding could decide.
- Check. Every binding is scope-checked at its variable’s level (NJK’s binding rule with pruning),
or taken back into E when a non-pattern decides it. Fast paths skip it before any
∀°, on plain terms and for top-level variables. Wake-up retries E in rounds while a round binds, and terminates when hnf does. - ∀° and ⊃°. generic runs its body one universe deeper with a new eigenvariable and discharges
the residuals on exit (raise, close by ξ, retry, repeat). augment pushes closures on Γ. Dynamic relations
backchain on hypotheses first, most recent first, then on their static body; a clause’s free variables are
shared, its
∀variables renamed per use. - Stores.
≠°on λ-terms goes to N with a trial whose new variables are existential; D never holds a λ-term, and the prefixes a binding brings one into move to N, found per binding; two readings of , generic (default) and extensional.absent°looks into parts and watches flexible terms; types wait on flexible terms and are decided by their predicate. - Answers. β-normal, η-short, binders renamed apart; residual forms sorted, each kept once up to
α; residuals as
(assert (≐ u v)),(deny ...),(absent? ...), closed with∀when they keep an eigenvariable; never a free eigenvariable; ground answers are live terms.