Chapter 3
Hereditary Harrop formulas: implication and universal goals
In Chapter 2 we met the logic of first-order Horn clauses, fohc, the logic behind Prolog. Its search semantics was given by a handful of reduction rules, one per logical symbol, and two of them never fired: AUGMENT, for goals of the form , and GENERIC, for goals of the form . The reason is purely syntactic: in fohc neither goals nor clause bodies may contain implications or universal quantifiers, so the signature and the program stay fixed for the whole computation. Miller and Nadathur Dale Miller and Gopalan Nadathur. Programming with Higher-Order Logic. Cambridge University Press, Cambridge, 2012 observe that such a language “does not make very strong use of the structure afforded by logic” [MN p. 75].
This chapter lifts the restriction. The logic of first-order hereditary Harrop formulas, fohh, admits and in goals and hence, at any depth, in clause bodies. The two new rules have a simple operational reading:
- to prove , prove with temporarily added to the program;
- to prove , prove with a new constant temporarily added to the signature.
So “programs and signatures can grow dynamically in the course of searching for a proof”
[MN p. 75], and they grow and shrink with a stack discipline. Three things follow, and they organise
the chapter: hypothetical reasoning becomes a programming technique (Section 3.3); the
interplay of with logic variables imposes a scope condition on unification
(Section 3.4 and Section 3.5); and the declarative reading of the language is no longer
classical logic but intuitionistic, indeed minimal, logic (Section 3.6). The full power of
, binding names inside data, “must await the introduction of higher-order features”
[MN p. 75]; it returns in Chapter 6. Here shows its scoping face. The last section
(Section 3.8) collects what all this demands of a miniKanren, and of (aux kanren micro) in
particular.
3.1Syntax: goals, clauses and polarity#
Definition 3.1 (fohh goals and clauses [MN p. 75]). Let range over first-order atomic formulas. Goals and program clauses are given by the mutually recursive rules
A -formula is called a first-order hereditary Harrop formula; fohh names both this class of formulas and the logic programming framework built on it [MN p. 76].
Compare with fohc (Chapter 2), where and has the same grammar. Two remarks make the definition easy to remember.
- The grammar did not change. The restrictions on clauses “are, in fact, identical to the ones present in the fohc setting” [MN p. 76]: no top-level or , and the premise of a top-level implication is a goal. The class of clauses is larger only because goals, which appear as clause bodies, are now richer.
- The two grammars swap roles across . The premise of an implication goal is a clause (it will be assumed); the premise of an implication clause is a goal (it will be proved). Goals still are not freely generated: is not a goal, because is not a clause.
Concrete syntax. In λProlog, in a goal is written D => G; a clause
is written A :- G; , and & both denote (the chapter uses &
inside assumed conjunctions of clauses), ; is , pi x\ B is and
sigma x\ B is . Free capitalised variables of a clause are implicitly universally
quantified at the front of the clause; free variables of a query are implicitly existential. The scope
of x\ extends as far to the right as possible.
Pitfall (the precedence of =>). The connectives are listed in the order =>, &, ,, ;, :-; their precedences
follow that order, so => binds tightest; => and & are right associative
[MN p. 35]. Hence D => G1, G2 parses as (D => G1), G2, and the hypothesis does not
scope over G2. This is why the parentheses in the queries of this chapter, such as
fact (finished X Y) => (fact (graduates X), fact (cs_major X)) and (p 2 & p 3) => p X, are
essential, while p 2 => p 3 => p X means .
3.1.1Positive and negative occurrences#
With implications inside formulas it becomes meaningful to ask on which side of an arrow a subformula sits.
Definition 3.2 (polarity [MN p. 76]). is a positive subformula occurrence of . If is a positive (negative) occurrence in , then it is a positive (negative) occurrence in , , , , , and , and it is a negative (positive) occurrence in . Equivalently: is positive in if it lies to the left of an even number of implications, negative if odd.
Proposition 3.3 ([MN p. 76]). Positive subformulas of goals are goals and negative subformulas of goals are clauses; dually, positive subformulas of clauses are clauses and negative ones are goals. A fohc goal has no negative subformulas. A hereditary Harrop formula is exactly a formula in which no positive subformula occurrence is a disjunction or an existential quantification.
The last characterisation explains the name. The negative occurrences are the places where a formula is used as a hypothesis. Requiring that no positive part of a clause be a disjunction or an existential says that whatever we assume, now or later in the search, never forces us to reason by cases or to invent an anonymous witness. The adjective hereditary refers to this “at every positive position” requirement (Section 3.6).
Example 3.4. In the clause (Section 3.4) the body is negative, hence a goal, and the subformulas and are positive again (each lies to the left of exactly two implications): they are clauses, and indeed they will be assumed.
3.1.2Clausal order#
Definition 3.5 (clausal order [MN p. 76–77]).
In fohc goals have clausal order 0 and clauses order 0 or 1; in fohh both are unbounded [MN p. 77].
Reading as the type arrow , the definition is the same as that of the order of a type
(Chapter 1); the book stresses that this is “not accidental” and will exploit it in its
Section 7.6 [MN p. 77]. Worked values: q :- (q => q), that is ,
has order 2; the clause above has order 2; the clause of Listing 3.4 below has
order 3.
3.2Operational semantics: AUGMENT and GENERIC#
Nothing new has to be invented. The framework of Chapter 2 already contains the rules for implications and universal quantifiers at the top of goals: “These are to be treated by the AUGMENT and GENERIC reduction rules” [MN p. 77]. Atomic goals are still solved by backchaining, which is possible because -formulas have the same shape as in fohc, modulo the richer goals. For reference, Rules 3.6 collects the rules: the right-introduction rules for goals and the backchaining rules for a clause “in focus”, written .
Rules 3.6 (O-proofs).
The rules of O-proofs: right rules (book Figure 2.2) and backchaining rules (book Figure 2.3). In fohc the two rules of the second row are never used. With logic variables, R and L introduce a new variable instead of guessing , and initial unifies.
Definition 3.7 (O-proof [MN p. 77]). An O-proof in fohh is a derivation built with the typing rules for first-order terms and the rules of Rules 3.6 (book Figures 1.2, 2.2 and 2.3).
In the logic-variable versions of the rules (Chapter 2, [MN p. 61]) the typing premise of R and L is delayed and initial unifies. Section 3.4 shows that once generic is present the delayed choice must still respect the signature in which the variable was created.
Tutorial (programs grow and shrink like a stack). Take the goal and the program [MN p. 77]. and splits it in two. The left conjunct is an implication: augment moves into the program, and and splits again; each conjunct is an implication again. In the end we must prove
is never visible to , and is never visible to . Read as an interpreter state, the program is pushed when we enter the antecedent’s scope and popped when the subproof is done: “implicational goals allow logic programs to grow and shrink following a stack-based discipline” [MN p. 78]. Notice that in the proof tree nothing is popped: each branch simply carries its own program. Popping is what a sequential interpreter does when it walks the tree.
Programs are lists. Under a depth-first strategy the order of clauses matters, so programs
are “best thought of not as sets but rather as lists of clauses” [MN p. 78]. λProlog adds assumed
clauses at the front: “the most recently added clauses are the first to be used in backchaining”
[MN p. 78]. Inside an assumed conjunction D1 & D2 the textual order is kept. With a program
containing only p 1:
?- p 2 => p 3 => p X.
X = 3;
X = 2;
X = 1
?- (p 2 & p 3) => p X.
X = 2;
X = 3;
X = 1Kanren angle (answer order is a depth-first artefact). Running the same two queries through the small interpreter of Section 3.8.3, which uses the
interleaving or° of (aux kanren micro) for the choice among clauses, gives the same sets of answers
in a different order:
p 2 => p 3 => p X : (3 2 1)
(p 2 & p 3) => p X : (2 1 3)In the second query the L choice inside p 2 & p 3 is interleaved with the decide choice
over the rest of the program. Tests of this interpreter should not compare ordered answer lists with
λProlog’s; the order of the program still matters, since front clauses are tried first. The proposed
module does reproduce the book’s order here, (3 2 1) and (2 3 1), because a dynamic relation
is one flat disjunction of its hypotheses, most recent first (Definition 11.5,
Section 13.4.1). Compare ordered lists only where every clause answers without further search.
3.3Implicational goals and hypothetical reasoning#
3.3.1Entailment between Horn clauses#
Let be propositions (type ) and consider the program [MN p. 78]
s :- r, q.
t :- q, u.
q :- r.It has no atomic consequences at all, yet clauses follow from it: t :- r, u. and s :- r.
[MN p. 79]. In fohh we can ask this directly. The query ?- s :- r. “is better written as”
?- r => s. [MN p. 79]: augment adds r and ordinary Horn reasoning proves s.
Tutorial (the O-proof of r => s). Write for the three clauses and ; the signature is omitted. The search, read
goal-first (each line is reduced to the next ones):
- : by R (augment) it suffices to show .
- : decide on the clause ; by L we need the head to match, (initial), and the body, .
- : by R, both and .
- : decide on the assumed clause , then initial.
- : decide on ; initial for the head, and the body as in step 4.
The only new step is the first one; the
rest is the Horn backchaining of Chapter 2, run in a larger program. In the same way
(r => u) => (r => t) is provable [MN p. 79]: it assumes the clauses r => u and r, and then
t follows through q and u. (This is a different entailment from t :- r, u, which as a
query is r => u => t.)
The last example of the section is a warning [MN p. 79]:
?- (q :- (q => q)) => (q :- (q => q)).It has the form , so it has an O-proof from the empty program, but a depth-first interpreter
“will not terminate on the given query”. To see why, unfold it. augment assumes
; the goal is again , so augment assumes , i.e. the
clause q :- q, at the front. Now the program is [q :- q, q :- (q => q)] and the goal
is q. Depth-first search picks q :- q and loops for ever. The O-proof picks the other clause:
its body q => q assumes q and proves q at once.
Pitfall (provable, yet the interpreter loops). Depth-first backchaining is incomplete, and AUGMENT makes this easier to hit, because assumed clauses
go to the front. The book makes the same point with conjunction: loop, fail loops while
fail, loop fails, with loop :- loop. [MN p. 88]. In the interleaving search of miniKanren the
clause choice is fair, and the interpreter of Section 3.8.3 does find the proof of , in fact
infinitely many of them (run 3 returns (α α α)); conjunction, however, remains as
order-sensitive as in λProlog.
3.3.2Hypothetical reasoning on a database#
Implications in goals express hypothetical questions: “what if this were true?”. Listing 3.1 is the book’s course database: facts about which students finished which courses, rules for being a CS major and for graduating, and a constraint saying it is inconsistent to have finished both 210 and 250.
kind entry type.
type fact entry -> o.
type false o.
kind person type.
type kim, dana person.
type finished person -> int -> entry.
type cs_major, graduates person -> entry.
fact (finished kim 102) & fact (finished dana 101).
fact (finished kim 210) & fact (finished dana 250).
fact (cs_major X) :-
(fact (finished X 101); fact (finished X 102)),
fact (finished X 250), fact (finished X 301).
fact (graduates X) :-
(fact (finished X 101); fact (finished X 102)),
(fact (finished X 210); fact (finished X 250)),
fact (finished X 301).
false :- fact (finished X 210), fact (finished X 250).Note the clauses on the two fact lines, and that false is an ordinary proposition: it
has a clause, so it can be proved, but it has no logical meaning (Section 3.6.2). The queries
and answers of the book [MN p. 80–81]:
?- fact (finished dana X) => false.
X = 210;
no
?- fact (finished X Y) => (fact (graduates X), fact (cs_major X)).
X = dana
Y = 301;
no
?- fact (finished kim X) => fact (finished kim Y) =>
(fact (graduates kim), fact (cs_major kim)).
X = 250
Y = 301
?- fact (finished kim 250) => fact (finished kim 301) => false.
solvedThe first asks whether some course would make the database inconsistent if Dana finished it (210, and only 210). The second asks: “If person X took just one more course Y, will he or she graduate with a CS degree?” (only Dana, with 301); this “indirectly implies that there is no single course” Kim can take [MN p. 80], hence the third query, with two hypotheses: Kim needs 250 and 301. The fourth shows that this plan is inconsistent, so “there is no consistent way for Kim to graduate as a computer science major” [MN p. 81].
Tutorial (a logic variable inside an assumed clause). Follow the first query. Its free variable is existential, so R makes it a logic variable
before augment runs. The assumed clause is therefore fact (finished dana X) with
not universally quantified: it is one specific, still unknown fact. Now the goal false
backchains on the constraint clause, whose own variable (call it ) is renamed by L:
fact (finished Z 210): decide on the assumed clause unifies , ;fact (finished dana 250): true in the database.
So proving false binds the variable inside the hypothesis, and the binding is reported to
the query. In the second query the single hypothesis fact (finished X Y) likewise has one binding
for and , shared by every use of the clause. Section 3.5 turns this into a
programming technique.
Kanren angle (the four queries on (aux kanren micro)). The interpreter of Section 3.8.3 reproduces the four answers: (210) for Dana’s
inconsistency, ((dana 301)) for the one-course question, a success for the inconsistency of Kim’s
plan, and, asked for all answers, (250 301) and the symmetric (301 250), each
twice, for the two-course question: the book shows only the first answer, and the others correspond to
different proofs: the symmetric pair because either hypothesis can supply either course, the duplicates
because the “210 or 250” disjunct in the body of graduates can be proved both from the database
(210) and from the hypothesis that supplies 250. As for what this demands of
the engine: the program must be part of what a goal sees, it must be extended for the duration of a
subgoal only, and an assumed clause must be able to mention logic variables of the surrounding
computation without renaming them (Section 3.8.1).
3.3.3An interactive “what if” database#
Listing 3.2 turns hypothetical reasoning into a small interactive program; it uses the
non-logical print, read and cut ! [MN p. 81].
type db o.
kind command type.
type do command -> o.
type enter, query, whatif, check entry -> command.
type quit, consis command.
db :- print "Command?", read Command, do Command.
do quit.
do (enter Fact) :- fact Fact => db.
do (query Q) :- (fact Q, !, print "yes\n"; print "no\n"), db.
do (whatif Conjecture) :- (fact Conjecture => db),
print "Resuming\n", db.
do consis :- false, print "no\n", !; print "yes\n".
do (check Entry) :- (fact Entry, print "yes\n", !;
fact Entry => false, print "no\n", !;
print "no, but it could be true\n"), db.The book’s session [MN p. 81–82] is reproduced in Listing 3.3.
?- db.
Command? query (graduates dana).
no
Command? whatif (finished dana 301).
Command? query (graduates dana).
yes
Command? query (cs_major dana).
yes
Command? quit.
Resuming.Command? query (finished kim 101).
no
Command? query (graduates kim).
no
Command? whatif (finished kim 301).
Command? query (graduates kim).
yes
Command? query (cs_major kim).
no
Command? whatif (finished kim 250).
Command? query (cs_major kim).
yes
Command? consis.
no
Command?The interesting point is where the “database state” lives: in the stack of nested
augments. enter F runs the rest of the session inside fact F => db, so
persists; whatif F runs a sub-session inside fact F => db, and when quit ends that
sub-session the clause continues with print "Resuming\n", db in the outer program, where is gone.
That is why Dana stops graduating after Resuming. The Kim hypotheses nest: the innermost session sees
both 301 and 250, so cs_major kim holds and consis reports an inconsistency (210 and 250 together
prove false). No assert/retract is involved: undoing a hypothesis is just leaving a scope.
Remark 3.8. The transcript is slightly idealised: do consis is the only command besides quit whose clause
does not end with db, so after consis the current sub-session ends and the enclosing whatif
should print Resuming before the next prompt.
3.4Universal goals and scoped constants#
generic transforms the goal in the context into in the context for a token not in ; which token is chosen does not matter [MN p. 82].
Definition 3.9 (eigenvariable, scoped constant [MN p. 82]). The new token introduced by generic is an eigenvariable. Since it is never instantiated during computation, the book also calls it a scoped constant.
The parallel with implication is exact: implication augments the program for part of the computation, augments the signature [MN p. 82].
Tutorial (sterile jars [MN p. 83]). A jar is sterile if every bug in it is dead; a bug in a heated jar is dead; jar j has been heated:
kind jar, bug type.
type j jar.
type sterile, heated jar -> o.
type dead, bug bug -> o.
type in bug -> jar -> o.
sterile J :- pi x\ bug x => in x J => dead x.
dead B :- heated J, in B J, bug B.
heated j.The signature has no constants of type : the program assumes nothing about the existence
of bugs. Now solve sterile j.
- Backchain on the first clause: the goal becomes
pi x\ bug x => in x j => dead x. - generic: pick a fresh
g; the goal becomesbug g => in g j => dead g, andg : bugjoins the signature. - augment twice:
bug gandin g jjoin the program; the goal isdead g. - Backchain on the second clause:
heated Jsucceeds with , thenin g jandbug gsucceed by the two assumptions.
“After this goal succeeds, the constant g is removed from the signature, and the two clauses
bug g and in g j are similarly removed from the program” [MN p. 83]. The proof talks about
an arbitrary bug, never about a particular one.
3.4.1An intensional universal quantifier#
The jar proof illustrates that fohh’s is intensional: “Proofs of universal goals do not make any assumptions about the structure of the domain of quantification, and in fact, the same generic proof must work for every element of the domain” [MN p. 83]. The alternative, extensional, reading would prove every instance, possibly in different ways, typically by induction; but “the fohh logic does not encompass rules for induction” [MN p. 83–84]. With
kind nat type.
type zero nat.
type succ nat -> nat.
type plus nat -> nat -> nat -> o.
plus zero L L.
plus (succ N) M (succ P) :- plus N M P.the query ?- pi N\ plus N zero N. is not provable, although every closed instance is: the
generic goal plus c zero c matches no clause head, since c is neither zero nor a
succ. The base and step cases of the obvious induction are provable,
?- plus zero zero zero,
pi N\ plus N zero N =>
plus (succ N) zero (succ N).but no rule of fohh combines them into pi N\ plus N zero N [MN p. 84].
Pitfall ( is not “for every value”). Do not expect pi to enumerate a domain, and do not confuse it with the existential query
plus N zero N, which enumerates zero, succ zero, … for ever. An empty type is harmless
for : the jar proof works although no bug exists. The bibliographic notes call the two readings
generic and universal judgments; they coincide under the open-world assumption of fohh,
and under a closed world Miller and Tiu’s quantifier captures the generic one [MN p. 94],
Dale Miller and Alwen Tiu. A proof theory for generic judgments. ACM Transactions on Computational Logic, 6(4):749–783, 2005.
The dual remark concerns . The typing premise of R is,
with logic variables, delayed: “all the remaining, delayed typing judgments must be provable for
instances of the logic variables” [MN p. 61]. A query that ends with an unbound logic variable of an empty
type (say a sigma over bug in the jar signature, with a body that does not constrain it) has no
O-proof, because no closed term of type bug exists, although an interpreter reports success. Inside
a generic scope over bug the type is inhabited by the scoped constant, which is why the jar
proof is fine. An untyped miniKanren silently assumes every unbound answer variable has an instance.
3.4.2Substitution must avoid capture#
In fohc a clause is with all quantifiers outermost, so instantiating them is plain replacement [MN p. 84]. In fohh quantifiers occur inside clauses, and plain replacement can capture.
Definition 3.10 (free for [MN p. 85]). Let be a free variable of and a term of the same type. is free for in if no free occurrence of in is in the scope of a quantifier that binds a variable free in .
If is free for in , replacement realises soundly; otherwise one first renames bound variables of , and “we shall assume that substitution is always performed in this logically sound fashion” [MN p. 85].
Example 3.11 ([MN p. 85]). Substituting (f y) for X in p X :- pi y\ q X y by naive replacement gives
p (f y) :- pi y\ q (f y) y, where the constant y has been captured: there are now two bound
occurrences where there was one. The correct result is p (f y) :- pi z\ q (f y) z.
3.4.3Quantifier order matters#
“Possibly the simplest example illustrating the relevance of quantifier scopes in computation” is [MN p. 85]
?- sigma x\ pi y\ x = y.It is not provable: pi y\ t = y has no proof for any term in which does not occur. It is
true in a model with a single element, but not every model is like that [MN p. 85–86]. Proof
search agrees: generic creates a new constant and must prove , which fails. Choosing
itself for does not help, because capture-avoiding substitution turns the goal into
pi z\ y = z [MN p. 86]. Swapping the quantifiers changes everything: pi y\ sigma x\ x = y
is provable, with witness the scoped constant itself.
Tutorial (the scope condition, derived from the rules). Where does the asymmetry come from in the rules of Rules 3.6? From the side condition of R: the witness must satisfy , where is the signature at the moment the existential is reduced.
- In , R is applied first, with not containing the constant that generic will create later. No -term equals .
- In , generic runs first, the signature becomes , and is a legal witness.
With logic variables the witness is chosen later, by unification. The side condition does not go away; it becomes a constraint on unification: a logic variable created when the signature was may only be bound to terms built from (and from other variables bound under the same restriction). This is the scope condition behind the remark that unification “must be modified … so as to ensure that quantifier scopes are respected” when fohh computations alternate essential existential and universal quantifiers [MN p. 94].
The condition has a subtle consequence when a variable is bound to a term that contains other, younger variables. Nadathur, Jayaraman and Kwon’s implementation of goals tags every constant and logic variable with a universe index: generic increments the index and tags the new constant with it, a logic variable is tagged with the index current at its creation, and (tag ) may be bound to only if (1) the occurs check passes, (2) contains no constant with tag , and (3) before binding, the tags of the variables of that are are lowered to 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. Rule (3) is the subtle one. Their example: with the program clause , consider the goal .
- : a logic variable with tag 1. : a constant with tag 2. augment: assume ; the goal is .
- Backchain on the clause: L creates with the current tag 2; unify , binding , which is allowed: belongs to the original signature (tag 1).
- The body must now be proved from the assumption , i.e. . If still had tag 2 this would succeed, and would be , a term mentioning a constant that did not exist when was created. Rule (3) lowered to tag 1 when was bound, so fails, as it should.
The goal is not provable, since must be fixed before , and only the lowering detects it.
Kanren angle (what demands of the unifier). A miniKanren that wants fohh’s needs two things that (aux kanren micro) does not have
Weixi Ma, Kuang-Chen Lu, and Daniel P. Friedman. Higher-order logic programming with Kanren. In miniKanren and Relational Programming Workshop, 2020; Jason 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; and 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:
- A new kind of term, the scoped (eigen) constant: unique, never bound, equal only to
itself. It must be distinct from every existing term, including records with equal slots,
since
(aux kanren micro)unifies records slot-wise. - A scope check: no variable that existed before the constant was created may ever reach it through the substitution, including through younger variables (rule (3) above). Known designs: an explicit quantifier prefix consulted by unification, as in λKanren 2020 Weixi Ma, Kuang-Chen Lu, and Daniel P. Friedman. Higher-order logic programming with Kanren. In miniKanren and Relational Programming Workshop, 2020; numeric universe levels with lowering, as in Teyjus and ELPI 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; and Cvetan Dunchev, Ferruccio Guidi, Claudio Sacerdoti Coen, and Enrico Tassi. ELPI: fast, embeddable, Prolog interpreter. In Logic for Programming, Artificial Intelligence, and Reasoning (LPAR-20), volume 9450 of LNCS, pages 460–468. Springer, 2015; an absento-like “eigen” constraint between the constants and the list of variables in scope, as in miniKanren with symbolic constraints Jason 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; or a check of the answers when the scope is left, as the interpreter of Section 3.8.3 does.
Which of these fits (aux kanren micro), and how variable creation numbers relate to levels, is a design question
taken up in Chapter 11. Note also that αKanren’s names do not play this role: a nom “only
unifies with itself or with an unassociated variable” William E. Byrd. Relational Programming in miniKanren: Techniques, Applications, and Implementations. PhD thesis, Indiana University, 2009, so nothing prevents an older
variable from being bound to it. Section 3.8.2 runs three tempting shortcuts and shows each
one proving .
3.5Quantification links goals and clauses#
In Prolog the program is fixed, so logic variables only ever occur in goals. In λProlog an implication goal can assume a clause that mentions a logic variable created by an enclosing or by the head of the clause being used; logic variables then “may appear eventually in program clauses” [MN p. 86]. We met this in the Dana query. Here it becomes a technique.
Listing 3.4 defines reverse through an accumulator predicate rev whose clauses exist only
while a reverse goal is being solved.
type reverse list A -> list A -> o.
type rev list A -> list A -> list A -> o.
reverse L K :-
((pi L\ rev nil L L) &
(pi X\ pi L\ pi K\ pi M\ rev (X::L) K M :- rev L K (X::M)))
=> rev L K nil.type reverse, rev list A -> list A -> o.
reverse L K :-
(rev nil K &
(pi X\ pi L\ pi K\ rev (X::L) K :- rev L (X::K)))
=> rev L nil.With the first version, ?- reverse (1::2::nil) P. reduces to ?- rev (1::2::nil) P nil. in the
program augmented with
rev nil L L.
rev (X::L) K M :- rev L K (X::M).and eventually binds P to (2::1::nil) [MN p. 86–87]. The explicit pis “cannot be
dropped: Doing so will change the scope of the quantification and hence also the meaning” [MN p. 86]:
without pi L\ the clause rev nil L L would mention the head’s L, the list being
reversed, instead of being a general fact.
The second version starts from a different observation [MN p. 87]. From the program
rv nil (c::b::a::nil).
rv (X::N) M :- rv N (X::M).one can prove rv (a::b::c::nil) nil; replacing (c::b::a::nil) by any list L, the goal
rv K nil is provable if and only if L and K are reverses of each other. This cannot be
written in fohc, “because to do so we require the ability to ‘tie’ the binding for a variable in the
specification of the reverse predicate to one that appears in a goal at a particular point in the
computation” [MN p. 87]. In fohh it is the second program of Listing 3.4.
Tutorial (running the two-place reverse). Solve ?- reverse (1::2::nil) P. with the second program.
Backchain on the
reverseclause: L renames itsL,Kto fresh logic variables; unification binds the first to1::2::niland identifies the second withP.augment adds, at the front,
rev nil K. rev (X::L) K :- rev L (X::K).Here the
Kof the first clause is the logic variable shared withP: “not like the usual implicitly universally quantified variables” [MN p. 88]. TheKof the second clause is bound by its ownpi K\and is renamed at every use.The goal
rev (1::2::nil) nilbecomesrev (2::nil) (1::nil), thenrev nil (2::1::nil).This last goal matches
rev nil Kby binding the sharedK, “and henceP”, to2::1::nil[MN p. 88].
The base case of the recursion was written before the recursion ran, with a hole for the answer; the computation fills the hole from inside the scope.
Pitfall (implicit quantification lies inside assumed clauses). The display convention “actually becomes somewhat misleading when such variables can appear in
clauses” [MN p. 88]: in rev nil K the capital K looks universally quantified but is a single
shared unknown. Two practical consequences. First, one may not copy an assumed clause wholesale at each
use (the copy_term reflex of Prolog meta-interpreters): only the variables bound by the clause’s own
quantifiers are renamed, the others stay shared 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. Second, rev is an
ordinary global predicate name, so the local clauses mix with any other assumption about rev. Under a
stray assumption rev nil Z, the interpreter of Section 3.8.3 returns two answers to the reverse
query, the second one produced by the stray clause:
under rev () Z : (((2 1) α) (α (2 1)))Making rev truly local requires quantifying over the predicate itself, a higher-order feature
(Chapter 5).
Kanren angle (shared variables come for free with closures). In a miniKanren embedded in Scheme, an assumed clause can be represented
by a host closure that, when called with the arguments of a goal, runs fresh° for , unifies
the arguments with and then runs . Every use renames , as L requires, while
every logic variable that is merely free in the clause, like K above or Dana’s X, is
captured by the closure and therefore shared, exactly the semantics of this section, with no copying
machinery. What closures do not provide is the scope information of Section 3.4.3 for the renamed
: in the universe-index scheme each such variable is tagged with the index current at the time of use
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, and that index must come from the search state. See Section 12.4.
3.6The logic behind fohh#
Logic is useful for programs because logically equivalent formulas, , ought to be
interchangeable. With side effects or incomplete search they are not: print "yes", print "no"
differs from its swap, and loop, fail from fail, loop. “Nevertheless … if we rule out
programs with side effects and consider complete proof-search strategies, then logical equivalences can be
used meaningfully in reasoning about logic programs” [MN p. 88]. The question is then: which logic?
3.6.1Not classical logic#
For fohc the rules are complete for both classical and intuitionistic logic (Chapter 2). Not so for fohh.
Theorem 3.12 ([MN p. 89]). The operational semantics for sequents in fohh is sound and complete for intuitionistic logic, but classical logic is not sound for this operational semantics.
Take from the empty program. By R it is provable iff is provable from (no) or is provable from (no). So there is no O-proof, in agreement with intuitionistic logic. Classically, however [MN p. 89],
so , which is clearly provable. Classical logic lets the scope of an implication be “extruded” over a disjunction,The term comes from the π-calculus, [MN p. 95]. and so “the interpretation we desire for implication as a scoping mechanism is not valid in classical logic” [MN p. 89]. Three more classically valid goals without O-proofs [MN p. 89]:
The middle one is Peirce’s formula. “It is clear from all these examples that classical logic cannot provide the declarative semantics of λProlog” [MN p. 89].
Tutorial (why the three formulas fail). First. augment assumes the clause q :- r a, r b; R makes ;
augment assumes ; the goal backchains and needs and . The only -fact is
: the first subgoal binds and then fails. Classically one could argue “by cases on
”; a single O-proof must commit to one witness.
Peirce. augment assumes , i.e. p :- (p => q),
goal . Backchaining gives the goal : assume , prove . Nothing proves .
Drinker. (The third formula is a form of the classical “drinker paradox”; the name is not the book’s.) R makes , generic makes , augment assumes , goal . The only way is to unify , i.e. , which the scope condition forbids. This is exactly the failure of , and indeed an engine without the scope check “proves” it (Section 3.8.3).
3.6.2Minimal and intuitionistic negation#
Define as . Minimal logic treats as essentially a non-logical constant; intuitionistic logic adds ex falso quodlibet [MN p. 89–90]:
A program is inconsistent if it entails ; intuitionistically, it then entails everything
[MN p. 90]. In λProlog one picks a proposition, say false, for ; since it is non-logical, ex falso
is unavailable, and the negation obtained is minimal logic negation [MN p. 90]. That is what the
database constraint of Listing 3.1 uses. The interpreter can be extended to intuitionistic negation:
“before failing on a given query, the interpreter would try to determine if false is provable. If it
is, then it would have to succeed on the query in question. Such a check for inconsistency would have to be
coordinated with each (sub)query that leads to the program being augmented” [MN p. 90].
Example 3.13 (where minimal and intuitionistic negation part ways). Consider the goal p => (p => false) => q, i.e. . augment twice puts
p and the clause false :- p in the program; the goal q matches no clause head, so there is
no O-proof, and the formula is not provable in minimal logic either. If false is read as , it is
intuitionistically provable: false follows by backchaining on false :- p, and ex falso gives
q. The extended interpreter described above finds this proof: before failing on q it tries
false, in the augmented program, and succeeds. The check must be made in the augmented program,
which is why it has to be “coordinated” with augment: the empty program is consistent, the
program is not. (The interpreter of Section 3.8.3, which has no ex falso, returns
() for this goal.)
Minimal negation is weak but not useless. These are provable [MN p. 90]:
(p => q) => ((q => false) => (p => false)).
p => ((p => false) => false).Their converses are provable neither minimally nor intuitionistically, but are classically. The instance of
excluded middle ?- p; (p => false). is not provable; its double negation
?- ((p; (p => false)) => false) => false. is.
Tutorial (a proof that uses a hypothesis twice [MN p. 91]). In the display below, the formulas assumed so far are written to the left of ?-:
(p; (p => false)) => false ?- false.
(p; (p => false)) => false ?- p; (p => false).
(p; (p => false)) => false ?- p => false.
p, (p; (p => false)) => false ?- false.
p, (p; (p => false)) => false ?- p; (p => false).
p, (p; (p => false)) => false ?- p.In line 1 augment has assumed the clause false :- p; (p => false). From line 1 to 2 we
backchain on it; from 2 to 3 we choose the right disjunct; from 3 to 4 augment assumes p;
from 4 to 5 we backchain on the same clause again, now in a larger program; from 5 to 6 we choose the
left disjunct, and “This last query succeeds immediately because the goal p is also in the program at
that point.” The pattern, a
hypothesis used twice, the second time in a bigger world, is typical of intuitionistic proofs.
Theorem 3.14 ([MN p. 91]). If is a fohh program and a fohh goal over , then has an O-proof if and only if it is provable in minimal logic.
Since fohh formulas contain no (only the non-logical false), minimal and intuitionistic
provability coincide on them, “for this reason, we shall say that the declarative semantics of λProlog is
also given by intuitionistic logic” [MN p. 91].
Kanren angle (=> false is not negation as failure). Minimal negation needs nothing from the engine: false is an ordinary predicate, and
as a goal is “assume , prove false”. It must not be confused with the soft-cut negation
(if° g ✗° ✓°) available in (aux kanren micro), which is negation as failure and unsound on non-ground goals, nor
with the disequality constraint ≠°. Under the open-world reading of fohh the book notes that
for atomic “can never be true because there is always some future world in which is
true” [MN p. 94]. Classical principles (excluded middle, Peirce, scope extrusion) must not be built
into a fohh engine: they are unsound for its operational semantics.
3.6.3Why “hereditary Harrop”#
Harrop showed that if all assumptions (the formulas left of the sequent arrow) are of the form , with arbitrary, then intuitionistic logic has the disjunction property (a proof of yields a proof of or of ) and the existence property (a proof of yields a witness with a proof of ) R. Harrop. Concerning formulas of the types , in intuitionistic formal systems. Journal of Symbolic Logic, 25:27–32, 1960, [MN p. 93]. Intuitively, these are what goal-directed search relies on: when the goal is a disjunction or an existential, committing to one disjunct or one witness loses nothing. Harrop’s condition gives them only at the root of a proof; to have them at every point of goal-directed search, disjunctions and existentials are prohibited “hereditarily at all positive locations” [MN p. 93], whence hereditary Harrop 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. Semantically, intuitionistic logic is modelled by Kripke models over possible worlds; identifying worlds with signature–program pairs, a fohh computation moves to larger worlds (the open-world assumption) [MN p. 94].
3.7Notable subsets of fohh#
Can the grammar be simplified without losing expressiveness? The book gives two restrictions [MN p. 91–92]:
Atomic heads, (3.2). Clauses of (3.1) can be preprocessed, “without changing their essential operational interpretation”, into clauses whose top-level implications have atomic conclusions [MN p. 91]; declaratively, every (3.1) clause is intuitionistically (and minimally) equivalent to a set of (3.2) clauses [MN p. 92]. The equivalences doing the work are those of fohc normalisation (Chapter 2, [MN p. 64]):
and when is not free in .
Example 3.15 (normalising a clause to atomic heads). The (3.1) clause has a conjunction and an implication in the conclusion of its top-level implication. Distributing over , then over , and finally currying the inner implication gives the two (3.2) clauses
that is, p X :- g X. and q X :- g X, h X. Note that the body now occurs twice. The book
warns, for fohc, that this kind of preprocessing can make programs exponentially larger (from
to the goal is duplicated) and need not preserve
operational behaviour such as the number of derivations [MN p. 64–65]. Which of and is
tried first in the second clause is an operational choice that the logic does not fix.
No , no , (3.3). Dropping disjunction and existentials from goals gives with as in (3.2); “now the G- and D-formulas are identical” (up to the normalisation above), so one grammar (3.3) serves for both: atoms closed under unrestricted , and [MN p. 92].
Pitfall (equivalent as programs, not as formulas). The passage from (3.1)/(3.2) to (3.3) is not a logical equivalence [MN p. 92]. The clause is legal in (3.2) but is not intuitionistically equivalent to any set of (3.3) formulas; it implies , but not conversely (classically the two are equivalent). Yet “as program clauses, however, these two formulas prove exactly the same atomic formulas” [MN p. 92]. The book does not spell out why; one way to see it is operational. To use the clause on the goal we must prove the goal , i.e. assume and then, in the augmented program, commit to or to : exactly what the two split clauses test. The intuitionistic difference would only show if could be assumed, and in fohh it never is, because it is not a clause.
Another way to get rid of and is to define them as non-logical predicates with higher-order Horn clauses (Chapter 5).
3.8What implication and universal goals ask of a miniKanren#
We can now say precisely what is missing from (aux kanren micro) (Chapter 10). A (aux kanren micro) goal maps a state
(a substitution indexed by variable creation number, plus constraint stores) to a lazy stream of states;
relations are Scheme procedures, so the program is the fixed Scheme environment: exactly the
fohc situation this chapter started from.
| fohh | (aux kanren micro) today |
|---|---|
| , , | ✓°, and°, or°/cond° (fair interleaving) |
| (R with a logic variable) | fresh° |
| in a clause (L) | fresh° in a relation body |
| decide and L over the clauses of a predicate | the cond° of a define-relation |
| initial, by unification | =° against the head |
| (augment) | missing: the program is not part of the state |
| (generic) | missing: no scoped constants, no scope check |
3.8.1The program context belongs to the search state#
The sequent shows the program as an inherited, read-only context: no rule returns a modified program to its caller. In a miniKanren this translates into four requirements.
- A goal must be able to read the current program when it reaches an atomic goal, so that assumed clauses are tried together with (and, in λProlog, before) the static ones.
- The extension is local to a subgoal. After in produces an answer, the
conjunction that follows must see the old program again. If the program lives in the state that
and°threads from one conjunct to the next, each answer state of must have its program restored. - The extension is local to a branch. Two disjuncts with different hypotheses must not see each other’s clauses, even though the interleaving search alternates between them.
- Free logic variables of an assumed clause are shared, not renamed (Section 3.5).
Requirements 2 and 3 are what make a host-language dynamic binding (parameterize,
fluid-let, or a global variable set and restored) tempting, and wrong. A (aux kanren micro) goal does almost
nothing when applied to a state: fresh° and define-relation wrap the real work in a promise
(δ), which is forced later by whoever consumes the stream, after the dynamic extent of the binding
has ended. The following file puts a “current program” in a parameter and tries it three ways.
(import scheme (chicken base) (only (scheme base) make-parameter parameterize)
(aux base) (aux stream) (aux kanren micro))
;; The "current program" in a host-language parameter: a list of clauses (λ (x) goal).
(define program (make-parameter '()))
(define (any-clause° cs x) ; try every clause, most recent first
(if (null? cs) ✗° (or° ((car cs) x) (any-clause° (cdr cs) x))))
(define-relation (hyp° x) ; a predicate whose clauses live in `program`
(λ (s) ((any-clause° (program) x) s)))
(define (assume° clause g) ; D ⊃ G by dynamic binding: WRONG
(λ (s) (parameterize ((program (cons clause (program)))) (g s))))
(define (fact a) (λ (y) (=° y a))) ; the clause hyp a.
(define (show x) (display x) (newline))
(show (μkanren-run (q -1 #t) (assume° (fact 'a) (hyp° q)))) ; 1
(show (μkanren-run (q -1 #t) (parameterize ((program (list (fact 'a)))) (hyp° q)))) ; 2
(show (parameterize ((program (list (fact 'a)))) (μkanren-run (q -1 #t) (hyp° q)))) ; 3()
()
(a)Run 1 binds the parameter around the application of the goal to the state; run 2 around the
construction of the goal. Both lose the hypothesis: (hyp° q) returns a promise, and the
program is read only when the promise is forced, outside parameterize. Only run 3, which forces the
entire search inside the binding, works, and it is useless for scoping, since the “scope” is then the
whole query.The parameter-based assume in the code accompanying λKanren 2020 loses hypotheses in
the same way for relation calls nested in delayed bodies; the paper also describes a state-threaded design
without the problem.Weixi Ma, Kuang-Chen Lu, and Daniel P. Friedman. Higher-order logic programming with Kanren. In miniKanren and Relational Programming Workshop, 2020 Hence: hypotheses must live in the search state (or be
passed as an explicit argument, as in Section 3.8.3), never in host dynamic state; see
Chapter 11.
3.8.2Scoped constants need a scope check#
Three shortcuts suggest themselves for in a miniKanren. Each one “proves” , which has no proof (Section 3.4.3):
(import scheme (chicken base) (aux base) (aux stream) (aux kanren micro))
(define (show x) (display x) (newline))
;; Three wrong encodings of the goal ∃x ∀y (x = y), which has no proof.
; (a) ∀ read as ∃: y is just another logic variable
(show (μkanren-run (x -1 #t) (fresh° (y) (=° x y))))
; (b) ∀ read as "a brand new constant", with no scope check
(show (μkanren-run (x -1 #t) (let ((c (gensym 'c))) (=° x c))))
; (c) ∀ read as "a fresh variable that must still be unbound at the end"
(define (naive-∀° f)
(fresh° (y) (f y) (project° ((v y)) (if (μkanren-var? v) ✓° ✗°))))
(show (μkanren-run (x -1 #t) (naive-∀° (λ (y) (=° x y)))))
(show (μkanren-run (x -1 #t) (naive-∀° (λ (y) (=° x (list 'f y))))))(α)
(c118)
(α)
((f α))(a) confuses the quantifiers. (b) gets a rigid constant but lets it escape into the answer: this is the
“scope extrusion” that the scope condition forbids. (c) is the subtle one: (aux kanren micro) binds the older
variable x to the younger y, so y stays unbound and the check passes; and with
(=° x (list 'f y)) it is x that gets bound in any miniKanren, so checking y can
never detect the escape. A rigid constant plus a check on the variables older than it is required,
as stated in the kanren box of Section 3.4.3.
Pitfall (scoped constants and the constraint stores). (aux kanren micro) also has disequality, type and absento constraints, and the book’s language has none of them.
Moiseenko remarks that “there is no sound implementation of eigen variables with the support of
disequality constraints” Evgenii Moiseenko. Constructive negation for miniKanren. In miniKanren and Relational Programming Workshop, 2019, and the eigen of miniKanren with symbolic
constraints is documented as unsupported with constraints other than ==
Jason 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. Take , with outer. Under an
extensional reading of Ende Jin, Gregory Rosenblatt, Matthew Might, and Lisa Zhang. Universal quantification and implication in miniKanren. In miniKanren and Relational Programming Workshop, 2021 it should fail, since could be ’s value;
under generic’s reading of as a new name, as in λProlog’s pi x\ not (x = A), it holds.
A naive eigen constant gives the second answer by accident, without a scope check. The proposal implements
both readings consistently, the generic one by default (Definition 14.1,
Section 12.5).
3.8.3A throwaway interpreter of the rules#
To check the examples of this chapter on today’s (aux kanren micro), and to see the rules of Rules 3.6
at work, here is a small interpreter of O-proofs. It is not a proposal for the new module
(Chapter 11 and Chapter 12 do that): formulas are data, it re-examines every clause at every atomic goal,
and the program is an explicit argument P. But it is faithful to the rules, and it is complete with
respect to the clause choice thanks to the interleaving or°.
(import scheme (chicken base) (aux base) (aux stream) (aux kanren micro))
;; A throwaway interpreter of O-proofs over (aux kanren micro): formulas are data,
;; binders are Scheme closures.
;; G ::= #t | A | (and G ...) | (or G ...) | (some ,(λ (x) G)) | (eq t u)
;; | (imp D G) | (all ,(λ (x) G))
;; D ::= A | (if G D) | (both D D) | (all ,(λ (x) D))
(define (tag? t F) (and (pair? F) (eq? (car F) t)))
(define (all-of° gs) (if (null? gs) ✓° (and° (car gs) (μ s ((all-of° (cdr gs)) s)))))
(define (one-of° gs) (if (null? gs) ✗° (or° (car gs) (μ s ((one-of° (cdr gs)) s)))))
(define (solve° P G) ; Σ; P ⟶ G
(cond
((eq? G #t) ✓°) ; ⊤R
((tag? 'and G) (all-of° (map (λ (g) (solve° P g)) (cdr G)))) ; ∧R
((tag? 'or G) (one-of° (map (λ (g) (solve° P g)) (cdr G)))) ; ∨R
((tag? 'some G) (fresh° (x) (solve° P ((cadr G) x)))) ; ∃R, logic variable
((tag? 'eq G) (=° (cadr G) (caddr G)))
((tag? 'imp G) (solve° (cons (cadr G) P) (caddr G))) ; AUGMENT, at the front
((tag? 'all G) (generic° P (cadr G) #t)) ; GENERIC
((tag? 'all/unchecked G) (generic° P (cadr G) #f))
(else (decide° P P G)))) ; atomic goal
(define (decide° P Ds A) ; decide: some D ∈ P, front first
(if (null? Ds) ✗° (or° (bc° P (car Ds) A) (μ s ((decide° P (cdr Ds) A) s)))))
(define (bc° P D A) ; Σ; P —D→ A
(cond
((tag? 'if D) (and° (bc° P (caddr D) A) (μ s ((solve° P (cadr D)) s)))) ; ⊃L
((tag? 'both D) (or° (bc° P (cadr D) A) (bc° P (caddr D) A))) ; ∧L
((tag? 'all D) (fresh° (x) (bc° P ((cadr D) x) A))) ; ∀L
(else (=° D A)))) ; initial
;; GENERIC: a new constant c; an answer of G[c/x] survives only if no variable
;; created before c (index < n) reaches c through the substitution.
(define (mentions? c w) ; does the walked term w contain c?
(or (eq? w c) (and (pair? w) (or (mentions? c (car w)) (mentions? c (cdr w))))))
(define (generic° P body check?)
(λ (s)
(let* ((n (μkanren-state-vars-count s))
(c (gensym 'c))
(ok? (λ (s*) (let loop ((i 0))
(or (= i n)
(and (not (mentions? c (μkanren-state-find/value (make-μkanren-var i) s*)))
(loop (add1 i)))))))
(answers ((solve° P (body c)) s)))
(if check? (filter§ ok? answers) answers))))
(define-syntax ask ; (ask n (q) P G): first n answers, -1 = all
(syntax-rules () ((_ n (q) P G) (μkanren-run (q n #t) (solve° P G)))))
(define (show label x) (display label) (display x) (newline))How the code mirrors the rules: augment is (solve° (cons D P) G), so the new clause goes to
the front, the scope ends with the Scheme call, and each branch carries its own P (requirements 2
and 3 of Section 3.8.1 hold by construction). Binders are Scheme closures, so L and
R call fresh° when the clause or goal is used: a clause’s own variables are renamed at each
use, while a logic variable merely mentioned in it is shared (requirement 4). generic creates a
gensym constant ((aux kanren micro) compares symbols with eq?) and enforces the scope condition lazily:
an answer of is kept only if no variable with creation index below n, i.e. older than
c, reaches c; the deep walk also catches escapes through younger variables. It prunes late,
which is acceptable for a test bench, not for an engine. all/unchecked omits the check.
The examples. The file below begins with (include "hh.scm"), the listing above, and
runs a selection of the chapter’s queries, in the book’s order.
(include "hh.scm")
;; Section 3.2 of the book: clause order, Horn entailment, B ⊃ B
(show "p 2 => p 3 => p X : " (ask -1 (x) '((p 1)) `(imp (p 2) (imp (p 3) (p ,x)))))
(show "(p 2 & p 3) => p X : " (ask -1 (x) '((p 1)) `(imp (both (p 2) (p 3)) (p ,x))))
(define P0 '((if (and r q) s) (if (and q u) t) (if r q)))
(show "r => s ; t : " (list (ask -1 (q) P0 '(imp r s)) (ask -1 (q) P0 't)))
(show "B => B, 3 proofs : " (ask 3 (q) '() '(imp (if (imp q q) q) (imp (if q q) q))))
;; Figure 3.1, the course database
(define (fin x c) `(fact (finished ,x ,c)))
(define DB
`((both ,(fin 'kim 102) ,(fin 'dana 101))
(both ,(fin 'kim 210) ,(fin 'dana 250))
(all ,(λ (X) `(if (and (or ,(fin X 101) ,(fin X 102)) ,(fin X 250) ,(fin X 301))
(fact (cs_major ,X)))))
(all ,(λ (X) `(if (and (or ,(fin X 101) ,(fin X 102)) (or ,(fin X 210) ,(fin X 250))
,(fin X 301))
(fact (graduates ,X)))))
(all ,(λ (X) `(if (and ,(fin X 210) ,(fin X 250)) false)))))
(show "dana X => false : " (ask -1 (x) DB `(imp ,(fin 'dana x) false)))
(show "X Y => grad, major : "
(μkanren-run (q -1 #t)
(fresh° (x y) (=° q (list x y))
(solve° DB `(imp ,(fin x y) (and (fact (graduates ,x)) (fact (cs_major ,x))))))))
(show "kim X => kim Y => .. : "
(μkanren-run (q -1 #t)
(fresh° (x y) (=° q (list x y))
(solve° DB `(imp ,(fin 'kim x) (imp ,(fin 'kim y)
(and (fact (graduates kim)) (fact (cs_major kim)))))))))
(show "kim 250, 301 => false: " (ask -1 (q) DB `(imp ,(fin 'kim 250) (imp ,(fin 'kim 301) false))))
;; Section 3.3: jars, quantifier order, levels
(define JAR
`((all ,(λ (J) `(if (all ,(λ (x) `(imp (bug ,x) (imp (in ,x ,J) (dead ,x))))) (sterile ,J))))
(all ,(λ (B) `(all ,(λ (J) `(if (and (heated ,J) (in ,B ,J) (bug ,B)) (dead ,B))))))
(heated j)))
(show "sterile Q : " (ask -1 (q) JAR `(sterile ,q)))
(show "pi y\\ X = f y : " (ask -1 (x) '() `(all ,(λ (y) `(eq ,x (f ,y))))))
(show " ... unchecked : " (ask -1 (x) '() `(all/unchecked ,(λ (y) `(eq ,x (f ,y))))))
(show "pi y\\ sigma x\\ x = y : " (ask -1 (q) '() `(all ,(λ (y) `(some ,(λ (x) `(eq ,x ,y)))))))
(define PQ `((all ,(λ (z) `(if (q ,z) (p (d ,z)))))))
(show "pi y\\ (q y => p X) : " (ask -1 (x) PQ `(all ,(λ (y) `(imp (q ,y) (p ,x))))))
(show " ... unchecked : " (ask -1 (x) PQ `(all/unchecked ,(λ (y) `(imp (q ,y) (p ,x))))))
;; Figure 3.4: reverse; the base clause captures the outer K
(define REV
`((all ,(λ (L) `(all ,(λ (K)
`(if (imp (both (rev () ,K)
(all ,(λ (X) `(all ,(λ (L) `(all ,(λ (K)
`(if (rev ,L (,X . ,K)) (rev (,X . ,L) ,K)))))))))
(rev ,L ()))
(reverse ,L ,K))))))))
(show "reverse (1 2) P : " (ask -1 (p) REV `(reverse (1 2) ,p)))
(show "reverse P (1 2 3) : " (ask 1 (p) REV `(reverse ,p (1 2 3))))
(show "under rev () Z : "
(μkanren-run (q -1 #t)
(fresh° (p z) (=° q (list p z)) (solve° REV `(imp (rev () ,z) (reverse (1 2) ,p))))))
;; Section 3.4: Peirce, the drinker, double negation of excluded middle
(show "Peirce : " (ask -1 (q) '() '(imp (if (imp p q) p) p)))
(show "drinker : " (ask -1 (q) '() `(some ,(λ (x) `(all ,(λ (y) `(imp (p ,x) (p ,y))))))))
(show " ... unchecked : "
(ask -1 (q) '() `(some ,(λ (x) `(all/unchecked ,(λ (y) `(imp (p ,x) (p ,y))))))))
(show "p ; (p => false) : " (ask -1 (q) '() '(or p (imp p false))))
(show "not not (p ; not p) : " (ask 1 (q) '() '(imp (if (or p (imp p false)) false) false)))
(show "p => not p => q : " (ask -1 (q) '() '(imp p (imp (if p false) q))))p 2 => p 3 => p X : (3 2 1)
(p 2 & p 3) => p X : (2 1 3)
r => s ; t : ((α) ())
B => B, 3 proofs : (α α α)
dana X => false : (210)
X Y => grad, major : ((dana 301))
kim X => kim Y => .. : ((301 250) (250 301) (250 301) (301 250))
kim 250, 301 => false: (α)
sterile Q : (j)
pi y\ X = f y : ()
... unchecked : ((f c489))
pi y\ sigma x\ x = y : (α)
pi y\ (q y => p X) : ()
... unchecked : ((d c564))
reverse (1 2) P : ((2 1))
reverse P (1 2 3) : ((3 2 1))
under rev () Z : (((2 1) α) (α (2 1)))
Peirce : ()
drinker : ()
... unchecked : (α)
p ; (p => false) : ()
not not (p ; not p) : (α)
p => not p => q : ()A provable closed goal answers (α) (a proof, nothing to report); an unprovable one answers
(). Every line agrees with the book; the Kim query lists all answers, while the book shows only
the first. The goal t on its own fails, since the Horn program has no atomic consequences, and the
last line is the minimal-logic failure of discussed in Section 3.6.2. In sterile Q the outer variable is bound to the constant j, which is fine: j
belongs to the signature in which Q was created. In the reverse example, (rev () ,K) is built
with the outer K, a logic variable, which the closure captures: the base case shares the
answer with the query. The three unchecked lines are the instructive ones. Without the scope
condition a scoped constant leaks into an answer, once directly and once through the clause variable of
the level-lowering example, and the drinker formula , valid
classically but not intuitionistically, becomes “provable”. Dropping the scope check does not only produce
odd answers: it changes the logic.
3.9Summary#
- fohh extends fohc with and in goals; the clause grammar is unchanged, and the two grammars swap roles across . Hereditary Harrop formulas are those with no positive or (Definition 3.1 and Proposition 3.3).
- augment proves with added at the front of the program; generic proves with a new scoped constant in the signature. Both follow a stack discipline (Rules 3.6).
- Implication gives hypothetical reasoning: entailment between clauses, “what if” queries, and a database whose state is the stack of open hypotheses (Section 3.3).
- is intensional: one generic proof for all elements, no induction, empty types harmless (Section 3.4).
- With logic variables, and differ through a scope condition: a variable may only be bound to terms over the signature of its creation, and binding must propagate this restriction to the variables of the bound term (universe levels and lowering, Section 3.4.3).
- Assumed clauses may contain logic variables of the surrounding computation; these are shared, not renamed, which lets a clause “tie” its binding to a goal (reverse, Section 3.5).
- O-proofs are sound and complete for intuitionistic logic and coincide with minimal provability on
fohh; classical logic is unsound for them (scope extrusion, Peirce, drinker).
falsegives minimal negation, not negation as failure (Theorem 3.12 and Theorem 3.14). - Clauses can be normalised to atomic heads (3.2); removing and (3.3) preserves atomic consequences but not logical equivalence (Section 3.7).
- For a miniKanren: the program must live in the search state (per branch, restored after each answer of the scoped subgoal), never in host dynamic binding, because goals run lazily; needs rigid scoped constants and a scope check in, or around, unification (Section 3.8, and Chapter 11 for the design).