Chapter 2
Logic programming as proof search
Chapter 1 gave the overall plan of this document: read Miller and Nadathur’s Programming with
Higher-Order Logic Dale Miller and Gopalan Nadathur. Programming with Higher-Order Logic. Cambridge University Press, Cambridge, 2012 with a miniKanren programmer’s eyes, and find out what
(aux kanren micro) would need in order to host its ideas. This chapter lays the first-order foundation. It covers the
book’s Introduction and its Chapters 1 and 2, plus the parts of the Teyjus appendix needed to run the
examples. Nothing here goes beyond Prolog in expressive power. What is new, compared with the usual
Prolog textbook, is the point of view. A logic program is a set of formulas, a query is a formula,
and running the query means searching for a proof in a sequent calculus. Each logical connective
has a fixed search meaning, independent of the program. Atomic goals are solved by backchaining
on program clauses. A language counts as a logic programming language when this goal-directed search
is complete.
For a miniKanren programmer the punchline comes early. Pure miniKanren, with =°,
fresh°, cond° and recursive relations, is first-order Horn-clause logic programming, except for its
search strategy and its lack of types. This chapter makes that statement precise, so that later
chapters can say exactly what Horn clauses lack: local constants and local clauses
(Chapter 3), and -terms as data (Chapter 4 and Chapter 6).
2.1Computation as deduction#
The Introduction distinguishes two ways of using logic in computer science [MN p. 1–3]. In computation-as-model, a computation is a mathematical structure (states, transitions), and logic talks about it from outside, as Hoare triples or temporal modalities do. In computation-as-deduction, the logical objects themselves (formulas, terms, proofs) are the elements of the computation. This second view splits in two again:
- proof normalization: the state is a proof (a -term), and computing means reducing it to normal form. This is the basis of functional programming;
- proof search: the state is a sequent, that is, a goal together with its assumptions, and computing means searching for a derivation of it. The way sequents change during the search is the dynamics of the computation. This is the basis of logic programming.
Proof search in logic programming is not the proof search of mathematicians. Mathematicians use lemmas, and the proof rule for lemmas is the cut rule: to prove , state a lemma , then prove and prove from . Gentzen’s cut-elimination theorem Gerhard Gentzen. Investigations into logical deductions. In M. E. Szabo, editor, The Collected Papers of Gerhard Gentzen, pages 68–131. North-Holland, Amsterdam, 1969. Translation of articles that appeared in 1934–35 says that cut can always be eliminated, for classical and for intuitionistic logic. Cut-free proofs are huge and of little use to a mathematician, but they are exactly what a machine can look for. So in logic programming “the cut rule is excluded from the execution of logic programs, and computation is based on the search for cut-free proofs”; cut and cut elimination remain useful to reason about programs [MN p. 3]. We come back to this in Section 2.10.
Programs, goals, sequents. A formula is either part of a logic program, which gives meaning to the non-logical constants it mentions, or a goal, which we try to derive from the program [MN p. 3]. The state of the search is a collection of sequents
where is a signature (the typed non-logical constants available), is the program and is the goal. The Introduction states the principle that drives the whole book [MN p. 3–4]:
- if is not atomic, the search commits to decomposing its top-level connective. The search semantics of a connective is fixed and does not depend on the program;
- if is atomic, the program is consulted. The search backchains: it looks in for an implication whose conclusion matches the atom, and then tries to prove the premise.
“Logic programming can be seen abstractly as a logical framework in which a strategy that alternates between goal reduction and backchaining is complete” [MN p. 4].
How can a sequent change? The Introduction then asks a qualitative question [MN p. 4]: if proving leads to proving , what can differ between the two? For Horn clauses, and : signature and program are global and fixed, and only the atom changes. For hereditary Harrop formulas, and : the search can add constants and clauses that are visible only in part of the computation, which gives modular programming and data abstraction. Since more of the dynamics then comes from the logic and not from the particular predicates, “the metatheory of the logic can be of more value in proving properties of those programs” [MN p. 4]. This chapter treats the first case; the second is Chapter 3.
2.2Typed first-order terms#
Before writing relations we need data. Book Chapter 1 fixes the language of terms. It has no
predicates and no programs yet. It uses actual λProlog syntax and is the -free special
case of what Chapter 4 generalises.
2.2.1Sorts, type constructors and kinds#
λProlog has built-in sorts (atomic types) [MN p. 10–11]: int, real, string,
in_stream, out_stream, and o, the type of formulas, which has a special status
(Section 2.4). It also has the built-in type constructor list, so (list int)
is a type. Type constructors are classified by kinds:
A kind is therefore just an arity: int : type, list : type -> type. New type constructors are
declared with kind [MN p. 12]:
kind pair type -> type -> type.after which (pair string int) is a type. Type expressions are type variables (uppercase tokens),
arrows (written ->, right associative), and type constructors applied to exactly as
many arguments as their arity [MN p. 12–13].
Definition 2.1 (Target type, order [MN p. 13]). Every type can be written uniquely as with not an arrow. is the target type and are the argument types; is functional when . The order of a type is
The order counts how deeply the arrow is nested to the left. For example int and
list (int -> int) have order 0 (the order does not look inside constructor arguments),
int -> string -> o has order 1, and int -> (int -> o) -> o has order 2 [MN p. 14]. In the
first-order language every declared constant has a type of order at most 1 that does not mention
o, every variable has a type of order 0, and type variables may only be instantiated with order-0
types [MN p. 13–16]. The last condition is needed because order is not stable under type substitution:
A -> list A -> o has order 1, but instantiating A with int -> int gives a type of
order 2 [MN p. 13–14].
2.2.2Terms, polymorphism and typing#
All symbols are constants; a constant of functional type is a value constructor. Lists use
the polymorphic constants nil : list A and :: : A -> list A -> list A, where :: is infix and
right associative, so 2 :: 1 :: nil has type list int [MN p. 15]. Constants are declared with
type [MN p. 16]:
type pr A -> B -> pair A B.A crucial asymmetry governs polymorphism [MN p. 17]:
- each occurrence of a constant may take its own instance of the declared type. In
(2 :: 1 :: nil) :: (1 :: nil) :: nilthe first twonils have typelist intand the last one has typelist (list int); - a variable has one type at all its occurrences. So
((X :: nil) :: X :: nil)cannot be typed, because would need both a type and the typelist.
The rules are those of the type assignment calculus of the book’s Figure 1.2 [MN p. 18], with judgments , where types the constants and the variables:
Here (“ is an instance of ”) holds when is obtained from by substituting order-0 types other than for type variables. A first-order term is a with for some of order 0 different from [MN p. 18]. The first rule is where constants are polymorphic: the instance is chosen per occurrence. The second rule is where variables are monomorphic: gives one type per variable.
The book states a principal typing property [MN p. 18–19]: if a term has some typing, it has a most general
one, unique up to renaming of type variables. For example (X :: nil) :: nil can be typed with
or , and most generally with , the whole term having type
list (list A). Application is left associative. In canonical form a term is a variable, a constant,
or whose head is always a constant [MN p. 19]: first-order variables cannot
be applied.
2.2.3Representing data#
The recipe for representing a class of objects is [MN p. 19]: pick a type for it; declare one value constructor per way of building an object, all with that common target type; let recursive components have the target type as argument type. Binary trees [MN p. 20]:
kind btree type -> type.
type empty btree A.
type node A -> btree A -> btree A -> btree A.(node 3 (node 1 empty empty) (node 4 empty empty)) has type btree int, while a tree that mixes
3 and "cat" is ill typed. This declaration is parametric: every type variable of an
argument type also occurs in the target type. λProlog does not require this; the declaration
type node A -> btree -> btree -> btree. gives heterogeneous trees [MN p. 21]. Unlike ML datatypes, the
set of constructors of a type is open (declarations can be added later), and terms can contain
variables, so a term describes a whole class of objects [MN p. 21–22].
The same recipe encodes the abstract syntax of a language. First-order formulas [MN p. 22–23]:
kind term, form type.
type a, b term.
type f term -> term -> term.
type var string -> term.
% f(a, f(x, b)) is represented as (f a (f (var "x") b))
type p term -> term -> form.
type q term -> form.
type ff, % encoding the false proposition
tt form. % encoding the true proposition
type &&, % encoding conjunction
!!, % encoding disjunction
==> form -> form -> form. % encoding implication
infixl && 5.
infixl !! 4.
infixr ==> 3.With the precedences above, (p a b) && (q a) !! (q (f a b)) ==> (p b (f b a)) stands for
.
The declarations infixl, infixr (and infix, prefix, postfix, …) are
operator declarations :
they change only the concrete syntax, a higher number binding more tightly. For instance, after
infixl pr 5. the expression (3 pr 4 pr "three") stands for ((pr ((pr 3) 4)) "three")
[MN p. 16].
Imperative programs are encoded in the same way [MN p. 24–25]. The book deliberately uses only two sorts,
expr and stmt, and one type-neutral sort for all expressions, whether integer or boolean
valued; object-level typing is left to a later analysis written as a logic program:
kind stmt, expr type.
type id string -> expr.
type c int -> expr.
type t, f expr.
type &&, !!,
plus, minus,
mult, < expr -> expr -> expr.
type := expr -> expr -> stmt. % for assignment
type cond expr -> stmt -> stmt -> stmt. % for conditionals
type while expr -> stmt -> stmt. % for while loops
type seq stmt -> stmt -> stmt. % for composition
infixl &&, mult 5.
infixl !!, plus, minus 4.
infix < 3.
infix := 2.The C-like program v = 1; i = n; while (0 < i) { v = v * i; i = i - 1; } is then the term
(seq ((id "v") := (c 1))
(seq ((id "i") := (id "n"))
(while ((c 0) < (id "i"))
(seq ((id "v") := (id "v") mult (id "i"))
((id "i") := (id "i") minus (c 1))))))Because := has the lowest precedence, (id "v") := (id "v") mult (id "i") parses as
(:= (id "v") (mult (id "v") (id "i"))). The term is the program’s abstract syntax tree:
“first-order terms are a generalization of the labeled trees that are used in depicting abstract
syntax” [MN p. 25]. Types do not express every well-formedness condition (the left side of := must
encode an identifier); such conditions are checked by logic programs over the representation.
Pitfall (First-order syntax does not capture binding). Adding type all term -> form -> form. lets us write as
(all (var "x") ((p a (var "x")) && (q (var "x")))). The term has the right tree shape, but nothing
in it says that (var "x") is bound by all: renaming, capture-avoiding substitution and
scoping must be programmed by hand in every computation over the syntax. “This is a fundamental
limitation of first-order approaches to the treatment of syntax” [MN p. 23]. Representing object
variables by meta-level logic variables instead makes object scoping uncontrollable [MN p. 22]. The book
removes the limitation with -tree syntax (Chapter 6).
2.3First-order unification#
Unification is the engine under backchaining. The book presents it as a nondeterministic rewriting of a multiset of equations [MN p. 26–29], the Martelli–Montanari style. A miniKanren programmer knows the algorithm; the point of this section is the precise vocabulary (mgu, solved form, occurs check) and the role of types.
Remark 2.2. The book is deliberately “not a formal development of logic” [MN p. 6–7]: it states its results in running prose, without numbered definitions or theorems. The definition, theorem and proposition environments in this chapter are our packaging of those statements, each with the page where the book makes it.
Before the definitions, note the three ways a program uses unification [MN p. 26–27]. Take , .
Decomposition: has the unifier : the left side is a pattern that extracts head and tail.
Recognition: the same pattern unifies only with non-empty lists, and with repeated the pattern recognises the non-empty trees whose two subtrees are identical.
Construction: in
the first equation takes an input apart, the last builds a new term from its pieces, and the “output” variable receives .
The construction case is how a clause head such as append (X :: L1) L2 (X :: L3) computes.
Definition 2.3 (Unification problem, unifier, mgu [MN p. 26–28]). A unification problem is a finite multiset of equations between first-order terms, the two sides of each equation having the same type. A unifier is a type-preserving substitution that makes the two sides of every equation identical. A substitution is more general than if is obtained from by further substitution. A most general unifier (mgu) is a unifier more general than every other.
Substitutions are constraints on the values of variables. says only that and are equal; satisfies that constraint but says more [MN p. 27]. A good unifier is as general as possible, because later steps of the computation will add more constraints, and an over-specific choice could make them fail.
Theorem 2.4 (mgu [MN p. 28]). Typed first-order unification problems have most general unifiers whenever they have unifiers, and these are unique up to substitutions that rename variables.
For instance the problem has the two mgu’s
which differ by the renaming , and infinitely many less general ground unifiers [MN p. 27–28].
The transformation system. The book gives three transformations, term reduction, reorientation and variable elimination [MN p. 28]. We split them into six rules.This split is ours, the content is the book’s. is multiset union, is a problem with no unifier, the set of variables, and means an occurrence of at type .
Decompose and Clash are term reduction. They are justified because a rigid term keeps its head under any substitution: different heads, or the same name at two different types, can never be made equal [MN p. 28–29]. Orient is bookkeeping. Delete, Check and Eliminate are variable elimination, and they rest on the finiteness of terms: with strictly inside has no finite solution. This failure is the occurs check. The side condition of Clash is stated here for types without type variables; with polymorphic constants, “” becomes “ and have no common instance”, and Decompose first unifies with as generally as possible [MN p. 30–31].
Definition 2.5 (Solved form [MN p. 29]). is in solved form if every equation has a variable on the left, and each such variable occurs nowhere else in . A solved form is read as a substitution, and it is its own mgu.
Theorem 2.6 (Termination and correctness [MN p. 29]). If variable elimination is never applied twice to the same unchanged equation, every sequence of transformations terminates in or in a solved form, and every transformation preserves the set of unifiers. The transformations thus define a nondeterministic algorithm for computing mgu’s.
Tutorial (Three unification traces [MN p. 29–30]). Success. The repeated variable makes the pattern recognise trees with two identical subtrees. Write for :
The last step removes equations between constants: Decompose with arguments. The result is a solved form, hence the mgu.
Constant clash. If the right subtree is instead, the same steps reach the equation , and term reduction yields .
Occurs check. fails at once, because occurs in the right-hand side.
Types in unification. Types enter only in term reduction, when two heads have the same name: their types must agree [MN p. 30–31]. With polymorphic constants the type of an occurrence is not determined by its name, so types cannot simply be checked once in advance. The book’s example: with and , the problem is well typed (both sides have type ), but in the constant occurs at type and in at . Ignoring types yields the ill-typed unifier [MN p. 31]. The book stops there; completing the example, term reduction with types sees two occurrences of at the types and , which have no common instance, and fails: the typed problem has no unifier. Types are themselves first-order terms, so the same algorithm unifies them. The book concludes [MN p. 31] that types can be erased safely when the original problem’s typing guarantees that the intermediate problems stay well typed, in particular when every type variable in a constructor’s argument types also appears in its target type (the parametric condition of Section 2.2.3).
Logical reading and the occurs-check policy. Constants behave like universally quantified variables and logic variables like existentially quantified ones, so a unification problem is a formula [MN p. 31–32]. Later chapters mix the quantifier prefix (Chapter 3 and Chapter 7). Many Prologs omit the occurs check for speed; the book does not: “we will require failure in any case where the occurs-check test is satisfied”, because “finiteness of terms, enforced through this test, will be important to encoding quantifier dependencies” [MN p. 32]. Without it, deduction can be unsound [MN p. 33].
Kanren angle (Unification in (aux kanren micro)). (aux kanren micro)’s unifier already is the unifier of this section, minus types. Terms are Scheme data, so pairs,
vectors and records decompose structurally (Decompose), and different atoms or different shapes
fail (Clash). The substitution is triangular: binding never rewrites the
other equations, and walking a term on demand plays the role of Eliminate. The occurs check is
on. Here are the book’s problems, run on today’s (aux kanren micro) (file unify.scm; each q collects
the variables of interest, and each result is printed after its label):
; U1 {(X :: L) = (1 :: 2 :: nil)}
(μkanren-run (q -1 #t) (fresh° (x l) (=° q (list x l)) (=° (cons x l) '(1 2))))
; U2 {(node El T T) = (node 1 (node 2 empty empty) (node 2 empty empty))}
(μkanren-run (q -1 #t)
(fresh° (el t) (=° q (list el t))
(=° `(node ,el ,t ,t) '(node 1 (node 2 empty empty) (node 2 empty empty)))))
; U3 the same with a 3 in the right subtree: constant clash
(μkanren-run (q -1 #t)
(fresh° (el t) (=° q (list el t))
(=° `(node ,el ,t ,t) '(node 1 (node 2 empty empty) (node 3 empty empty)))))
; U4 {(X :: L1) = (1 :: nil), L2 = (2 :: nil), (X :: L2) = L3}: construction
(μkanren-run (q -1 #t)
(fresh° (x l1 l2) (=° (cons x l1) '(1)) (=° l2 '(2)) (=° (cons x l2) q)))
; U5 {(X :: L) = (Y :: Z :: nil)}: an mgu, shown up to renaming
(μkanren-run (q -1 #f)
(fresh° (x l y z) (=° q (list x l y z)) (=° (cons x l) (list y z))))
; U6 {T = (bt 1 T T)}: occurs check
(μkanren-run (q -1 #t) (=° q `(bt 1 ,q ,q)))
; U7 {(c 1 Y) = (c X a)}: untyped unification returns the ill-typed unifier
(μkanren-run (q -1 #t) (fresh° (x y) (=° q (list x y)) (=° `(c 1 ,y) `(c ,x a))))U1 ((1 (2)))
U2 ((1 (node 2 empty empty)))
U3 ()
U4 ((1 2))
U5 ((λ (α β) (cons α (cons (cons β (quote ())) (cons α (cons β (quote ())))))))
U6 ()
U7 ((1 a))In U4, q plays the output variable . U5 is run with #f as the third argument of μkanren-run, which prints the raw reified answer,
a λ over the unbound variables, instead of evaluating it as #t does; it reads , , , . Reification picks one
representative of the mgu “up to renaming” (Theorem 2.4). U7 is the warning of the book come
true: an untyped engine happily returns the ill-typed unifier. A typed layer would require typed
constant occurrences, or a static check plus erasure for parametric signatures. The proposal stays untyped
(Section 14.2.2); simple types are a later work item (Section 14.5.6).
2.4First-order formulas#
Book Chapter 2 relaxes the signature: constants may now have target type o. They are the
predicate symbols, and an expression of type o headed by one of them is an atomic
formula [MN p. 34–35]:
type memb A -> list A -> o.
type append list A -> list A -> list A -> o.The logical constants and their λProlog spellings are [MN p. 35]:
| math | λProlog | type | fixity | conventional use |
|---|---|---|---|---|
true | o | |||
=> | o -> o -> o | infix, right assoc. | implication in goals | |
& | o -> o -> o | infix, right assoc. | joins program clauses | |
, | o -> o -> o | infix, left assoc. | joins goals | |
; | o -> o -> o | infix, left assoc. | ||
| (reversed) | :- | o -> o -> o | infix, non assoc. | “is implied by” |
pi x\ F | binder | |||
sigma x\ F | binder |
The two spellings of and of are a stylistic convention [MN p. 47–48]; breaking it does not
affect well-formedness. All these operators bind less tightly than application [MN p. 35], and &
binds more tightly than :- [MN p. 48], so A & B :- G reads as . Only the
logical constants may take arguments of type o in the first-order setting [MN p. 35]. Quantifiers carry an optional type, (pi (x:T)\ F), inferred most generally when
omitted; the scope of x\ extends as far to the right as possible, and only the binding pattern
matters, so pi x\ (p x) => sigma y\ (q x y, pi x\ (q y x)) and
pi z\ (p z) => sigma y\ (q z y, pi v\ (q y v)) are the same formula [MN p. 36–37]. The typing rules
of the quantifiers (Figure 2.1, [MN p. 38]) extend those of terms:
with the proviso, for the first two, that is not typed by or ; the third rule renames bound variables so that the proviso can be met. A first-order -formula is an with ; such formulas are closed [MN p. 38].
2.5The search semantics of goals#
A logic programming language is fixed by four ingredients [MN p. 38]: signatures, program clauses, goals, and a calculus for building proofs. A sequent has a set of -formulas as its program, and it states the judgment “ is provable from and ”.
Definition 2.7 (Search semantics of the logical symbols [MN p. 39]). Read as steps of an interpreter:
- and reduce to both and ;
- or reduce to either or ;
- instan reduce to for some -term of type ;
- augment reduce to ;
- generic reduce to , where is a new constant, not in ;
- true is provable at once.
None of these looks at . Read downwards, they are the right-introduction rules of a sequent calculus, the book’s Figure 2.2 [MN p. 40]:
( not declared in in ). Each rule is sound in “any interesting logic”. The question is completeness [MN p. 41]: if a sequent with a non-atomic goal is provable, must the premise(s) of the corresponding rule be provable too? The answer depends on which formulas are allowed and on the logic.
Example 2.8 (Why goal-directedness can fail [MN p. 41–42]). Let .
- is provable, but or leaves or , and neither is provable. A disjunction in the program breaks goal-directed search.
- is a classical tautology (excluded middle), but or leaves , unprovable, or , which augment reduces to the unprovable .
- is classically provable by cases on , but every choice of witness leaves an unprovable sequent.
The book concludes [MN p. 42] that programs must not contain disjunctions (they must be definite, “because they do not contain indefinite information”), and that the logic should be intuitionistic, where excluded middle does not hold. Counterexamples 2 and 3 need in the goal, which Horn clauses forbid; the switch of logic pays off only from Chapter 3 on.
Atomic goals need rules that look at the program; the general framework leaves them open on purpose [MN p. 42]. When the search succeeds, the system reports an answer substitution: the free variables of a query are read as existentially quantified at its head, and the answer maps them to terms that make the computation succeed [MN p. 42–43].
2.6Horn clauses and backchaining#
Definition 2.9 (fohc [MN p. 43]). With ranging over atomic formulas, the goals and program clauses of first-order Horn clauses (fohc) are
Only and are missing at the top of goals, and only and at the top of clauses. The family contains the familiar Prolog shape , but is more liberal: the head may sit under further implications, conjunctions and universals [MN p. 43–44].
Backchaining is first explained informally [MN p. 44]: if contains , succeed; if it contains , reduce the goal to . Formally it uses a focused sequent , “try to prove the atom by backchaining on ”. The rules of the book’s Figure 2.3 [MN p. 45] are
decide picks a clause; initial closes the branch when the focused atom is identical to the goal; proves the body and continues on ; picks a conjunct; instantiates. The formula over the arrow is on the left of the sequent, in focus, so these are left-introduction rules complementing Figure 2.2. For a Prolog-shaped clause the rules compose into one step [MN p. 45]:
where maps each to a -term of its type and : the instance follows from , and modus ponens gives . This grouping of small rules into large ones is a first instance of Andreoli’s focusing Jean-Marc Andreoli. Logic programming with focusing proofs in linear logic. Journal of Logic and Computation, 2(3):297–347, 1992, which the book cites as the general setting [MN p. 73].
Definition 2.10 (O-proof [MN p. 45]). An O-proof is a proof built with the rules of the book’s Figures 1.2, 2.2 and 2.3.
Theorem 2.11 (Completeness of goal-directed search for fohc [MN p. 45]). If is an fohc program and an fohc goal, then has an O-proof iff it is provable in classical logic iff it is provable in intuitionistic logic.
Proposition 2.12 (Flatness [MN p. 46]). Every sequent in an O-proof of has the form or , with the same and .
So in fohc the program and signature are flat and global, and augment and generic never fire. These two rules are exactly what Chapter 3 adds. The book’s term for a logic in which this kind of goal-directed (“uniform”) search is complete is abstract logic programming language 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; and Dale Miller and Gopalan Nadathur. Programming with Higher-Order Logic. Cambridge University Press, Cambridge, 2012 [MN p. 73]; fohc is the base case.
Tutorial (An O-proof for a query with two answers). Take the program of append (Section 2.7), with
and , and the goal . Instead of guessing terms in and we use logic variables and let
initial unify (this is the practical version of the rules, Section 2.9).
- twice: logic variables ; goal , atomic.
- decide ; with a new ; initial unifies with the goal: , , . First answer: , .
- Back to step 2, decide instead. four times with new , then splits into a focused premise and a goal premise. initial on the focused premise unifies with the goal: , , , . The goal premise is now .
- For : decide succeeds with , . Second answer: , . decide fails: its head needs the third argument to be , which clashes with .
The O-proof for the second answer, with the unifier already applied. Write for and for :
Every sequent in it has the same and , as Proposition 2.12 promises.
2.7λProlog concrete syntax and interaction#
In program clauses, an unbound token beginning with an uppercase letter is a variable universally
quantified over the whole clause; _ is an anonymous variable, each occurrence distinct [MN p. 46–47].
So [MN p. 47]
type append list A -> list A -> list A -> o.
append nil L L.
append (X :: L1) L2 (X :: L3) :- append L1 L2 L3.abbreviates pi L\ append nil L L. and
pi X\ pi L1\ pi L2\ pi L3\ append (X :: L1) L2 (X :: L3) :- append L1 L2 L3.; the types of the
variables are inferred (X : A, the lists list A). Anonymous variables save names for values
that are never used again [MN p. 47]:
type sublist list A -> list A -> o.
sublist L K :- append _ T K, append L _ T.is the same clause as sublist L K :- append U T K, append L V T.: is a sublist of if
has a suffix of which is a prefix.
Equivalent groupings of clauses. Because the D-grammar allows and to nest, one
predicate can be written in several equivalent ways [MN p. 48–49]. With
kind bool type., constructors neg, and, or, imp and type ident bool -> bool -> o.,
the four clauses of Form 1 can be compressed into a single clause, Form 3:
ident (neg B) (neg D) :- ident B D.
ident (and B C) (and D E) :- ident B D, ident C E.
ident (or B C) (or D E) :- ident B D, ident C E.
ident (imp B C) (imp D E) :- ident B D, ident C E.ident (neg B) (neg D) &
(ident (and B C) (and D E) &
ident (or B C) (or D E) &
ident (imp B C) (imp D E) :- ident C E) :- ident B D.How does Form 3 parse and run? Since & binds more tightly than :-, it is the single D-formula
(universally closed), where stands for the goal ident B D, for
ident C E, and for the four heads. It is legal because the D-grammar allows
and to nest. To solve an atom ident (and B0 C0) X, decide picks this
clause, instantiates its variables, sets the body ident B D aside as a goal
premise and keeps backchaining on the conjunction, chooses the right conjunct, sets
ident C E aside, chooses , and initial unifies it with the goal.
The two goals set aside are exactly the body of the second clause of Form 1. The book claims that the
forms are equivalent in derivable goals and in observable behaviour, and that a smart implementation
preprocesses Form 3 into Form 1 [MN p. 49].Figure 2.3 does not say in which order the two
premises of are explored; for the behaviour to match Form 1, whose body is
ident B D, ident C E, the outer premise must be solved first. This remark is ours. (As printed, ident has no base case,
so it proves no closed goal; the example is about clause structure only.)
The read–prove–print loop. Programs live in modules (Section 5.10). Teyjus compiles a
module with tjcc, links it with tjlink and runs it with tjsim, which shows the
prompt [lists] ?- [MN p. 281–282]. In queries the convention for variables is dual: an
uppercase token is existentially quantified, with outermost scope [MN p. 50]. The prove phase looks
for an O-proof, with three possible outcomes: a proof, no proof, or non-termination. Non-termination cannot
be ruled out by any interpreter, because provability in fohc is undecidable [MN p. 51]. The print phase
shows the bindings of the named query variables only [MN p. 51–53]:
[lists] ?- append (1::nil) (2::nil) (3::nil).
no
[lists] ?- append (1::nil) (2::nil) (1::2::nil).
solved
[lists] ?- append (1::nil) (2::nil) X.
X = (1::2::nil)
[lists] ?- append X Y (1::nil).
X = nil
Y = 1::nil;
X = 1::nil
Y = nil;
noTyping ; asks for another proof. The queries sigma X\ append (1::nil) (2::nil) X and
append (1::nil) (2::nil) _ attempt the same sequent as the third query, but print just
solved: sigma-bound and anonymous variables are not shown [MN p. 51–52].
Kanren angle (The same session in (aux kanren micro)). A fohc predicate becomes a define-relation whose body is a cond° with one line per clause:
fresh° for the clause variables, =° for head unification, then the body goals. File
append.scm:
;; append nil L L.
;; append (X :: L1) L2 (X :: L3) :- append L1 L2 L3.
(define-relation (append° l k m)
(cond° ((=° l '()) (=° k m))
((fresh° (x l1 l3)
(=° l (cons x l1)) (=° m (cons x l3))
(append° l1 k l3)))))
(μkanren-run (q -1 #t) (append° '(1) '(2) '(3)))
(μkanren-run (q -1 #t) (append° '(1) '(2) '(1 2)))
(μkanren-run (q -1 #t) (append° '(1) '(2) q))
(μkanren-run (q -1 #t) (fresh° (x y) (=° q (list x y)) (append° x y '(1))))append (1) (2) (3) => ()
append (1) (2) (1 2) => (α)
append (1) (2) X => ((1 2))
append X Y (1) => ((() (1)) ((1) ()))() is no. The answer (α) is solved: one proof, with the query variable left
unconstrained. The run argument -1 asks for all answers, what typing ; repeatedly does in
Teyjus. The variables of an inner fresh° are hidden like sigma-bound ones.
2.8Core examples#
The book illustrates three programming styles [MN p. 53–59]: search problems, relations over recursive data, and relations over abstract syntax.
2.8.1Search: finite-state machines#
The book’s Figure 2.4 [MN p. 54] describes acceptance by a finite-state machine whose arcs are labelled by words:
kind state, letter type.
type q1, q2, q3, q4, q5 state.
type a, b letter.
type start, final state -> o.
type path, trans state -> list letter -> state -> o.
type accept list letter -> o.
path S nil S.
path S Letters T :- trans S Arc M, append Arc Rest Letters,
path M Rest T.
accept W :- start S, path S W F, final F.The goal append Arc Rest Letters consumes the arc’s word as a prefix of the input. Figure 2.5 is a
nondeterministic machine for , the words ending in or :
start q1 & final q2 & final q3.
trans q1 (a::nil) q1 & trans q1 (b::nil) q1.
trans q1 (a::b::nil) q2 & trans q1 (b::a::nil) q3.To enumerate accepted words, the book first generates lists of increasing length [MN p. 55]:
type lists list A -> o.
lists nil.
lists (_::L) :- lists L.and reports [MN p. 55–56]
[fsm1] ?- accept (b::b::a::b::nil).
solved
[fsm1] ?- accept (b::a::X::Y::nil).
X = a
Y = b ;
X = b
Y = a ;
no
[fsm1] ?- lists L.
L = nil ;
L = T1 :: nil ;
L = T1 :: T2 :: nil ;
L = T1 :: T2 :: T3 :: nil
[fsm1] ?- lists L, accept L.
L = a :: b :: nil ;
L = b :: a :: nil ;
L = a :: a :: b :: nil ;
L = a :: b :: a :: nil ;
L = b :: a :: b :: nilOf the last two queries the book notes that “both these queries have an unbounded number of successful
proofs”; a depth-first engine “will systematically produce lists of increasing length” [MN p. 55–56].
Note the answer L = T1 :: nil: an answer substitution may contain variables, and then every instance
of it is an answer. Why is the generator needed? Under
depth-first search, accept W with W unbound tries the first trans clause
trans q1 (a::nil) q1 first; append then binds W = a :: Rest, and path q1 Rest F is
in the same situation again, forever. No answer is ever printed. lists L breaks the loop by giving
accept lists of fixed length, one length at a time.
Pitfall (An erratum in Figure 2.6). The book also gives a deterministic five-state machine (Figure 2.6, [MN p. 54]), printed as
start q1 & final q4 & final q5.
trans q1 (a::nil) q2 & trans q1 (b::nil) q3.
trans q2 (a::nil) q1 & trans q2 (b::nil) q4.
trans q3 (a::nil) q5 & trans q3 (b::nil) q1.
trans q4 (a::nil) q5 & trans q4 (b::nil) q3.
trans q5 (a::nil) q2 & trans q5 (b::nil) q4.and says that exactly the same behaviour would be observed with it [MN p. 56]. As printed it does not
accept the stated language: the
clauses trans q2 (a::nil) q1 and trans q3 (b::nil) q1 send the machine back to the start, so it
rejects aab, bba, and so on. Replacing them by trans q2 (a::nil) q2 and
trans q3 (b::nil) q3 fixes it. A brute-force comparison with the regular expression on all words of
length up to 8 confirms both the defect and the fix.
2.8.2Recursive data: insertion into a search tree#
Relations over recursive data follow the structure of the data [MN p. 57]:
type insert int -> btree int -> btree int -> o.
insert X empty (node X empty empty).
insert X (node A L R) (node A NL R) :- X < A, insert X L NL.
insert X (node A L R) (node A L NR) :- X >= A, insert X R NR.[btree] ?- insert 4 (node 3 (node 2 empty empty) empty) T.
T = node 3 (node 2 empty empty) (node 4 empty empty)The comparisons < and >= are built-ins “correctly used only when both arguments are
instantiated to numbers” [MN p. 49], so insert is well defined only when its first two arguments are
closed terms [MN p. 57]. This is a mode restriction: the relation is not usable in every direction.
2.8.3Abstract syntax: a sequent prover#
The third style uses fohc to animate an inference system. The book encodes a classical propositional sequent calculus with multisets on both sides (Figure 2.7, [MN p. 58]), over the formulas of Section 2.2.3:
Several formulas on the right make the calculus classical. Here are schema variables of the object calculus, not logic variables of λProlog. Multisets are lists, and a rule matches “” by selecting and keeping the rest:
type memb_and_rest A -> list A -> list A -> o.
memb_and_rest X (X :: L) L.
memb_and_rest X (Y :: L) (Y :: L1) :- memb_and_rest X L L1.The translation recipe is mechanical [MN p. 59]: a rule’s conclusion becomes the head of a clause, its premises become the body, and the schema variables become clause variables. The eight clauses, one per rule in the order , initial, , , , , , , as printed:
type prv list form -> list form -> o.
prv Gamma Delta :- memb_and_rest ff Gamma _.
prv Gamma Delta :- memb_and_rest A Gamma _,
memb_and_rest A Delta _.
prv Gamma Delta :-
memb_and_rest (A && B) Gamma Gamma',
prv (A :: B :: Gamma') Delta.
prv Gamma Delta :-
memb_and_rest (A !! B) Gamma Gamma',
prv (A :: Gamma') Delta, prv (B :: Gamma') Delta.
prv Gamma Delta :-
memb_and_rest (A ==> B) Gamma Gamma',
prv Gamma' (A :: Delta), prv (B :: Gamma') Delta.
prv Gamma Delta :-
memb_and_rest (A && B) Delta Delta',
prv Gamma (A :: Delta'), prv Gamma (B :: Delta').
prv Gamma Delta :-
memb_and_rest (A !! B) Delta Delta',
prv Gamma (A :: B :: Delta').
prv Gamma Delta :-
memb_and_rest (A ==> B) Delta Delta',
prv (A :: Delta) (B :: Gamma').Read the clause against its rule: the conclusion becomes the
head prv Gamma Delta together with the selection memb_and_rest (A !! B) Gamma Gamma' (so the
clause’s Gamma' is the rule’s ), and the two premises become the two body goals. The
initial clause needs no selection of the rest: it only asks that some be on both sides.
[logic] ?- prv nil (((p a b) !! ((p a b) ==> (q a a))) :: nil).
solvedNote the level shift. This is , the formula that Example 2.8 showed
goal-directed search cannot prove (it is not even an fohc goal, since it contains ). Here it is
object-level data, proved by an object-level classical calculus that is programmed in
fohc: the search proves the meta-level atom prv nil (...), by and then and
initial on p a b.
Pitfall (An erratum in the last prv clause). The clause for is printed [MN p. 59] with the body prv (A :: Delta) (B :: Gamma'). It should be
prv (A :: Gamma) (B :: Delta'). As printed, Gamma' is a singleton variable, the right-hand side
becomes an open list, and the initial clause can unify a hypothesis into that open tail. The printed
program then “proves” , which is not valid. A (aux kanren micro) port of the printed clause
confirms it: with the printed clause, the query below for (p a b) ==> (q a a) returns (α)
instead of () (file prv-printed.scm).
Kanren angle (The prover in (aux kanren micro)). The port keeps the clause-per-line shape (file prv.scm, last clause corrected). Formulas are
lists such as (!! A B):
(define-relation (memb-and-rest° x l r)
(cond° ((=° l (cons x r)))
((fresh° (y l1 r1)
(=° l (cons y l1)) (=° r (cons y r1)) (memb-and-rest° x l1 r1)))))
(define-relation (prv° Γ Δ)
(cond°
((fresh° (_) (memb-and-rest° 'ff Γ _))) ; ⊥L
((fresh° (a _1 _2) (memb-and-rest° a Γ _1) (memb-and-rest° a Δ _2))) ; initial
((fresh° (a b Γ*) (memb-and-rest° `(&& ,a ,b) Γ Γ*) ; ∧L
(prv° `(,a ,b . ,Γ*) Δ)))
((fresh° (a b Γ*) (memb-and-rest° `(!! ,a ,b) Γ Γ*) ; ∨L
(prv° (cons a Γ*) Δ) (prv° (cons b Γ*) Δ)))
((fresh° (a b Γ*) (memb-and-rest° `(==> ,a ,b) Γ Γ*) ; ⊃L
(prv° Γ* (cons a Δ)) (prv° (cons b Γ*) Δ)))
((fresh° (a b Δ*) (memb-and-rest° `(&& ,a ,b) Δ Δ*) ; ∧R
(prv° Γ (cons a Δ*)) (prv° Γ (cons b Δ*))))
((fresh° (a b Δ*) (memb-and-rest° `(!! ,a ,b) Δ Δ*) ; ∨R
(prv° Γ `(,a ,b . ,Δ*))))
((fresh° (a b Δ*) (memb-and-rest° `(==> ,a ,b) Δ Δ*) ; ⊃R
(prv° (cons a Γ) (cons b Δ*))))))
(define pab '(p a b))
(define qaa '(q a a))
(μkanren-run (q 1 #t) (prv° '() `((!! ,pab (==> ,pab ,qaa)))))
(μkanren-run (q 1 #t) (prv° '() `((==> ,pab ,qaa))))prv nil (p a b !! (p a b ==> q a a)) => (α)
prv nil (p a b ==> q a a) => ()2.9Pragmatics of the search#
The rules of Section 2.5 and Section 2.6 are nondeterministic. λProlog resolves the choices with a “simple and rigid search strategy” so that a programmer can predict behaviour and resource usage [MN p. 60]:
- for and , the left subformula is tried before the right one;
- for , the left premise is derived first;
- for decide, is a list, not a set: clauses are tried in textual order, and order and multiplicity matter;
- the terms of and are not enumerated (most types are infinite) but replaced by logic variables, instantiated by unification [MN p. 61].
The price is incompleteness: “there may be sequents that have derivations but for which no
derivations will be found because of the strategy. In fact, the chosen strategy even can cause indefinite
looping when a more flexible search strategy might be able to find a proof” [MN p. 60]. Since the strategy
is known, programs can usually be restructured, as lists L did for accept.
With a logic variable that is new in the search, the quantifier rules and initial become [MN p. 61]
where the unifier must be “percolated all over the derivation that has been constructed thus far”, and typed unification guarantees that the delayed typing premises hold. Finally the program can be precompiled [MN p. 61–62]: applying and in advance turns it into a list of clauses , which are then partitioned by predicate name, compiled, and indexed on their arguments, as in the Warren Abstract Machine.
Cut, negation as failure, arithmetic. Book Chapter 2 has no pruning operator; it only
stresses that the cut rule “has no connection to Prolog’s pruning operator !” [MN p. 63]. Teyjus
provides !, fail and not as metalogical predicates, with the warning that
“negation-by-failure has a problematic semantics in a situation where implicational goals are used in an
essential way” [MN p. 287]. The book later defines [MN p. 137]
type not o -> o.
not P :- P, !, fail.
not P.and shows how far this is from logic: ?- X = 2, not (1 = X). succeeds, whereas
?- not (1 = X), X = 2. fails, so “even a basic property such as commutativity of conjunctions becomes
invalid” [MN p. 137–138] (Chapter 5). Arithmetic is intensional: 2 + 3 is a term, so the goal
(2 + 3 = 5) fails [MN p. 66], and only the non-logical predicate is evaluates
[MN p. 67, 286]. The comparisons used by insert are of the same non-logical kind.
2.10Logical notions: cut and presentations of fohc#
Theorem 2.11 gives fohc the duality the book wants: solving a goal means both “it follows logically” and “a certain derivation exists” [MN p. 62]. The cut rule [MN p. 63] is
It uses a lemma . Choosing lemmas takes ingenuity, so cut is not used to compute, but it is used to reason about computation. Cut elimination says that adding cut to classical or intuitionistic logic does not change the derivable sequents, and the completeness of O-proofs means that an adapted cut is admissible for them. Consequence: replacing a subformula of a program by a logically equivalent one gives a program that proves the same goals, “in the sense of O-provability, although maybe not under a depth-first search strategy” [MN p. 63].
This licenses three equivalent presentations of fohc clauses [MN p. 63–64]: the liberal one of Definition 2.9; the common Prolog one, , ; and a compact one, . A clause of one presentation is equivalent to a set of clauses of another through equivalences such as
together with distributivity of and and the others listed on [MN p. 64].
Example 2.13 (Size and behaviour [MN p. 64–66]). In the common presentation, must become four clauses
which duplicates , exponentially in general. It also changes behaviour: with the original clause is derived at most once per use, with the four clauses it is derived again for each clause that mentions it. Introducing new predicates for and instead,
grows the program only linearly. This is not a logical equivalence (there are new constants), but it is conservative: for every goal over the original signature , is provable iff is.
2.11The role of types#
Types classify expressions. In the first-order setting the only distinction types
force is between propositions (o) and everything else [MN p. 66]. Equality is syntactic: “two
closed expressions are equal only if they are exactly the same”, so 2 + 3, 3 + 2 and 5
are different elements of int, and o is a set of formulas, not of truth values
[MN p. 66–67].
Polymorphism, transparency, determinacy. The declaration type nil list A. is read as
: nil has many types [MN p. 67].
Definition 2.14 (Transparent, determinate [MN p. 67–68]). For an order-1 type , a type variable occurring in is transparent; the type is determinate if all its type variables are transparent.
Knowing the target type of a determinate constructor fixes the types of its arguments: all elements of a
list A have the same type. The constructor type cons A -> lst -> lst. is not determinate and
builds heterogeneous lists [MN p. 68].
Checking and inference. λProlog is strongly typed: types of constants are declared, types of
variables are inferred most generally, and checking is static [MN p. 68–69]. The asymmetry of
Section 2.2 returns: append (1::nil) (2::nil) X, append ("abc"::nil) ("efg"::nil) Y. is well
typed, with the two append occurrences at different instances, but replacing Y by X makes it
ill typed, since a variable has one type [MN p. 68].
Types at run time. With polymorphism and non-determinate constructors, types cannot always be
compiled away [MN p. 69]. The book’s Figure 2.8 builds heterogeneous lists with the non-determinate
cons and dispatches on the run-time type of their elements [MN p. 70]:
kind lst type.
type null lst.
type cons A -> lst -> lst.
type separate lst -> list int -> list real -> o.
separate (cons (X:int) L) (X::K) M :- separate L K M.
separate (cons (X:real) L) K (X::M) :- separate L K M.
separate null nil nil.The annotation (X:int) must be matched, during the search, against the type of the head element of
the incoming list: this is run-time type processing. Figure 2.9 achieves the same with
injections, so that the dispatch is on terms [MN p. 70]:
kind numb type.
type inj_int int -> numb.
type inj_real real -> numb.
type separate list numb -> list int -> list real -> o.
separate ((inj_int X)::L) (X::K) M :- separate L K M.
separate ((inj_real X)::L) K (X::M) :- separate L K M.
separate nil nil nil.The book recommends determinate constructors and injections [MN p. 71–72]: static typing then catches more
errors, and less type information has to be carried during proof search. Giving constants the type A
would make nonsense well typed. The book poses the queries
separate (cons 1.0 (cons 2 (cons 3.0 null))) L K
separate ((inj_real 1.0)::(inj_int 2)::(inj_real 3.0)::nil) L Kto the two figures and says that both bind “K to (2 :: nil) and L to (1.0 :: 3.0 :: nil)” [MN p. 70].
That swaps the answers: the second argument collects the integers, so L = (2 :: nil) and
K = (1.0 :: 3.0 :: nil). The (aux kanren micro) port below confirms it.
Kanren angle (Types and (aux kanren micro)). (aux kanren micro) has one universe of Scheme data. The book observes that in the first-order setting the only
distinction types force is between o and the rest, so all other sorts could be collapsed into
one [MN p. 66]; (aux kanren micro) is that collapsed case. What the collapse gives up is static error detection,
typed unification (U7 above) and the run-time dispatch of Figure 2.8. Injections (Figure 2.9) are ordinary
miniKanren style, tagged lists such as (inj_int 2), and port clause by clause (file
separate.scm):
(define-relation (separate° ns is rs)
(cond° ((fresh° (x l k) (=° ns `((inj_int ,x) . ,l)) (=° is (cons x k)) (separate° l k rs)))
((fresh° (x l m) (=° ns `((inj_real ,x) . ,l)) (=° rs (cons x m)) (separate° l is m)))
((=° ns '()) (=° is '()) (=° rs '()))))
(μkanren-run (q -1 #t)
(fresh° (l k) (=° q (list l k))
(separate° '((inj_real 1.0) (inj_int 2) (inj_real 3.0)) l k)))separate (...) L K => (((2) (1.0 3.0)))The answer is the pair : the integers first, as the types demand. Where a type layer could live (a static
checker written as a relation over declared signatures, since type unification is just =° on type
terms) is left open: the proposal stays untyped (Section 14.2.2); simple types are a later
work item (Section 14.5.6).
2.12From fohc to (aux kanren micro)#
We can now state precisely how fohc maps onto (aux kanren micro) (described in Chapter 10):
| fohc (book) | (aux kanren micro) | remark |
|---|---|---|
, true () | ✓° | |
, , () | (and° g1 g2) | bind interleaves answers |
, ; () | (or° g1 g2), cond° | interleaving, not left first |
, sigma (, logic variable) | (fresh° (x) g) | exactly the rule of [MN p. 61] |
| atomic goal, decide | call (p° t ...) | clause choice compiled into the relation |
| clauses of , | define-relation with one cond° line per clause | precompiled and indexed by name, [MN p. 61–62] |
| with logic variable | fresh° opening each line | renaming apart is automatic |
| initial with unification | =° against the clause head | the threaded substitution percolates |
| occurs check | built in | as the book requires, [MN p. 32] |
| answer substitution | reified answer, α, β, … | up to renaming |
| typed unification | none | see U7 |
<, >=, is | project° + Scheme | non-logical, moded |
! (pruning) | no hard cut; soft cut if°, take° | control, not logic |
not | (if° g ✗° ✓°) | same unsoundness |
| (augment), (generic) | absent | not needed in fohc; Chapter 3 |
So pure miniKanren is fohc, with two caveats. First, the shape of a relation (one disjunction of
existentially quantified equations per predicate) is the precompiled form of [MN p. 61–62], and the
built-in =° is definable in fohc by the single clause .
Second, a Scheme-hosted miniKanren is strictly larger than fohc: goals are first-class Scheme
values, and project° leaves the logic altogether. The fohc fragment is a discipline, not something
the host enforces.
Kanren angle (The FSM, side by side with its λProlog original). File fsm.scm ports Figures 2.4 and 2.5 clause by clause (append° as above):
;; Figure 2.4
(define-relation (path° s letters t)
(cond° ((=° letters '()) (=° s t))
((fresh° (arc m rest)
(trans° s arc m) (append° arc rest letters) (path° m rest t)))))
(define-relation (accept° w)
(fresh° (s f) (start° s) (path° s w f) (final° f)))
;; Figure 2.5
(define-relation (start° s) (=° s 'q1))
(define-relation (final° s) (cond° ((=° s 'q2)) ((=° s 'q3))))
(define-relation (trans° s arc t)
(cond° ((=° (list s arc t) '(q1 (a) q1)))
((=° (list s arc t) '(q1 (b) q1)))
((=° (list s arc t) '(q1 (a b) q2)))
((=° (list s arc t) '(q1 (b a) q3)))))
(define-relation (lists° l)
(cond° ((=° l '())) ((fresh° (h t) (=° l (cons h t)) (lists° t)))))
(μkanren-run (q -1 #t) (accept° '(b b a b)))
(μkanren-run (q -1 #t) (fresh° (x y) (=° q (list x y)) (accept° `(b a ,x ,y))))
(μkanren-run (q 4 #t) (lists° q))
(μkanren-run (q 5 #t) (lists° q) (accept° q))
(μkanren-run (q 5 #t) (accept° q))accept (b b a b) => (α)
accept (b a X Y) => ((a b) (b a))
lists L (4) => (() (α) (α β) (α β γ))
lists L, accept L (5) => ((a b) (b a) (a a b) (a b a) (b a b))
accept L (5) => ((a b) (b a) (a a b) (a b a) (b a b))The first four lines agree with the book (lists L gives nil, T1 :: nil, …). The last
line is the interesting one: (accept° q) without the generator produces answers, where
depth-first search loops on the -arc. The order happens to coincide with the book’s here; in general
one should not expect (aux kanren micro) to reproduce λProlog’s answer order.
2.12.1Depth-first search versus interleaving#
λProlog commits to the depth-first, left-to-right, clause-order strategy of Section 2.9.
Teyjus compiles it to an abstract machine [MN p. 277]. (aux kanren micro) keeps the same goals but changes the
strategy, as μKanren does Jason Hemann and Daniel P. Friedman. Kanren: A minimal functional core for relational programming. In Proceedings of the 2013 Workshop on Scheme and Functional Programming (Scheme ’13), 2013: or° interleaves its two answer streams, switching
on each suspension, and a relation call suspends. A clause that recurses forever therefore gets only a
share of the search, and the remaining clauses still run. That is why (accept° q) terminates
answer by answer.
What does this buy, logically? Theorem 2.11 is a statement about the proof system: O-proofs exist
whenever proofs exist. A search strategy is complete if it finds a proof whenever one exists, and, for answers, if
every answer substitution of an O-proof is eventually produced (up to instantiation). Depth-first search
is not [MN p. 60]. For miniKanren’s interleaving search, Rozplokhas, Vyatkin and
Boulytchev Dmitry Rozplokhas, Andrey Vyatkin, and Dmitry Boulytchev. Certified semantics for relational programming. In Programming Languages and Systems (APLAS 2020), volume 12470 of LNCS, pages 167–185. Springer, 2020 proved soundness and completeness with respect to a
denotational semantics: every answer is eventually produced. (aux kanren micro)’s particular interleaving has not
been checked against the hypotheses of that proof, so read it as a strong expectation for (aux kanren micro), not a
theorem about it. Interleaving is fair for disjunction only. Termination is not
promised: a query with no answers, or the rest of a query after its last answer, can still diverge,
which is unavoidable since fohc provability is undecidable [MN p. 51]. Conjunction remains
order-sensitive. For example
(μkanren-run (q 1 #t) (lists° q) (=° q 'not-a-list))never returns: lists° offers infinitely many lists, and each is rejected by the second conjunct. We
ran it with a 10-second timeout, and it produced no output. With the conjuncts swapped it fails at once.
Pitfall (Answer order is not part of the logic). The book stresses that programs are lists, so the order and multiplicity of clauses are observable under
depth-first search [MN p. 60], and logically equivalent transformations can change the number of
derivations (Example 2.13). Under interleaving the same holds, with a different order. A port of a
book example to (aux kanren micro) should compare answer sets, unless the order has been checked.
Kanren angle (Negation as failure and moded built-ins in (aux kanren micro)). (aux kanren micro) has a soft cut, (if° g? gt gf): if g? has answers, all of them continue with gt,
otherwise gf runs. With it, not is one line, and the book’s commutativity failure [MN p. 137–138]
reproduces exactly (file naf.scm). For contrast, the last two lines use the disequality constraint
≠°, which is not part of fohc (Chapter 10) but is commutative:
(define (not° g) (if° g ✗° ✓°))
(μkanren-run (q -1 #t) (=° q 2) (not° (=° 1 q)))
(μkanren-run (q -1 #t) (not° (=° 1 q)) (=° q 2))
(μkanren-run (q -1 #t) (=° q 2) (≠° 1 q))
(μkanren-run (q -1 #t) (≠° 1 q) (=° q 2))X = 2, not (1 = X) => (2)
not (1 = X), X = 2 => ()
X = 2, X =/= 1 => (2)
X =/= 1, X = 2 => (2)Moded built-ins behave as in λProlog. The port of insert guards with project°, which hands the
current values to Scheme (file insert.scm):
(define-relation (insert° x t t*)
(cond° ((=° t 'empty) (=° t* `(node ,x empty empty)))
((fresh° (a l r nl)
(=° t `(node ,a ,l ,r)) (=° t* `(node ,a ,nl ,r))
(project° ((x° x) (a° a)) (if (< x° a°) ✓° ✗°))
(insert° x l nl)))
((fresh° (a l r nr)
(=° t `(node ,a ,l ,r)) (=° t* `(node ,a ,l ,nr))
(project° ((x° x) (a° a)) (if (>= x° a°) ✓° ✗°))
(insert° x r nr)))))
(μkanren-run (q -1 #t) (insert° 4 '(node 3 (node 2 empty empty) empty) q))
(μkanren-run (q -1 #t) (fresh° (x) (insert° x '(node 3 empty empty) q))) ; mode brokeninsert 4 (node 3 (node 2 empty empty) empty) T => ((node 3 (node 2 empty empty) (node 4 empty empty)))
insert X (node 3 empty empty) T =>
Error: (<) bad argument type - not a number: _1The second query breaks the mode: Scheme’s < receives the unbound logic variable _1 and the run
aborts with the error shown (printed on standard error). Likewise intensional
arithmetic (file arith.scm):
(μkanren-run (q -1 #t) (=° '(+ 2 3) 5))
(μkanren-run (q -1 #t) (=° q '(+ 2 3)))
(μkanren-run (q -1 #t)
(fresh° (e) (=° e '(+ 2 3)) (project° ((e* e)) (=° q (apply + (cdr e*))))))2 + 3 = 5 => ()
X = 2 + 3 => ((+ 2 3))
X is 2 + 3 => (5)Kanren angle (What fohc does not need, and later chapters will). By Proposition 2.12, nothing in this chapter needs the program or the signature to change during
the search, so (aux kanren micro) can keep relations as closed Scheme procedures and needs no signature object.
Chapter 3 adds augment (clauses that are visible only along one branch of the search) and
generic (fresh constants, together with a scoping check in unification that the occurs-check
discussion of [MN p. 32] anticipates). Chapter 4 and Chapter 7 add -terms as data. The
corresponding requirements on (aux kanren micro) are collected in Chapter 11.
2.13Summary#
- Logic programming is computation as proof search: the state is a sequent , computing means looking for a cut-free proof, and cut is used to reason about programs, not to run them [MN p. 3, 63].
- Data are typed first-order terms. Kinds are arities. Each occurrence of a polymorphic constant takes its own instance of the type, but a variable has one type. Principal types exist. First-order encodings of syntax do not capture binding [MN p. 10–25].
- First-order unification is a terminating transformation system on multisets of equations. It computes mgu’s, unique up to renaming. The occurs check is mandatory in the book. Types matter only when two heads have the same name, and they can be erased for parametric signatures [MN p. 26–32].
- Connectives in goals have a fixed search semantics, the right rules (and, or, instan, augment, generic, true); atoms are solved by backchaining, the focused left rules decide, initial, , , [MN p. 39–45].
- In fohc (; ) O-proofs are complete for classical and intuitionistic logic, and the program and signature never change during the search [MN p. 43–46].
- λProlog fixes depth-first, left-to-right, clause-order search with logic variables and
unification. It is predictable but incomplete.
!,not,isand comparisons are non-logical [MN p. 60–62, 137, 286]. - Logically equivalent presentations of clauses prove the same goals but may differ in size and in the number of derivations; introducing predicates is conservative [MN p. 63–66].
- Types classify expressions, not values; equality is syntactic. Determinate constructors and injections are preferred to run-time type dispatch [MN p. 66–72].
- Pure miniKanren is fohc, without types and with an interleaving search. The interleaving search
finds answers that depth-first search misses (
(accept° q)), but conjunction order still decides termination.(aux kanren micro)reproduces the book’s examples and its warnings (ill-typed unifier, non-commutativenot, moded built-ins).