Chapter 5

Higher-order programming

Chapter 4 replaced first-order terms by simply typed λ\lambda-terms and allowed quantification at every type, including predicate types (types whose target is 𝗈\mathsf{o}); it also showed that unification of such terms is undecidable and may have infinitely many incomparable solutions. This chapter, which follows Chapter 5 of the book Dale Miller and Gopalan Nadathur. Programming with Higher-Order Logic. Cambridge University Press, Cambridge, 2012 and the core of its Chapter 6, asks the practical question: what logic programming languages do we get, and what do they buy us?

Two kinds of higher-order variable will appear, and it is worth keeping them apart from the start.

  • Predicate variables (target type 𝗈\mathsf{o}) are instantiated by relations and then invoked as goals. They give higher-order programming in the style a Scheme programmer knows: mappred, folds, closures of relations, continuation passing.
  • Non-predicate function variables (target type not 𝗈\mathsf{o}) are instantiated by λ\lambda-terms that are only ever evaluated by βη\beta\eta-conversion. Their values can also be found by solving unification problems; the book calls this “perhaps the single most novel aspect of higher-order logic programming” [MN p. 138].

We first fix which formulas may be goals and which may be clauses (Section 5.1), then program with predicate variables (Section 5.2, Section 5.3, Section 5.4, Section 5.5 and Section 5.6), then with function variables (Section 5.7 and Section 5.8), compare with functional programming (Section 5.9), and finally show how the same two logical devices that hide a predicate, ∀\forall in goals and ⊃\supset in goals, also give a modules language (Section 5.10).

A question runs through the whole chapter, and the kanren boxes answer it case by case: in a miniKanren hosted in Scheme, where a relation is a Scheme procedure, which of these features are free, and which really need λ\lambda-terms in the term language? Section 5.11 collects the answers.

Tutorial (How to run the Scheme listings). Every Scheme listing in this chapter was run on today’s (aux kanren micro) and its output is shown verbatim below it. Each file begins with (include "prelude.scm"), which loads this prelude (the include line is left out of the listings):

(import scheme (chicken base) (chicken pretty-print)
        (aux base) (aux stream) (aux kanren micro))
(define-syntax-rule (show label expr)
  (begin (display label) (display " ") (write expr) (newline)))

(μkanren-run (q n grounded) g ...) returns up to n answers for q (all answers when n is negative). With grounded set to #t it returns them as plain data; with #f it returns them as reified Scheme λ\lambda-expressions.

5.1Which formulas are goals and which are clauses

At first order (Chapter 2 and Chapter 3) goals and clauses of fohh were

G::=⊤∣A∣G∧G∣G∨G∣∀x G∣∃x G∣D⊃GD::=A∣G⊃D∣∀x D∣D∧D \begin{aligned} G &::= \top \mid A \mid G\wedge G \mid G\vee G \mid \forall x\,G \mid \exists x\,G \mid D\supset G\\ D &::= A \mid G\supset D \mid \forall x\,D \mid D\wedge D \end{aligned}

and fohc is the fragment without ∀\forall and ⊃\supset in goals [MN p. 118]. The higher-order languages keep this top-level shape. What changes is what an atom AA may be: once quantification over predicates is allowed, an atom may contain λ\lambda-terms and predicate variables, and its head may itself be a variable.

5.1.1Rigid and flexible atoms

Definition 5.1 (Rigid and flexible atoms [MN p. 119]). The λ\lambda-normal form of a higher-order atomic formula has the shape (h t1…tn)(h\,t_1\ldots t_n) where hh is either a variable or a non-logical constant. The atom is rigid if hh is a constant and flexible if hh is a variable.

So age bob 23 and mappred P L K are rigid, while P X Y is flexible. The atom (x\ age x 23) bob is rigid too, because its λ\lambda-normal form is age bob 23. Flexible atoms in goals are what make higher-order programming possible: in the body of mappred P (X::L) (Y::K) :- P X Y, mappred P L K. the goal P X Y is flexible. Flexible atoms as clause heads are a different matter.

5.1.2Why clause heads must be rigid

The book gives two reasons for rejecting flexible heads [MN p. 119–120].

Consistency. A program is inconsistent if every formula is provable from it. Every fohc and fohh program is consistent. This matters in practice: otherwise a complete interpreter would have to check the program for consistency before it could answer “no”. With flexible heads, inconsistent programs are easy to write:

P 5 :- q.
q.

To prove any goal BB, backchain on the first clause with P:=λx. BP := \lambda x.\, B; what is left is q, which is provable. The single clause ∀p p\forall p\,p is an even shorter example [MN p. 120].

Modularity. A clause ∀x1…∀xm(A1∧⋯∧An⊃A0)\forall x_1\ldots\forall x_m(A_1\wedge\cdots\wedge A_n\supset A_0) is read as part of the definition of the relation named by the head of A0A_0. If that head is a variable, the clause adds meaning to every predicate. That defeats modular reading of code, and it also defeats indexing clauses by predicate name.

Two natural uses are lost, and the book argues that losing them is acceptable. Leibniz equality (two terms are equal if they satisfy the same properties) would turn x+0=xx+0=x into

P (X + 0) :- P X.
P X :- P (X + 0).

This is logically meaningful but operationally a disaster. A goal containing nn occurrences of, say, 5 + 0 admits 2n2^n abstractions for P, and even a goal with no occurrence can always backchain on the first clause, so the search loops [MN p. 120]. Computed clauses, as in ?- convert d P, P => g., put a variable where a clause is expected. There is no simple way to guarantee statically that the value bound to P will be a legal clause [MN p. 121].

5.1.3No implications inside terms

Logical symbols inside the arguments of atoms are useful (the symmetric closure x\y\ adj x y ; adj y x is a term containing ∨\vee), but an implication inside a term breaks goal-directed search. The book’s counterexample [MN p. 121] uses constants r:𝗈→𝗈r:\mathsf{o}\to\mathsf{o} and s,t:𝗈s,t:\mathsf{o}, and a variable Q:𝗈→𝗈→𝗈Q:\mathsf{o}\to\mathsf{o}\to\mathsf{o}:

∃Q [ ∀p ∀q [ r (p⊃q)⊃r (Q p q) ] ∧ Q (t∨s) (s∨t) ]. \exists Q\,\big[\,\forall p\,\forall q\,[\,r\,(p\supset q)\supset r\,(Q\,p\,q)\,]\ \wedge\ Q\,(t\vee s)\,(s\vee t)\,\big].

The first conjunct forces Q:=λx. λy. x⊃yQ := \lambda x.\, \lambda y.\, x\supset y: after the ∀\forall and ⊃\supset introductions the goal r (Q p q)r\,(Q\,p\,q) must match the hypothesis r (p⊃q)r\,(p\supset q). The second conjunct then becomes (t∨s)⊃(s∨t)(t\vee s)\supset(s\vee t), which is provable in any reasonable logic, but not by the goal-directed rules of Chapter 2: the instance of QQ moved a disjunction from a goal position into a hypothesis, where a left rule for ∨\vee would be needed.

Definition 5.2 (Polarity [MN p. 121–122]). When implications are excluded from terms, an occurrence of a logical symbol is positive if and only if it is either within an atomic formula or is in the scope of only logical constants and to the left of an even number of implications. All other occurrences are negative.

The point of the definition is an invariant: during cut-free proof search, positive occurrences stay positive and negative ones stay negative. Goal-directed search relies on it. In the counterexample both disjunctions start out positive, and instantiating QQ makes one of them negative.The ban is a design choice, not the only one possible: the bibliographic notes recall Felty’s result that ⊃\supset may occur in terms if ∨\vee and ∃\exists are banned from formulas and terms instead [MN p. 148].

5.1.4Herbrand universes, hohc and hohh

The quantifier rules ∃R\exists R and ∀L\forall L substitute terms. To keep goals goals and clauses clauses, the terms that may be substituted have to be restricted.

Definition 5.3 (Herbrand universes [MN p. 122]). Let Σ\Sigma contain at least the logical constants. ℋ1Σ\mathcal{H}_1^\Sigma is the set of all (possibly open) λ\lambda-normal terms over Σ\Sigma that contain neither ∀\forall nor ⊃\supset. ℋ2Σ\mathcal{H}_2^\Sigma is the set of all (possibly open) λ\lambda-normal terms over Σ\Sigma that do not contain ⊃\supset.

Terms of ℋ1Σ\mathcal{H}_1^\Sigma may contain ⊤,∧,∨,∃\top,\wedge,\vee,\exists, and the types of their subterms are unrestricted. ℋ2Σ\mathcal{H}_2^\Sigma also allows ∀\forall.

Definition 5.4 (hohc: higher-order Horn clauses [MN p. 122]). Let AA range over atoms in ℋ1Σ\mathcal{H}_1^\Sigma and ArA_r over rigid atoms in ℋ1Σ\mathcal{H}_1^\Sigma. Goals and clauses are the formulas whose λ\lambda-normal forms are

G::=⊤∣A∣G∧G∣G∨G∣∃τx GD::=Ar∣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_r \mid G\supset D \mid D\wedge D \mid \forall_\tau x\,D \end{aligned}

with no restriction on τ\tau. The GG-formulas are exactly the formulas of ℋ1Σ\mathcal{H}_1^\Sigma of type 𝗈\mathsf{o}.

The operational semantics is the goal-directed calculus of Chapter 2, with three changes [MN p. 123]: formulas are taken in λ\lambda-normal form, initial works up to α\alpha-conversion, and the quantifier rules instantiate with λ\lambda-terms from the Herbrand universe (⊩\Vdash is the typing judgement for the instantiation term):

