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 λ\lambda-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 λ\lambda-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 BB, state a lemma CC, then prove CC and prove BB from CC. 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

Σ;𝒫⟶G \Sigma;\mathcal{P}\longrightarrow G

where Σ\Sigma is a signature (the typed non-logical constants available), 𝒫\mathcal{P} is the program and GG is the goal. The Introduction states the principle that drives the whole book [MN p. 3–4]:

  • if GG 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 GG is atomic, the program is consulted. The search backchains: it looks in 𝒫\mathcal{P} 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 Σ;𝒫⟶A\Sigma;\mathcal{P}\longrightarrow A leads to proving Σ′;𝒫′⟶A′\Sigma';\mathcal{P}'\longrightarrow A', what can differ between the two? For Horn clauses, Σ′=Σ\Sigma'=\Sigma and 𝒫′=𝒫\mathcal{P}'=\mathcal{P}: signature and program are global and fixed, and only the atom changes. For hereditary Harrop formulas, Σ′⊇Σ\Sigma'\supseteq\Sigma and 𝒫′⊇𝒫\mathcal{P}'\supseteq\mathcal{P}: 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 λ\lambda-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:

⟨kind⟩::=𝗍𝗒𝗉𝖾∣𝗍𝗒𝗉𝖾→⟨kind⟩. \langle\text{kind}\rangle ::= \mathsf{type} \mid \mathsf{type}\to\langle\text{kind}\rangle .

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 τ1→τ2\tau_1\to\tau_2 (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 τ=τ1→⋯→τn→τ0\tau=\tau_1\to\cdots\to\tau_n\to\tau_0 with τ0\tau_0 not an arrow. τ0\tau_0 is the target type and τ1,…,τn\tau_1,\dots,\tau_n are the argument types; τ\tau is functional when n≥1n\ge1. The order of a type is

ord⁡(τ)=0 if τ is not functional,ord⁡(τ1→τ2)=max⁡(ord⁡(τ1)+1, ord⁡(τ2)). \begin{gathered} \operatorname{ord}(\tau)=0 \text{ if $\tau$ is not functional},\\ \operatorname{ord}(\tau_1\to\tau_2)=\max(\operatorname{ord}(\tau_1)+1,\ \operatorname{ord}(\tau_2)). \end{gathered}

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) :: nil the first two nils have type list int and the last one has type list (list int);
  • a variable has one type at all its occurrences. So ((X :: nil) :: X :: nil) cannot be typed, because XX would need both a type τ\tau and the type list τ\tau.

The rules are those of the type assignment calculus of the book’s Figure 1.2 [MN p. 18], with judgments Σ;Γ⊩ft:τ\Sigma;\Gamma\Vdash_f t:\tau, where Σ\Sigma types the constants and Γ\Gamma the variables:

c:σ∈Στ⊲fσΣ;Γ⊩fc:τx:τ∈ΓΣ;Γ⊩fx:τΣ;Γ⊩fg:τ1→τ2Σ;Γ⊩ft:τ1Σ;Γ⊩f(g t):τ2 \dfrac{c:\sigma\in\Sigma \qquad \tau\vartriangleleft_f\sigma}{\Sigma;\Gamma\Vdash_f c:\tau} \qquad\qquad \dfrac{x:\tau\in\Gamma}{\Sigma;\Gamma\Vdash_f x:\tau} \qquad\qquad \dfrac{\Sigma;\Gamma\Vdash_f g:\tau_1\to\tau_2 \qquad \Sigma;\Gamma\Vdash_f t:\tau_1}{\Sigma;\Gamma\Vdash_f (g\ t):\tau_2}

