Chapter 6
λ-tree syntax: computing with binders
The previous chapters gave us two kinds of machinery. Chapter 4 and Chapter 5 gave us simply typed -terms as data, with an equality that already contains -, - and -conversion. Chapter 3 gave us the two goal connectives of hereditary Harrop formulas: the universal goal pi x\ G, proved with a fresh eigenvariable, and the implicational goal D => G, proved with the program temporarily extended by D. This chapter, which follows Chapter 7 of the bookDale Miller and Gopalan Nadathur. Programming with Higher-Order Logic. Cambridge University Press, Cambridge, 2012 ([MN p. 175]–[MN p. 210]), shows what the two kinds of machinery can do together: they let a logic program compute over syntax that contains binders.
This is the chapter that motivates the whole proposal of this document. Every program in it manipulates formulas with quantifiers or -terms. None of them contains a single line about variable names, renaming, or capture-avoiding substitution. All of that is “relegated to the meta-level”. A miniKanren that wants to run these programs must therefore provide the meta-level: -terms as data, eigenvariables with a scope discipline, and a scoped program extension. We will read the book’s programs closely, walk through how pi and => make a binder “mobile”, and, in the Kanren angle boxes, record what each concept asks of (aux kanren micro).
6.1The problem: syntax with binders#
Many symbolic objects contain binders [MN p. 175]–[MN p. 176]: the in , in and in ; quantifiers; -abstractions; local declarations and formal parameters in programming languages; type quantifiers of polymorphic types; name restriction in the -calculus. Programs that handle such objects (differentiators, compilers, interpreters, theorem provers, type checkers) all need the same three notions [MN p. 176]:
- the distinction between free and bound occurrences of a variable;
- the irrelevance of bound names (-conversion): the formulas and are the same;
- capture-avoiding substitution, needed both for instantiating quantifiers and for passing parameters.
The book observes that “a computational treatment of such binding-related notions is complicated, and programming language support for realizing them can be valuable” [MN p. 176]. Anyone who has written a substitution function over a named representation, with its renaming case, knows why.
The book’s answer has three parts. We state them now and spend the chapter on them.
- Encoding. Each object-level binder becomes a constant applied to a -abstraction of the meta-level. So
all (x\ B)encodes the formula , andabs (x\ t)encodes the term . - Substitution is . Instantiating the bound variable of an abstraction
BwithTis just writing the application(B T); the meta-level -conversion does the rest. - Mobility. To recurse under a binder, the program turns the term-level into a formula-level
pi, which proof search turns into a proof-level eigenvariable; facts about the new eigenvariable are assumed with=>.
6.2Encoding objects with binding structure#
6.2.1First-order formulas#
The object logic is first-order logic over two sorts, term and form. The propositional connectives are ordinary constants (re-listed on [MN p. 177]):
type ff, % encoding the false proposition
tt form. % encoding the true proposition
type &&, % encoding conjunction
!!, % encoding disjunction
==> form -> form -> form. % encoding implication
type neg form -> form. % encoding negation
infixl && 5.
infixl !! 4.
infixr ==> 3.A sample non-logical signature [MN p. 177]:
type p term -> form.
type q term -> term -> form.
type f term -> term.
type a term.Terms of type term -> form are “abstractions of a term over a formula” [MN p. 178], for example
x\ (p x) ==> (p (f x))
Z\ (p Z) ==> (p (f Z))
Z\ (p Z) && (p (f Z))The first two are the same -term, since they differ only in the bound name. Note that the capital Z after Z\ is a bound variable, not a logic variable. The quantifiers are then second-order constants: their argument has a functional type [MN p. 178].
type all, some (term -> form) -> form.all x\ (p x) ==> (p (f x)) % ∀x (p(x) ⊃ p(f(x)))
some Z\ (p Z) && (p (f Z)) % ∃Z (p(Z) ∧ p(f(Z)))The book states the principle behind this as follows: “the mechanism that we have described divides the encoding of the object logic quantifiers into two parts: a second order constant that identifies the quantifier and an abstraction that captures its binding effect” [MN p. 178]. For instance is encoded as
all x\ all y\ (q x y) ==> some z\ p z && q z y.where \ extends as far to the right as possible and && (priority 5) binds tighter than ==> (priority 3).
Definition 6.1 (The encoding of formulas). For first-order terms and formulas over the signature above, define by
The book does not state as a definition or prove anything about it; this formal version is ours, and so is the name. The chapter relies on two properties of it without stating them. First, it is a bijection between closed object formulas over the signature, taken up to renaming of bound variables, and closed terms of type form over the same signature, taken up to -conversion. A canonical representative of each class is the -normal, -long term, which is what produces. Second, it commutes with substitution: . The second property is what makes “substitution is ” correct.
6.2.2Untyped λ-terms#
The second running object language is the untyped -calculus [MN p. 178]–[MN p. 179]:
kind tm type.
type app tm -> tm -> tm.
type abs (tm -> tm) -> tm.| untyped term | encoding |
|---|---|
(abs x\x) | |
(abs x\ (app x x)) | |
(abs x\ abs y\ x) | |
(abs x\ abs y\ y) | |
(abs x\ abs y\ app y x) | |
(abs x\abs y\abs z\ (app (app x z) (app y z))) | |
(app (abs x\ app x x) (abs x\ app x x)) |
Each object application becomes one app; each object becomes one abs followed by one meta-level . Two remarks help in reading the rest of the chapter.
- No closed term of type
tmcan be built fromappalone: every closed term starts with anabs, whose argument (of typetm -> tm) is something likex\xorx\ app x x. - “the type tm can be seen as admitting new constructors as one descends under binders” [MN p. 179]. Below
abs x\ abs y\bothxandybehave as extra constants of typetm. Mobility (Section 6.4) makes this literally true: under a binder the program works with a genuinely new constant.
6.2.3What the encoding gives for free#
The abstractions over syntax live at arrow types (term -> form, tm -> tm), and the equality of those types includes the three conversions of Chapter 4.
- . The object language identifies formulas up to renaming of bound variables, and so does the meta-language. “Since -conversion is included within the logical notion of equality, it is impossible to access the names of bound variables” [MN p. 180]. The book presents this as a strength: the programmer is spared what does not matter, and the implementer may drop names entirely (for instance with de Bruijn indicesN. 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). The cost is that printing and parsing must invent names.
- . This is the subject of Section 6.3.
- . Its effect is “rather mild” [MN p. 180]: for , . Hence may be written
(all x\ p x)or(all p): “not only does the hohh language abstract away from names of bindings, but it also sometimes allows one to abstract away from the presence of actual binders” [MN p. 180].
Pitfall (An η-short quantifier is still a quantifier). A head pattern (all B) must also match the term (all p), and (B T) must then reduce to (p T). An implementation either unifies modulo or keeps terms -long. A representation that stores the binder “shape” syntactically and expects every quantifier to carry an explicit will reject (all p).
6.3Object-level substitution is meta-level β#
6.3.1Instantiating quantifiers#
The formula is all x\ p x ==> some y\ q x y. To instantiate it with we simply apply the abstraction to (f a) [MN p. 180]–[MN p. 181]:
(x\ p x ==> some y\ q x y) (f a)which -converts to p (f a) ==> some y\ q (f a) y.The book prints p (h a) here, a typo; the page image confirms it, and it must be p (f a). Note what was not needed: no renaming of the inner y, no check that (f a) has no free y. Capture avoidance is the meta-level’s job.
The predicate list_instan relates a list of terms and a formula with at least outer universal quantifiers to the result of instantiating the first [MN p. 181]:
type list_instan list term -> form -> form -> o.
list_instan nil B B.
list_instan (T::Ts) (all B) C :- list_instan Ts (B T) C.The head (all B) is -equal to (all x\ B x): matching it binds B to the abstraction itself, and “the substitution for a bound variable is realized simply by writing down (B T)” [MN p. 181].
6.3.2An interpreter for an object logic#
A more substantial example is an interpreter for first-order Horn clauses, written in higher-order Horn clauses (Figure 7.1, [MN p. 181]). The object-level program is an explicit argument D, a single formula.
type interp form -> form -> o.
type backchain form -> form -> form -> o.
type atom form -> o.
interp D tt.
interp D (G1 && G2) :- interp D G1, interp D G2.
interp D (G1 !! G2) :- interp D G1; interp D G2.
interp D (some G) :- interp D (G X).
interp D A :- atom A, backchain D D A.
backchain D A A.
backchain D (D1 && D2) A :- backchain D D1 A; backchain D D2 A.
backchain D (all D1) A :- backchain D (D1 X) A.
backchain D (G ==> D1) A :- backchain D D1 A, interp D G.The two higher-order clauses are the interesting ones. An object goal (some G) is solved by solving (G X) for a fresh logic variable X: the meta-level plugs the logic variable in for the object-bound variable, and later unification will find a witness. An object clause (all D1) is used by instantiating it with a fresh logic variable as well. The sample object program of Figure 7.2 ([MN p. 182]) is
type a, b, c term.
type adj, path term -> term -> form.
type prog form -> o.
atom (adj _ _) & atom (path _ _).
prog ((adj a b) && (adj b c) &&
(all x\ all y\ (adj x y) ==> (path x y)) &&
(all x\ all y\ all z\ (adj x y) && (path y z) ==> (path x z))).Two notational points recur in the rest of the chapter. An & between two clause heads, as in atom (adj _ _) & atom (path _ _)., is clause-level conjunction. The heads share one body (here an empty one), so the line stands for two clauses written together. The underscore _ is an anonymous logic variable. The predicate atom is not part of the interpreter. It is defined for each object signature by listing its predicate constants, and here it says that adj and path atoms are atomic. The query ?- prog P, interp P (path a X). has two answers, X = b and then X = c [MN p. 182].
Tutorial (How interp finds X = b). The goal interp P (path a X) matches the last interp clause, because atom (path a X) holds. We must prove backchain P P (path a X). The program P is a left-nested && of four parts, so the second backchain clause descends into it. The two adj facts do not match path a X. The third part is all x\ all y\ (adj x y) ==> (path x y): the (all D1) clause applies it to a fresh X1, giving (D1 X1) all y\ (adj X1 y) ==> (path X1 y); once more with Y1, giving (adj X1 Y1) ==> (path X1 Y1). The ==> clause then requires backchain P (path X1 Y1) (path a X) (the fact clause, binding X1 = a, Y1 = X) and then interp P (adj a X), which backchains to the fact adj a b with X = b. On backtracking, the fourth part of the program yields X = c through adj a b and path b c. At no point did the interpreter rename a bound variable: each -step (D1 X1) replaced an object-level bound variable by a logic variable.
6.3.3Evaluators for the untyped λ-calculus#
Call-by-name and call-by-value evaluation are four clauses (Figure 7.3, [MN p. 182]):
type cbn, cbv tm -> tm -> o.
cbn (abs R) (abs R).
cbn (app M N) V :- cbn M (abs R), cbn (R N) V.
cbv (abs R) (abs R).
cbv (app M N) V :- cbv M (abs R), cbv N U, cbv (R U) V.(R N) is the object-level -contraction, done by the meta-level .The text on [MN p. 182] says “the term U such that eval N U is provable”; eval is a loose name for cbv. The behaviour is the expected one [MN p. 183]. has no value under either evaluator: the search for a derivation is infinite. On , call-by-name terminates and call-by-value loops:
?- cbn (app (abs x\ abs w\w) (app (abs x\ app x x) (abs x\ app x x))) V.
% V = (abs w\w)
?- cbv (app (abs x\ abs w\w) (app (abs x\ app x x) (abs x\ app x x))) V.
% infinite searchThe book draws the moral of this section in one paragraph [MN p. 183]. The specifications are succinct and declarative because “all the details regarding object-level bound variables and object-level substitution has been relegated to the meta-level”. They are still formal and precise: the details “have not gone away; they simply have become the burden of an implementation of a metalogic such as Prolog”, and the programmer “is relieved of dealing with the details behind such ‘concrete nonsense’ as binder names, capture avoiding substitutions, etc.”
Kanren angle (What works today: abstractions as Scheme closures). All the programs of this section use an abstraction only as an input. The abstraction is already known when (R N) is formed. A miniKanren can imitate this with functional higher-order abstract syntax: represent abs R by a list holding a Scheme procedure, and perform (R N) with project°. This runs on today’s (aux kanren micro), unchanged:
(define (abs f) `(abs ,f))
(define (app m n) `(app ,m ,n))
(define ω (abs (λ (x) (app x x))))
(define Ω (app ω ω))
(define K* (abs (λ (x) (abs (λ (w) w))))) ; λx λw w
; call-by-name evaluation, Figure 7.3: (R N) is Scheme application, available only through project°
(define-relation (cbn° m v)
(cond°
((fresh° (r) (=° m `(abs ,r)) (=° v m)))
((fresh° (m1 n r) (=° m `(app ,m1 ,n)) (cbn° m1 `(abs ,r))
(project° ((r* r)) (cbn° (r* n) v))))))
; printing a HOAS term needs invented names: apply each closure to a generated symbol
(define (hoas->sexp t)
(let loop ((t t) (k 1))
(cond
((and (pair? t) (eq? (car t) 'abs))
(let ((w (string->symbol (string-append "w" (number->string k)))))
`(λ (,w) ,(loop ((cadr t) w) (+ k 1)))))
((and (pair? t) (eq? (car t) 'app)) `(,(loop (cadr t) k) ,(loop (caddr t) k)))
(else t))))
(print (μkanren-run (q -1 #t) (fresh° (v) (cbn° (app K* Ω) v) (project° ((v* v)) (=° q (hoas->sexp v*))))))
; α-equivalent closures are different Scheme objects: unification fails
(print (μkanren-run (q -1 #t) (=° (abs (λ (x) x)) (abs (λ (y) y)))))((λ (w1) w1))
()The first answer is the book’s V = (abs w\w). The second answer is the problem. Two -equivalent abstractions are distinct procedures, and (aux kanren micro) compares procedures with eq?, so they do not unify. A closure cannot be printed without being applied to invented names (that is what hoas->sexp does). A closure cannot be inspected except by applying it, and no unification can produce one. Recognisers such as term, bnorm and typeof below could still be run on closures. They only apply an input abstraction to a fresh constant, although they also need pi and =>. But every program that builds an abstraction as output (red1, path synthesis, trans backwards, nnf, prenex, copy, subst backwards), and every program that asks whether a body depends on its bound variable (vacuous, the -redex), is out of reach. Section 6.8 comes back to this “functional” reading of higher-order abstract syntax.
6.4Mobility of binders#
6.4.1Why an abstraction cannot be taken apart#
Equal expressions should have equal parts: equal non-empty lists have equal heads and equal tails. Applied to -terms, this principle says that “we should not be able to decompose an abstraction into the variable that it binds and its body” [MN p. 183]. The terms (all x\ some y\ p x ==> p y) and (all z\ some y\ p z ==> p y) are equal, yet the names x and z differ, and so do the would-be bodies (some y\ p x ==> p y) and (some y\ p z ==> p y). “Such decompositions, in fact, have no logical status within the hohh language: Because equality includes -conversion, the name for a bound variable is a fiction, and an implementation may not represent it at all” [MN p. 183].
So how does a program recurse into the body of a binder? The book’s answer [MN p. 184]: “during proof search, a term-level binding (i.e., a -abstraction) can be converted into a formula-level binding (i.e., a quantifier), which then can be converted into a proof-level binding (i.e., an eigenvariable).”
6.4.2The proof-search rules behind mobility#
Recall from Chapter 3 the rules for the two connectives that make mobility work, together with the backchaining rule. A goal is proved relative to a signature (constants and eigenvariables in scope) and a program .
For an atomic goal , backchain picks a clause of and an instance with , then proves . In an implementation the term of instance and the substitution are found by unification with logic variables. Then the side condition becomes the scoping constraint: a logic variable created before the eigenvariable must never be instantiated with a term containing , because at the time it was created its witness had to be a -term. This is why sigma X\ pi y\ X = y fails while pi y\ sigma X\ X = y succeeds. Chapter 7 never mentions the constraint, but several of its programs (vacuous, the -redex clause, prenex) are correct only because of it.
6.4.3A first example: recognising terms#
Because of typing, the predicate term : tm -> o could be defined by the single clause term T.. A more instructive definition reflects the two constructors of tm into two clauses [MN p. 184]. Written so that their logical content is visible:
pi M\ term M => pi N\ term N => term (app M N).
pi R\ (pi x\ term x => term (R x)) => term (abs R).or, equivalently, in the usual clause syntax:
term (app M N) :- term M, term N.
term (abs R) :- pi x\ term x => term (R x).Tutorial (Following the binder of (abs y\ app y y)). The book traces the query ?- (term (abs y\ app y y)). [MN p. 184]–[MN p. 185].
?- (term (abs y\ app y y)).
?- pi x\ term x => term ((y\ app y y) x). % backchain on abs clause
?- pi x\ term x => term (app x x). % β-conversion: term-level y -> formula-level x
?- term (app c c). % eigenvariable c, program + (term c)- Backchaining on the
absclause unifiesRwith the abstractiony\ app y y. Nothing has been decomposed:Rholds the whole abstraction. - The body of the clause applies
Rto thepi-boundx. The redex((y\ app y y) x)is a -redex (Section 6.9): a applied to a bound variable. Contracting it moves the term-level binderyto the formula-level binderx. - generic replaces
xby a new eigenvariablec. augment adds the clauseterm cto the program. The formula-level binder has become a proof-level binder. term (app c c)backchains on theappclause, and both subgoalsterm care closed by the assumed clause.
Here c is exactly one of the “new constructors” of tm that appear under a binder. The program has no clause for variables, and it needs none: each variable gets its clause at the moment its binder is crossed, and loses it when the proof of the body is complete.
The book distils the example into a programming idiom. We record it as a definition because every program of the chapter is an instance of it.
Definition 6.2 (The binder-mobility idiom, [MN p. 185]). “In order to continue a recursive analysis within the scope of a binder, first, apply that binder to a universal quantified goal variable, for which the metalogic will substitute an eigenvariable, and second, using an implicational goal, assume new clauses that extend the definition of various predicates so that they can deal with the presence of this new eigenvariable.”
In code, the idiom is always the shape p (c R) ... :- pi x\ (hyp x => p (R x) ...). The abstraction R is never opened. It is applied to a fresh eigenvariable, and the assumed hyp x tells the predicates of the program what to do when they meet it.
Pitfall (A fresh constant is not an eigenvariable). Proving pi x\ G with a fresh constant is only half of generic. The other half is the scoping constraint. Here is what happens without it, in today’s (aux kanren micro), if a universal goal is “implemented” by handing a gensym to the body:
; a NAIVE universal goal: a fresh Scheme constant, with no eigenvariable scope check
(define (naive-pi f) (f (gensym 'c)))
; λProlog: ?- sigma X\ pi y\ X = y. must fail; the naive encoding succeeds
(print (μkanren-run (q -1 #t) (naive-pi (λ (y) (=° q y)))))
; λProlog: ?- pi y\ sigma X\ X = y. must succeed (X is created inside the scope of y)
(print (μkanren-run (q -1 #t) (naive-pi (λ (y) (fresh° (x) (=° x y) (=° q 'ok))))))(c103)
(ok)The first query should fail. The query variable q was created before the constant, yet it now holds that constant, which has escaped its scope. The same mistake in a unifier, letting a clause variable be bound to a term that mentions a variable bound inside its scope, makes vacuous (Section 6.6) accept formulas whose quantifier is not vacuous. The constraint is not a matter of efficiency: it is part of the meaning of .
Kanren angle (What mobility requires of a miniKanren). Mobility needs three things that (aux kanren micro) lacks (see Chapter 10 for the engine).
- Eigenvariables: constants created during the search, distinct from every other term, with a scope. The engine must enforce the scoping constraint: a logic variable older than an eigenvariable can never be bound to a term containing it, even indirectly through younger variables (binding and later leaks into ). λProlog implementations use universe levelsGopalan 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 miniKanren with symbolic constraints uses an absento-like “eigen” constraint over the variables in scopeJason Hemann, William E. Byrd, and Daniel P. Friedman. The eigen operator of miniKanren-with-symbolic-constraints. Software, 2013. URL https://github.com/webyrd/miniKanren-with-symbolic-constraints.
- Scoped program extension:
D => GaddsDonly whileGis being proved. Other branches of the search and the answers of the enclosing goal must not seeD. Because miniKanren’s search interleaves branches, the extension must live in the search state, not in a host-language dynamic variable. A relation must be able to consult the assumed clauses as well as its static ones. - Application of an abstraction to an eigenvariable,
(R x), on both sides of the equation: as input (whenRis known) and as output (whenRis a logic variable to be solved, as in most programs below).
How the proposal provides each of these is the subject of Chapter 11.
6.5Computing with untyped λ-terms#
This section applies the idiom to the untyped -calculus. The programs grow from pure recognisers to programs that build abstractions as output, to programs that assume rules with bodies.
6.5.1β-normal forms#
Definition 6.3 (β-normal, β-body-normal, [MN p. 185]). An untyped -term is in -normal form if it contains no -redex. Equivalently and positively, it has the shape with , where is a variable and every is -normal. The inner part is called -body-normal.
The definition becomes three inference rules and three clauses [MN p. 186]:
type bnorm, bbnorm tm -> o.
bnorm (abs M) :- pi x\ bbnorm x => bnorm (M x).
bnorm H :- bbnorm H.
bbnorm (app M N) :- bbnorm M, bnorm N.There is no static clause saying that a variable is -body-normal, and there could not be one, since bound variables are not terms of the program. A variable becomes body-normal only through the assumption bbnorm x made when its binder is crossed. A redex app (abs R) N is rejected because bbnorm (abs R) has no clause.
Tutorial (A normal term and a redex). This walk-through is ours; the book gives no query for bnorm. Take first ?- bnorm (abs x\ app x x).
- The
absclause matches withM = x\ app x x. The body ispi x\ bbnorm x => bnorm (M x): an eigenvariablecis created,bbnorm cis assumed, and the goal isbnorm (app c c)(after ). bnorm (app c c)is not anabs, so the second clause reduces it tobbnorm (app c c), and the third clause tobbnorm candbnorm c.bbnorm cis the assumption.bnorm cgoes through the second clause tobbnorm cagain, also the assumption. The query succeeds.
Now take ?- bnorm (app (abs x\x) (abs x\x)). The abs clause does not match. The second clause asks for bbnorm (app (abs x\x) (abs x\x)), and the third clause for bbnorm (abs x\x). No static clause has a head bbnorm (abs _), and the only assumptions ever made are bbnorm c on eigenvariables, so the query fails. The structure of the clauses alone, “a variable is body-normal only when its binder said so”, rules the redex out.
A pleasant consequence is a substitution lemma that costs nothing.
Theorem 6.4 (Substitution lemma “for free”, [MN p. 186]). Let , , with the eigenvariables. If (bnorm (abs R)) and (bbnorm S) are both derivable from the program above together with , then (bnorm (R S)) is derivable too. In object-level terms: if is -normal and is -body-normal, then is -normal.
Proof (book’s argument, with the inversion step made explicit). A derivation of bnorm (abs R) must end with the abs clause, so pi x\ bbnorm x => bnorm (R x) is derivable. Derivability is intuitionistic, so the universal quantifier can be instantiated with S, giving bbnorm S => bnorm (R S), and modus ponens with bbnorm S gives bnorm (R S). □
The book says only “since derivability is based on intuitionistic logic”. Two facts sit behind that phrase: cut admissibility, and the fact that an eigenvariable may be instantiated by any term. The inversion step (“must end with the abs clause”) also uses the shape of . contains only atoms bbnorm c on eigenvariables, so no assumption can match bnorm (abs R). In a named representation this lemma is a page of index bookkeeping. Here the logic proves it.
6.5.2Reduction to normal form#
Figure 7.4 ([MN p. 187]) specifies one-step reduction and reduction to normal form:
type redex, red1, reduce tm -> tm -> o.
redex (app (abs R) N) (R N).
red1 M N :- redex M N.
red1 (app M N) (app P N) & red1 (app N M) (app N P) :- red1 M P.
red1 (abs M) (abs N) :- pi x\ red1 (M x) (N x).
reduce M M :- bnorm M.
reduce M N :- red1 M P, reduce P N.
type repeat (A -> A -> o) -> A -> A -> o.
type reduce' tm -> tm -> o.
repeat Pred M N :- Pred M P, !, repeat Pred P N.
repeat Pred M M.
reduce' M N :- repeat red1 M N.redexrelates a -redex to its contractum, again by meta-level :(R N).red1contracts exactly one redex somewhere in the term. Theabsclause is new. Its output is the abstractionN, and the goalred1 (M x) (N x)asks unification to solve(N x) = tfor an unknownN: the answer isNx\ t, with the eigenvariable abstracted out oft. This is a higher-order pattern problem (Section 6.9 and Chapter 7). There is no=>here:red1should simply fail on a bare variable, so no clause aboutxis needed.reduceusesbnormto decide when to stop.reduce'uses the polymorphic higher-orderrepeat, which iterates its argument until it fails. The cut!“prune[s] away alternative solutions to the parent goal” [MN p. 186]. (The text there saysrepeat'; the figure’s predicate isrepeat.)
Tutorial (One step under a binder: red1 (abs x\ app (abs y\y) x) N). This is our own example of an output abstraction, traced against the clauses of Figure 7.4 without the -clause below. The term is , with a redex under the binder.
red1 M N :- redex M Nfails: the term is anabs, not anapp. The twoappclauses do not match either.- The
absclause matches withM = x\ app (abs y\y) xandN = abs N1for a new logic variableN1 : tm -> tm. It creates an eigenvariablec. The goal isred1 (app (abs y\y) c) (N1 c). - The
redexclause applies withR = y\yand contractum(R c), which isc. Now unification must solve(N1 c) = c. This is a pattern equation:N1is applied to the eigenvariableconly. Its unique solution abstractscout of the right-hand side:N1 := x\ x. - The answer is
N = abs x\x. On backtracking, theappclauses try to reduce(abs y\y)orcin one step. The first descends undery\to the goalred1 d _on a new eigenvariabled, the second givesred1 c _. Both fail, because no clause, static or assumed, applies to a bare eigenvariable. There is no other answer.
The program contains no code for “rebuild the binder around the reduced body”. Unification does it in step 3, and the scoping constraint guarantees that N1, created before c, receives c only through its argument.
The -redex needs one clause [MN p. 187]:
redex (abs x\ app M x) M.It is correct because of the scoping constraint. M is a clause variable, quantified outside the binder x, so no unifier can let M depend on x. This is exactly the side condition of : not free in . For instance, abs x\ app x x is not an -redex: matching it against abs x\ app M x would need M = x, and the scoping constraint forbids that binding. With this clause added, the term of the tutorial above is also an -redex. Matching abs x\ app (abs y\y) x against abs x\ app M x gives M = abs y\y, which does not mention x, so red1 now finds abs y\y first, through redex, and then the -equal abs x\x again through the abs clause.
The book adds a semantic remark [MN p. 186]–[MN p. 187]. A model of the untyped -calculus is a domain with maps and ; tm plays , app plays , abs plays . The -clause states and the -clause states : “these are the familiar properties stating that f and g are, in fact, retracts”.
6.5.3Reduction based on paths#
A path walks from the root of a term to an occurrence of a variable. It passes through an abstraction and chooses left or right at an application [MN p. 187]. Paths contain binders too:
kind path type.
type bnd (path -> path) -> path.
type left, right path -> path.
type path tm -> path -> o.
path (app M _) (left P) &
path (app _ M) (right P) :- path M P.
path (abs R) (bnd S) :- pi x\ pi p\ path x p => path (R x) (S p).The abs clause introduces two eigenvariables at once: a term variable x and a path variable p. The assumption path x p links them: the path to the occurrence of x is p. The paths of (abs x\ app x (abs y\ app y x)) are [MN p. 188]
bnd u\ left u
bnd u\ right (bnd v\ left v)
bnd u\ right (bnd v\ right u)The relation also runs backwards: from a set of paths it synthesises the term, using foreach from Chapter 5 (foreach P nil. foreach P (X::L) :- P X, foreach P L.) [MN p. 188]:
?- foreach (path N)
((bnd u\ left u) ::
(bnd u\ right (bnd v\ left v))::
(bnd u\ right (bnd v\ right u))::nil).
N = abs W1\ app W1 (abs W2\ app W2 W1);
noTutorial (Synthesising a term from its paths). Take the first path. path N (bnd u\ left u) can only use the abs clause, so N = abs R and S = u\ left u. Under eigenvariables x, p with path x p assumed, the goal is path (R x) (left p). The left clause requires (R x) = app M _. Unification solves this pattern problem with R := x\ app (M' x) (K x), two new logic variables applied to x. Then path (M' x) p is solved by the assumption path x p itself, giving M' := x\ x. The second and third paths fill in the right branch in the same way. Nothing in the program says “build an abstraction”. The abstraction in the answer is produced by unification, which abstracts the eigenvariable x out of a term that contains it. This is the operation that Scheme closures could not perform.
Paths can also cross a marked -redex. A path through (app (abs R) N) goes through the body R; when it reaches the bound variable of R, it continues into N. Marked redexes are written (beta N R) (Figure 7.5, [MN p. 189]):
type beta tm -> (tm -> tm) -> tm.
type addbeta tm -> tm -> o.
type bpath tm -> path -> o.
bpath (app M _) (left P) &
bpath (app _ M) (right P) :- bpath M P.
bpath (abs R) (bnd S) :- pi x\ pi p\ bpath x p =>
bpath (R x) (S p).
bpath (beta N R) P :-
pi x\ (pi Q\ bpath x Q :- bpath N Q) => bpath (R x) P.
addbeta (app (abs R) N) (beta M S) :- addbeta (abs R) (abs S),
addbeta N M.
addbeta (app (app M N) P) (app O Q) :- addbeta (app M N) O,
addbeta P Q.
addbeta (abs R) (abs S) :-
pi x\ (pi M\ pi N\ addbeta (app x M) (app x N) :- addbeta M N) =>
(addbeta x x) => addbeta (R x) (S x).Two features are new.
- The
betaclause assumes a rule, not a fact:pi Q\ bpath x Q :- bpath N Q, “the paths ofxare the paths ofN”. The assumed clause has a body and its own universally quantified variableQ, renamed at each use. It also mentionsN, a variable of the enclosing clause, which it shares rather than renames. addbetamarks every redex. It dispatches on the head of an application: anabshead is marked, anapphead recurses, and a bound-variable headxis handled by the rule assumed whenx’s binder was crossed. A bare variable is copied by the assumed factaddbeta x x.
Normalisation then has two stages: collect the bpaths, then synthesise with path [MN p. 189]:
?- sigma B\ addbeta (app (abs x\x) (abs x\x)) B, bpath B Path.
Path = bnd W1\ W1;
no
?- foreach (P\ path T P) (bnd (W1\ W1) :: nil).
T = abs W1\ W1;
noFor with and [MN p. 189]–[MN p. 190], the query
?- sigma K\ sigma S\ sigma B\
K = (abs x\ abs y\ x),
S = (abs x\ abs y\ abs z\ app (app x z) (app y z)),
addbeta (app K (app S K)) B, bpath B Path.yields four paths, and synthesis gives
?- foreach (path T)
((bnd W1\ bnd W2\ bnd W3\ left (left (bnd W4\ bnd W5\ W4)))::
(bnd W1\ bnd W2\ bnd W3\ left (right W3))::
(bnd W1\ bnd W2\ bnd W3\ right (left W2))::
(bnd W1\ bnd W2\ bnd W3\ right (right W3))::nil).
T = abs W1\ abs W2\ abs W3\
app (app (abs W4\ abs W5\ W4) W3) (app W2 W3);
noThe result is not -normal. The redex was created by the reduction, so it was not marked. Iterating “mark, collect, synthesise” reaches the normal form if it terminates, and in the untyped calculus it need not terminate [MN p. 190].
Pitfall (Collecting all answers is outside the logic). The two-stage method collects all solutions of bpath B Path into a list. The book stresses that this “is not formally possible in the simple proof-theoretic framework that we have described here” [MN p. 190]. Some Prolog systems provide bagof, and persistent storage can simulate it. A miniKanren has the same situation. A goal that consumes a whole sub-search, such as the aggregation goals of (aux kanren micro) (Chapter 10), is available, but it is extra-logical. It also terminates only when the sub-search is finite.
6.5.4Type inference#
The book’s type inference for the untyped calculus ([MN p. 190]–[MN p. 191]) is the best-known instance of the idiom:
kind ty type.
type arr ty -> ty -> ty.
type typeof tm -> ty -> o.
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.Read as inference rules, the typing context is the set of assumed atoms typeof c A:
The context is not a data structure of the program. It is the set of clauses that the => goals have added, and the variable rule of the type system is backchain on one of them. The interaction is [MN p. 191]:
?- 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.
noTutorial (Why typeof (abs x\x) Ty answers arr T1 T1).
- Backchaining on the
absclause bindsTy = arr A Bfor fresh logic variablesA,B, andM = x\x. - generic creates an eigenvariable
c. augment adds the clausetypeof c A. This assumed clause contains the logic variableA, which is shared with the rest of the derivation. Assumptions are not closed facts. - The goal is now
typeof ((x\x) c) B, that is,typeof c B. Neither static clause applies, sincecis neither anappnor anabs. The assumed clause applies and unifiesBwithA. - So
Ty = arr A A, printedarr T1 T1.
For abs x\ app x x the same steps give the assumption typeof c A, and typeof (app c c) B needs typeof c (arr B0 B) and typeof c B0. With the assumption these are A = arr B0 B and A = B0, hence B0 = arr B0 B. The occurs check rejects this, and the answer is no. Without an occurs check the answer would be a cyclic type.
Two more details matter. The type ty has only the constructor arr, so it has no closed inhabitants. Inferred types are therefore necessarily open, which links back to the distinction between unifiers and solutions of Chapter 4. With an added constant type i ty. one can ask closed questions [MN p. 191]:
?- typeof (abs x\x) (arr i i).
yes
?- typeof (abs x\x) (arr i Ty).
Ty = iTheorem 6.5 (Subject reduction for call-by-name, [MN p. 191]–[MN p. 192]). If (cbn P V) and (typeof P A) are derivable, then (typeof V A) is derivable.
Proof (book’s argument). By induction on the derivation of cbn P V. If it uses the first cbn clause, . Otherwise P = (app M N), and there are shorter derivations of cbn M (abs R) and cbn (R N) V. From typeof (app M N) A there is a B with typeof M (arr B A) and typeof N B. By the induction hypothesis, typeof (abs R) (arr B A). Hence pi x\ typeof x B => typeof (R x) A is derivable. Instantiating x with N and using typeof N B gives typeof (R N) A. The induction hypothesis on cbn (R N) V gives typeof V A. □
The book adds that the same holds for cbv (left to the reader), and comments: “The hard technical part in such a proof is establishing a substitution lemma … Here, that substitution lemma is obtained essentially for free by referring to well-known properties of intuitionistic logic” [MN p. 192].
Kanren angle (The usual miniKanren rendering: an explicit context). The standard miniKanren way to write a type inferencer avoids both pi and =>. It uses de Bruijn indices, so that bound names do not exist, and it passes the context as an explicit list. This runs on today’s (aux kanren micro) (indices are Peano numerals and start from z for the innermost binder; the book’s de Bruijn indices in Section 6.5.5 start from 1):
(define-relation (nth° Γ k a)
(fresh° (b Γ* k*)
(=° Γ `(,b . ,Γ*))
(cond° ((=° k 'z) (=° a b))
((=° k `(s ,k*)) (nth° Γ* k* a)))))
(define-relation (typeof° Γ m a)
(cond°
((fresh° (k) (=° m `(var ,k)) (nth° Γ k a)))
((fresh° (m1 n b) (=° m `(app ,m1 ,n)) (typeof° Γ m1 `(arr ,b ,a)) (typeof° Γ n b)))
((fresh° (body a1 b) (=° m `(lam ,body)) (=° a `(arr ,a1 ,b)) (typeof° `(,a1 . ,Γ) body b)))))
(define S '(lam (lam (lam (app (app (var (s (s z))) (var z)) (app (var (s z)) (var z)))))))
(define I '(lam (var z)))
(define ω '(lam (app (var z) (var z))))
(print (μkanren-run (q -1 #t) (typeof° '() S q)))
(print (μkanren-run (q -1 #t) (typeof° '() I q)))
(print (μkanren-run (q -1 #t) (typeof° '() ω q)))((arr (arr α (arr β γ)) (arr (arr α β) (arr α γ))))
((arr α α))
()These are the book’s three answers. The occurs check of (aux kanren micro) rejects exactly as in the tutorial above. The difference between the two programs is where the context lives. In typeof° it is data, threaded through every call and looked up with a hand-written nth°. In typeof it is part of the program, and the logic guarantees the substitution lemma behind Theorem 6.5. With an explicit context, every relation that may meet a bound variable must accept and pass on the context. With =>, a predicate written without any knowledge of binders, such as atom in Section 6.6, keeps working under them. Supporting the second style is the point of the proposal (Chapter 11).
6.5.5Translating to and from de Bruijn syntax#
In de Bruijn’s notationN. 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 a variable is a positive integer that refers to the -th enclosing abstraction, counting from 1 [MN p. 192]:
| term | de Bruijn | term | de Bruijn |
|---|---|---|---|
The same variable receives different numbers at different depths (the of the last row is 1, 2 and 3). The encoding [MN p. 193], in which deb is both a kind and a constructor, and the translation are:
kind deb type.
type ab deb -> deb.
type ap deb -> deb -> deb.
type deb int -> deb.type trans int -> tm -> deb -> o.
type depth int -> tm -> o.
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).In trans D t d, D is one more than the number of enclosing binders. Each eigenvariable is tagged, by the assumption depth D c, with the level at which it was bound. At an occurrence, the index is the current level minus the binding level. The relation works in both directions [MN p. 193]:
?- 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))Tutorial (Tracing ?- trans 1 (abs x\ abs y\ abs z\ y) P.). The book traces this query [MN p. 193]–[MN p. 194].
P := (ab P1). A new eigenvariablecis introduced anddepth 1 cis assumed. Goal:trans 2 (abs y\ abs z\ y) P1. (The meta-level has replaced the boundxbyc; sincexdoes not occur in the body, nothing visible changes.)P1 := (ab P2), eigenvariabled, assumedepth 2 d. Goal:trans 3 (abs z\ d) P2.P2 := (ab P3), eigenvariablee, assumedepth 3 e. Goal:trans 4 d P3.- Only the third clause applies:
P3 := (deb E)anddepth N d, E is (4 - N). The assumption givesN = 2, soE = 2. - Answer:
P = (ab (ab (ab (deb 2)))).
The book’s text writes the assumptions as “depth c 1”, “depth d 2”, “depth e 3”, with the arguments swapped with respect to type depth int -> tm -> o. The program assumes depth 1 c, and so on. In the reverse direction the same clauses run with P unknown. The third clause then finds the eigenvariable X whose depth gives the right index, and the (M c) of the first clause is solved as a pattern problem, as in the path synthesis of Section 6.5.3.
A variant ([MN p. 194]) with no depth predicate assumes new trans clauses for each eigenvariable. It has no static clause for variables:
trans D (app M N) (ap P Q) :- trans D M P, trans D N Q.
trans D (abs M) (ab P) :-
pi u\
(pi N\ pi H\ trans N u (deb H) :- H is (N - D))
=> (D' is D + 1, trans D' (M u) P).For the query traced above, the assumed clauses are
pi N\ pi H\ trans N c (deb H) :- H is (N - 1).
pi N\ pi H\ trans N d (deb H) :- H is (N - 2).
pi N\ pi H\ trans N e (deb H) :- H is (N - 3).and ?- trans 4 d P3. is solved by the second. Each assumed clause has captured the value of the outer D at the time it was assumed. It behaves as a closure over the context.
Kanren angle (The same translation with an explicit environment). In (aux kanren micro) the translation is written with an explicit environment of names. It is the miniKanren analogue of the depth assumptions:
; named terms: a symbol, (app m n), (λ x b); de Bruijn terms as in typeof.scm (z = innermost binder)
(define-relation (index° env x k)
(fresh° (y env*)
(=° env `(,y . ,env*))
(cond° ((=° x y) (=° k 'z))
((fresh° (k*) (≠° x y) (=° k `(s ,k*)) (index° env* x k*))))))
(define-relation (trans° env t d)
(cond°
((symbol° t) (fresh° (k) (=° d `(var ,k)) (index° env t k)))
((fresh° (m n p r) (=° t `(app ,m ,n)) (=° d `(app ,p ,r)) (trans° env m p) (trans° env n r)))
((fresh° (x b p) (=° t `(λ ,x ,b)) (symbol° x) (=° d `(lam ,p)) (trans° `(,x . ,env) b p)))))
; λx (x (λy (x (λw (w x))))), the p.193 example, forwards
(print (μkanren-run (q -1 #t) (trans° '() '(λ x (app x (λ y (app x (λ w (app w x)))))) q)))
; λx λy x backwards: the binder names come back as constrained logic variables
(print (μkanren-run (q -1 #f) (trans° '() q '(lam (lam (var (s z)))))))((lam (app (var z) (lam (app (var (s z)) (lam (app (var z) (var (s (s z))))))))))
((λ (α β) (begin (deny (equal? β α))) (assert (every (μ v (symbol? v)) (list α β))) (cons (quote λ) (cons α (cons (cons (quote λ) (cons β (cons α (quote ())))) (quote ()))))))The forward answer is the book’s D, shifted to 0-based indices. The backward answer shows what names cost. λProlog answers abs W1\ abs W2\ W1: there are no names, and the printer invents W1, W2. The named miniKanren answer is for any two symbols . The disequality is needed to rule out the shadowed reading , which would be . The names are logic variables with side conditions, and the programmer had to write the ≠° that excludes capture. In λ-tree syntax there is no such condition to write.
6.6Computations over first-order formulas#
6.6.1Vacuous quantifiers and quantifier-free formulas#
Figure 7.6 ([MN p. 195]):
type vacuous form -> form -> o.
type quantfree form -> o.
vacuous (all x\ P) P.
vacuous (some x\ P) P.
quantfree tt & quantfree ff.
quantfree F :- atom F.
quantfree (neg F) :- quantfree F.
quantfree (F && G) & quantfree (F !! G) & quantfree (F ==> G) :-
quantfree F, quantfree G.vacuous “succeeds exactly when the top-level abstracted variable does not appear in the body of the formula and, in this case, binds the second argument to the body” [MN p. 195]. There is no occurrence test in the code. Matching (all x\ P) against (all x\ p a) succeeds with P = p a. Matching it against (all x\ p x) would need P = p x, but P is quantified outside x\, so x cannot appear in its value and unification fails. The scoping constraint performs the occurrence test. quantfree relies on atom (as in Figure 7.2), which is defined for each object signature.
6.6.2Negation normal form#
A formula is in negation normal form (NNF) if it contains no implication and negation is applied only to atoms. It is in prenex normal form if no quantifier is in the scope of a connective. In classical first-order logic every formula is equivalent to one in NNF, to one in prenex form, and to one in both [MN p. 195]. The NNF transformation orients the equivalences
from left to right (Figure 7.7, [MN p. 196]):
type nnf form -> form -> o.
nnf A A & nnf (neg A) (neg A) :- atom A.
nnf (neg (neg B)) D :- nnf B D.
nnf (neg (B && C)) (D !! E) &
nnf (neg (B !! C)) (D && E) :- nnf (neg B) D, nnf (neg C) E.
nnf (B ==> C) (D !! E) :- nnf (neg B) D, nnf C E.
nnf (B !! C) (D !! E) &
nnf (B && C) (D && E) :- nnf B D, nnf C E.
nnf (neg (all B)) (some D) &
nnf (neg (some B)) (all D) :- pi x\ nnf (neg (B x)) (D x).
nnf (all B) (all D) &
nnf (some B) (some D) :- pi x\ nnf (B x) (D x).The quantifier clauses are the idiom without =>. Under pi x\ the eigenvariable x is an object term, and the only predicate that meets the atoms containing it is atom, which does not look inside terms. The output (D x) is again a pattern problem. Its solution abstracts x out of the transformed body, rebuilding the quantifier around it. For example (our trace, assuming atom holds of p atoms), ?- nnf (neg (all x\ p x)) D. skips the two atom-guarded clauses, since neither the whole formula nor all x\ p x is atomic. It reaches the neg (all B) clause with B = x\ p x and D = some D1. Under an eigenvariable c the goal is nnf (neg (p c)) (D1 c). The clause nnf (neg A) (neg A) :- atom A gives (D1 c) = neg (p c), so D1 := x\ neg (p x) and D = some x\ neg (p x), the formula .
The book claims that no two heads overlap, so nnf is a partial function, and that “a simple argument by induction shows also that the function represented is total” [MN p. 196]. Both claims need qualification.
Pitfall (Non-overlap modulo a guard, and a missing case). Syntactically, the head nnf A A overlaps every other head, since A is a variable. The clauses are disjoint only modulo the guard atom A, which fails on compound formulas. A miniKanren port must keep that guard decisive. The atom relation must fail, not enumerate or suspend, on compound or unbound input, or nnf produces spurious answers. Moreover, tt, ff and neg (B ==> C) have no clause. The last matches none of neg (neg _), neg (_ && _), neg (_ !! _), neg (all _), neg (some _). Totality holds only for the formulas without these cases. The fix when porting is one more clause, nnf (neg (B ==> C)) (D && E) :- nnf B D, nnf (neg C) E.
6.6.3Prenex normal form#
For formulas in NNF, the prenex transformation uses the equivalences [MN p. 196]
and, for and , and . The usual side condition, not free in , is not written anywhere in the program, because it is automatic: in the clauses below B and C are clause variables quantified outside the pi x\.The restriction to NNF input “is not necessary and is used only to shorten the specification”, [MN p. 196]. Figure 7.8 ([MN p. 197]):
type prenex, merge form -> form -> o.
prenex A A & prenex (neg A) (neg A) :- atom A.
prenex (B && C) D :- prenex B U, prenex C V,
merge (U && V) D.
prenex (B !! C) D :- prenex B U, prenex C V,
merge (U !! V) D.
prenex (all B) (all D) &
prenex (some B) (some D) :- pi x\ prenex (B x) (D x).
merge ((all B) && (all C)) (all D) :-
pi x\ merge ((B x) && (C x)) (D x).
merge ((all B) && C) (all D) &
merge ((some B) && C) (some D) :-
pi x\ merge ((B x) && C) (D x).
merge (B && (all C)) (all D) &
merge (B && (some C)) (some D) :-
pi x\ merge (B && (C x)) (D x).
merge ((some B) !! (some C)) (some D) :-
pi x\ merge ((B x) !! (C x)) (D x).
merge ((some B) !! C) (some D) &
merge ((all B) !! C) (all D) :-
pi x\ merge ((B x) !! C) (D x).
merge (B !! (some C)) (some D) &
merge (B !! (all C)) (all D) :-
pi x\ merge (B !! (C x)) (D x).
merge B B :- quantfree B.Look at the clause merge ((all B) && C) (all D) :- pi x\ merge ((B x) && C) (D x). The formula C moves under the new quantifier without any renaming, because C is a closed value with respect to x. Capture is impossible by construction.
Some formulas have a unique prenex form [MN p. 196]. For example
(all x\ (p x) && (all y\ q x y) && (p (f x))) !! (p a).has only
all x\ all y\ ((p x) && (q x y) && (p (f x))) !! (p a).In general, though, prenex is a relation, not a function [MN p. 196]–[MN p. 197]:
?- prenex ((all x\ q x x) && (all z\ all y\ q z y)) P.has five answers [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)Tutorial (Where the five prenex forms come from). Both conjuncts are already prenex, so the goal reduces to merge ((all x\ q x x) && (all z\ all y\ q z y)) P. The following explanation is our own hand trace against the clause order of Figure 7.8. It reproduces the book’s order under depth-first search.
- The clause shares one eigenvariable between
xandz, leavingmerge ((q c c) && (all y\ q c y)), which pullsyout: answer 1. - The
((all B) && C)clause pullsxalone, thenzandycome out of the right side one at a time: answer 2. - The
(B && (all C))clause pullszfirst, leavingmerge ((all x\ q x x) && (all y\ q c y)). That subproblem again has three ways out: the clause sharingxwithy(answer 3), pullingxtheny(answer 4), or pullingythenx(answer 5).
Every answer is a correct prenex form. No other clause applies at any step: the clauses need !!, and merge B B :- quantfree B fails while a quantifier remains. A miniKanren port with the same clauses would have to produce exactly these five answers, but its interleaving search may list them in a different order.
6.6.4Syntactic classes and a richer interpreter#
Figure 7.9 ([MN p. 198]) recognises the goal and clause formulas of fohc and fohh (Chapter 2 and Chapter 3):
type fohcG, fohcD, fohhG, fohhD form -> o.
fohcG tt.
fohcG A :- atom A.
fohcG (some B) :- pi x\ fohcG (B x).
fohcG (B && C) & fohcG (B !! C) :- fohcG B, fohcG C.
fohcD A :- atom A.
fohcD (G ==> D) :- fohcG G, fohcD D.
fohcD (D1 && D2) :- fohcD D1, fohcD D2.
fohcD (all D) :- pi x\ fohcD (D x).
fohhG tt.
fohhG A :- atom A.
fohhG (D ==> G) :- fohhD D, fohhG G.
fohhG (B && C) & fohhG (B !! C) :- fohhG B, fohhG C.
fohhG (some B) & fohhG (all B) :- pi x\ fohhG (B x).
fohhD A :- atom A.
fohhD (D1 && D2) :- fohhD D1, fohhD D2.
fohhD (G ==> D) :- fohhG G, fohhD D.
fohhD (all D) :- pi x\ fohhD (D x).Here the book remarks on the pi x\ without =>, a deviation from the idiom [MN p. 198]. The eigenvariables are object terms and atom does not inspect terms, so no assumptions are needed.The same silent deviation occurs in red1, nnf and prenex. The book also notes a free substitution theorem: “If is a first-order Horn clause and t is a term, then is a first-order Horn clause” [MN p. 198]. It is the analogue of Theorem 6.4 and is proved the same way.
Two clauses extend the interpreter of Figure 7.1 from fohc to fohh [MN p. 198]:
interp D (D1 ==> G) :- interp (D1 && D) G.
interp D (all G) :- pi x\ interp D (G x).Object , , in goals are handled by meta , , , and the object in goals by the meta pi. Object implication in goals extends the object program. Since the object program is an explicit argument, the extension is just (D1 && D), and no meta-level => is used.
6.7Specifying substitution without β#
Substitution into a term with an abstraction, by , is one clause [MN p. 199]:
type subst (tm -> tm) -> tm -> tm -> o.
subst R N (R N).As Chapter 4 showed, however, “full -conversion is a complex operation on terms” [MN p. 199]. The book therefore shows how to specify substitution with only the weak of Section 6.9. The tools are a copy predicate and a hypothetical assumption.
6.7.1Copy clauses#
Figure 7.10 ([MN p. 200]):
type copy tm -> tm -> o.
type subst (tm -> tm) -> tm -> tm -> o.
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 specifies equality: for closed terms, copy t s is derivable if and only if . A trace [MN p. 199]:
?- copy (abs x\ abs y\ app y x) M.
% M := (abs M1); eigenvariable c; assume (copy c c)
?- copy (abs y\ app y c) (M1 c).
% (M1 c) := (abs M2); eigenvariable d; assume (copy d d)
?- copy (app d c) (M2 d).
% three backchainings: app clause, then (copy d d), then (copy c c)
% finally (M2 d) unified with (app d c)
M2 = u\app u c
M1 = v\abs u\app u v
M = abs v\abs u\app u v.The equations (M1 c) = (abs M2) and (M2 d) = (app d c) are pattern problems, solved by abstracting the eigenvariable out. So copy rebuilds its input binder by binder, and the abstractions of the output are produced by unification.
Tutorial (Reading subst as a hypothetical copy). subst M T S copies the body of M except that the outermost bound variable copies to T [MN p. 200]. The clause does this in three steps:
- the binder of
Mbecomes a formula-levelpi x\; - the assumption
copy x Tsays “wherever you meetx, produceT”; copy (M x) Scopies the body.
Inside the body, the assumptions copy c c for inner binders preserve inner variables. The assumption copy x T replaces the substituted one. Since T is closed with respect to every eigenvariable created inside, no capture can happen.
Proposition 6.6 (Correctness of subst, [MN p. 200]). If (subst M T S) is derivable, then S is equal to (M T).
Proof. pi x\ copy x T => copy (M x) S is derivable. Since copy is equality in the program without assumptions, copy T T is derivable. Instantiate x with T: the assumption becomes copy T T and can be discharged by modus ponens. So copy (M T) S is derivable from the program without assumptions, hence (M T) S. □
6.7.2Copy clauses for first-order formulas, and where they come from#
For the first-order formulas over the signature
type a term.
type f term -> term.
type g term -> term -> term.
type p term -> form.
type q term -> term -> form.the copy clauses and substitution are Figure 7.11 ([MN p. 201]):
kind term, form type.
type copyterm term -> term -> o.
type copyform form -> form -> o.
type subst (term -> form) -> term -> form -> o.
copyterm a a.
copyterm (f X) (f U) :- copyterm X U.
copyterm (g X Y) (g U V) :- copyterm X U, copyterm Y V.
copyform tt tt.
copyform ff ff.
copyform (neg B) (neg D) :- copyform B D.
copyform (B && C) (D && E) &
copyform (B !! C) (D !! E) &
copyform (B ==> C) (D ==> E) :- copyform B D, copyform C E.
copyform (all B) (all D) &
copyform (some B) (some D) :- pi y\ copyterm y y =>
copyform (B y) (D y).
copyform (p X) (p U) :- copyterm X U.
copyform (q X Y) (q U V) :- copyterm X U, copyterm Y V.
subst M T N :- pi x\ copyterm x T => copyform (M x) N.These clauses are not ad hoc. They are generated from the signature by a translation that “lowers” the equality at a higher type to relations at the base types [MN p. 201]–[MN p. 202].
Definition 6.7 (Type lowering, [MN p. 201]–[MN p. 202]). For terms of type built from the base types term and form, define the formulas (for goals) and (for clauses) by
The positive case is the idiom itself: to compare two functions, apply both to a fresh and assume that is related to itself. The negative case, used for clauses, compares arguments pairwise. Polarity flips at each arrow, just as an arrow-typed argument of a constructor turns a clause into a hypothetical goal.
Example 6.8 (Lowering the quantifier all, [MN p. 201]–[MN p. 202]). For :
This is the all clause of Figure 7.11. “In fact, the clauses in that figure are exactly the formulas for each of the constants c : of the object logic” [MN p. 202].
Proposition 6.9 ([MN p. 202]). (copyterm T S) is derivable if and only if T and S are equal terms, and (copyform B C) is derivable if and only if B and C are equal formulas. Hence, if (subst M T S) is provable, then S is equal to (M T).
Two remarks from [MN p. 202]. First, these programs are signature-dependent: the object signature is reflected into clauses, whereas the one-line version is not. Second, lowering is general. Each primitive type maps to its own predicate, the relation need not be binary, and the term predicate of Section 6.4.3 is the arity-one lowering for the signature abs, app.
Substitution can also be defined by direct recursion on the abstraction, with no copy predicate (Figure 7.12, [MN p. 203]):
type subst (term -> form) -> term -> form -> o.
type substterm (term -> term) -> term -> term -> o.
subst (x\ tt) T tt.
subst (x\ ff) T ff.
subst (x\ neg (B x)) T (neg D) :- subst B T D.
subst (x\ (B x) && (C x)) T (D && E) &
subst (x\ (B x) !! (C x)) T (D !! E) &
subst (x\ (B x) ==> (C x)) T (D ==> E) :- subst B T D,
subst C T E.
subst (x\ all (B x)) T (all D) &
subst (x\ some (B x)) T (some D) :-
pi y\ substterm (x\y) T y => subst (x\ B x y) T (D y).
subst (x\ p (X x)) T (p U) :- substterm X T U.
subst (x\ q (X x) (Y x)) T (q U V) :- substterm X T U,
substterm Y T V.
substterm (x\ x) T T.
substterm (x\ a) T a.
substterm (x\ f (F x)) T (f S) :- substterm F T S.
substterm (x\ g (F x) (G x)) T (g S R) :-
substterm F T S,
substterm G T R.The book says only that these clauses are signature dependent, and in its notes that they are loosely based on Andrews’ equational presentation of -conversion [MN p. 210]. Three points are worth seeing. The patterns (x\ a) and (x\y) are vacuous abstractions: they match only bodies that do not depend on x. Under a nested quantifier the body becomes a two-place abstraction (x\ B x y). The assumption substterm (x\y) T y says that the inner bound y, seen as a constant function of x, substitutes to itself.
6.7.3Substitution runs backwards#
Every version of subst is a relation ([MN p. 202]). Given T and the result, it computes the abstraction:
?- 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))Each of the two occurrences of (f a) may or may not be abstracted, so there are answers. They are the four existential generalisations of on the term [MN p. 203]: , , , . The “abstracted” answer comes first. This is consistent with the convention of Chapter 3 that clauses added by an implication are tried before the static ones, so copyterm x (f a) is tried before copyterm (f X) (f U).
Pitfall (Copy is equality logically, not operationally). “the operational behavior of the copy predicate can be quite different from that of the equality notion it encodes” [MN p. 207]. ?- M = N. binds M to N at once. ?- copy M N. builds terms. With
kind i type.
type a i.
type f i -> i.
type copyi i -> i -> o.
copyi a a.
copyi (f X) (f Y) :- copyi X Y.?- copyi M N. enumerates a, (f a), (f (f a)), …, and “if the order of the clauses for copyi were reversed, then this query would cause the depth-first Prolog interpreter to loop without providing any solution” [MN p. 207].
Kanren angle (Clause order and interleaving). The same predicate in (aux kanren micro), in both clause orders:
(define-relation (copyi° m n)
(cond° ((=° m 'a) (=° n 'a))
((fresh° (x y) (=° m `(f ,x)) (=° n `(f ,y)) (copyi° x y)))))
(define-relation (copyi-rev° m n)
(cond° ((fresh° (x y) (=° m `(f ,x)) (=° n `(f ,y)) (copyi-rev° x y)))
((=° m 'a) (=° n 'a))))
(print (μkanren-run (q 4 #t) (fresh° (m n) (=° q `(,m ,n)) (copyi° m n))))
(print (μkanren-run (q 4 #t) (fresh° (m n) (=° q `(,m ,n)) (copyi-rev° m n))))((a a) ((f a) (f a)) ((f (f a)) (f (f a))) ((f (f (f a))) (f (f (f a)))))
((a a) ((f a) (f a)) ((f (f a)) (f (f a))) ((f (f (f a))) (f (f (f a)))))The reversed order loops in λProlog but produces the same answers here. define-relation delays the recursive call and cond° interleaves its branches, so the base case is reached. Interleaving changes the order of answers (the five prenex forms come out in the order 1 3 2 4 5, Section 13.7.2; the four generalisations happen to keep the book’s order, Section 13.6) and turns some depth-first loops into productive streams. It does not remove genuine divergence. cbv on has no answer under any strategy, and a conjunction such as “copyi° and then fail” still runs forever, because it has infinitely many candidates and no finite failure.
6.8The λ-tree approach to abstract syntax#
Concrete syntax (strings, whitespace, parentheses, infix operators, comments) is for humans. Parsing produces abstract syntax, a tree [MN p. 203]. For binders there are several choices [MN p. 204]: keep explicit names; or map object binding to the meta-language’s binding, which is called higher-order abstract syntax (HOAS)Frank Pfenning and Conal Elliott. Higher-order abstract syntax. In Proceedings of the ACM-SIGPLAN Conference on Programming Language Design and Implementation, pages 199–208, New York, 1988. ACM Press. The term covers “a range of encoding techniques”, and the book distinguishes two of them sharply.
- In functional programming, and in constructive type theories that compute by evaluation, meta-level abstraction builds rich function spaces. “Because of the richness of these spaces, it is not possible to compare function-valued expressions for equality in any simple way”. If quantified formulas are encoded with such functions, “we cannot also compare or structurally analyze formulas under such an encoding” [MN p. 204].
- Most logic programming languages have no meta-level binders in terms at all.
- The -terms of hohh use “a -calculus with a weak notion of functionality that makes it possible to analyze the structures of objects under the encoding” [MN p. 204].
The book contrasts “the two extremes in the treatment of binding—one using functions that are best thought of extensionally and the other using -expressions that are easily treated intensionally”.
Definition 6.10 (λ-tree syntax, [MN p. 204]). “We shall use the term -tree syntax to denote the approach to higher-order abstract syntax that uses typed -terms modulo equality based on -conversion, some sufficiently weak form of -conversion, and possibly -conversion.”
In this chapter is “weakened” by simple typing, which makes it terminating. The next section weakens it much further, to .
The book’s bibliographic notes ([MN p. 208]–[MN p. 210]) trace the idea back a long way. Encoding a binder as a constant applied to a -abstraction goes back at least to Church’s simple theory of types (1940), and λProlog’s pi and sigma are named after Church’s and . Computing with such terms starts with Huet and Lang (1978) and Miller and Nadathur (1987). The phrase “higher-order abstract syntax” comes from Pfenning and ElliottFrank Pfenning and Conal Elliott. Higher-order abstract syntax. In Proceedings of the ACM-SIGPLAN Conference on Programming Language Design and Implementation, pages 199–208, New York, 1988. ACM Press, and the name “-tree syntax” from Miller and Palamidessi (1999). The copy clauses of Section 6.7 go back to Miller (1991) at second order and to Felty for arbitrary orders. The fragment of the next section is Miller’sDale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991.
For a miniKanren programmer, the options can be compared directly. The first column is the “functional” reading of HOAS that we ran in Section 6.3. The second is nominal logic programming as in KanrenWilliam 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; and William E. Byrd. Relational Programming in miniKanren: Techniques, Applications, and Implementations. PhD thesis, Indiana University, 2009, based on nominal unificationChristian Urban, Andrew M. Pitts, and Murdoch J. Gabbay. Nominal unification. Theoretical Computer Science, 323(1–3):473–497, 2004. The third is -tree syntax.
| host closures | names + freshness (Kanren) | -tree syntax | |
|---|---|---|---|
| -equivalence | no (eq? only) | yes, via swapping | yes, built in |
| substitution | host application | a user relation with freshness side conditions | meta-level (or + copy) |
| analysing a body | only by applying to a name | by unification under tie | by mobility (pi, =>) |
| building an abstraction by unification | impossible | yes | yes (pattern unification) |
| “ not free in ” | not expressible | freshness constraint | scoping of variables |
The same notes ([MN p. 209]–[MN p. 210]) name nominal logic as the alternative approach: it is first-order, with name-swapping and freshness, and binding is derived from these primitives. Porting the book’s programs to Kanren would mean rewriting them, not transliterating them: there is no , mobility is replaced by fresh names, and hypothetical contexts must be threaded explicitly.
6.9The Lλ subset#
Predicate quantification is useful for manipulating -tree syntax, but “it is certainly not central to it” [MN p. 205]. Can be weakened further? The book recalls the chapter’s two principles: bound names are a fiction (), and binders are mobile, from term level to formula level to proof level. It then identifies the variables that carry mobility.
Definition 6.11 (Essentially universal and essentially existential occurrences, [MN p. 205]). In a goal formula , a bound variable occurrence is essentially universal if it is bound by a positive , a negative , or a term-level . It is essentially existential otherwise, that is, if it is bound by a negative or a positive . In a program clause the classification is dual: an occurrence is essentially universal if it is bound by a negative , a positive , or a term-level , and essentially existential if it is bound by a positive or a negative .
During proof search, essentially existential variables become logic variables, instantiated by unification with general terms. Essentially universal ones are instantiated only with eigenvariables. “It is the essentially universal bound variable occurrences that provide mobility during proof search” [MN p. 205]. In the clause typeof (abs M) (arr A B) :- pi x\ typeof x A => typeof (M x) B., the clause variables M, A, B are essentially existential, while the pi-bound x sits in the negative body of the clause and is essentially universal.
Definition 6.12 (Lλ, [MN p. 205]–[MN p. 206]). restricts hohh by requiring (1) that all quantification be over non-predicate types, and (2) that “Every subterm in B with an essentially existential variable occurrence as its head, that is, a subterm of the form () (), where x is essentially existentially quantified in B, must be such that are distinct essentially universal variable occurrences bound in the scope of x.”
Such an application is a higher-order pattern. If is ever instantiated with a term , the only redexes created have the form with the not free in . Up to and , , and the reduction just strips the binders [MN p. 206]. Only this sub-case of is needed.
Definition 6.13 (β₀, [MN p. 206]).
In the presence of -conversion this is equivalent to , provided is not free in .
Example 6.14 (Goal versus clause, [MN p. 206]). With and , the formula is an goal: both quantifiers are positive, so and are essentially universal, and nothing existential is applied. As a program clause it is not in : there both and are essentially existential, and applies an existential variable to an existential one. Membership in depends on polarity.
The book states which programs of the chapter belong to [MN p. 206]: “all the program clauses in Figures 7.7 through 7.12 belong to ”, and exactly one clause of Figure 7.4 does not, namely redex (app (abs R) N) (R N)., where R is applied to the existential N. By the same definition, more programs of the chapter are outside , although the book singles out only redex. The table summarises the situation; the classification of the rows other than redex and Figures 7.7–7.12 is ours.
in (applications are (M x) with x pi-bound) | outside |
|---|---|
term, bnorm, red1, reduce, path, bpath, addbeta, typeof, trans, vacuous, nnf, prenex, fohcG …, copy, every subst of Figures 7.10–7.12 | redex ((R N)); list_instan ((B T)); interp/backchain ((G X), (D1 X)); cbn/cbv ((R N), (R U)); the one-line subst R N (R N); repeat and foreach (they quantify over predicates) |
In every non- clause of the chapter, the abstraction is applied to an argument of base type (term or tm). Instantiating R : tm -> tm with N : tm therefore never creates a new redex. It is plain “instantiate the bound variable”, provided R is known when the application is formed.
A non- program can often be rewritten into [MN p. 206]. With the copy clauses of Figure 7.10, the offending clause becomes
redex (app (abs R) N) S :- subst R N S.“If we do this, we obtain a specification that is entirely within .” The translation has two costs [MN p. 207]. The signature must be reflected into copy clauses with . And copy behaves operationally unlike equality (the copyi pitfall above).
Why care? Compare the two rules [MN p. 207]:
A step removes one abstraction–application pair, and the result is strictly smaller and has no new redexes. A step may shrink the term (if does not occur in ), may blow it up (if occurs many times and is large), and may create new redexes (if occurs applied in ). The difference carries over to unification, the subject of Chapter 7 [MN p. 208]:
- unification modulo is undecidable and may have several most general unifiers;
- unification is “much more like first-order unification”: it is decidable, and when a unifier exists there is a single most general oneDale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991; and 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;
- “an overwhelming majority of clauses in ‘typical’ Prolog programs are within the fragment”.
Pitfall (β₀ is not the same as Lλ). All unification problems are problems modulo , , , but not conversely [MN p. 208]. Finding with needs only to justify the solutions and . It is not an problem, because is applied to the same universal variable twice, and it has two incomparable most general unifiers. A unifier for a miniKanren must decide what to do with such non-pattern equations: reject them, or postpone them until they become patterns.
Finally, raising (Chapter 4), the transformation of into that implementations use to simplify quantifier alternation, “preserves the class of formulas” [MN p. 208]: is a pattern.
Kanren angle (A requirements checklist for (aux kanren micro)). Gathering the boxes of this chapter, a miniKanren that runs the book’s programs needs the following. Each item is justified by a program above. The design that provides them is in Chapter 11 and Chapter 12.
| requirement | needed by |
|---|---|
| abstractions as data, equal up to (and ) | every program; (all p); answers like abs W1\ W1 |
| application of a known abstraction to a term | list_instan, interp, cbn, cbv, redex |
| eigenvariables with the scoping constraint | every pi; correctness of vacuous, -redex, prenex |
| scoped assumed facts, possibly with logic variables | term, bnorm, typeof, trans, copy |
| scoped assumed rules with bodies and own variables | bpath, addbeta, the trans variant |
pattern unification for output abstractions (D x) | red1, path synthesis, nnf, prenex, copy, subst backwards |
| occurs check, also through abstractions | typeof (abs x\ app x x) |
| printing binders with invented names | every answer containing an abstraction |
Some of this exists in the miniKanren literature. The miniKanren with symbolic constraints has an “eigen” operator with a scope checkJason Hemann, William E. Byrd, and Daniel P. Friedman. The eigen operator of miniKanren-with-symbolic-constraints. Software, 2013. URL https://github.com/webyrd/miniKanren-with-symbolic-constraints. Kanren adds tie, application, all and assumed relations to KanrenWeixi Ma, Kuang-Chen Lu, and Daniel P. Friedman. Higher-order logic programming with Kanren. In miniKanren and Relational Programming Workshop, 2020, and its successor discusses the -equivalence surprises of combining higher-order unification with miniKanrenWeixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for Kanren. In miniKanren and Relational Programming Workshop, 2021 (see Chapter 9). Today’s (aux kanren micro) has none of these features. It does have first-order unification with occurs check and records, which can represent de Bruijn terms, and an interleaving search, which already changes some of the book’s loops into productive streams.
6.10Summary#
- An object-level binder is a constant applied to a meta-level abstraction:
all (x\ B),abs (x\ t). Equality of the meta-language includes (bound names are a fiction), and (so(all p)is a quantifier too). - Object-level substitution is meta-level :
(B T). Interpreters (interp) and evaluators (cbn,cbv) need no renaming code at all. - An abstraction cannot be decomposed into a name and a body. Recursion under a binder uses mobility: term-level , then formula-level
pi, then proof-level eigenvariable, with=>assuming the clauses that describe the new eigenvariable (Definition 6.2). - The eigenvariable’s scoping constraint is part of the meaning of
pi. It silently implements every “ not free in ” side condition (vacuous, , prenex). A fresh constant without it is unsound. - Assumptions are scoped, may contain logic variables (
typeof x A), and may be rules with bodies and their own quantifiers (bpath,addbeta,trans). Some predicates have no static clause for variables at all. - Metatheory comes cheap: the substitution lemma for
bnorm, subject reduction fortypeof, and the correctness ofsubstall follow from instantiating apiand discharging a=>. - Programs that build abstractions (
red1,nnf,prenex,copy, path synthesis,transbackwards) rely on unification solving(D x) = tby abstracting the eigenvariable out: pattern unification. - Copy clauses, generated from the signature by type lowering , specify substitution using only . They are logically equality but operationally term generators.
- The relations are not functions:
prenexhas five answers on the book’s example,substrun backwards enumerates the four existential generalisations. - -tree syntax is HOAS with -terms modulo , a weak and possibly , which can be analysed intensionally, unlike host-language closures. restricts existential variables to patterns, so that only is needed and unification is decidable and unitary (Chapter 7).
- On today’s
(aux kanren micro), abstractions as closures work only as inputs, and explicit contexts with de Bruijn indices replacepi/=>at the cost of threading the context and writing capture conditions by hand. The requirements checklist above is the starting point of the proposal (Chapter 11).