Σ;𝒫→A′A  initial (A′≡αA)Σ;𝒫⟶B[t/x]Σ;∅⊩t:τt∈ℋ1ΣΣ;𝒫⟶∃τx B  ∃RΣ;𝒫→D[t/x]AΣ;∅⊩t:τt∈ℋ1ΣΣ;𝒫→∀τx DA  ∀L \begin{gathered} \dfrac{}{\Sigma;\mathcal{P}\xrightarrow{A'}A}\;\text{initial}\ (A'\equiv_\alpha A) \qquad \dfrac{\Sigma; \mathcal{P} \longrightarrow B[t/x] \qquad \Sigma;\emptyset\Vdash t:\tau \qquad t\in\mathcal{H}_1^\Sigma}{\Sigma; \mathcal{P} \longrightarrow \exists_\tau x\,B}\;\exists\text{R} \\[2ex] \dfrac{\Sigma;\mathcal{P}\xrightarrow{D[t/x]}A \qquad \Sigma;\emptyset\Vdash t:\tau \qquad t\in\mathcal{H}_1^\Sigma}{\Sigma;\mathcal{P}\xrightarrow{\forall_\tau x\,D}A}\;\forall\text{L} \end{gathered}

Why is the restriction needed? Without it, the goal ∃p p\exists p\,p could be instantiated with ∀x (q x)\forall x\,(q\,x) for some q∈Σq\in\Sigma, which is not an hohc goal. Substituting a term of ℋ1Σ\mathcal{H}_1^\Sigma into a goal or a clause keeps it in its category. Intuitively, we never substitute something that could not appear as the argument of an atom or in the structure of a goal [MN p. 123]. In an implementation, tt is not guessed: it is a logic variable that higher-order unification later fixes in initial.

Theorem 5.5 (Completeness of goal-directed search for hohc [MN p. 123–124], [MN p. 148]). Derivability of goals from program clauses in this calculus coincides exactly with provability in classical higher-order logic. By the bibliographic notes, this holds for both the classical and the intuitionistic versions of Church’s Simple Theory of Types, without the axioms of extensionality, infinity and choice Gopalan Nadathur and Dale Miller. Higher-order Horn clauses. Journal of the ACM, 37(4):777–814, 1990.

Since ∀R\forall R and ⊃R{\supset}R never fire in hohc, the signature and the program stay fixed during a computation [MN p. 124].

Definition 5.6 (hohh: higher-order hereditary Harrop formulas [MN p. 124]). Let AA range over atoms in ℋ2Σ\mathcal{H}_2^\Sigma and ArA_r over rigid atoms in ℋ2Σ\mathcal{H}_2^\Sigma:

G::=⊤∣A∣G∧G∣G∨G∣∃τx G∣D⊃G∣∀τx GD::=Ar∣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 \mid D\supset G \mid \forall_\tau x\,G\\ D &::= A_r \mid G\supset D \mid D\wedge D \mid \forall_\tau x\,D \end{aligned}

The instances for ∃R\exists R and ∀L\forall L are terms of ℋ2Σ\mathcal{H}_2^\Sigma, where Σ\Sigma is the signature current at that point of the derivation.

Goals are richer than ℋ2Σ\mathcal{H}_2^\Sigma (they may contain ⊃\supset; no term of ℋ2Σ\mathcal{H}_2^\Sigma does). Derivability now coincides with provability in higher-order intuitionistic logic 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 [MN p. 124]. Unlike hohc, ∀R\forall R (generic) and ⊃R{\supset}R (augment) are active, so the signature and the program change during computation, as in Chapter 3.

5.1.5hohh⁺: hiding predicate names

Chapter 3 could limit the scope of an auxiliary predicate’s clauses with ⊃\supset, but not the visibility of its name. A context that already had clauses for rev could corrupt a reverse that assumed its own rev. One small liberalisation fixes this.

Definition 5.7 (hohh⁺ [MN p. 125]). hohh+^+ is hohh in which the head of an atomic program clause may also be a variable, provided that variable is bound by an essentially universal quantifier that has the clause in its scope.

In a goal, a bound variable is essentially universal if it is bound by a positive ∀\forall, a negative ∃\exists, or a term-level λ\lambda. It is essentially existential otherwise. The definition is dualised for clauses ([MN p. 205]; see Chapter 6). Essentially universal variables only ever become eigenvariables. When search reaches the goal ∀p (…D…⊃G)\forall p\,(\ldots D\ldots\supset G), ∀R\forall R has already replaced pp by a new constant, so by the time DD is added to the program it is a legal hohh clause with a rigid head. Hence hohh+^+ does not change computational behaviour; it only lets a program introduce closed, hidden predicate definitions. The book’s two versions of reverse [MN p. 126]:

type reverse   list A -> list A -> o.
reverse L K :-
  pi rev\
    (pi L\ rev nil L L) &
    (pi X\ pi L\ pi K\ pi M\ rev (X::L) K M :- rev L K (X::M))
    => rev L K nil.
type reverse   list A -> list A -> o.
reverse L K :- pi rv\
  ( rv nil K &
    (pi X\ pi N\ pi M\ rv (X::N) M :- rv N (X::M)))
  => rv L nil.

Tutorial (What the interpreter does with reverse (1::2::3::nil) K). Using the first version [MN p. 125]:

  1. backchain on reverse; the body is a pi goal, so ∀R\forall R generates a new predicate symbol, call it c, and adds it to the signature;

  2. the body is now an implication, so ⊃R{\supset}R adds the two clauses

    pi L\ c nil L L.
    pi X\ pi L\ pi K\ pi M\ c (X::L) K M :- c L K (X::M).
  3. it proves c (1::2::3::nil) K nil by ordinary backchaining and obtains K = (3::2::1::nil);

  4. on leaving the goal, it removes c and its clauses from the context.

No clause outside reverse can mention c: the name did not exist when those clauses were written.

Pitfall (Shadowing and shared variables in assumed clauses). In the first version the inner pi L\ and pi K\ shadow the outer L and K. In the second version the assumed fact rv nil K mentions the outer logic variable K, so the hypothetical clause is not closed: K is shared with the caller and is not renamed at each use of the clause.

Kanren angle (Hidden predicates are lexical scope). In a Scheme-hosted miniKanren a relation is a procedure, and Scheme already has a way to make a name invisible: a local definition. The first reverse, with rev hidden, is one let:

;; Figure 5.1 with the hidden predicate rev as a lexically local relation
(define reverse°
  (let ()
    (define-relation (rev l k m)
      (cond° ((null° l) (=° k m))
             ((fresh° (x l*) (cons° x l* l) (rev l* k (cons x m))))))
    (λ (l k) (rev l k '()))))
(show 1 (μkanren-run (q -1 #t) (reverse° '(1 2 3) q)))
(show 2 (μkanren-run (q 1 #t) (reverse° q '(1 2 3))))
1 ((3 2 1))
2 ((3 2 1))

No client of reverse° can add clauses to rev. This is the encapsulation that hohh+^+ provides, and it costs nothing. (The second query asks for one answer: in that mode a request for all answers does not terminate.) What lexical scope does not give is a clause set that grows during the search, such as the memo table of Example 5.9, or a hidden name that exists as a first-class constant, one that can be stored in terms and must not escape its scope. Both need new machinery in the state: a dynamic clause store for ⊃\supset, and eigenvariables with a scope check for ∀\forall. See Chapter 11.

5.2Higher-order relational programming

5.2.1Mapping, filtering and quantifying over lists

The basic higher-order relations of the book [MN p. 127]:

type foreach, forsome   (A -> o) -> list A -> o.
type mappred            (A -> B -> o) -> list A -> list B -> o.
type sublist            (A -> o) -> list A -> list A -> o.

foreach P nil.
foreach P (X::L) :- P X, foreach P L.

forsome P (X::L) :- P X; forsome P L.

mappred P nil nil.
mappred P (X::L) (Y::K) :- P X Y, mappred P L K.

sublist P (X::L) (X::K) :- P X, sublist P L K.
sublist P (X::L) K :- sublist P L K.
sublist P nil nil.

Read relationally [MN p. 126]: mappred P L K says the lists have equal length and are related pointwise by P; forsome P L says some member satisfies P; foreach P L says all members do; sublist P L K says K is an order-preserving sublist of L whose members all satisfy P. Because of the clause order, the maximal sublists come first. A small database:

kind name    type.
type bob, sue, ned   name.
type age     name -> int -> o.
type male, female    name -> o.

age bob 23 & age sue 24 & age ned 23.
male bob & female sue & male ned.

Example 5.8 (Queries over the database [MN p. 126–127]).

?- mappred age (ned::bob::sue::nil) L.
L = (23::23::24::nil)
?- mappred age L (23::24::nil).
L = (bob::sue::nil);
L = (ned::sue::nil)
?- sublist male (ned::bob::sue::nil) L.
L = ned::bob::nil;
L = ned::nil;
L = bob::nil;
L = nil;
no
?- forsome female (ned::bob::sue::nil).
solved
?- foreach female (ned::bob::sue::nil).
no

The second query runs mappred “backwards”: age is a relation, not a function, so the list of names is computed from the list of ages.

5.2.2λ-terms of predicate type as arguments

A predicate argument need not be a constant. x\ age jane x has type int -> o (it is η\eta-equivalent to age jane), and n\ age n 24 has type name -> o [MN p. 129]. The book reports:

?- (n\ age n 24) W.          % β-equal to ?- age W 24.
W = sue
?- mappred (x\y\ age x y) (ned::bob::sue::nil) L.
L = (23::23::24::nil)
?- mappred (x\y\ age y x) (23::24::nil) K.
K = (bob::sue::nil);
K = (ned::sue::nil)
?- foreach (x\ sigma y\ age x y) (ned::bob::sue::nil).
solved
?- foreach (x\ age x A) (ned::bob::sue::nil).
no
?- foreach (x\ age x A) (ned::bob::nil).
A = 23

Pitfall (A logic variable inside a λ is shared, not abstracted). In x\ age x A, the variable A lies outside the abstraction: the same A is used by every instance of the body. The last two queries therefore ask for a common age. Compare x\ sigma y\ age x y, where each element gets its own y.

Kanren angle (Predicate variables with known values are free). In a Scheme-hosted miniKanren, a predicate argument whose value is known when it is called is just a procedure that returns a goal. x\y\ age y x becomes (λ (x y) (age° y x)), and x\ sigma y\ age x y becomes (λ (x) (fresh° (y) (age° x y))). A logic variable captured by the Scheme λ is shared by every call, exactly as in the pitfall above:

;; Figure 5.4: the age database, one relation per predicate constant
(define-relation (age° n a)
  (cond° ((=° n 'bob) (=° a 23))
         ((=° n 'sue) (=° a 24))
         ((=° n 'ned) (=° a 23))))
(define-relation (male° n) (or° (=° n 'bob) (=° n 'ned)))
;; Figure 5.3: the argument P is a Scheme procedure returning a goal
(define-relation (mappred° P L K)
  (cond° ((null° L) (null° K))
         ((fresh° (X L* Y K*) (cons° X L* L) (cons° Y K* K)
            (P X Y) (mappred° P L* K*)))))
(define-relation (foreach° P L)
  (cond° ((null° L))
         ((fresh° (X L*) (cons° X L* L) (P X) (foreach° P L*)))))
(define-relation (sublist° P L K)
  (cond° ((fresh° (X L* K*) (cons° X L* L) (cons° X K* K)
            (P X) (sublist° P L* K*)))
         ((fresh° (X L*) (cons° X L* L) (sublist° P L* K)))
         ((null° L) (null° K))))

(show 1 (μkanren-run (q -1 #t) (mappred° age° '(ned bob sue) q)))
(show 2 (μkanren-run (q -1 #t) (mappred° age° q '(23 24))))
(show 3 (μkanren-run (q -1 #t) (sublist° male° '(ned bob sue) q)))
;; λ-terms of predicate type are Scheme lambdas
(show 4 (μkanren-run (q -1 #t) (mappred° (λ (x y) (age° y x)) '(23 24) q)))
(show 5 (μkanren-run (q -1 #t)
          (foreach° (λ (x) (fresh° (y) (age° x y))) '(ned bob sue))
          (=° q 'solved)))
(show 6 (μkanren-run (q -1 #t) (foreach° (λ (x) (age° x q)) '(ned bob sue))))
(show 7 (μkanren-run (q -1 #t) (foreach° (λ (x) (age° x q)) '(ned bob))))
1 ((23 23 24))
2 ((bob sue) (ned sue))
3 (() (bob) (ned) (ned bob))
4 ((bob sue) (ned sue))
5 (solved)
6 ()
7 (23)

Every answer set matches the book. The order of the sublist answers (line 3) does not, because cond° interleaves its branches while λProlog searches them depth-first in clause order. Compare answer sets unless the search strategy is part of the specification.

5.2.3Closures, composition and folds

Relations that take relations and return relations [MN p. 127–128]:

type ref, sym, trans   (A -> A -> o) -> A -> A -> o.
ref   R X Y :- X = Y; R X Y.
sym   R X Y :- R X Y; R Y X.
trans R X Y :- R X Y.
trans R X Z :- R X Y, trans R Y Z.

kind node  type.
type a, b, c, d, e   node.
type adj   node -> node -> o.
adj a b & adj b c & adj b d & adj d c & adj c e.

Both ?- trans adj a d. and ?- sym adj b a. succeed. Thanks to currying, the equivalence closure is just the partial application (trans (sym (ref adj))). The non-recursive closures can also be written as λ\lambda-terms, for example (x\y\ x = y ; adj x y). The book adds a warning [MN p. 128]. The transitive closure can be written declaratively as a single term,

x\y\ pi p\
   (pi U\ pi V\ adj U V => p U V) =>
   (pi U\ pi V\ pi W\ adj U V => p V W => p U W) =>
   p x y

but it contains ⊃\supset. It is therefore not in ℋ2Σ\mathcal{H}_2^\Sigma and cannot be passed as an argument (Section 5.1.3).

Union, composition and a left fold [MN p. 130]:

type union    (A -> B -> o) -> (A -> B -> o) -> A -> B -> o.
type compose  (A -> B -> o) -> (B -> C -> o) -> A -> C -> o.
type foldl    (A -> B -> B -> o) -> list A -> B -> B -> o.

union   R S X Y :- R X Y; S X Y.
compose R S X Y :- R X Z, S Z Y.
foldl P nil X X.
foldl P (Z::L) X Y :- P Z X W, foldl P L W Y.

If P : A -> B -> B -> o is a family of binary relations on B indexed by A, then (foldl P) composes them one after another along a list. Reversing a list then means pushing every element onto a stack and popping them all off [MN p. 130–131]:

kind stack   type -> type.
type emp     stack A.
type stk     A -> stack A -> stack A.
type empty   stack A -> o.
type enter, remove   A -> stack A -> stack A -> o.
type reverse list A -> list A -> o.

empty emp.
enter X S (stk X S).
remove X (stk X S) S.
reverse L K :- compose (foldl enter L) (foldl remove K) emp emp.

Kanren angle (Partial application is curried define). λProlog is curried, while define-relation has a fixed arity. A relation-returning relation is written with CHICKEN’s curried define, (define ((sym° R) x y) ...); a recursive one defines a local relation and returns it:

(define-relation (adj° x y)
  (cond° ((=° x 'a) (=° y 'b)) ((=° x 'b) (=° y 'c)) ((=° x 'b) (=° y 'd))
         ((=° x 'd) (=° y 'c)) ((=° x 'c) (=° y 'e))))
;; curried closure builders: (sym° R) is itself a binary relation
(define ((ref° R) x y) (or° (=° x y) (R x y)))
(define ((sym° R) x y) (or° (R x y) (R y x)))
(define (trans° R)
  (define-relation (T x z) (cond° ((R x z)) ((fresh° (y) (R x y) (T y z)))))
  T)
(show 1 (μkanren-run (q -1 #t) ((trans° adj°) 'a 'd) (=° q 'solved)))
(show 2 (μkanren-run (q -1 #t) ((sym° adj°) 'b 'a) (=° q 'solved)))
(show 3 (μkanren-run (q -1 #t) ((trans° adj°) 'a q)))
(show 4 (μkanren-run (q 1 #t)
          ((trans° (sym° (ref° adj°))) 'e 'a) (=° q 'solved)))
1 (solved)
2 (solved)
3 (b c d e c e)
4 (solved)

Line 3 shows that trans is a relation, not a set: c and e come back once per path. Line 4 uses the equivalence closure built by partial application. Composition and the stack-based reverse:

;; Figures 5.5 and 5.6: compose, foldl, and reverse through a stack
(define ((compose° R S) x y) (fresh° (z) (R x z) (S z y)))
(define-relation (foldl° P L X Y)
  (cond° ((null° L) (=° X Y))
         ((fresh° (Z L* W) (cons° Z L* L) (P Z X W) (foldl° P L* W Y)))))
(define-relation (enter° X S S*) (=° S* `(stk ,X ,S)))
(define-relation (remove° X S S*) (=° S `(stk ,X ,S*)))
(define-relation (reverse° L K)
  ((compose° (λ (s s*) (foldl° enter° L s s*))
             (λ (s s*) (foldl° remove° K s s*)))
   'emp 'emp))
(show 1 (μkanren-run (q -1 #t) (reverse° '(1 2 3) q)))
(show 2 (μkanren-run (q -1 #t) (foldl° enter° '(1 2 3) 'emp q)))
1 ((3 2 1))
2 ((stk 3 (stk 2 (stk 1 emp))))

The partial application (foldl enter L) becomes an explicit λ. None of this needs anything beyond Scheme closures.

5.2.4Binary clauses: continuation passing

Predicate variables of type 𝗈\mathsf{o} are goal-valued, so a program can pass its own continuation [MN p. 131]. For each predicate p:τ1→⋯→τj→𝗈p:\tau_1\to\cdots\to\tau_j\to\mathsf{o} introduce p′:τ1→⋯→τj→𝗈→𝗈p':\tau_1\to\cdots\to\tau_j\to\mathsf{o}\to\mathsf{o}, and write A′A' for (p′ t1…tj)(p'\,t_1\ldots t_j) when A=(p t1…tj)A=(p\,t_1\ldots t_j). Then rewrite every clause:

∀x¯ [A1∧⋯∧An⊃A0] (n>0) ⇝ ∀x¯ ∀K [ (A1′ (…(An′ K)… ))⊃(A0′ K) ]∀x¯ A0 ⇝ ∀x¯ ∀K [ K⊃(A0′ K) ] \begin{gathered} \forall\bar x\,[A_1\wedge\dots\wedge A_n\supset A_0]\ (n>0)\ \rightsquigarrow\ \forall\bar x\,\forall K\,[\,(A'_1\,(\dots(A'_n\,K)\dots))\supset(A'_0\,K)\,]\\ \forall\bar x\,A_0\ \rightsquigarrow\ \forall\bar x\,\forall K\,[\,K\supset(A'_0\,K)\,] \end{gathered}

with K:𝗈K:\mathsf{o}. Conjunction becomes explicit sequencing, and every clause body has at most one, possibly complex, atom. For example

adj a b.
adj b c.
path X Y :- adj X Y.
path X Y :- adj X Z, path Z Y.

becomes

adj' a b K :- K.
adj' b c K :- K.
path' X Y K :- adj' X Y K.
path' X Y K :- adj' X Z (path' Z Y K).

and ?- path X Y. is provable if and only if ?- path' X Y true. is provable [MN p. 132].

Kanren angle (Goals are already first-class). In μKanren a goal is a value, so the binary-clause form is an idiom, not a feature. The continuation is a goal argument:

;; Section 5.3: binary clauses, the continuation K is a goal
(define (adj/k° x y k)
  (cond° ((=° x 'a) (=° y 'b) k) ((=° x 'b) (=° y 'c) k)))
(define-relation (path/k° x y k)
  (cond° ((adj/k° x y k))
         ((fresh° (z) (adj/k° x z (path/k° z y k))))))
(show 1 (μkanren-run (q -1 #t)
          (fresh° (x y) (path/k° x y ✓°) (=° q (list x y)))))
(show 2 (μkanren-run (q -1 #t)
          (fresh° (x y) (path/k° x y (=° q (list x y))))))
1 ((a b) (b c) (a c))
2 ((a b) (b c) (a c))

In the second query the continuation does the work of the query itself. Conjunction in μKanren (andª, which feeds every state of the first goal to the second) is this same continuation composition.

5.2.5Memoisation with hidden, growing predicates

Example 5.9 (Memoised Fibonacci in hohh⁺ [MN p. 132]).

type fib_memo   int -> ((int -> int -> o) -> o) -> o.
fib_memo N G :-
   pi memo\ pi loop\
     memo 0 0 => memo 1 1 =>
     (pi F1\ pi F2\ pi F3\ pi C\ pi C'\
        (loop C F1 F2 :- (C >  N, (G memo)) ;
                         (C =< N, C' is C + 1, F3 is F1 + F2,
                          memo C F3 => loop C' F2 F3))) =>
     loop 2 0 1.

memo and loop are hidden predicates, bound by pi and used as heads of assumed clauses. The memo table grows through memo C F3 => .... When C > N, the continuation G, a predicate that takes a predicate, is called with the hidden name memo, whose extension is then {(0,0),(1,1),…,(N,fib N)}\{(0,0),(1,1),\ldots,(N,\mathit{fib}\,N)\}. For the query

?- fib_memo 20 (fib\ sigma M\ fib N M, M is N * N).

the book states, without listing them, that “there are exactly three values for N that make this atom provable” [MN p. 132]. A short computation gives N∈{0,1,12}N\in\{0,1,12\}: the continuation asks for fib N=N⋅N\mathit{fib}\,N=N\cdot N, and fib 0=0\mathit{fib}\,0=0, fib 1=1\mathit{fib}\,1=1, fib 12=144\mathit{fib}\,12=144.

This example mixes three things: higher-order programming, dynamic clause addition, and a hidden name handed to a continuation. A Scheme letrec cannot express the growing table, which is why the kanren box of Section 5.1.5 lists dynamic clauses as a genuine requirement.

5.3Flexible goals

What happens when a goal’s head is a variable that is still unbound when the goal is reached? Take P bob 23 against the age database. P := age works, but so do x\y\ age x 23, age ned y, x\y\ age sue 24, x\y\ memb 4 (3::4::5::nil), and in fact x\y\ g for any provable closed goal g [MN p. 132–133]. Such a goal is underconstrained. Three treatments are possible [MN p. 134]:

  1. Suspend the goal in the hope that other goals will instantiate its head, and resume it when it becomes rigid. If only flexible goals remain, solve each of them by instantiating its head with λx1. …λxn. ⊤\lambda x_1.\, \ldots\lambda x_n.\, \top, the universally true relation of the right type, which is “the (extensionally) largest one that works”.
  2. Eagerly bind the head to the universally true relation.
  3. Issue a run-time error.

The first option is complete with respect to provability in intuitionistic higher-order logic. The other two are incomplete. Yet experience with λProlog implementations says the third is the most useful while developing code: a flexible goal met by depth-first search is usually a bug, for example a predicate constant mistyped with a capital letter [MN p. 134]. Option 1 is the same idea that unification-based interpreters apply to flexible-flexible unification problems: the completeness results “provide the foundations for a unification-based interpreter … that explicitly delays the consideration of flexible-flexible unification problems as well as flexible goals” [MN p. 148].

A predicate variable becomes meaningful when the program first constrains it to a structured space of candidates [MN p. 133]:

kind i  type.
type jane, mary, john   i.
type mother, father, wife, husband   i -> i -> o.
type primrel, rel   (i -> i -> o) -> o.

primrel father & primrel mother & primrel wife & primrel husband.
rel R :- primrel R.
rel (x\y\ sigma z\ R x z, S z y) :- primrel R, primrel S.
mother jane mary & wife john jane.

?- R john mary. on its own is underconstrained. ?- rel R, R john mary. is meaningful: rel enumerates candidate relations, after which R john mary is rigid. The only answer is R = x\y\ sigma Z\ wife x Z, mother Z y. Note that the head of the second rel clause contains a λ\lambda-term with ∃\exists and ∧\wedge. This is legal because the term lies in ℋ1Σ\mathcal{H}_1^\Sigma. Whether a flexible goal is underconstrained thus “depends on when the goal is invoked” [MN p. 133]: goal order matters operationally.

Tutorial (Depth-first search for rel R, R john mary). Rename the clause variables of the second rel clause to R1 and S1, so that they are not confused with the query’s R.

  1. rel R backchains on the first clause and primrel R binds R := father. The second goal is now the rigid atom father john mary, which has no clauses and fails. Backtracking tries mother, wife and husband in turn; all fail the same way.
  2. rel R backchains on the second clause: R := x\y\ sigma z\ R1 x z, S1 z y, with the subgoals primrel R1 and primrel S1. After they bind R1 and S1, the goal R john mary is β\beta-reduced to sigma z\ R1 john z, S1 z mary, which is again built from rigid atoms.
  3. With R1 := father or R1 := mother the atom R1 john z fails for every choice of S1. With R1 := wife it gives z := jane; then S1 := father fails on father jane mary and S1 := mother succeeds on mother jane mary.

The answer is R with R1 and S1 instantiated, which is the book’s answer. The predicate variable is never invoked while unbound: rel always gives it a value first.

Kanren angle (Binding a logic variable to a relation: possible, but opaque). Any Scheme value can be bound to a logic variable, procedures included, so rel can be transcribed. The composed relation is built by project° once r and s are known, and invoking the value of R means walking it and applying it:

(import (chicken condition))
;; Figure 5.8: relations as values of logic variables
(define-relation (mother° x y) (=° x 'jane) (=° y 'mary))
(define-relation (wife° x y) (=° x 'john) (=° y 'jane))
(define-relation (father° x y) ✗°)
(define-relation (husband° x y) ✗°)
(define-relation (primrel° R)
  (cond° ((=° R father°)) ((=° R mother°)) ((=° R wife°)) ((=° R husband°))))
(define-relation (rel° R)
  (cond° ((primrel° R))
         ((fresh° (r s) (primrel° r) (primrel° s)
            (project° ((r* r) (s* s))
              (=° R (λ (x y) (fresh° (z) (r* x z) (s* z y)))))))))
;; invoking the value of R: walk it, then apply it
(define-relation (rel-john-mary° R)
  (rel° R) (project° ((R* R)) (R* 'john 'mary)))
(show 1 (μkanren-run (q -1 #f) (rel-john-mary° q)))
(show 2 (μkanren-run (q -1 #f) (fresh° (R) (rel-john-mary° R) (=° q 'found))))
;; a flexible goal: R is still unbound when it is invoked
(show 3 (handle-exceptions exn
            (list 'error ((condition-property-accessor 'exn 'message) exn))
          (μkanren-run (q -1 #t) (project° ((R* q)) (R* 'bob 23)))))
1 ((λ () #<procedure (? x y)>))
2 ((λ () (quote found)))
3 (error "call of non-procedure")

The search finds the single answer (line 2), but the answer itself is #<procedure (? x y)>, not x\y\ sigma Z\ wife x Z, mother Z y. Grounded reification (#t) even fails on it, because it evals the reified expression, and eval rejects a procedure as an “illegal non-atomic object”. Line 3 is a flexible goal: project° hands over an unbound variable record, and applying it is a Scheme error. That is the book’s option 3, but only by accident. Options 1 and 2 need a goal that can be inspected before it is run. Option 1 also needs a store of suspended goals that unification wakes up, much as the disequality store is re-checked after each =°. Printing R as a λ\lambda-term needs relations represented as terms. The proposal keeps relations as closures (Section 14.2.1); predicate quantification is sketched as Section 14.5.5.

5.4Reasoning about programs by substitution

Logic gives a means of reasoning about programs, and hidden predicates make it sharper [MN p. 134–136]. Claim: the second reverse of Section 5.1.5 is symmetric, that is, if reverse L K is provable then so is reverse K L. The proof outline [MN p. 135–136]:

  1. The only way to prove reverse L K is by backchaining, so its body is provable:

    pi rv\ ( rv nil K &
             (pi X\ pi N\ pi M\ rv (X::N) M :- rv N (X::M)))
           => rv L nil
  2. A provable universal has provable instances. Instantiate rv with x\y\ (not (rv y x)), where not is logical negation, not negation as failure:

    not(rv K nil) &
    (pi X\ pi N\ pi M\ not(rv M (X::N)) :- not(rv (X::M) N))
    => not(rv nil L).
  3. Take the contrapositive of each implication, which is classically valid:

    rv nil L & (pi X\ pi N\ pi M\ rv (X::M) N :- rv M (X::N))
    => rv K nil.
  4. This is a first-order Horn entailment, and on Horn clauses classical and intuitionistic provability coincide.

  5. Generalise over rv and rename M and N. The result is the body of reverse with L and K swapped. □

Intuitively, the trace of rv on (a::b::c::nil) is a table with rows (a::b::c::nil) nil, (b::c::nil) (a::nil), (c::nil) (b::a::nil), nil (c::b::a::nil). Swapping the columns and reading the rows in reverse order gives a valid trace for the reverse of (c::b::a::nil) [MN p. 135].

Three subtleties are worth noting. The rv inside the instantiating term x\y\ (not (rv y x)) is a new predicate variable that happens to reuse the name; step 5 generalises over it. The instantiating term contains ¬\neg, that is ⊃⊥\supset\bot, so it is not in ℋ2Σ\mathcal{H}_2^\Sigma. That is fine, because the argument uses the metatheory (soundness, then instantiation, contraposition and completeness), not goal-directed search. And the argument needs rv to be hidden: no other clause can mention it, so any λ\lambda-term may be “plugged in” at its place.

Kanren angle (Not available to closures). A relation that is a Scheme closure offers nothing to substitute into: the argument above treats the program as a formula. A port can at most turn the theorem into a property test (for random lists, reverse L K implies reverse K L). Reasoning of this kind belongs to a deep embedding, where clauses are data.

5.5Defining the logical constants

Predicate variables are powerful enough to define logical constants inside the logic [MN p. 136–137]. In hohc, clauses can specify the right-introduction rules:

type tt, ff   o.
type or       o -> o -> o.
type exists   (A -> o) -> o.
tt.                  % true
or P Q :- P.         % disjunction
or P Q :- Q.
exists B :- B T.     % existential quantifier

ff has no clauses, so proving it fails. Only the right rules are captured. The left rules (for example the rule of cases for a disjunctive hypothesis) are not. In hohh and hohh+^+, ∀\forall and ⊃\supset give the standard impredicative encodings [MN p. 136]:

⊥≡∀p p⊤≡∀p (p⊃p)B∨C≡∀p ((B⊃p)⊃(C⊃p)⊃p)∃x (G x)≡∀p ((∀x (G x⊃p))⊃p) \begin{gathered} \bot \equiv \forall p\,p \qquad \top \equiv \forall p\,(p\supset p)\\ B\vee C \equiv \forall p\,((B\supset p)\supset(C\supset p)\supset p)\\ \exists x\,(G\,x) \equiv \forall p\,((\forall x\,(G\,x\supset p))\supset p) \end{gathered}

(the last three are hohh+^+ goals, since pp heads assumed clauses and is bound by a positive ∀\forall).

Tutorial (Running the encodings). Goal-directed search reads them as follows. For ∀p p\forall p\,p, pp becomes a fresh constant with no clauses, so the goal fails. For ∀p ((B⊃p)⊃(C⊃p)⊃p)\forall p\,((B\supset p)\supset(C\supset p)\supset p), a fresh cc is created, the clauses cc :- BB and cc :- CC are assumed, and cc is proved by backchaining on either clause, that is, by proving BB or CC. For ∀p ((∀x (G x⊃p))⊃p)\forall p\,((\forall x\,(G\,x\supset p))\supset p), a fresh cc is created, the clause ∀x (c\forall x\,(c :- G x)G\,x) is assumed, and cc is proved by backchaining: xx becomes a logic variable XX and the goal G XG\,X remains.

Kanren angle (Which definitions are free). The hohc definitions are one-liners over existing goals: tt is ✓°, ff is ✗°, or is or°, and exists B :- B T is (fresh° (t) (B t)). The hohh encodings are not free. They need a goal-level ∀\forall that creates a fresh constant and a goal-level ⊃\supset that assumes clauses for it. Those are the two state extensions of the kanren box in Section 5.1.5.

5.6Conditional and negation-as-failure

With the cut !, the book defines a conditional and negation-as-failure [MN p. 137]:

type if   o -> o -> o -> o.
if P Q R :- P, !, Q.
if P Q R :- R.

type not  o -> o.
not P :- P, !, fail.
not P.
% alternatively
not P :- if P fail true.

if P Q R tries P. If it succeeds, the cut commits to its first solution and Q is proved; only if P fails is R proved. This is not logic: ?- X = 2, not (1 = X). succeeds, while ?- not (1 = X), X = 2. fails. “Thus even a basic property such as commutativity of conjunctions becomes invalid in this setting”, and the book uses these predicates “extremely sparingly” [MN p. 137–138].

Kanren angle (The cut as take° 1). (aux kanren micro) has the soft cut if°, which keeps every answer of its test (like miniKanren’s conda), and take°. The cut-based if commits to the first answer, so the faithful transcription of not P is (if° (take° 1 P) ✗° ✓°). The take° 1 is not cosmetic: without it, a test with infinitely many answers would make the conditional fail on each of them forever. The non-commutativity reproduces exactly, and the disequality constraint ≠° is the declarative alternative that commutes:

;; Section 5.7: not P :- if P fail true, the cut read as "first answer only"
(show 1 (μkanren-run (q -1 #t) (=° q 2) (if° (take° 1 (=° 1 q)) ✗° ✓°)))
(show 2 (μkanren-run (q -1 #t) (if° (take° 1 (=° 1 q)) ✗° ✓°) (=° q 2)))
;; the declarative alternative: a disequality constraint commutes
(show 3 (μkanren-run (q -1 #t) (=° q 2) (≠° 1 q)))
(show 4 (μkanren-run (q -1 #t) (≠° 1 q) (=° q 2)))
1 (2)
2 ()
3 (2)
4 (2)

5.7λ-terms as functions

So far the higher-order variables have been predicate variables. Variables of non-predicate functional type are instantiated by λ\lambda-terms that are only evaluated, by βη\beta\eta-conversion. As Chapter 4 showed, these functions are weak. “This weakness, however can be an asset for a different kind of computation: Rather than instantiating function variables with λ\lambda-terms, we can think of finding values for them by solving unification problems” [MN p. 138].

5.7.1mapfun and reducefun

type mapfun     (A -> B) -> list A -> list B -> o.
type reducefun  (A -> B -> B) -> list A -> B -> B -> o.

mapfun F nil nil.
mapfun F (X::L) ((F X)::K) :- mapfun F L K.

reducefun F nil Z Z.
reducefun F (H::T) Z (F H R) :- reducefun F T Z R.

Assume a type i, constants a, b, c, d : i and g : i -> i -> i.

Forwards. ?- mapfun (x\ g a x) (a::b::nil) L. has exactly one answer, L = ((g a a)::(g a b)::nil), obtained by β\beta-normalising ((x\ g a x) a) and ((x\ g a x) b) [MN p. 138]. mappred runs arbitrary goals, so it is strictly more powerful. In fact mapfun F L K :- mappred (x\y\ y = F x) L K.

Backwards: function synthesis. [MN p. 139]

?- mapfun F (a::b::nil) ((g a a)::(g a b)::nil).
F = x\ g a x                        % the only answer

The first element alone poses F a = g a a, which has four unifiers:

(x\ g x x)   (x\ g a x)   (x\ g x a)   (x\ g a a)

Only x\ g a x also solves F b = g a b, so an interpreter that tries another unifier first has to backtrack. Weakness can also show up as failure: ?- mapfun F (a::b::nil) (c::d::nil). answers no. Simply typed λ\lambda-terms cannot do case analysis on constants, so no term maps a to c and b to d (Chapter 4) [MN p. 139–140].

reducefun. Here + is only a term constructor, with no arithmetic [MN p. 140]:

?- reducefun (x\y\ x + y) (3::4::8::nil) 6 R.
R = 3 + (4 + (8 + 6));
?- reducefun F (4::8::nil) 6 (1 + (4 + (1 + (8 + 6)))).
F = x\y\ 1 + (4 + (1 + (8 + 6)));
F = x\y\ 1 + (x + (1 + (8 + 6)));
F = x\y\ 1 + (x + y);
no
?- pi z\ reducefun F (4::8::nil) z (1 + (4 + (1 + (8 + z)))).
F = x\y\ 1 + (x + y);
no

Tutorial (Why three answers, and then one). Unfolding the two clauses turns the second query into the single equation F 4 (F 8 6)=1+(4+(1+(8+6)))F\,4\,(F\,8\,6) = 1+(4+(1+(8+6))). Its solutions are the bodies obtained by abstracting some occurrences of the constants of the target consistently. The constant function abstracts nothing. The second answer abstracts the 4. The third abstracts both the 4 and the inner 1 + (8 + 6), which has the shape x + y. A candidate such as x\y\ 1 + (4 + y) fails, because F 8 6F\,8\,6 would give 1+(4+6)≠1+(8+6)1+(4+6)\neq 1+(8+6). In the third query, 66 is replaced by a new constant zz introduced by pi inside the scope of FF’s implicit ∃\exists. Instantiations of FF may not contain zz, and that eigenvariable check removes the two answers that would have to copy the base case into FF. Only the real fold function is left.

Kanren angle (Forwards is free, synthesising F is not). With F a Scheme procedure that builds a term, mapfun and reducefun run forwards unchanged. Since F is applied to a logic variable while the goal is being built, they also run backwards in the list argument:

;; Figure 5.10, forward mode only: F is a Scheme procedure that builds a term
(define-relation (mapfun° F L K)
  (cond° ((null° L) (null° K))
         ((fresh° (X L* K*) (cons° X L* L) (cons° (F X) K* K)
            (mapfun° F L* K*)))))
(define-relation (reducefun° F L Z R)
  (cond° ((null° L) (=° Z R))
         ((fresh° (H T R*) (cons° H T L) (=° R (F H R*))
            (reducefun° F T Z R*)))))
(show 1 (μkanren-run (q -1 #t) (mapfun° (λ (x) `(g a ,x)) '(a b) q)))
(show 2 (μkanren-run (q -1 #t)
          (reducefun° (λ (x y) `(+ ,x ,y)) '(3 4 8) 6 q)))
;; F is applied to a logic variable while the goal is built:
;; the term (g a X) contains X, so the list argument can be unknown
(show 3 (μkanren-run (q -1 #t)
          (mapfun° (λ (x) `(g a ,x)) q '((g a a) (g a b)))))
1 (((g a a) (g a b)))
2 ((+ 3 (+ 4 (+ 8 6))))
3 ((a b))

What cannot be transcribed is the case where F itself is unknown. A Scheme procedure is opaque, so there is nothing to unify F a against. Function synthesis needs λ\lambda-terms as data, with β\beta-normalisation, and a unifier that handles applications of a variable. The problems above, F a = g a a and F 4 R = ..., are not higher-order patterns in the sense of Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, because F is applied to constants. The first is a second-order matching problem (its right-hand side is closed); the second is close to one (the flexible side also contains the unknown R). Both need Huet-style branching Gérard Huet. A unification algorithm for typed λ\lambda-calculus. Theoretical Computer Science, 1:27–57, 1975 (see Chapter 7). Section 14.5.4 discusses where that belongs in (aux kanren micro).

5.7.2Functional difference lists

A first-order difference list (dl L K), with K a suffix of L, denotes L without K. For instance, both of the terms (dl (1::2::3::4::5::nil) (4::5::nil)) and (dl (1::2::3::L) L) denote the list (1::2::3::nil), and with the second form concatenation needs no recursion. A functional difference listDue to Brisset and Ridoux.Pascal Brisset and Olivier Ridoux. Naïve reverse can be linear. In Eighth International Logic Programming Conference, Paris, France, 1992. MIT Press represents the list as a function from its tail to the whole list [MN p. 140–142]. The book’s Figure 5.11 collects the labels of a binary tree into a list in two ways, with ordinary and with functional difference lists. Here are the declarations and the functional version:

kind dlist    type -> type.
type dl       list A -> list A -> dlist A.

type concat   dlist A -> dlist A -> dlist A -> o.
concat (dl L1 L2) (dl L2 L3) (dl L1 L3).

kind btree    type -> type.
type empty    btree A.
type bt       A -> btree A -> btree A -> btree A.

kind fdlist   type -> type.
type fdl      (list A -> list A) -> fdlist A.

type collect'  btree A -> list A -> o.
type aux'      btree A -> fdlist A -> o.
collect' Bt (A nil) :- aux' Bt (fdl A).
aux' empty (fdl x\ x).
aux' (bt N L R) (fdl x\ A (N::(B x))) :- aux' L (fdl A),
                                         aux' R (fdl B).

(fdl x\ (1::2::3::x)) denotes (1::2::3::nil), with a “pointer” to its tail. Each operation is a single unification [MN p. 142]:

  • head and tail: unify with x\ (H::(T x)); the head is H and the tail is (fdl T);
  • last and front: unify with x\ F (Y::x); the last element is Y and the front is (fdl F);
  • concatenation of (fdl A) and (fdl B): (fdl x\ A (B x)), that is, function composition;
  • conversion to a list: apply to nil, as (A nil) in collect'.

Palindromes then need no explicit reversal [MN p. 142]:

type palindrome   fdlist A -> o.
palindrome (fdl x\x).
palindrome (fdl x\ Y::x).
palindrome (fdl x\ Y::(F (Y::x))) :- palindrome (fdl F).
?- palindrome (fdl x\ a::b::c::b::a::x).
solved
?- palindrome (fdl x\ a::b::a::(F x)).
F = x\ x;
F = x\ b::a::x;
F = x\ a::b::a::x;
F = x\ Y::a::b::a::x;
F = x\ Z::Z::a::b::a::x;
F = x\ Y::Z::Y::a::b::a::x;
F = x\ Y::Z::Z::Y::a::b::a::x;
F = x\ Y::Z::U::Z::Y::a::b::a::x;
F = x\ Y::Z::U::U::Z::Y::a::b::a::x

The second query has infinitely many answers. It finds the F whose list, appended after a::b::a, makes a palindrome.

Pitfall (Types do not enforce the invariants). (dl (1::2::3::nil) (4::5::nil)) is well typed, but it does not denote a list in the intended sense. Likewise a function that ignores its argument, as in (fdl x\ (1::2::3::nil)), has no tail “pointer” [MN p. 143]. (The book prints the second term as (fdl x\ (1::2::3)), which is literally ill typed.)

Kanren angle (A closure is an fdl you can only run). In its intended mode (tree given, list wanted), collect' needs no higher-order unification. Every clause head is unified with a fresh variable, so the only requirement is λ\lambda-terms that can be built and applied. A Scheme closure provides that, using project° to compose once the parts are known:

;; Figure 5.11, collect' in its intended mode, an fdl as a Scheme closure
(define-relation (aux/fdl° bt F)
  (cond° ((=° bt 'empty) (=° F (λ (x) x)))
         ((fresh° (n l r a b) (=° bt `(bt ,n ,l ,r))
            (aux/fdl° l a) (aux/fdl° r b)
            (project° ((a* a) (b* b))
              (=° F (λ (x) (a* (cons n (b* x))))))))))
(define-relation (collect/fdl° bt L)
  (fresh° (a) (aux/fdl° bt a) (project° ((a* a)) (=° L (a* '())))))
(define tree '(bt 2 (bt 1 empty empty) (bt 3 empty empty)))
(show 1 (μkanren-run (q -1 #t) (collect/fdl° tree q)))
1 ((1 2 3))

project° makes this non-relational: it only works when the subtrees are known. The operations that make functional difference lists interesting (head and tail by unification with x\ (H::(T x)), last and front with x\ F (Y::x), palindrome, and collect' run backwards) all unify a pattern against a λ\lambda-term. They need λ\lambda-terms in the term language, and x\ F (Y::x) already applies a variable to a non-variable argument (Chapter 7).

5.8Higher-order unification is not a panacea

It is tempting to make higher-order unification do all the work. The book’s examples show why that is often a mistake [MN p. 143–145]. Take kind i type. type a,b i. type f i -> i -> i.. The aim is to abstract all occurrences of a in (f a (f a b)), that is, to obtain (x\ f x (f x b)). The naive program:

type extract_a  i -> (i -> i) -> o.
extract_a (F a) F.

?- extract_a (f a (f a b)) F.
F = x\ f x (f x b);
F = x\ f x (f a b);
F = x\ f a (f x b);
F = x\ f a (f a b);
no

With nn occurrences there are 2n2^n “extractions”. A cut, extract_a (F a) F :- !., relies on the order in which the unifiers are enumerated, so it is not declarative. Two better options:

  • Reorder the quantifiers so that the eigenvariable check does the selection:

    pi a\ sigma F\ (F a) = (f a (f a b)).   % four proofs
    sigma F\ pi a\ (F a) = (f a (f a b)).   % exactly one: F = x\ (f x (f x b))

    In the second line a is a constant that is new for F, so F cannot mention it and every occurrence must be abstracted. (This is also a higher-order pattern, F applied to a distinct bound variable, which is what makes it well behaved; see Chapter 6.)

  • Recurse on the syntax, using the signature of i:

    extract_a a x\x.
    extract_a b x\b.
    extract_a (f T S) (x\ f (U x) (V x)) :- extract_a T U, extract_a S V.

A second example is rewriting by congruence [MN p. 145]:

type rewrite  int -> int -> o.
rewrite (0 + X) X.
rewrite (1 * X) X.
rewrite (X - X) 0.
rewrite (C X) (C Y) :- rewrite X Y.

The last clause uses C as a “context with a hole”. rewrite ((1 * 5) - 5) (5 - 5) is derivable, but it has infinitely many derivations: the last clause can be used any number of times with C = x\x before C = x\ x - 5 is finally chosen. The remedy is again explicit recursion over the structure of terms.

Kanren angle (Interleaving as a home for non-unitary unification). Every example in this section is a case where unification returns a stream of solutions. In a miniKanren, alternative unifiers are naturally branches of a disjunction, and interleaving enumerates infinite families fairly. That fits Huet’s procedure Gérard Huet. A unification algorithm for typed λ\lambda-calculus. Theoretical Computer Science, 1:27–57, 1975 well. The lesson of the book still applies: design relations so that unification has at most one answer (patterns, structural recursion, the right quantifier order), and treat branching unification as a last resort. Chapter 7 and Section 14.5.4 take this up.

5.9Comparison with functional programming

Most higher-order idioms of Scheme or ML carry over to logic programming easily (mappred, sublist, folds). The book argues that the logic programming notion is stronger in two ways [MN p. 146–147]:

  1. predicate variables are only one kind of functional variable. Non-predicate function variables give new kinds of computation (Section 5.7), developed in Chapter 6 for syntax with binders;

  2. predicate expressions can be compared, intensionally:

    type eq_pred (A -> o) -> (A -> o) -> o.
    eq_pred R R.

    succeeds if and only if its arguments are unifiable predicate expressions. For example, ?- eq_pred (x\ p x, q x) (x\ q x, p x). fails whatever the clauses for p and q. The comparison is structural, modulo λ\lambda-conversion, not equality of sets. Functional languages forbid comparing functions because their semantics is extensional, and extensional equality is undecidable.

A design remark follows [MN p. 147]. If the only goal were functional-style higher-order programming, a more restricted syntax would do, for example one that forbids quantification over higher-order non-predicate types. What general higher-order quantification adds is λ\lambda-terms that represent syntax with binding, together with functional quantification to manipulate them. That was “much of the impetus for the development of λProlog”. Nor is λProlog a merger of functional and logic programming: typed λ\lambda-terms are too weak as functions for that [MN p. 148].

Kanren angle (Unification on closures is pointer identity). (aux kanren micro) unifies procedures by eq?, which is finer than λProlog’s λ\lambda-convertibility:

;; Section 5.10: unification on procedures is pointer identity (eq?)
(define-relation (age° n a)
  (cond° ((=° n 'bob) (=° a 23)) ((=° n 'sue) (=° a 24))))
(define (older-than n)
  (λ (x) (fresh° (a) (age° x a) (project° ((a* a)) (if (> a* n) ✓° ✗°)))))
(show 1 (μkanren-run (q -1 #t) (=° age° age°) (=° q 'same)))
(show 2 (μkanren-run (q -1 #t)
          (=° (older-than 20) (older-than 20)) (=° q 'same)))
(show 3 (μkanren-run (q -1 #t)
          (let ((p (older-than 20))) (=° p p)) (=° q 'same)))
1 (same)
2 ()
3 (same)

Two evaluations of the same λ with a captured value give distinct closures (line 2), whereas eq_pred (x\ p x) (x\ p x) succeeds in λProlog. Intensional comparison, and every feature that inspects a predicate (printing it, matching on it, eq_pred), needs predicates represented as terms.

5.10Modules: programming in the large with logic

Languages usually start with programming-in-the-small, and later “a second modules language is often imposed on the previously existing core language”. Its constructs may have “little or no connection” with the semantics of the core [MN p. 150]. Chapter 6 of the book argues the opposite for logic programming: the abstractions needed for modularity are already present in hohh+^+ [MN p. 150–151]:

  • composing code is conjunction of program clauses;
  • visibility of names is existential quantification over program clauses (in effect, ∀\forall in goals);
  • using a module to answer a query is an implicational goal E⊃GE\supset G.

The modules language is designed to support abstraction, information hiding, parametrization, interfaces and separate compilation. It must not complicate the meaning of the core language, and it must let higher-order programming coexist with modules (in Prolog, getting call/1 to interact correctly with modules). Finally, it should support a notion of module equivalence (representation independence) [MN p. 150–151].

5.10.1Modules, signatures and accumulation

A module is a named sequence of kind, type and clause declarations, and a signature with the same name is its interface [MN p. 152–153]. The book’s module smlists declares and defines id, memb, member (a deterministic membership test that uses the cut), an auxiliary revapp, reverse (via revapp), append and memb_and_rest (select an element and return the rest). Its signature is

sig smlists.
type id              list A -> list A -> o.
type memb, member    A -> list A -> o.
type reverse         list A -> list A -> o.
type append          list A -> list A -> list A -> o.
type memb_and_rest   A -> list A -> list A -> o.
end

The signature restricts the external visibility of the module’s names to exactly those it mentions, so revapp is hidden. Hiding applies to predicates and also to constants and data constructors, and “such hidden symbols remain hidden even through the results of computations” [MN p. 153]. A query [smlists] ?- revapp ... is ill formed: a static error, not a run-time failure [MN p. 154]. accumulate m1, ..., mn. conceptually inserts the code of the listed modules, after renaming their private constants, so that the accumulated copy is entirely local to the accumulating module [MN p. 154]. accum_sig inserts signatures, which is how names are re-exported [MN p. 155–156].

A module matches a signature when its implicit signature (its own declarations, plus the explicit signatures of the modules it accumulates) is mergeable with it: kinds are identical, types are identical up to renaming of type variables, and operator declarations agree [MN p. 156–158]. The book’s running example [MN p. 158]:

module m1.
kind   item   type.
type   p,q    item -> o.
type   a      item.
type   r      list item -> o.
p X :- q X.
r (a :: nil).
end

sig m1.
kind   item   type.
type   p,q    item -> o.
type   a      item.
end
module m2.
kind   item   type.
type   q, r   item -> o.
type   a      item.
q X :- r X.
r a.
end

sig m2.
kind   item   type.
type   q, r   item -> o.
type   a      item.
end
module m3.
accumulate m1, m2.
type   s, t   item -> o.
type   b      item.
s X :- p X.
t b.
end

sig m3.
kind   item   type.
type   s, t   item -> o.
type   a      item.
end

r is hidden in m1 at type list item -> o, while m2 exports an r : item -> o. The two never meet. If sig m1 also exported r, the signatures of m1 and m2 would not be mergeable and m3 would be ill formed [MN p. 159–160]. Hiding is what lets two modules use the same name at incompatible types. The name q, on the other hand, is exported by both m1 and m2 at the same type, so in m3 it is one constant. It is the only link between m1’s clause p X :- q X and m2’s clause q X :- r X.

5.10.2The logical reading: ∃ over clauses, ⊃ for queries

Two equivalences, valid in most logics, motivate the construction [MN p. 160]:

∃y ∀x (D(x)⊃G(y))≡∃y ((∃x D(x))⊃G(y))∃x (D1(x)∧D2)≡(∃x D1(x))∧D2 \begin{gathered} \exists y\,\forall x\,(D(x)\supset G(y)) \equiv \exists y\,((\exists x\,D(x))\supset G(y)) \\ \exists x\,(D_1(x)\wedge D_2) \equiv (\exists x\,D_1(x))\wedge D_2 \end{gathered}

(when xx is not free in G(y)G(y), respectively in D2D_2). The first says that a universal in a goal makes xx local to the clause D(x)D(x). The second lets the scope of such an ∃\exists be narrowed to part of a large conjunction.

Definition 5.10 (E-formulas [MN p. 161]). The goals of hohh+^+ are extended to

G::=⊤∣A∣G∧G∣G∨G∣∃x G∣E⊃G∣∀x GD::=Ar∣G⊃D∣D∧D∣∀x DE::=D∣E∧E∣∃x E \begin{aligned} G &::= \top \mid A \mid G\wedge G \mid G\vee G \mid \exists x\,G \mid E\supset G \mid \forall x\,G\\ D &::= A_r \mid G\supset D \mid D\wedge D \mid \forall x\,D\\ E &::= D \mid E\wedge E \mid \exists x\,E \end{aligned}

A rigid head may now also be a variable bound by an ∃\exists of an enclosing E-formula. E-formulas are not user syntax. They appear only in the translation of modules [MN p. 162].

A program contains only DD-formulas, so ⊃R{\supset}R is replaced by a small phase that decomposes the antecedent. It uses a sequent Σ;𝒫− ⁣⟨Δ⟩ ⁣ ⁣⟶G\Sigma;\mathcal{P}\mathrel{-\!\langle \Delta\rangle\!\!\longrightarrow}G, where Δ\Delta is a multiset of E-formulas [MN p. 161]:

Σ;𝒫− ⁣⟨E⟩ ⁣ ⁣⟶GΣ;𝒫⟶E⊃G  ⊃R′Σ;𝒫⟶GΣ;𝒫− ⁣⟨⟩ ⁣ ⁣⟶G  finishΣ;𝒫,D− ⁣⟨Δ⟩ ⁣ ⁣⟶GΣ;𝒫− ⁣⟨D,Δ⟩ ⁣ ⁣⟶G  reclassifyΣ;𝒫− ⁣⟨E1,E2,Δ⟩ ⁣ ⁣⟶GΣ;𝒫− ⁣⟨E1∧E2,Δ⟩ ⁣ ⁣⟶G  ∧L′Σ,y;𝒫− ⁣⟨E[y/x],Δ⟩ ⁣ ⁣⟶GΣ;𝒫− ⁣⟨∃x E,Δ⟩ ⁣ ⁣⟶G  ∃L′ (y∉Σ) \begin{gathered} \dfrac{\Sigma;\mathcal{P}\mathrel{-\!\langle E\rangle\!\!\longrightarrow}G}{\Sigma;\mathcal{P}\longrightarrow E\supset G}\;{\supset}\text{R}^{\prime} \qquad \dfrac{\Sigma;\mathcal{P}\longrightarrow G}{\Sigma;\mathcal{P}\mathrel{-\!\langle \rangle\!\!\longrightarrow}G}\;\text{finish} \qquad \dfrac{\Sigma;\mathcal{P},D\mathrel{-\!\langle \Delta\rangle\!\!\longrightarrow}G}{\Sigma;\mathcal{P}\mathrel{-\!\langle D,\Delta\rangle\!\!\longrightarrow}G}\;\text{reclassify} \\[2ex] \dfrac{\Sigma;\mathcal{P}\mathrel{-\!\langle E_1,E_2,\Delta\rangle\!\!\longrightarrow}G}{\Sigma;\mathcal{P}\mathrel{-\!\langle E_1\wedge E_2,\Delta\rangle\!\!\longrightarrow}G}\;\wedge\text{L}^{\prime} \qquad \dfrac{\Sigma,y;\mathcal{P}\mathrel{-\!\langle E[y/x],\Delta\rangle\!\!\longrightarrow}G}{\Sigma;\mathcal{P}\mathrel{-\!\langle \exists x\,E,\Delta\rangle\!\!\longrightarrow}G}\;\exists\text{L}^{\prime}\ (y\notin\Sigma) \end{gathered}

All these rules are invertible, so this phase never backtracks. “During this new phase, the local constants are introduced dynamically into computation, and the clauses using these new constants are integrated with the ambient logic program” [MN p. 161]. Note that ∃L′\exists L' is the same mechanism as ∀R\forall R for goals: a fresh constant is added to Σ\Sigma.

Definition 5.11 (A module as a formula [MN p. 162]). Let h1,…,hkh_1,\ldots,h_k be the hidden constants of a module MM, that is, those in its implicit signature but not in its explicit one. If MM accumulates M1,…,MnM_1,\ldots,M_n and has its own clauses C1,…,CmC_1,\ldots,C_m, then

⟦M⟧=∃h1⋯∃hk (⟦M1⟧∧⋯∧⟦Mn⟧∧C1∧⋯∧Cm). \llbracket M\rrbracket = \exists h_1\cdots\exists h_k\,\big(\llbracket M_1\rrbracket\wedge\cdots\wedge\llbracket M_n\rrbracket\wedge C_1\wedge\cdots\wedge C_m\big).

A query [M] ?- g X. is the goal ∃x (⟦M⟧⊃g x)\exists x\,(\llbracket M\rrbracket\supset g\,x) [MN p. 163].

For the running example [MN p. 162–163]:

⟦m1⟧=∃r ((∀x(q x⊃p x))∧(r (a::nil)))⟦m2⟧=∀x(r x⊃q x)∧(r a)⟦m3⟧=∃p∃q∃r∃b(∃r((∀x(q x⊃p x))∧(r (a::nil)))∧(∀x(r x⊃q x)∧(r a))∧(∀x(p x⊃s x)∧(t b))) \begin{aligned} \llbracket m1\rrbracket &= \exists r\,\big((\forall x(q\,x\supset p\,x))\wedge (r\,(a::nil))\big)\\ \llbracket m2\rrbracket &= \forall x(r\,x\supset q\,x)\wedge(r\,a)\\ \llbracket m3\rrbracket &= \exists p\exists q\exists r\exists b\Big(\exists r\big((\forall x(q\,x\supset p\,x))\wedge(r\,(a::nil))\big)\\ &\qquad\qquad\wedge(\forall x(r\,x\supset q\,x)\wedge(r\,a))\wedge(\forall x(p\,x\supset s\,x)\wedge(t\,b))\Big) \end{aligned}

The inner ∃r\exists r (m1’s private r) shadows the outer one (m2’s exported r, hidden again by m3), as α\alpha-conversion dictates. a, s and t stay free, because they are m3’s exports.

Tutorial (Using a hidden constant versus exposing it). The book reports [MN p. 163–164]:

[m3] ?- sigma x\ t x.      % succeeds (x instantiated to the hidden constant b)
[m3] ?- t X.               % FAILS

[m3] ?- p a. is ill formed (p is not in sig m3), and [m3] ?- s a. succeeds. The difference between the first two lies in where the quantifiers sit.

  • t X is ∃x (⟦m3⟧⊃t x)\exists x\,(\llbracket m3\rrbracket\supset t\,x). The logic variable XX is created first, at a signature that does not contain b. Then ⊃R′{\supset}R' and ∃L′\exists L' introduce a fresh b′b'. Backchaining on t b' needs X:=b′X := b', which is not a term over XX’s signature, so the goal fails.
  • sigma x\ t x is ⟦m3⟧⊃∃x (t x)\llbracket m3\rrbracket\supset\exists x\,(t\,x). ∃L′\exists L' adds b′b' to the signature before the existential is processed, so b′b' is an admissible witness and the goal succeeds.

In the book’s words, this is “the difference between using a constant in the course of searching for a solution … and attempting to expose the identity of this constant externally” [MN p. 164].

Tutorial (The rules of the E-phase at work on [m3] ?- s a.). The query has no logic variables, so it is the goal ⟦m3⟧⊃s a\llbracket m3\rrbracket\supset s\,a. Read the derivation bottom-up, starting from the empty program:

  1. ⊃R′{\supset}R' moves ⟦m3⟧\llbracket m3\rrbracket into the E-multiset: Σ;∅− ⁣⟨⟦m3⟧⟩ ⁣ ⁣⟶s a\Sigma;\emptyset\mathrel{-\!\langle \llbracket m3\rrbracket\rangle\!\!\longrightarrow}s\,a.
  2. ∃L′\exists L' four times introduces fresh constants p′,q′,r′,b′p',q',r',b' for m3’s hidden names and adds them to Σ\Sigma.
  3. ∧L′\wedge L' splits the body into its conjuncts: m1’s formula ∃r (…)\exists r\,(\ldots), the clauses ∀x(r′ x⊃q′ x)\forall x(r'\,x\supset q'\,x) and r′ ar'\,a from m2, and the clauses ∀x(p′ x⊃s x)\forall x(p'\,x\supset s\,x) and t b′t\,b' of m3.
  4. ∃L′\exists L' once more introduces a fresh r′′r'' for m1’s private r, and ∧L′\wedge L' yields ∀x(q′ x⊃p′ x)\forall x(q'\,x\supset p'\,x) and r′′ (a::nil)r''\,(a::nil).
  5. reclassify moves each of these DD-formulas into the program, and finish returns to an ordinary sequent Σ,p′,q′,r′,b′,r′′;𝒫m3⟶s a\Sigma,p',q',r',b',r'';\mathcal{P}_{m3}\longrightarrow s\,a.
  6. Backchaining now proves s as\,a from p′ ap'\,a, p′ ap'\,a from q′ aq'\,a, q′ aq'\,a from r′ ar'\,a, and r′ ar'\,a is a fact.

Steps 1–5 make no choices, which is what invertibility means in practice: loading a module never backtracks. The fact r′′ (a::nil)r''\,(a::nil) is never used, and it could not be: no clause outside m1’s own formula can mention r′′r''.

Elaboration. Rather than replay Definition 5.11 for every query, an implementation inlines the accumulated modules and renames their private names. The elaborated m3 contains the clauses p X :- q X., r' (a :: nil)., q X :- r X., r a., s X :- p X. and t b., where r' is a new name for m1’s local r [MN p. 165]. The book’s implementation section adds that, at run time, the machinery that already handles alternating ∃/∀\exists/\forall in goals also handles local constants, provided they are annotated properly when the module is used to prove queries [MN p. 172].

5.10.3Abstract datatypes

Exporting a type constructor while hiding its data constructors gives an abstract datatype [MN p. 166]:

sig stack.
kind store           type -> type.
type init            store A -> o.
type add, remove     A -> store A -> store A -> o.
end
module stack.
kind store           type -> type.
type emp             store A.
type stk             A -> store A -> store A.
type init            store A -> o.
type add, remove     A -> store A -> store A -> o.
init emp.
add    X S (stk X S).
remove X (stk X S) S.
end

[stack] ?- init A. fails, because it tries to exhibit the representation of the empty stack. [stack] ?- sigma A\ sigma B\ sigma C\ init A, add 1 A B, remove X B C. uses the representation anonymously and succeeds with X = 1 [MN p. 166]. A client such as graph_search can hold store values in its variables, but only init, add and remove can examine them [MN p. 167].

Extension and parametrization. An exported predicate can be extended by later modules. A propositional prover proplogic exports the type form and the predicate prove, and a module quantlogic that accumulates it adds both constructors and clauses [MN p. 168–169]:

sig quantlogic.
accum_sig proplogic.
kind term        type.
type all, some   (term -> form) -> form.
end

module quantlogic.
accumulate proplogic, smlists.
kind term        type.
type all, some   (term -> form) -> form.

prove L F :- memb_and_rest (some P) L L',
             pi c \ prove ((P c)::L) F.
prove L (all P) :- pi c\ prove L (P c).
prove L (some P) :- prove L (P T).
prove L F :- memb_and_rest (all P) L L',
             append L' [all P] L'', prove ((P T)::L'') F.
end

This works because form and prove are in proplogic’s explicit signature, so accumulation neither renames nor hides them. The recursive calls inside proplogic’s clauses reach the new quantifier clauses too. Both provers accumulate smlists, which gives two private copies. The book calls this “at least wasteful” [MN p. 169] and offers an alternative: accumulate the signature smlists into both modules, and supply one implementation when everything is accumulated at the top [MN p. 170]. Parametrization is then done by shared names that are closed at the top, not by passing arguments explicitly.

5.10.4Higher-order programming and predicate visibility

The test case for the second desideratum [MN p. 171]:

sig comblibrary.
type  call  o -> o.
end

module comblibrary.
type  call  o -> o.
type  p  list int -> o.
p (1 :: nil).
call Q :- Q.
end

sig test.
type  test  list int -> o.
end

module test.
accumulate comblibrary.
type  test  list int -> o.
type  p  list int -> o.
p (2 :: nil).
test X :- call (p X).
end

For [test] ?- test X., which p does call (p X) invoke: the one visible where call is defined (X = 1 :: nil), or the one visible where the name is written (X = 2 :: nil)? “The second interpretation is the commonly used resolution”, and it “is a natural consequence of the semantics that we have presented” [MN p. 171]. In the elaborated module, comblibrary’s p is renamed p', so the only answer is 2 :: nil [MN p. 171–172]. p X is a term of type o whose head is fixed when the program is parsed. It is not a name looked up at run time.

Kanren angle (Modules: what Scheme scoping gives, and what it does not). Scheme’s lexical scope already does module elaboration with renaming: a local definition is private, and each evaluation of a scope creates fresh closures. Goals are closures, so Figure 6.10 resolves to the book’s “second interpretation” automatically. A Scheme-level abstract type is equally easy:

;; Figure 6.10: a "module" is a lexical scope returning its exported relations
(define call°                            ; module comblibrary, exports call
  (let ()
    (define-relation (p l) (=° l '(1)))  ; hidden
    (define (call g) g)
    call))
(define test°                            ; module test, exports test
  (let ()
    (define-relation (p l) (=° l '(2)))
    (define-relation (test x) (call° (p x)))
    test))
(show 1 (μkanren-run (q -1 #t) (test° q)))
;; Figure 6.6: the stack "abstract datatype", constructors made by gensym
(define-values (init° add° remove°)
  (let ((emp (gensym 'emp)) (stk (gensym 'stk)))
    (define-relation (init s) (=° s emp))
    (define-relation (add x s s*) (=° s* (list stk x s)))
    (define-relation (remove x s s*) (=° s (list stk x s*)))
    (values init add remove)))
(show 2 (μkanren-run (q -1 #t)
          (fresh° (a b c) (init° a) (add° 1 a b) (remove° q b c))))
(show 3 (μkanren-run (q -1 #f) (init° q)))
1 ((2))
2 (1)
3 ((λ () (quote emp224)))

Line 1 is the book’s answer, and line 2 uses the stack anonymously, as the sigma query does. Line 3 shows the honest difference. Scheme hides the name emp, but the answer to init A still exhibits the representation, where λProlog fails. Matching the book needs hidden constructors that are eigen-constants, introduced when the module is used, and a scope check in unification that stops a query variable created earlier from being bound to them. That is the same machinery as ∀\forall in goals (Section 5.1.5). Two more things are not free. One is extensible predicates (quantlogic adding clauses to proplogic’s prove), because a define-relation is closed. The other is parametrization by shared names closed at the top. Signature matching is mostly about types and kinds, which an untyped miniKanren can only approximate (names and arities). The proposal is in Chapter 11 and Chapter 12. One rule follows directly from Figure 6.10: never resolve a relation from a symbol at run time, because that reintroduces exactly the Prolog call/1 ambiguity.

5.11What a Scheme-hosted miniKanren gets for free

Table 5.1 collects the kanren boxes of this chapter.

FeatureWith closuresWhat is needed beyond closures
mappred, foreach, forsome, sublist, folds, composefreenothing (curried define for partial application)
λ\lambda-terms of predicate type as argumentsfreenothing (Scheme λ)
closures ref/sym/trans, binary clauses (CPS)freenothing
hidden predicates with fixed clauses (reverse)freelexical scope
if, notfreeif° with take° 1
mapfun/reducefun forwards, collect' forwardsfreeclosures that build terms; project°
module hiding, predicate visibility (Fig. 6.10)freelexical scope
rel R, R john maryopaque answersrelations as terms, to print or compare them
flexible goalsaccidental errorinspectable goals; a store of suspended goals
growing hidden predicates (fib_memo), ∀\forall/⊃\supset encodings of ∨\vee, ∃\existsnogoal-level ∀\forall (eigenvariables, scope check) and ⊃\supset (dynamic clauses)
abstract datatypes that stay hidden in answerspartialeigen-constants and a scope check
extensible predicates across modulesnoopen clause sets, linking
eq_pred, reasoning by substitutionnopredicates and clauses as λ\lambda-terms
mapfun/reducefun backwards, extract_a, palindrome, fdl destructuringnoλ\lambda-terms, βη\beta\eta-normalisation, higher-order unification
Table 5.1: Book features versus a miniKanren whose relations are Scheme procedures.

The dividing line is simple. Whatever only calls a predicate or a function is free, because a Scheme procedure can be called. Whatever must look inside one (unify it, print it, compare it, synthesise it) needs λ\lambda-terms in the term language. A third group, ∀\forall and ⊃\supset in goals, needs neither λ\lambda-terms nor inspection but does need new components in the search state: eigenvariables with a scope check, and a dynamic clause store. Chapter 11 builds on this classification.

5.12Summary

  • Atoms are rigid (constant head) or flexible (variable head). Clause heads must be rigid, which keeps programs consistent and modular; flexible atoms are allowed in goals.
  • Implications may not occur inside terms. Instantiation terms are drawn from Herbrand universes: ℋ1\mathcal{H}_1 (no ∀,⊃\forall,\supset) for hohc and ℋ2\mathcal{H}_2 (no ⊃\supset) for hohh. Goal-directed search is then complete: classical and intuitionistic for hohc, intuitionistic for hohh.
  • hohh+^+ lets a variable bound by an essentially universal quantifier head assumed clauses, which gives hidden, closed predicate definitions.
  • Predicate variables give mappred, sublist, closures, compose, foldl and the CPS transformation. Logic variables inside a λ\lambda are shared.
  • An unbound flexible goal is underconstrained. Suspending it is complete; in practice it is reported as an error. Constrain predicate variables first (rel R, R john mary).
  • Hidden predicates support reasoning by substitution (the symmetry of reverse). Logical constants are definable. if and not via cut are non-logical.
  • Function variables are evaluated by βη\beta\eta and can be synthesised by unification (mapfun, reducefun, functional difference lists). Higher-order unification is not unitary, so prefer structural recursion and the right quantifier order.
  • Unlike functions in functional programs, predicate expressions can be compared intensionally, with eq_pred.
  • Modules are logic: conjunction composes code, ∃\exists over clauses hides names, and a query against a module is ∃x (⟦M⟧⊃G)\exists x\,(\llbracket M\rrbracket\supset G). Hidden constants may be used but not exposed, and predicate names resolve statically.
  • In a Scheme-hosted miniKanren, calling is free and looking inside is not; ∀\forall and ⊃\supset in goals need new state (Table 5.1 and Chapter 11).