Here τ⊲fσ\tau\vartriangleleft_f\sigma (“τ\tau is an instance of σ\sigma”) holds when τ\tau is obtained from σ\sigma by substituting order-0 types other than 𝗈\mathsf{o} for type variables. A first-order term is a tt with Σ;Γ⊩ft:τ\Sigma;\Gamma\Vdash_f t:\tau for some τ\tau of order 0 different from 𝗈\mathsf{o} [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: Γ\Gamma 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 X:𝗂𝗇𝗍X:\mathsf{int} or X:𝗅𝗂𝗌𝗍 𝗂𝗇𝗍X:\mathsf{list}\ \mathsf{int}, and most generally with X:AX:A, the whole term having type list (list A). Application is left associative. In canonical form a term is a variable, a constant, or (f t1 … tn)(f\ t_1\ \dots\ t_n) whose head ff 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 ((p(a,b)∧q(a))∨q(f(a,b)))⊃p(b,f(b,a))((p(a,b)\wedge q(a))\vee q(f(a,b)))\supset p(b,f(b,a)).

The declarations infixl, infixr (and infix, prefix, postfix, …) are operator declarations ⟨fixity⟩ c1,…,cn ⟨precedence⟩\langle\text{fixity}\rangle\ c_1,\dots,c_n\ \langle\text{precedence}\rangle: 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 ∀x (p(a,x)∧q(x))\forall x\,(p(a,x)\wedge q(x)) 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 λ\lambda-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 X:𝗂𝗇𝗍X:\mathsf{int}, L:𝗅𝗂𝗌𝗍 𝗂𝗇𝗍L:\mathsf{list}\ \mathsf{int}.

  • Decomposition: {(X: ⁣:L)=(1: ⁣:2: ⁣:𝗇𝗂𝗅)}\{(X\mathbin{:\!:}L)=(1\mathbin{:\!:}2\mathbin{:\!:}\mathsf{nil})\} has the unifier {⟨X,1⟩,⟨L,2: ⁣:𝗇𝗂𝗅⟩}\{\langle X,1\rangle,\langle L,2\mathbin{:\!:}\mathsf{nil}\rangle\}: the left side is a pattern that extracts head and tail.

  • Recognition: the same pattern unifies only with non-empty lists, and with TT repeated the pattern (𝗇𝗈𝖽𝖾 El T T)(\mathsf{node}\ El\ T\ T) recognises the non-empty trees whose two subtrees are identical.

  • Construction: in

    {(X: ⁣:L1)=(1: ⁣:𝗇𝗂𝗅), L2=(2: ⁣:𝗇𝗂𝗅), (X: ⁣:L2)=L3} \{(X\mathbin{:\!:}L_1)=(1\mathbin{:\!:}\mathsf{nil}),\ L_2=(2\mathbin{:\!:}\mathsf{nil}),\ (X\mathbin{:\!:}L_2)=L_3\}

    the first equation takes an input apart, the last builds a new term from its pieces, and the “output” variable L3L_3 receives 1: ⁣:2: ⁣:𝗇𝗂𝗅1\mathbin{:\!:}2\mathbin{:\!:}\mathsf{nil}.

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 t=st=s 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 θ\theta is more general than φ\varphi if φ\varphi is obtained from θ\theta by further substitution. A most general unifier (mgu) is a unifier more general than every other.

Substitutions are constraints on the values of variables. {⟨X,Y⟩}\{\langle X,Y\rangle\} says only that XX and YY are equal; {⟨X,1⟩,⟨Y,1⟩}\{\langle X,1\rangle,\langle Y,1\rangle\} 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 {(X: ⁣:L)=(Y: ⁣:Z: ⁣:𝗇𝗂𝗅)}\{(X\mathbin{:\!:}L)=(Y\mathbin{:\!:}Z\mathbin{:\!:}\mathsf{nil})\} has the two mgu’s

{⟨X,Y⟩,⟨L,Z: ⁣:𝗇𝗂𝗅⟩}and{⟨Y,X⟩,⟨L,Z: ⁣:𝗇𝗂𝗅⟩}, \{\langle X,Y\rangle,\langle L,Z\mathbin{:\!:}\mathsf{nil}\rangle\} \quad\text{and}\quad \{\langle Y,X\rangle,\langle L,Z\mathbin{:\!:}\mathsf{nil}\rangle\},

which differ by the renaming X↔YX\leftrightarrow Y, 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. E⊎{… }E\uplus\{\dots\} is multiset union, ⊥\bot is a problem with no unifier, 𝒱\mathcal V the set of variables, and fσf^\sigma means an occurrence of ff at type σ\sigma.

E⊎{fσ t1…tn=fσ s1…sn}E⊎{t1=s1,…,tn=sn}  DECOMPOSEE⊎{fσ t⃗=gσ′ s⃗}⊥  CLASH (f≠g or σ≠σ′) \dfrac{E\uplus\{f^{\sigma}\,t_1\ldots t_n = f^{\sigma}\,s_1\ldots s_n\}}{E\uplus\{t_1=s_1,\ldots,t_n=s_n\}}\;\text{\small DECOMPOSE} \qquad\qquad \dfrac{E\uplus\{f^{\sigma}\,\vec t = g^{\sigma'}\,\vec s\}}{\bot}\;\text{\small CLASH}\ (f\neq g\text{ or }\sigma\neq\sigma') E⊎{t=x}E⊎{x=t}  ORIENT (t∉𝒱)E⊎{x=x}E  DELETEE⊎{x=t}⊥  CHECK (x∈fv⁡(t), t≠x) \dfrac{E\uplus\{t=x\}}{E\uplus\{x=t\}}\;\text{\small ORIENT}\ (t\notin\mathcal V) \qquad\qquad \dfrac{E\uplus\{x=x\}}{E}\;\text{\small DELETE} \qquad\qquad \dfrac{E\uplus\{x=t\}}{\bot}\;\text{\small CHECK}\ (x\in\operatorname{fv}(t),\ t\neq x) E⊎{x=t}E[t/x]⊎{x=t}  ELIMINATE (x∉fv⁡(t), x∈fv⁡(E)) \dfrac{E\uplus\{x=t\}}{E[t/x]\uplus\{x=t\}}\;\text{\small ELIMINATE}\ (x\notin\operatorname{fv}(t),\ x\in\operatorname{fv}(E))

Decompose and Clash are term reduction. They are justified because a rigid term (f t1…tn)(f\ t_1\dots t_n) 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: x=tx=t with xx strictly inside tt 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, “σ≠σ′\sigma\neq\sigma'” becomes “σ\sigma and σ′\sigma' have no common instance”, and Decompose first unifies σ\sigma with σ′\sigma' as generally as possible [MN p. 30–31].

Definition 2.5 (Solved form [MN p. 29]). EE is in solved form if every equation has a variable on the left, and each such variable occurs nowhere else in EE. 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 ⊥\bot 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 TT makes the pattern recognise trees with two identical subtrees. Write n2n_2 for (𝗇𝗈𝖽𝖾 2 𝖾𝗆𝗉𝗍𝗒 𝖾𝗆𝗉𝗍𝗒)(\mathsf{node}\ 2\ \mathsf{empty}\ \mathsf{empty}):

{(𝗇𝗈𝖽𝖾 El T T)=(𝗇𝗈𝖽𝖾 1 n2 n2)}⟶ {El=1, T=n2, T=n2}term reduction⟶ {El=1, T=n2, n2=n2}variable elimination⟶ {El=1, T=n2, 2=2, 𝖾𝗆𝗉𝗍𝗒=𝖾𝗆𝗉𝗍𝗒, 𝖾𝗆𝗉𝗍𝗒=𝖾𝗆𝗉𝗍𝗒}term reduction⟶ {El=1, T=n2}term reduction×3 \begin{aligned} & \{(\mathsf{node}\ El\ T\ T) = (\mathsf{node}\ 1\ n_2\ n_2)\}\\ \longrightarrow\ & \{El=1,\ T=n_2,\ T=n_2\} && \text{term reduction}\\ \longrightarrow\ & \{El=1,\ T=n_2,\ n_2=n_2\} && \text{variable elimination}\\ \longrightarrow\ & \{El=1,\ T=n_2,\ 2=2,\ \mathsf{empty}=\mathsf{empty},\ \mathsf{empty}=\mathsf{empty}\} && \text{term reduction}\\ \longrightarrow\ & \{El=1,\ T=n_2\} && \text{term reduction}\times 3 \end{aligned}

The last step removes equations between constants: Decompose with n=0n=0 arguments. The result is a solved form, hence the mgu.

Constant clash. If the right subtree is (𝗇𝗈𝖽𝖾 3 𝖾𝗆𝗉𝗍𝗒 𝖾𝗆𝗉𝗍𝗒)(\mathsf{node}\ 3\ \mathsf{empty}\ \mathsf{empty}) instead, the same steps reach the equation 2=32=3, and term reduction yields ⊥\bot.

Occurs check. {T=(𝖻𝗍 1 T T)}\{T=(\mathsf{bt}\ 1\ T\ T)\} fails at once, because TT 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 c:A→A→ic:A\to A\to i and a:ia:i, the problem {(c 1 Y)=(c X a)}\{(c\ 1\ Y)=(c\ X\ a)\} is well typed (both sides have type ii), but in (c 1 Y)(c\ 1\ Y) the constant cc occurs at type 𝗂𝗇𝗍→𝗂𝗇𝗍→i\mathsf{int}\to\mathsf{int}\to i and in (c X a)(c\ X\ a) at i→i→ii\to i\to i. Ignoring types yields the ill-typed unifier {⟨X,1⟩,⟨Y,a⟩}\{\langle X,1\rangle,\langle Y,a\rangle\} [MN p. 31]. The book stops there; completing the example, term reduction with types sees two occurrences of cc at the types 𝗂𝗇𝗍→𝗂𝗇𝗍→i\mathsf{int}\to\mathsf{int}\to i and i→i→ii\to i\to i, 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 ∀x1…∀xn ∃y1…∃ym [t1=s1∧⋯∧tp=sp]\forall x_1\ldots\forall x_n\,\exists y_1\ldots\exists y_m\,[t_1=s_1\wedge\cdots\wedge t_p=s_p] [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 x↦tx\mapsto t 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 L3L_3. 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 X=αX=\alpha, L=(β)L=(\beta), Y=αY=\alpha, Z=βZ=\beta. 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λPrologtypefixityconventional use
⊤\toptrueo
⊃\supset=>o -> o -> oinfix, right assoc.implication in goals
∧\wedge&o -> o -> oinfix, right assoc.joins program clauses
∧\wedge,o -> o -> oinfix, left assoc.joins goals
∨\vee;o -> o -> oinfix, left assoc.
⊃\supset (reversed):-o -> o -> oinfix, non assoc.“is implied by”
∀τx F\forall_\tau x\,Fpi x\ Fbinder
∃τx F\exists_\tau x\,Fsigma x\ Fbinder

The two spellings of ∧\wedge and of ⊃\supset 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 G⊃(A∧B)G\supset(A\wedge B). 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:

Σ;Γ,x:τ⊩fB:𝗈Σ;Γ⊩f∀τx B:𝗈Σ;Γ,x:τ⊩fB:𝗈Σ;Γ⊩f∃τx B:𝗈Σ;Γ⊩fB:τΣ;Γ⊩fC:τ (B,C differ only in bound names) \dfrac{\Sigma;\Gamma,x:\tau\Vdash_f B:\mathsf{o}}{\Sigma;\Gamma\Vdash_f \forall_\tau x\,B:\mathsf{o}} \qquad\qquad \dfrac{\Sigma;\Gamma,x:\tau\Vdash_f B:\mathsf{o}}{\Sigma;\Gamma\Vdash_f \exists_\tau x\,B:\mathsf{o}} \qquad\qquad \dfrac{\Sigma;\Gamma\Vdash_f B:\tau}{\Sigma;\Gamma\Vdash_f C:\tau}\ (B, C \text{ differ only in bound names})

with the proviso, for the first two, that xx is not typed by Σ\Sigma or Γ\Gamma; the third rule renames bound variables so that the proviso can be met. A first-order Σ\Sigma-formula is an FF with Σ;∅⊩fF:𝗈\Sigma;\emptyset\Vdash_f F:\mathsf{o}; such formulas are closed [MN p. 38].

A logic programming language is fixed by four ingredients [MN p. 38]: signatures, program clauses, goals, and a calculus for building proofs. A sequent Σ;𝒫⟶G\Sigma;\mathcal{P}\longrightarrow G has a set 𝒫\mathcal{P} of Σ\Sigma-formulas as its program, and it states the judgment “GG is provable from 𝒫\mathcal{P} and Σ\Sigma”.

Definition 2.7 (Search semantics of the logical symbols [MN p. 39]). Read as steps of an interpreter:

  • and reduce Σ;𝒫⟶B1∧B2\Sigma;\mathcal{P}\longrightarrow B_1\wedge B_2 to both Σ;𝒫⟶B1\Sigma;\mathcal{P}\longrightarrow B_1 and Σ;𝒫⟶B2\Sigma;\mathcal{P}\longrightarrow B_2;
  • or reduce Σ;𝒫⟶B1∨B2\Sigma;\mathcal{P}\longrightarrow B_1\vee B_2 to either Σ;𝒫⟶B1\Sigma;\mathcal{P}\longrightarrow B_1 or Σ;𝒫⟶B2\Sigma;\mathcal{P}\longrightarrow B_2;
  • instan reduce Σ;𝒫⟶∃τx B\Sigma;\mathcal{P}\longrightarrow \exists_\tau x\,B to Σ;𝒫⟶B[t/x]\Sigma;\mathcal{P}\longrightarrow B[t/x] for some Σ\Sigma-term tt of type τ\tau;
  • augment reduce Σ;𝒫⟶B1⊃B2\Sigma;\mathcal{P}\longrightarrow B_1\supset B_2 to Σ;𝒫,B1⟶B2\Sigma;\mathcal{P},B_1\longrightarrow B_2;
  • generic reduce Σ;𝒫⟶∀τx B\Sigma;\mathcal{P}\longrightarrow \forall_\tau x\,B to c:τ,Σ;𝒫⟶B[c/x]c:\tau,\Sigma;\mathcal{P}\longrightarrow B[c/x], where cc is a new constant, not in Σ\Sigma;
  • true Σ;𝒫⟶⊤\Sigma;\mathcal{P}\longrightarrow \top is provable at once.

None of these looks at 𝒫\mathcal{P}. Read downwards, they are the right-introduction rules of a sequent calculus, the book’s Figure 2.2 [MN p. 40]:

Σ;𝒫⟶⊤  ⊤RΣ;𝒫⟶B1Σ;𝒫⟶B2Σ;𝒫⟶B1∧B2  ∧RΣ;𝒫⟶B1Σ;𝒫⟶B1∨B2  ∨RΣ;𝒫⟶B2Σ;𝒫⟶B1∨B2  ∨R \dfrac{}{\Sigma;\mathcal{P}\longrightarrow \top}\;\top R \qquad\qquad \dfrac{\Sigma;\mathcal{P}\longrightarrow B_1 \qquad \Sigma;\mathcal{P}\longrightarrow B_2}{\Sigma;\mathcal{P}\longrightarrow B_1\wedge B_2}\;\wedge R \qquad\qquad \dfrac{\Sigma;\mathcal{P}\longrightarrow B_1}{\Sigma;\mathcal{P}\longrightarrow B_1\vee B_2}\;\vee R \qquad\qquad \dfrac{\Sigma;\mathcal{P}\longrightarrow B_2}{\Sigma;\mathcal{P}\longrightarrow B_1\vee B_2}\;\vee R Σ;𝒫,B1⟶B2Σ;𝒫⟶B1⊃B2  ⊃RΣ;𝒫⟶B[t/x]Σ;∅⊩ft:τΣ;𝒫⟶∃τx B  ∃Rc:τ,Σ;𝒫⟶B[c/x]Σ;𝒫⟶∀τx B  ∀R \dfrac{\Sigma;\mathcal{P},B_1\longrightarrow B_2}{\Sigma;\mathcal{P}\longrightarrow B_1\supset B_2}\;{\supset}R \qquad\qquad \dfrac{\Sigma;\mathcal{P}\longrightarrow B[t/x] \qquad \Sigma;\emptyset\Vdash_f t:\tau}{\Sigma;\mathcal{P}\longrightarrow \exists_\tau x\,B}\;\exists R \qquad\qquad \dfrac{c:\tau,\Sigma;\mathcal{P}\longrightarrow B[c/x]}{\Sigma;\mathcal{P}\longrightarrow \forall_\tau x\,B}\;\forall R

(cc not declared in Σ\Sigma in ∀R\forall R). 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 Σ={p:𝗈,q:𝗈,r:i→𝗈,a:i,b:i}\Sigma=\{p:\mathsf{o},q:\mathsf{o},r:i\to\mathsf{o},a:i,b:i\}.

  1. Σ;p∨q⟶q∨p\Sigma;p\vee q\longrightarrow q\vee p is provable, but or leaves Σ;p∨q⟶q\Sigma;p\vee q\longrightarrow q or Σ;p∨q⟶p\Sigma;p\vee q\longrightarrow p, and neither is provable. A disjunction in the program breaks goal-directed search.
  2. Σ;∅⟶p∨(p⊃q)\Sigma;\emptyset\longrightarrow p\vee(p\supset q) is a classical tautology (excluded middle), but or leaves pp, unprovable, or p⊃qp\supset q, which augment reduces to the unprovable Σ;p⟶q\Sigma;p\longrightarrow q.
  3. Σ;(r a∧r b)⊃q⟶∃x (r x⊃q)\Sigma;(r\,a\wedge r\,b)\supset q\longrightarrow \exists x\,(r\,x\supset q) is classically provable by cases on r ar\,a, but every choice of witness tt 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 ⊃\supset 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 AA ranging over atomic formulas, the goals GG and program clauses DD of first-order Horn clauses (fohc) are

G::=⊤∣A∣G∧G∣G∨G∣∃τx GD::=A∣G⊃D∣D∧D∣∀τx D. \begin{aligned} G &::= \top \mid A \mid G\wedge G \mid G\vee G \mid \exists_\tau x\,G\\ D &::= A \mid G\supset D \mid D\wedge D \mid \forall_\tau x\,D . \end{aligned}

Only ⊃\supset and ∀\forall are missing at the top of goals, and only ∨\vee and ∃\exists at the top of clauses. The family contains the familiar Prolog shape ∀x1…∀xm (A1∧⋯∧An⊃A0)\forall x_1\ldots\forall x_m\,(A_1\wedge\cdots\wedge A_n\supset A_0), 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 𝒫\mathcal{P} contains AA, succeed; if it contains G′⊃AG'\supset A, reduce the goal AA to G′G'. Formally it uses a focused sequent Σ;𝒫→DA\Sigma;\mathcal{P}\xrightarrow{D}A, “try to prove the atom AA by backchaining on DD”. The rules of the book’s Figure 2.3 [MN p. 45] are

Σ;𝒫→DAΣ;𝒫⟶A  DECIDE (D∈𝒫)Σ;𝒫→AA  INITIALΣ;𝒫→DAΣ;𝒫⟶GΣ;𝒫→G⊃DA  ⊃L \dfrac{\Sigma;\mathcal{P}\xrightarrow{D}A}{\Sigma;\mathcal{P}\longrightarrow A}\;\text{\small DECIDE}\ (D\in\mathcal{P}) \qquad\qquad \dfrac{}{\Sigma;\mathcal{P}\xrightarrow{A}A}\;\text{\small INITIAL} \qquad\qquad \dfrac{\Sigma;\mathcal{P}\xrightarrow{D}A \qquad \Sigma;\mathcal{P}\longrightarrow G}{\Sigma;\mathcal{P}\xrightarrow{G\supset D}A}\;{\supset}L Σ;𝒫→D1AΣ;𝒫→D1∧D2A  ∧LΣ;𝒫→D2AΣ;𝒫→D1∧D2A  ∧LΣ;𝒫→D[t/x]AΣ;∅⊩ft:τΣ;𝒫→∀τx DA  ∀L \dfrac{\Sigma;\mathcal{P}\xrightarrow{D_1}A}{\Sigma;\mathcal{P}\xrightarrow{D_1\wedge D_2}A}\;\wedge L \qquad\qquad \dfrac{\Sigma;\mathcal{P}\xrightarrow{D_2}A}{\Sigma;\mathcal{P}\xrightarrow{D_1\wedge D_2}A}\;\wedge L \qquad\qquad \dfrac{\Sigma;\mathcal{P}\xrightarrow{D[t/x]}A \qquad \Sigma;\emptyset\Vdash_f t:\tau}{\Sigma;\mathcal{P}\xrightarrow{\forall_\tau x\,D}A}\;\forall L

decide picks a clause; initial closes the branch when the focused atom is identical to the goal; ⊃L{\supset}L proves the body GG and continues on DD; ∧L\wedge L picks a conjunct; ∀L\forall L 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 D=∀x¯ (A1∧⋯∧An⊃A0)D=\forall\bar x\,(A_1\wedge\cdots\wedge A_n\supset A_0) the rules compose into one step [MN p. 45]:

Σ;𝒫⟶A1θ⋯Σ;𝒫⟶AnθΣ;𝒫→DA \dfrac{\Sigma;\mathcal{P}\longrightarrow A_1\theta \qquad \cdots \qquad \Sigma;\mathcal{P}\longrightarrow A_n\theta}{\Sigma;\mathcal{P}\xrightarrow{D}A}

where θ\theta maps each xix_i to a Σ\Sigma-term of its type and A=A0θA=A_0\theta: the instance A1θ∧⋯∧Anθ⊃A0θA_1\theta\wedge\cdots\wedge A_n\theta\supset A_0\theta follows from 𝒫\mathcal{P}, and modus ponens gives A0θA_0\theta. 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 𝒫\mathcal{P} is an fohc program and GG an fohc goal, then Σ;𝒫⟶G\Sigma;\mathcal{P}\longrightarrow G 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 Σ;𝒫⟶G\Sigma;\mathcal{P}\longrightarrow G has the form Σ;𝒫⟶G′\Sigma;\mathcal{P}\longrightarrow G' or Σ;𝒫→DA\Sigma;\mathcal{P}\xrightarrow{D}A, with the same Σ\Sigma and 𝒫\mathcal{P}.

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 𝒫={D1,D2}\mathcal{P}=\{D_1,D_2\} of append (Section 2.7), with D1=∀l (𝖺𝗉𝗉 𝗇𝗂𝗅 l l)D_1=\forall l\,(\mathsf{app}\ \mathsf{nil}\ l\ l) and D2=∀x∀l1∀l2∀l3 (𝖺𝗉𝗉 l1 l2 l3⊃𝖺𝗉𝗉 (x: ⁣:l1) l2 (x: ⁣:l3))D_2=\forall x\forall l_1\forall l_2\forall l_3\,(\mathsf{app}\ l_1\ l_2\ l_3\supset\mathsf{app}\ (x\mathbin{:\!:}l_1)\ l_2\ (x\mathbin{:\!:}l_3)), and the goal ∃X∃Y 𝖺𝗉𝗉 X Y (1: ⁣:𝗇𝗂𝗅)\exists X\exists Y\,\mathsf{app}\ X\ Y\ (1\mathbin{:\!:}\mathsf{nil}). Instead of guessing terms in ∃R\exists R and ∀L\forall L we use logic variables and let initial unify (this is the practical version of the rules, Section 2.9).

  1. ∃R\exists R twice: logic variables X,YX,Y; goal 𝖺𝗉𝗉 X Y (1: ⁣:𝗇𝗂𝗅)\mathsf{app}\ X\ Y\ (1\mathbin{:\!:}\mathsf{nil}), atomic.
  2. decide D1D_1; ∀L\forall L with a new LL; initial unifies 𝖺𝗉𝗉 𝗇𝗂𝗅 L L\mathsf{app}\ \mathsf{nil}\ L\ L with the goal: X=𝗇𝗂𝗅X=\mathsf{nil}, L=YL=Y, Y=1: ⁣:𝗇𝗂𝗅Y=1\mathbin{:\!:}\mathsf{nil}. First answer: X=𝗇𝗂𝗅X=\mathsf{nil}, Y=1: ⁣:𝗇𝗂𝗅Y=1\mathbin{:\!:}\mathsf{nil}.
  3. Back to step 2, decide D2D_2 instead. ∀L\forall L four times with new X′,L1,L2,L3X',L_1,L_2,L_3, then ⊃L{\supset}L splits into a focused premise and a goal premise. initial on the focused premise unifies 𝖺𝗉𝗉 (X′: ⁣:L1) L2 (X′: ⁣:L3)\mathsf{app}\ (X'\mathbin{:\!:}L_1)\ L_2\ (X'\mathbin{:\!:}L_3) with the goal: X=X′: ⁣:L1X=X'\mathbin{:\!:}L_1, Y=L2Y=L_2, X′=1X'=1, L3=𝗇𝗂𝗅L_3=\mathsf{nil}. The goal premise is now 𝖺𝗉𝗉 L1 Y 𝗇𝗂𝗅\mathsf{app}\ L_1\ Y\ \mathsf{nil}.
  4. For 𝖺𝗉𝗉 L1 Y 𝗇𝗂𝗅\mathsf{app}\ L_1\ Y\ \mathsf{nil}: decide D1D_1 succeeds with L1=𝗇𝗂𝗅L_1=\mathsf{nil}, Y=𝗇𝗂𝗅Y=\mathsf{nil}. Second answer: X=1: ⁣:𝗇𝗂𝗅X=1\mathbin{:\!:}\mathsf{nil}, Y=𝗇𝗂𝗅Y=\mathsf{nil}. decide D2D_2 fails: its head needs the third argument to be x: ⁣:l3x\mathbin{:\!:}l_3, which clashes with 𝗇𝗂𝗅\mathsf{nil}.

The O-proof for the second answer, with the unifier already applied. Write A0A_0 for 𝖺𝗉𝗉 (1: ⁣:𝗇𝗂𝗅) 𝗇𝗂𝗅 (1: ⁣:𝗇𝗂𝗅)\mathsf{app}\ (1\mathbin{:\!:}\mathsf{nil})\ \mathsf{nil}\ (1\mathbin{:\!:}\mathsf{nil}) and A1A_1 for 𝖺𝗉𝗉 𝗇𝗂𝗅 𝗇𝗂𝗅 𝗇𝗂𝗅\mathsf{app}\ \mathsf{nil}\ \mathsf{nil}\ \mathsf{nil}:

Σ;𝒫→A0A0 INITIALΣ;𝒫⟶A1 DECIDE+∀L+INITIALΣ;𝒫→A1⊃A0A0 ⊃LΣ;𝒫→D2A0 ∀L×4Σ;𝒫⟶A0 DECIDEΣ;𝒫⟶∃X∃Y 𝖺𝗉𝗉 X Y (1: ⁣:𝗇𝗂𝗅) ∃R×2 \dfrac{\dfrac{\dfrac{\dfrac{\dfrac{}{\Sigma;\mathcal{P}\xrightarrow{A_0}A_0}\,\text{\small INITIAL} \qquad \dfrac{}{\Sigma;\mathcal{P}\longrightarrow A_1}\,\text{\small DECIDE}+\forall L+\text{\small INITIAL}} {\Sigma;\mathcal{P}\xrightarrow{A_1\supset A_0}A_0}\,{\supset}L} {\Sigma;\mathcal{P}\xrightarrow{D_2}A_0}\,\forall L\times 4} {\Sigma;\mathcal{P}\longrightarrow A_0}\,\text{\small DECIDE}} {\Sigma;\mathcal{P}\longrightarrow \exists X\exists Y\,\mathsf{app}\ X\ Y\ (1\mathbin{:\!:}\mathsf{nil})}\,\exists R\times 2

Every sequent in it has the same Σ\Sigma and 𝒫\mathcal{P}, 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.: LL is a sublist of KK if KK has a suffix TT of which LL is a prefix.

Equivalent groupings of clauses. Because the D-grammar allows ∧\wedge and ⊃\supset 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

G1⊃(D𝗇𝖾𝗀∧(G2⊃(D𝖺𝗇𝖽∧D𝗈𝗋∧D𝗂𝗆𝗉))) G_1\supset\bigl(D_{\mathsf{neg}}\wedge(G_2\supset(D_{\mathsf{and}}\wedge D_{\mathsf{or}}\wedge D_{\mathsf{imp}}))\bigr)

(universally closed), where G1G_1 stands for the goal ident B D, G2G_2 for ident C E, and D𝗇𝖾𝗀,…D_{\mathsf{neg}},\dots for the four heads. It is legal because the D-grammar allows G⊃DG\supset D and D∧DD\wedge D to nest. To solve an atom ident (and B0 C0) X, decide picks this clause, ∀L\forall L instantiates its variables, ⊃L{\supset}L sets the body ident B D aside as a goal premise and keeps backchaining on the conjunction, ∧L\wedge L chooses the right conjunct, ⊃L{\supset}L sets ident C E aside, ∧L\wedge L chooses D𝖺𝗇𝖽D_{\mathsf{and}}, 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 ⊃L{\supset}L 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;
no

Typing ; 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 (a+b)∗(ab+ba)(a+b)^*(ab+ba), the words ending in abab or baba:

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 :: nil

Of 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 Γ⟶Δ\Gamma\longrightarrow\Delta on both sides (Figure 2.7, [MN p. 58]), over the formulas of Section 2.2.3:

Γ,⊥⟶Δ  ⊥LΓ,A⟶Δ,A  INITIAL \dfrac{}{\Gamma,\bot\longrightarrow\Delta}\;\bot L \qquad\qquad \dfrac{}{\Gamma,A\longrightarrow\Delta,A}\;\text{\small INITIAL} Γ,A⟶ΔΓ,B⟶ΔΓ,A∨B⟶Δ  ∨LΓ⟶Δ,A,BΓ⟶Δ,A∨B  ∨R \dfrac{\Gamma,A\longrightarrow\Delta \qquad \Gamma,B\longrightarrow\Delta}{\Gamma,A\vee B\longrightarrow\Delta}\;\vee L \qquad\qquad \dfrac{\Gamma\longrightarrow\Delta,A,B}{\Gamma\longrightarrow\Delta,A\vee B}\;\vee R Γ,A,B⟶ΔΓ,A∧B⟶Δ  ∧LΓ⟶Δ,AΓ⟶Δ,BΓ⟶Δ,A∧B  ∧R \dfrac{\Gamma,A,B\longrightarrow\Delta}{\Gamma,A\wedge B\longrightarrow\Delta}\;\wedge L \qquad\qquad \dfrac{\Gamma\longrightarrow\Delta,A \qquad \Gamma\longrightarrow\Delta,B}{\Gamma\longrightarrow\Delta,A\wedge B}\;\wedge R Γ⟶Δ,AΓ,B⟶ΔΓ,A⊃B⟶Δ  ⊃LΓ,A⟶Δ,BΓ⟶Δ,A⊃B  ⊃R \dfrac{\Gamma\longrightarrow\Delta,A \qquad \Gamma,B\longrightarrow\Delta}{\Gamma,A\supset B\longrightarrow\Delta}\;{\supset}L \qquad\qquad \dfrac{\Gamma,A\longrightarrow\Delta,B}{\Gamma\longrightarrow\Delta,A\supset B}\;{\supset}R

Several formulas on the right make the calculus classical. Here Γ,Δ,A,B\Gamma,\Delta,A,B are schema variables of the object calculus, not logic variables of λProlog. Multisets are lists, and a rule matches “Γ,P\Gamma, P” by selecting PP 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 ⊥L\bot L, initial, ∧L\wedge L, ∨L\vee L, ⊃L{\supset}L, ∧R\wedge R, ∨R\vee R, ⊃R{\supset}R, 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 ∨L\vee L clause against its rule: the conclusion Γ,A∨B⟶Δ\Gamma,A\vee B\longrightarrow\Delta 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 Γ\Gamma), and the two premises become the two body goals. The initial clause needs no selection of the rest: it only asks that some AA be on both sides.

[logic] ?- prv nil (((p a b) !! ((p a b) ==> (q a a))) :: nil).
solved

Note the level shift. This is p∨(p⊃q)p\vee(p\supset q), the formula that Example 2.8 showed goal-directed search cannot prove (it is not even an fohc goal, since it contains ⊃\supset). 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 ∨R\vee R and then ⊃R{\supset}R and initial on p a b.

Pitfall (An erratum in the last prv clause). The clause for ⊃R{\supset}R 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” p a b⊃q a ap\,a\,b\supset q\,a\,a, 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]:

  1. for ∨R\vee R and ∧L\wedge L, the left subformula is tried before the right one;
  2. for ∧R\wedge R, the left premise is derived first;
  3. for decide, 𝒫\mathcal{P} is a list, not a set: clauses are tried in textual order, and order and multiplicity matter;
  4. the terms of ∃R\exists R and ∀L\forall L 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 XX that is new in the search, the quantifier rules and initial become [MN p. 61]

Σ;∅⊩fX:τΣ;𝒫⟶B[X/x]Σ;𝒫⟶∃τx BΣ;𝒫→D[X/x]AΣ;∅⊩fX:τΣ;𝒫→∀τx DAΣ;𝒫→A′A  INITIAL (A,A′ unifiable) \dfrac{\Sigma;\emptyset\Vdash_f X:\tau \qquad \Sigma;\mathcal{P}\longrightarrow B[X/x]}{\Sigma;\mathcal{P}\longrightarrow \exists_\tau x\,B} \qquad\qquad \dfrac{\Sigma;\mathcal{P}\xrightarrow{D[X/x]}A \qquad \Sigma;\emptyset\Vdash_f X:\tau}{\Sigma;\mathcal{P}\xrightarrow{\forall_\tau x\,D}A} \qquad\qquad \dfrac{}{\Sigma;\mathcal{P}\xrightarrow{A'}A}\;\text{\small INITIAL}\ (A, A'\text{ unifiable})

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 ⊃L{\supset}L and ∧L\wedge L in advance turns it into a list of clauses ∀x¯ (G1∧⋯∧Gn⊃A)\forall\bar x\,(G_1\wedge\cdots\wedge G_n\supset A), 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

Σ;𝒫⟶BΣ;𝒫,B⟶GΣ;𝒫⟶G  CUT \dfrac{\Sigma;\mathcal{P}\longrightarrow B \qquad \Sigma;\mathcal{P},B\longrightarrow G}{\Sigma;\mathcal{P}\longrightarrow G}\;\text{\small CUT}

It uses a lemma BB. 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, F::=A∣F∧FF ::= A\mid F\wedge F, D::=A∣F⊃A∣∀τx DD ::= A\mid F\supset A\mid\forall_\tau x\,D; and a compact one, D::=A∣A⊃D∣∀τx DD ::= A\mid A\supset D\mid\forall_\tau x\,D. A clause of one presentation is equivalent to a set of clauses of another through equivalences such as

∀x (B1∧B2)≡(∀x B1)∧(∀x B2),B1⊃(B2⊃B3)≡(B1∧B2)⊃B3,(B1∨B2)⊃B3≡(B1⊃B3)∧(B2⊃B3),B1⊃∀x B2≡∀x (B1⊃B2) (x∉fv⁡(B1)), \begin{gathered} \forall x\,(B_1\wedge B_2)\equiv(\forall x\,B_1)\wedge(\forall x\,B_2),\qquad B_1\supset(B_2\supset B_3)\equiv(B_1\wedge B_2)\supset B_3,\\ (B_1\vee B_2)\supset B_3\equiv(B_1\supset B_3)\wedge(B_2\supset B_3),\\ B_1\supset\forall x\,B_2\equiv\forall x\,(B_1\supset B_2)\ (x\notin\operatorname{fv}(B_1)), \end{gathered}

together with distributivity of ∧\wedge and ∨\vee and the others listed on [MN p. 64].

Example 2.13 (Size and behaviour [MN p. 64–66]). In the common presentation, ((p∨r)∧(q∨t))⊃s((p\vee r)\wedge(q\vee t))\supset s must become four clauses

(p∧q)⊃s,(r∧q)⊃s,(p∧t)⊃s,(r∧t)⊃s, (p\wedge q)\supset s,\quad (r\wedge q)\supset s,\quad (p\wedge t)\supset s,\quad (r\wedge t)\supset s,

which duplicates p,q,r,tp, q, r, t, exponentially in general. It also changes behaviour: with the original clause pp is derived at most once per use, with the four clauses it is derived again for each clause that mentions it. Introducing new predicates pr,qtpr, qt for p∨rp\vee r and q∨tq\vee t instead,

p⊃pr,r⊃pr,q⊃qt,t⊃qt,(pr∧qt)⊃s, p\supset pr,\quad r\supset pr,\quad q\supset qt,\quad t\supset qt,\quad (pr\wedge qt)\supset s,

grows the program only linearly. This is not a logical equivalence (there are new constants), but it is conservative: for every goal GG over the original signature Σ1\Sigma_1, Σ1;𝒫,D1⟶G\Sigma_1;\mathcal{P},D_1\longrightarrow G is provable iff Σ2;𝒫,D2⟶G\Sigma_2;\mathcal{P},D_2\longrightarrow G 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 ∀A (type nil (list A))\forall A\,(\mathit{type}\ \mathit{nil}\ (\mathit{list}\ A)): nil has many types [MN p. 67].

Definition 2.14 (Transparent, determinate [MN p. 67–68]). For an order-1 type τ1→⋯→τn→τ0\tau_1\to\cdots\to\tau_n\to\tau_0, a type variable occurring in τ0\tau_0 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 K

to 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 (L,K)(L, K): 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
⊤\top, true (⊤R\top R)✓°
G1∧G2G_1\wedge G_2, , (∧R\wedge R)(and° g1 g2)bind interleaves answers
G1∨G2G_1\vee G_2, ; (∨R\vee R)(or° g1 g2), cond°interleaving, not left first
∃x G\exists x\,G, sigma (∃R\exists R, logic variable)(fresh° (x) g)exactly the rule of [MN p. 61]
atomic goal, decidecall (p° t ...)clause choice compiled into the relation
clauses of pp, ∀x¯ (G⊃p t¯)\forall\bar x\,(G\supset p\,\bar t)define-relation with one cond° line per clauseprecompiled and indexed by name, [MN p. 61–62]
∀L\forall L with logic variablefresh° opening each linerenaming apart is automatic
initial with unification=° against the clause headthe threaded substitution percolates θ\theta
occurs checkbuilt inas the book requires, [MN p. 32]
answer substitutionreified answer, α, β, …up to renaming
typed unificationnonesee U7
<, >=, isproject° + Schemenon-logical, moded
! (pruning)no hard cut; soft cut if°, take°control, not logic
not(if° g ✗° ✓°)same unsoundness
⊃R{\supset}R (augment), ∀R\forall R (generic)absentnot 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 ∀x (𝖾𝗊 x x)\forall x\,(\mathsf{eq}\ x\ x). 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 aa-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. μ\muKanren: 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 broken
insert 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: _1

The 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 λ\lambda-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 Σ;𝒫⟶G\Sigma;\mathcal{P}\longrightarrow G, 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, ⊃L{\supset}L, ∧L\wedge L, ∀L\forall L [MN p. 39–45].
  • In fohc (G::=⊤∣A∣G∧G∣G∨G∣∃x GG ::= \top\mid A\mid G\wedge G\mid G\vee G\mid\exists x\,G; D::=A∣G⊃D∣D∧D∣∀x DD ::= A\mid G\supset D\mid D\wedge D\mid\forall x\,D) 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, is and 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-commutative not, moded built-ins).