Chapter 8

Applications: provers, functional programs, processes

The previous chapters assembled three tools: λ\lambda-tree syntax, which represents object-level binders by meta-level abstractions (Chapter 6); the universal and implicational goals of hereditary Harrop formulas, which give fresh constants and scoped hypotheses (Chapter 3); and the unification of λ\lambda-terms, decidable and most-general in the pattern fragment LλL_\lambda (Chapter 7). Chapters 9–11 of the bookDale Miller and Gopalan Nadathur. Programming with Higher-Order Logic. Cambridge University Press, Cambridge, 2012 put the three to work on three families of meta-programs: proof systems (intuitionistic and classical provers, proof checkers, tactics), functional programs (type inference, evaluators, partial evaluation, CPS conversion) and processes (the π\pi-calculus, its transitions, traces, and an encoding of the λ\lambda-calculus).

All three follow the same recipe, and it is the main idea of this chapter:

  1. a judgment of the object system becomes a predicate, and each inference rule becomes a clause (the book calls this a “reflection of provability relations directly into predicates”, [MN p. 240]);
  2. object-level binders are meta-level λ\lambdas, so object-level substitution is β\beta-reduction;
  3. to go under a binder, the program introduces a fresh constant with pi x\ ... and, usually, a hypothetical fact about it with =>.

The side conditions that clutter the usual presentations (“yy fresh”, “yy not free in the conclusion”, “w∉fn(P)w\notin fn(P)”) then disappear: the nesting of quantifiers already enforces them. For each application we ask three questions, since they decide what a miniKanren needs: which binding facilities does it use (∀\forall, ⊃\supset, pattern unification, more than patterns)? Which part runs on today’s (aux kanren micro) with a first-order encoding? What changes when depth-first search is replaced by miniKanren’s interleaving search? Four small ports below were actually run on (aux kanren micro). Their outputs are reproduced verbatim.

8.1Proof systems as logic programs

8.1.1Intuitionistic propositional logic: from a loop to a decision procedure

Formulas are built from two constants and three connectives [MN p. 229–230]:

kind  term, form    type.             % types for terms and formulas
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.

A sequent Γ⟶G\Gamma\longrightarrow G has a multiset Γ\Gamma of hypotheses and one conclusion. The book’s starting point is the following calculus [MN p. 230]. (In the printed figure the axiom for ⊤\top is mislabelled ⊥L\bot L.)

Γ,A⟶A  init (A atomic)Γ,⊥⟶G  ⊥LΓ⟶⊤  ⊤RΓ,A,B⟶GΓ,A∧B⟶G  ∧LΓ⟶AΓ⟶BΓ⟶A∧B  ∧RΓ,A⟶GΓ,B⟶GΓ,A∨B⟶G  ∨LΓ⟶AiΓ⟶A1∨A2  ∨RiΓ,A⊃B⟶AΓ,B⟶GΓ,A⊃B⟶G  ⊃LΓ,A⟶BΓ⟶A⊃B  ⊃R \begin{gathered} \dfrac{}{\Gamma, A\longrightarrow A}\;\text{init}\ (A\text{ atomic}) \qquad \dfrac{}{\Gamma,\bot\longrightarrow G}\;\bot L \qquad \dfrac{}{\Gamma\longrightarrow\top}\;\top R \\[2ex] \dfrac{\Gamma,A,B\longrightarrow G}{\Gamma,A\land B\longrightarrow G}\;\land L \qquad \dfrac{\Gamma\longrightarrow A \qquad \Gamma\longrightarrow B}{\Gamma\longrightarrow A\land B}\;\land R \\[2ex] \dfrac{\Gamma,A\longrightarrow G \qquad \Gamma,B\longrightarrow G}{\Gamma,A\lor B\longrightarrow G}\;\lor L \qquad \dfrac{\Gamma\longrightarrow A_i}{\Gamma\longrightarrow A_1\lor A_2}\;\lor R_i \\[2ex] \dfrac{\Gamma,A\supset B\longrightarrow A \qquad \Gamma,B\longrightarrow G}{\Gamma,A\supset B\longrightarrow G}\;\supset L \qquad \dfrac{\Gamma,A\longrightarrow B}{\Gamma\longrightarrow A\supset B}\;\supset R \end{gathered}

Why the direct translation loops. Each rule, read from conclusion to premises, removes a connective, except ⊃L\supset L, whose left premise still contains the principal formula A⊃BA\supset B. The instance

p⊃q⟶qq⟶qp⊃q⟶q  ⊃L \dfrac{p\supset q\longrightarrow q \qquad q\longrightarrow q}{p\supset q\longrightarrow q}\;\supset L

has a left premise identical to its conclusion. A depth-first interpreter that tries this premise first recurses forever. The book: “Depth-first search usually steers the interpreter into endless loops when trying to work backwards from a given sequent” [MN p. 230]. Soundness of such direct translations is easy. Completeness of their execution is not.

The cure: a better calculus, not a better interpreter. Replace ⊃L\supset L by six rules that look at the shape of the antecedentRoy Dyckhoff. Contraction-free sequent calculi for intuitionistic logic. Journal of Symbolic Logic, 57(3):795–807, 1992; and Jörg Hudelmaier. Bounds on cut-elimination in intuitionistic propositional logic. Archive for Mathematical Logic, 31:331–353, 1992 ([MN p. 231]). (The text says “four rules”. The figure shows six.)

Γ,A,B⟶GΓ,A,A⊃B⟶G  ⊃L1 (A atomic)Γ,C⊃D⊃B⟶GΓ,(C∧D)⊃B⟶G  ⊃L2Γ,C⊃B,D⊃B⟶GΓ,(C∨D)⊃B⟶G  ⊃L3Γ,D⊃B⟶C⊃DΓ,B⟶GΓ,(C⊃D)⊃B⟶G  ⊃L4Γ⟶GΓ,⊥⊃B⟶G  ⊃L5Γ,B⟶GΓ,⊤⊃B⟶G  ⊃L6 \begin{gathered} \dfrac{\Gamma,A,B\longrightarrow G}{\Gamma,A,A\supset B\longrightarrow G}\;{\supset}L_1\ (A\text{ atomic}) \qquad \dfrac{\Gamma,C\supset D\supset B\longrightarrow G}{\Gamma,(C\land D)\supset B\longrightarrow G}\;{\supset}L_2 \\[2ex] \dfrac{\Gamma,C\supset B,D\supset B\longrightarrow G}{\Gamma,(C\lor D)\supset B\longrightarrow G}\;{\supset}L_3 \qquad \dfrac{\Gamma,D\supset B\longrightarrow C\supset D \qquad \Gamma,B\longrightarrow G}{\Gamma,(C\supset D)\supset B\longrightarrow G}\;{\supset}L_4 \\[2ex] \dfrac{\Gamma\longrightarrow G}{\Gamma,\bot\supset B\longrightarrow G}\;{\supset}L_5 \qquad \dfrac{\Gamma,B\longrightarrow G}{\Gamma,\top\supset B\longrightarrow G}\;{\supset}L_6 \end{gathered}

Theorem 8.1 (Hudelmaier, Dyckhoff; [MN p. 230–231]). The calculus obtained by replacing ⊃L\supset L with ⊃L1{\supset}L_1–⊃L6{\supset}L_6 is sound and complete for this fragment of propositional intuitionistic logic, and every sequence of sequents produced by backward proof search is finite. A weight can be assigned to connectives and sequents so that every conclusion weighs more than each of its premises. Consequently the direct translation of the calculus into λ\lambdaProlog “actually constitutes a decision procedure” [MN p. 231].

The book does not give the weight function. Provability in this logic is PSPACE-complete (Statman, cited on [MN p. 245]). Here is the program [MN p. 232]:

type  atom     form -> o.
type  seq      list form -> form -> o.

seq Gamma A :- atom A, memb_and_rest A Gamma _.
seq Gamma tt.
seq Gamma (A && B)  :- seq Gamma A, seq Gamma B.
seq Gamma (A !! B)  &
seq Gamma (B !! A)  :- seq Gamma A.
seq Gamma (A ==> B) :- seq (A::Gamma) B.
seq Gamma _ :- memb_and_rest ff Gamma _.
seq Gamma G :- memb_and_rest (A && B) Gamma Gamma',
               seq (A::B::Gamma') G.
seq Gamma G :- memb_and_rest (A !! B) Gamma Gamma',
               (seq (A::Gamma') G; seq (B::Gamma') G).
seq Gamma G :- memb_and_rest (A ==> B) Gamma Gamma',
  ( atom A, memb_and_rest A Gamma' _, seq (B::Gamma') G;
    A = (C && D),  seq ((C ==> D ==> B)::Gamma') G;
    A = (C !! D),  seq ((C ==> B)::(D ==> B)::Gamma') G;
    A = (C ==> D), seq ((D ==> B)::Gamma') A,
                   seq (B::Gamma') G;
    A = ff,        seq Gamma' G;
    A = tt,        seq (B::Gamma') G  ).

The relation memb_and_rest X L R (from [MN p. 58]) holds when L contains X and R is L with that occurrence removed. It plays the role of multiset selection. The head H1 & H2 :- B is two clauses sharing a body, so one line gives both ∨R\lor R rules. The last clause is ⊃L1{\supset}L_1–⊃L6{\supset}L_6 written as a single six-way disjunction on the shape of A. The predicate atom is deliberately left open: “This predicate can be defined simply by adding clauses to the program that enumerate all the propositional letters” [MN p. 231]. The book proves the formula a⊃(a⊃b)⊃(a⊃b⊃c)⊃ca\supset(a\supset b)\supset(a\supset b\supset c)\supset c by introducing the letters locally [MN p. 231] (the printed formula has an unbalanced parenthesis):

?- pi a\ pi b\ pi c\ atom a => atom b => atom c =>
              seq nil (a ==> (a ==> b) ==> (a ==> b ==> c) ==> c).

The query “achieves the same effect by introducing three new constants and assuming that each of them satisfies the atom predicate” [MN p. 231]. It succeeds. It is a compact showcase of pi (fresh constants) together with => (local clauses).

Tutorial (the proof the program finds). Three ⊃R\supset R steps give the context [a⊃b⊃c, a⊃b, a][a\supset b\supset c,\ a\supset b,\ a] (most recent first, since ⊃R\supset R conses) and goal cc. The atom cc is not in the context. memb_and_rest (A ==> B) first selects a⊃(b⊃c)a\supset(b\supset c). Since aa is present, ⊃L1{\supset}L_1 replaces it by b⊃cb\supset c. On this implication ⊃L1{\supset}L_1 fails because bb is not yet present, so the search backtracks to a⊃ba\supset b, and ⊃L1{\supset}L_1 adds bb. Now ⊃L1{\supset}L_1 on b⊃cb\supset c adds cc, and init closes the branch. No rule ever puts back the formula it consumed. This is the decreasing weight of Theorem 8.1 at work.

Pitfall (a typo that makes the prover unsound). The ∨L\lor L clause printed in the figure reads (seq (A::Gamma') G; seq (B::Gamma') G). It succeeds if either branch succeeds, but ∨L\lor L needs both premises. With ; the sequent a∨b⟶aa\lor b\longrightarrow a is “proved”. The body must be the conjunction seq (A::Gamma') G, seq (B::Gamma') G. The page image confirms the semicolon is really there. The run below shows both versions.

Kanren angle (the decision procedure on today’s (aux kanren micro)). Nothing in this program needs binders, so it ports to (aux kanren micro) directly. Formulas become tagged lists, atoms become Scheme symbols, and atom becomes the type constraint symbol°. The constraint does not enumerate letters, and it stays pending if its argument is unbound. Because tt and ff are symbols too, they are excluded with ≠°. The parameter both chooses how the two ∨L\lor L premises combine: andª gives the correct rule, orª the printed typo.

(define-relation (atom° a) (symbol° a) (≠° a 'tt) (≠° a 'ff))

(define-relation (memb-and-rest° x l rest)
  (cond° ((fresh° (d) (=° l (cons x d)) (=° rest d)))
         ((fresh° (y d r) (=° l (cons y d)) (=° rest (cons y r)) (memb-and-rest° x d r)))))

;; Figure 9.3, with the ∨L clause written as a conjunction; `both` combines the two ∨L premises
(define ((seq°/with both) Γ G)
  (define seq° (seq°/with both))
  (λ (s)
    (δ ((cond°
          ((atom° G) (fresh° (r) (memb-and-rest° G Γ r)))
          ((=° G 'tt))
          ((fresh° (A B) (=° G `(&& ,A ,B)) (seq° Γ A) (seq° Γ B)))
          ((fresh° (A B) (=° G `(!! ,A ,B)) (or° (seq° Γ A) (seq° Γ B))))
          ((fresh° (A B) (=° G `(==> ,A ,B)) (seq° `(,A . ,Γ) B)))
          ((fresh° (r) (memb-and-rest° 'ff Γ r)))
          ((fresh° (A B r) (memb-and-rest° `(&& ,A ,B) Γ r) (seq° `(,A ,B . ,r) G)))
          ((fresh° (A B r) (memb-and-rest° `(!! ,A ,B) Γ r)
             (both (seq° `(,A . ,r) G) (seq° `(,B . ,r) G))))
          ((fresh° (A B r) (memb-and-rest° `(==> ,A ,B) Γ r)
             (cond°
               ((atom° A) (fresh° (r*) (memb-and-rest° A r r*)) (seq° `(,B . ,r) G))
               ((fresh° (C D) (=° A `(&& ,C ,D)) (seq° `((==> ,C (==> ,D ,B)) . ,r) G)))
               ((fresh° (C D) (=° A `(!! ,C ,D)) (seq° `((==> ,C ,B) (==> ,D ,B) . ,r) G)))
               ((fresh° (C D) (=° A `(==> ,C ,D)) (seq° `((==> ,D ,B) . ,r) A) (seq° `(,B . ,r) G)))
               ((=° A 'ff) (seq° r G))
               ((=° A 'tt) (seq° `(,B . ,r) G))))))
        s))))

(define seq° (seq°/with andª))          ; the correct ∨L: both premises
(define seq-typo° (seq°/with orª))      ; the printed ∨L: either premise

(define (proofs g) (length (μkanren-run (q -1 #t) g (=° q 'yes))))

(define f1 '(==> a (==> (==> a b) (==> (==> a (==> b c)) c))))   ; the formula of p.247
(define em '(!! a (==> a ff)))                                    ; excluded middle
(define peirce '(==> (==> (==> a b) a) a))                        ; Peirce's formula

(pretty-print
  (list (list 'f1      (μkanren-run (q 1 #t) (seq° '() f1) (=° q 'yes)) (proofs (seq° '() f1)))
        (list 'or-left (proofs (seq° '((!! a b)) 'a)) (proofs (seq-typo° '((!! a b)) 'a)))
        (list 'or-comm (proofs (seq° '() '(==> (!! a b) (!! b a)))))
        (list 'em      (proofs (seq° '() em)))
        (list 'peirce  (proofs (seq° '() peirce)))))
((f1 (yes) 3) (or-left 0 1) (or-comm 1) (em 0) (peirce 0))

The body of seq°/with is wrapped in (λ (s) (δ ...)), exactly as define-relation expands, so that building the recursive goal does not loop. Every run* above terminates, as Theorem 8.1 promises for a ground query. For the formula of [MN p. 231] the search finds three derivations. a∨b⟶aa\lor b\longrightarrow a has none with the correct rule and one with the typo. Excluded middle and Peirce’s formula, which are classically valid but not intuitionistically (Chapter 3), get the answer no.

Kanren angle (what interleaving changes for the looping calculus). Interleaving does not make the naive calculus terminate, but it does change which queries succeed. Take only the atomic, ⊃R\supset R and the original ⊃L\supset L rule:

(define-relation (naive° Γ G)
  (cond°
    ((symbol° G) (fresh° (r) (memb-and-rest° G Γ r)))
    ((fresh° (A B) (=° G `(==> ,A ,B)) (naive° `(,A . ,Γ) B)))
    ((fresh° (A B r) (memb-and-rest° `(==> ,A ,B) Γ r) (naive° Γ A) (naive° `(,B . ,r) G)))))

(pretty-print (μkanren-run (q 1 #t) (naive° '((==> p q) (==> q r) q) 'r) (=° q 'yes)))
(flush-output)
(pretty-print (μkanren-run (q 1 #t) (naive° '((==> p q)) 'q) (=° q 'yes)))
(yes)

The first query is a theorem, and run 1 answers immediately. A depth-first reading of the same clauses, in clause order, would select p⊃qp\supset q first and then loop on its left premise …⟶p\ldots\longrightarrow p, which reproduces itself. Interleaving gives the branch through q⊃rq\supset r its turn. The second query is the book’s looping instance p⊃q⟶qp\supset q\longrightarrow q, which is not a theorem. Here the stream is infinite and empty: the run was killed after 30 seconds with no output. In short, interleaving makes the search complete for answers, while termination still has to come from the calculus.

8.1.2Natural deduction with proof terms

For first-order intuitionistic logic, add the quantifiers type all, some (term -> form) -> form. of Chapter 6. Natural deduction has hypothetical premises (in ⊃I{\supset}I, ∨E{\lor}E, ∃E{\exists}E a derivation may start from a discharged assumption) and eigenvariable conditions (for ∀I{\forall}I and ∃E{\exists}E, “This variable must not be free in the conclusion of the rule or in any assumption that remains undischarged”, [MN p. 232]). Four representative rules out of the fourteen [MN p. 233]:

[A]⋮BA⊃B  ⊃IAA⊃BB  ⊃EA[y/x]∀x A  ∀I (y fresh)∀x AA[t/x]  ∀E \dfrac{\begin{array}{c}[A]\\ \vdots\\ B\end{array}}{A\supset B}\;{\supset}I \qquad \dfrac{A \qquad A\supset B}{B}\;{\supset}E \qquad \dfrac{A[y/x]}{\forall x\,A}\;{\forall}I\ (y\text{ fresh}) \qquad \dfrac{\forall x\,A}{A[t/x]}\;{\forall}E

The book records whole derivations as λ\lambda-terms of a type proof, with one constructor per rule [MN p. 233]. An excerpt of the fourteen declarations:

type imp_i           (proof -> proof) -> proof.
type imp_e           form -> proof -> proof -> proof.
type all_e           term  -> (term -> form) -> proof -> proof.
type all_i           (term -> proof) -> proof.

Three design choices are visible in the types. A rule that discharges a hypothesis takes an abstraction over proofs (imp_i (proof -> proof)), and the bound proof variable is the hypothesis label. A rule with an eigenvariable abstracts over terms (all_i (term -> proof)). Elimination rules store the formulas that appear in a premise but not in the conclusion, such as the antecedent in imp_e A, which makes checking syntax-directed. The checking relation P # A, “P is a proof of A”, follows FeltyAmy Felty. Implementing tactics and tacticals in a higher-order logic programming language. Journal of Automated Reasoning, 11(1):43–81, 1993 ([MN p. 234]):

type  #     proof -> form -> o.
infix # 2.

true_i # tt.
(and_i P1 P2) # (A && B) :- (P1 # A), (P2 # B).
(or_i1 P) # (A !! B)  :- P # A.
(or_i2 P) # (A !! B)  :- P # B.
(imp_i Q) # (A ==> B) :- pi p\ (p # A) => ((Q p) # B).
(some_i T P) # (some A)  :- P # (A T).
(all_i Q) # (all A)   :- pi y\ (Q y) # (A y).
(false_e A P) # A     :- P # ff.
(and_e1 B P) # A      :- P # (A && B).
(and_e2 A P) # B      :- P # (A && B).
(or_e A B P Q1 Q2) # C
   :- (P # (A !! B)),
      (pi p1\ (p1 # A) => ((Q1 p1) # C)),
      (pi p2\ (p2 # B) => ((Q2 p2) # C)).
(imp_e A P1 P2) # B   :- (P1 # A), (P2 # (A ==> B)).
(some_e A P1 Q) # B
   :- (P1 # (some A)),
      pi y\ pi p\ (p # (A y)) => ((Q y p) # B).
(all_e T A P) # (A T) :- (P # (all A)).

Tutorial (reading the ⊃I clause). To check imp_i Q against A⊃BA\supset B, the clause picks a fresh proof constant p (pi p\), assumes the atomic fact p # A (=>), and checks Q p against BB. Since Q has type proof -> proof, Q p β\beta-reduces and puts the hypothesis label in place. Discharge is automatic, because the assumption p # A disappears when the goal (Q p) # B has been proved. In the all_i clause, pi y\ produces a constant that occurs nowhere else, which is exactly the eigenvariable condition. In the book’s words, “implicational goals are used to capture the hypothetical judgments … and universal goals are used to introduce and subsequently abstract over the proofs of the assumed formulas” and “to enforce the newness constraint” [MN p. 234].

The same clauses can be run in four modes. Reading them is the best way to see what “relational” means for a meta-program. The vocabulary is a, b : form, q : term -> form, c : term, f : term -> term [MN p. 234].

1. Checking. All three queries are solvable [MN p. 234]:

?- (imp_i w\w) # (a ==> a).
?- (imp_i x\ imp_i y\ imp_e a x y) # (a ==> ((a ==> b) ==> b)).
?- (imp_i P\ all_i y\ imp_i Q\
      (imp_e (q (f y))
        (imp_e (q y) Q (all_e y (x\ (q x) ==> (q (f x))) P))
        (all_e (f y) (x\ (q x) ==> (q (f x))) P)))
   # ((all x\ (q x) ==> (q (f x))) ==>
      (all x\ (q x) ==> (q (f (f x))))).

The third proof term reads, from the outside in: assume P :∀x(q x⊃q(f x))\,:\forall x(q\,x\supset q(f\,x)); for a fresh y assume Q :q y\,:q\,y; all_e y _ P proves q y⊃q(f y)q\,y\supset q(f\,y), so the inner imp_e (q y) Q (...) proves q(f y)q(f\,y); all_e (f y) _ P proves q(f y)⊃q(f(f y))q(f\,y)\supset q(f(f\,y)), and the outer imp_e (q (f y)) ... concludes q(f(f y))q(f(f\,y)). Note that the instantiation bodies x\ (q x) ==> (q (f x)) are spelled out inside both all_e nodes: this is the information an elimination rule stores so that checking stays syntax-directed.

2. Inference. With the formula unknown, the checker computes it [MN p. 235]:

?- (imp_i w\ (and_i (and_e2 a w) (and_e1 b w))) # R.
R = a && b ==> b && a.

3. Completion. “Sometimes proofs can be incompletely described by including free variables in them” [MN p. 235]. Here the two instantiation bodies of the third checking query are replaced by logic variables A and A' (of type term -> form), and the formula by B. (Here P and Q are λ\lambda-bound variables, not logic variables, despite the capitals.)

?- (imp_i P\ all_i y\ imp_i Q\
      (imp_e (q (f y)) (imp_e (q y) Q (all_e y A P))
             (all_e (f y) A' P))) # B.

A = w\ p w ==> p (f w)
A' = w\ p w ==> p (f w)
B = all (w\ p w ==> p (f w)) ==> all (w\ p w ==> p (f (f w)))

The printed answer says p where the query says q. Read q.The two unknowns are found in different ways. A is found by a pattern equation: (all_e y A P) # (q y ==> q (f y)) yields A y = q y ==> q (f y) with y a pi-constant, which is in LλL_\lambda and has the unique solution λw. q w⊃q (f w)\lambda w.\, q\,w\supset q\,(f\,w). A' appears in A' (f y) = ..., which is not a pattern. It is fixed only because P # (all A') must match the stored hypothesis about P, forcing A' = A. A Teyjus-style implementation delays the non-pattern equation until then (Chapter 7).

4. Proving fails. ?- P # (a ==> ((a ==> b) ==> b)). loops, although the second checking query above contains its proof [MN p. 235]. After two imp_i steps the goal X # b matches no hypothesis. The elimination clauses then accept any formula as conclusion: (false_e A P) # A asks for P # ff, which again only false_e matches, and so on forever. Elimination rules used backwards have unconstrained premises.

Pitfall (mode matters). One specification serves as checker, inferencer and completer, and fails as a prover. The logical reading is the same in all four modes. The operational behaviour is not. When a specification is “relational”, it is worth asking for each argument whether it is given, partially given, or unknown.

Kanren angle (what natural deduction needs). ∀\forall. Fresh proof labels (pi p\) and eigenvariables (pi y\) are needed, the second with a scope check: a logic variable created before y must never be bound to a term containing y. ⊃\supset. Every hypothesis is an atomic fact (p # A). An explicit context argument with a lookup clause, the standard miniKanren technique for type environments, is therefore enough. Patterns. Checking and inference work with first-order named or locally nameless binders plus a substitution relation. Completion with an unknown A in all_e needs pattern unification (A y = t means “abstract y out of t”), and A' (f y) needs postponement. Search. Under interleaving the prover mode becomes complete in principle: the false_e branch is only one of several fair branches. The search space of the unconstrained elimination rules remains huge, however. The sources do not measure it. See Chapter 11 for how the proposal provides these features.

8.1.3A classical prover with bounded contraction

For classical first-order logic, the book uses formulas in negation normal form (no ⊃\supset, negation only on atoms) and a one-sided calculus CL with four zones [MN p. 236]:

Σ:ℒ; Γ; Φ \Sigma : \mathcal{L};\ \Gamma;\ \Phi

Here Σ\Sigma holds the eigenvariables, ℒ\mathcal{L} is a set of literals, Γ\Gamma is a list of formulas still to be introduced, and Φ\Phi is a list of existential formulas. The rules are (with AA atomic, tt a Σ\Sigma-term, y∉Σy\notin\Sigma):

Σ:A,ℒ; Γ; ΦΣ:ℒ; A,Γ; Φ  litΣ:¬A,ℒ; Γ; ΦΣ:ℒ; ¬A,Γ; Φ  litΣ:ℒ; Γ; Φ,∃x.BΣ:ℒ; ∃x.B,Γ; Φ  ∃Σ:ℒ; ⊤,Γ; Φ  ⊤RΣ:ℒ; B,Γ; ΦΣ:ℒ; C,Γ; ΦΣ:ℒ; B∧C,Γ; Φ  ∧RΣ:ℒ; B,C,Γ; ΦΣ:ℒ; B∨C,Γ; Φ  ∨RΣ∪{y}:ℒ; B[y/x],Γ; ΦΣ:ℒ; ∀x B,Γ; Φ  ∀RΣ:A,¬A,ℒ; ⋅; Φ  initΣ:ℒ; B[t/x]; Φ,∃x BΣ:ℒ; ⋅; ∃x B,Φ  ∃R \begin{gathered} \dfrac{\Sigma : A,\mathcal{L};\ \Gamma;\ \Phi}{\Sigma : \mathcal{L};\ A,\Gamma;\ \Phi}\;\text{lit} \qquad \dfrac{\Sigma : \neg A,\mathcal{L};\ \Gamma;\ \Phi}{\Sigma : \mathcal{L};\ \neg A,\Gamma;\ \Phi}\;\text{lit} \qquad \dfrac{\Sigma : \mathcal{L};\ \Gamma;\ \Phi,\exists x.B}{\Sigma : \mathcal{L};\ \exists x.B,\Gamma;\ \Phi}\;\exists \\[2ex] \dfrac{}{\Sigma : \mathcal{L};\ \top,\Gamma;\ \Phi}\;\top R \qquad \dfrac{\Sigma : \mathcal{L};\ B,\Gamma;\ \Phi \qquad \Sigma : \mathcal{L};\ C,\Gamma;\ \Phi}{\Sigma : \mathcal{L};\ B\land C,\Gamma;\ \Phi}\;\land R \qquad \dfrac{\Sigma : \mathcal{L};\ B,C,\Gamma;\ \Phi}{\Sigma : \mathcal{L};\ B\lor C,\Gamma;\ \Phi}\;\lor R \\[2ex] \dfrac{\Sigma\cup\{y\} : \mathcal{L};\ B[y/x],\Gamma;\ \Phi}{\Sigma : \mathcal{L};\ \forall x\,B,\Gamma;\ \Phi}\;\forall R \qquad \dfrac{}{\Sigma : A,\neg A,\mathcal{L};\ \cdot;\ \Phi}\;\text{init} \qquad \dfrac{\Sigma : \mathcal{L};\ B[t/x];\ \Phi,\exists x\,B}{\Sigma : \mathcal{L};\ \cdot;\ \exists x\,B,\Phi}\;\exists R \end{gathered}

The calculus is a systematic tableau in the sense of SmullyanRaymond M. Smullyan. First-Order Logic. Springer-Verlag, New York, 1968. A non-empty Γ\Gamma determines the rule completely. When Γ\Gamma is empty, the only choices are init versus ∃R\exists R, and the witness tt. The rule ∃R\exists R puts ∃x B\exists x\,B back at the end of Φ\Phi, so all existentials get their turn. This alone does not give termination: for ⋅:⋅; ∃x.q(x); ⋅\cdot:\cdot;\ \exists x.q(x);\ \cdot, “proof search … leads to the attempt to prove sequents of the form ⋅:q(t1),…,q(tn);⋅;∃x.q(x)\cdot : q(t_1),\ldots,q(t_n);\cdot;\exists x.q(x), for increasingly larger sets of terms” [MN p. 237]. The remedy is to bound the number of instances of each existential and to retry with a larger bound (iterative deepening).

Pitfall (no rule for ⊥). “If the first formula in the introduction zone is ⊥\bot … that sequent is not provable” [MN p. 236]. Hence ⊥∨⊤\bot\lor\top is not provable as written. In a one-sided classical calculus ⊥\bot should simply be dropped from Γ\Gamma. A port should add prv (ff::Gamma) Phi :- prv Gamma Phi. (This is our notes’ analysis. The book does not comment.)

Literals are p A and n A for an atom A : atm. The existential zone is a queue of pairs (formula, remaining uses), implemented as a functional difference list [MN p. 238]: a list is represented by a function from its tail to the whole list, so the empty queue is que x\x and qpush X (que k\ Phi k) (que k\ Phi ((pr X N)::k)) :- bound N. appends at the end by β\beta-reduction. qpop takes the front pair and, if uses remain, re-appends it with one use fewer. All these matches are LλL_\lambda patterns. Popping the empty queue fails because x\x and k\ (pr X 1)::(Phi k) clash rigidly, so no emptiness test is needed. The prover itself is [MN p. 239]:

type lit         form -> o.
type prv         list form -> que form -> o.

prv (tt       :: Gamma) Phi.
prv ((B && C) :: Gamma) Phi :- prv (B::Gamma) Phi,
                               prv (C::Gamma) Phi.
prv ((B !! C) :: Gamma) Phi :- prv (B::C::Gamma) Phi.
prv ((all B)  :: Gamma) Phi :- pi x\ prv ((B x)::Gamma) Phi.
prv ((some B) :: Gamma) Phi :- qpush (some B) Phi Q,
                               prv Gamma Q.
prv (p A      :: Gamma) Phi :- lit (p A) => prv Gamma Phi.
prv (n A      :: Gamma) Phi :- lit (n A) => prv Gamma Phi.
prv nil Phi :- lit (n A), lit (p A).
prv nil Phi :- qpop (some B) Phi Q, prv ((B T)::nil) Q.

posints 1.
posints N :- posints M, N is M + 1.

thm B :- posints N, bound N => prv (B::nil) (que x\x).

Two of the four zones are not arguments at all. Σ\Sigma is realized by the pi x\ of the ∀R\forall R clause: “it uses λ\lambdaProlog-level universal quantifiers and the generic constants they introduce during computation to implicitly realize the eigenvariables” [MN p. 238]. ℒ\mathcal{L} is realized by lit A =>, a hypothetical fact. In the ∃R\exists R clause the witness T is a fresh logic variable. It is not guessed: the initial clause lit (n A), lit (p A) chooses it later, by unification. The side condition “tt is a Σ\Sigma-term” is enforced by the unifier, which refuses to bind T to an eigenvariable introduced after T was created. Iterative deepening comes from posints: a failure at bound NN backtracks into posints, which produces N+1N+1. “B represents a formula in negation normal form that has a CL proof if and only if the goal (thm B) is provable” [MN p. 239]. On non-theorems thm runs forever, since first-order logic is only semi-decidable.

Pitfall (cut plus logic variables loses completeness). An improvement closes a branch as soon as a complementary literal arrives [MN p. 239]: prv (p A :: Gamma) Phi :- lit (n A) ; lit (p A) => prv Gamma Phi. (and the dual clause). Adding a cut, lit (n A), ! ; ..., “is acceptable when there are no existential quantifiers”, but with them “the interaction between such logic variables and the Prolog-cut (!) can lead to incompleteness” [MN p. 240]. The counterexample is

((p (r c)) !! (p (r t)) !! (p (g c)) !! (some x\ (n (r x)) && (n (g x)))).

It is a theorem, but “the logic variable that instantiates x gets bound to t first and the cut then eliminates the path in which it would get bound to c” [MN p. 240]. Cut never breaks soundness, since it only removes alternatives. It keeps completeness only after a test that cannot bind logic variables.

Kanren angle (what the classical prover needs, and what interleaving gives). ∀\forall with a scope check is soundness-critical here. Our notes derive two tests (not in the book). The drinker formula ∃x(Dx⊃∀y Dy)\exists x(D x\supset\forall y\,D y), in NNF some x\ (n (d x)) !! (all y\ p (d y)), must need bound 2: the first witness is created before yy and cannot become yy. The invalid (∀y∃x R(x,y))⊃∃x∀y R(x,y)(\forall y\exists x\,R(x,y))\supset\exists x\forall y\,R(x,y) must never be proved. Without the scope check a port proves it. ⊃\supset. Only atomic facts (lit A, bound N) are assumed, so an explicit literal-list argument and an explicit bound suffice. Patterns. The functional difference list needs LλL_\lambda. A naive first-order open-tailed list is wrong: popping an empty (dl V V) unifies V with a cons and conjures an item. With a ground spine, an ordinary list and append° is the safe port. Search. Under interleaving the round-robin queue alone already makes the prover complete, because every node has finitely many children and the infinite ∃R\exists R chain is interleaved with the init alternatives. The bound then serves only to make failing searches stop. Cut. (aux kanren micro)’s if° is a soft cut: it keeps every answer of the test. Translating ! as (if° (take° 1 test) ...) reproduces the book’s incompleteness exactly. Plain if° happens to prove the formula above but is still incomplete in general. Only the cut-free disjunction is safe. See Chapter 11.

8.1.4Tactics and tacticals

Direct reflection “has the benefit of yielding a transparently correct specification. However, it also means that we must use the control regimen of the interpreter” [MN p. 240]. The remedy is the LCF architectureMichael J. Gordon, Arthur J. Milner, and Christopher P. Wadsworth. Edinburgh LCF: A Mechanised Logic of Computation, volume 78 of LNCS. Springer-Verlag, New York, 1979, recast as relationsAmy Felty and Dale Miller. Specifying theorem provers in a higher-order logic programming language. In Ninth International Conference on Automated Deduction, volume 310 of LNCS, pages 61–80, New York, 1988. Springer-Verlag; and Amy Felty. Implementing tactics and tacticals in a higher-order logic programming language. Journal of Automated Reasoning, 11(1):43–81, 1993. An inference rule becomes data: a relation between the goal of proving the conclusion and the goal of proving the premises. Search strategies then become ordinary higher-order predicates over such relations.

Definition 8.2 (goals, tactics, tacticals; [MN p. 241]). A primitive goal is an object to be proved (a sequent, a typing judgment P # A, …). Compound goals are trueg (closed), G1 cc G2 (both) and allg (x\ G) (for a generic x). A tactic is a predicate of type goal -> goal -> o relating a primitive goal to the goal of its premises. It fails when it does not apply, and it may leave logic variables, such as quantifier witnesses, in its output. A tactical is a higher-order predicate combining tactics.

The goal language and its simplifier are [MN p. 241]:

kind  goal     type.
type  trueg    goal.                    % vacuously true goal
type  cc       goal -> goal -> goal.    % conjunctive goal
type  allg     (A -> goal) -> goal.     % universally quantified goal
infixl cc 3.

type  goalreduce, redex, red1   goal -> goal -> o.
type  primgoal                  goal -> o.

redex (trueg cc G) G & redex (G cc trueg) G.
redex (allg x\trueg) trueg.
red1 G H :- redex G H, !.
red1 (G cc H) (Gx cc H) &
red1 (H cc G) (H cc Gx) :- red1 G Gx.
red1 (allg G) (allg Gx) :- pi x\ red1 (G x) (Gx x).
goalreduce G H :- red1 G Gx, !, goalreduce Gx H.
goalreduce G G.

goalreduce rewrites with ⊤gccG→G\top_g\mathbin{cc}G\to G, Gcc⊤g→GG\mathbin{cc}\top_g\to G and allg (λx. ⊤g)→⊤g\mathit{allg}\,(\lambda x.\, \top_g)\to\top_g anywhere in a goal, until no rewrite applies. A goal “is proved” when it reduces to trueg. The pattern allg x\trueg matches only a vacuous abstraction, one whose body does not mention x. The binder type A of allg is polymorphic, so the same goal language serves goals over terms and over proofs. The cuts are safe here because the input is ground and the rewriting is confluent.

A first example: reachability. The book’s smallest instance has nodes, edges as primitive goals adj X Y, and paths as primitive goals path X Y [MN p. 242]:

kind node   type.
type a, b, c, d, e   node.
type adj, path   node -> node -> goal.

primgoal (adj _ _)  &  primgoal (path _ _).

type adj_tac, path_base_tac, path_rec_tac   goal -> goal -> o.

adj_tac (adj a b) trueg  &  adj_tac (adj a c) trueg.
adj_tac (adj b d) trueg  &  adj_tac (adj c d) trueg.
adj_tac (adj d a) trueg  &  adj_tac (adj d e) trueg.

path_base_tac  (path X Y) (adj X Y).
path_rec_tac   (path X Y) ((adj X Z) cc (path Z Y)).

adj_tac closes an edge goal. The two path tactics are the two inference rules for path. In path_rec_tac the intermediate node Z appears only in the output: a tactic may leave an unknown in the premises, to be fixed later when adj_tac is applied to adj X Z. The graph (a→ba{\to}b, a→ca{\to}c, b→db{\to}d, c→dc{\to}d, d→ad{\to}a, d→ed{\to}e) has the cycle a→b→d→aa{\to}b{\to}d{\to}a. The book gives no query for this figure. A run on (aux kanren micro) is in the kanren box below.

Sequent calculus as tactics. The rules of an intuitionistic sequent calculus for ∧\land, ⊃\supset and ∀\forall become tactics [MN p. 242]:

type sq   list form -> form -> goal.
primgoal (sq _ _).

type initial, and_r, imp_r, all_r, and_l, imp_l, all_l, all_l'   goal -> goal -> o.

initial (sq Gamma A) trueg :- memb_and_rest A Gamma _.
and_r   (sq Gamma (A && B)) ((sq Gamma A) cc (sq Gamma B)).
imp_r   (sq Gamma (A ==> B)) (sq (A::Gamma) B).
all_r   (sq Gamma (all A)) (allg x\ sq Gamma (A x)).
and_l   (sq Gamma A) (sq (B::C::Gamma') A) :-
          memb_and_rest (B && C) Gamma Gamma'.
imp_l   (sq Gamma A) ((sq Gamma B) cc (sq (C::Gamma') A)) :-
          memb_and_rest (B ==> C) Gamma Gamma'.
all_l   (sq Gamma A) (sq ((B T)::Gamma) A) :-
          memb_and_rest (all B) Gamma Gamma'.
all_l'  (sq Gamma A) (sq ((B T)::Gamma') A) :-
          memb_and_rest (all B) Gamma Gamma'.

Each clause relates a conclusion to the goal of its premises. imp_l is the plain ⊃L{\supset}L of the first calculus: its left premise sq Gamma B keeps B⊃CB\supset C. The tactic all_r does not introduce the eigenvariable itself. It returns a quantified goal allg x\ ..., and the eigenvariable becomes a real pi-constant only when a tactical enters that goal. The tactic all_l keeps the universal hypothesis (contraction: it uses the original Gamma), while all_l' drops it (it uses Gamma'). In both, T is an open witness. The tacticals are [MN p. 244]:

type maptac   (goal -> goal -> o) -> goal -> goal -> o.

maptac Tac trueg trueg.
maptac Tac (I1 cc I2) (O1 cc O2) :- maptac Tac I1 O1,
                                    maptac Tac I2 O2.
maptac Tac (allg In) (allg Out) :- pi t\ maptac Tac (In t) (Out t).
maptac Tac In Out :- primgoal In, Tac In Out.

type idtac          goal -> goal -> o.
type repeat, try    (goal -> goal -> o) -> goal -> goal -> o.
type then,
     orelse, orelse! (goal -> goal -> o) ->
                     (goal -> goal -> o) -> goal -> goal -> o.

idtac             In In.
then    Tac1 Tac2 In Out :- Tac1 In Mid, maptac Tac2 Mid Out.
orelse  Tac1 Tac2 In Out :- Tac1 In Out  ; Tac2 In Out.
orelse! Tac1 Tac2 In Out :- Tac1 In Out, ! ; Tac2 In Out.
repeat  Tac       In Out :- orelse (then Tac (repeat Tac))
                                   idtac In Out.
try     Tac       In Out :- orelse Tac idtac In Out.

Read tactics as binary relations. Then idtac is the identity, orelse is union, orelse! is “the first answer of the first tactic, else the second”, try T is “T if it applies, else no change”, and repeat T applies T as often as possible first, with fewer applications on backtracking. maptac T lifts T from primitive goals to compound goals. It enters allg with pi t\ and re-abstracts the result through the pattern Out t, and it fails if T fails on any primitive leaf. then T1 T2 is the relational composition of T1 with maptac T2. It cannot simply be T1 In Mid, T2 Mid Out, because Mid may be compound [MN p. 243].

Invertible rules first. A rule is invertible when its premises are provable iff its conclusion is. Such rules “can be forced to appear at the end of a proof without any loss of completeness” [MN p. 243]:

invertible In Out :-
   repeat (orelse and_r (orelse and_l (orelse imp_r all_r))) In Out.

With p : term -> form and f : term -> term, the book reports [MN p. 243–244]:

?- invertible (sq [] ((a && (a ==> b)) ==> (a && b))) Out.
Out = ((sq (a :: (a ==> b) :: nil) a) cc (sq (a :: (a ==> b) :: nil) b))

?- invertible (sq [] ((all x\ (p x) ==> (p (f x))) ==>
                      (all x\ (p x) ==> (p (f (f x))))))
              Out.
Out = (allg (w\ sq (p w :: (all w\ p w ==> p (f w)) :: nil)
                   (p (f (f w)))))

What remains in the second answer becomes propositional after two instantiations of the universal hypothesis. To finish it, the book links the decision procedure of Section 8.1.1 in as a tactic and composes a script [MN p. 244–245]:

ip_decide (sq Gamma A) trueg :- seq Gamma A.

?- then invertible (then all_l (then all_l' ip_decide))
       (sq [] ((all x\ (p x) ==> (p (f x))) ==>
               (all x\ (p x) ==> (p (f (f x))))))
       Out.
Out = allg W1\ trueg

Tutorial (how the script closes the goal). invertible leaves allg w\ sq [p w, all (...)] (p (f (f w))). maptac enters the allg with a fresh constant w. all_l adds p T1 ==> p (f T1) and keeps the ∀\forall. all_l' adds p T2 ==> p (f T2) and drops it. Because T1 and T2 were created inside the scope of w, they may be bound to terms containing w. ip_decide runs seq. There, ⊃L1{\supset}L_1 on the first implication needs the atom p T2 in the context, and memb_and_rest unifies T2 := w, adding p (f w). The second implication then gets T1 := f w, adding p (f (f w)), and init closes the sequent. The witnesses are found by unification at the leaves, exactly as in the classical prover. (seq needs atom for first-order atoms, for example atom (p _)., which the book does not show.) The output allg W1\ trueg reduces to trueg with the goal-simplifier goalreduce of [MN p. 241].

Kanren angle (tacticals in Scheme, and what interleaving does to them). Tacticals are higher-order relations, and in Scheme they are just procedures from relations to relations. Everything except allg is first order, so the reachability example [MN p. 242] runs on (aux kanren micro) today. Goals are tagged lists, and maptac° has no allg case:

(define-relation (primgoal° g)
  (fresh° (x y) (or° (=° g `(adj ,x ,y)) (=° g `(path ,x ,y)))))

(define-relation (adj-tac° in out)
  (=° out 'trueg)
  (cond° ((=° in '(adj a b))) ((=° in '(adj a c))) ((=° in '(adj b d)))
         ((=° in '(adj c d))) ((=° in '(adj d a))) ((=° in '(adj d e)))))
(define-relation (path-base-tac° in out)
  (fresh° (x y) (=° in `(path ,x ,y)) (=° out `(adj ,x ,y))))
(define-relation (path-rec-tac° in out)
  (fresh° (x y z) (=° in `(path ,x ,y)) (=° out `(cc (adj ,x ,z) (path ,z ,y)))))

(define (maptac° tac)
  (define-relation (m in out)
    (cond° ((=° in 'trueg) (=° out 'trueg))
           ((fresh° (i1 i2 o1 o2) (=° in `(cc ,i1 ,i2)) (=° out `(cc ,o1 ,o2)) (m i1 o1) (m i2 o2)))
           ((primgoal° in) (tac in out))))
  m)
(define (idtac° in out) (=° in out))
(define ((then° t1 t2) in out) (fresh° (mid) (t1 in mid) ((maptac° t2) mid out)))
(define ((orelse° t1 t2) in out) (or° (t1 in out) (t2 in out)))
(define ((try° t) in out) ((orelse° t idtac°) in out))
(define ((repeat° t) in out)
  (λ (s) (δ (((orelse° (then° t (repeat° t)) idtac°) in out) s))))

;; stands in for `goalreduce Out trueg`: Out is made of trueg and cc only
(define-relation (closed° g)
  (cond° ((=° g 'trueg))
         ((fresh° (g1 g2) (=° g `(cc ,g1 ,g2)) (closed° g1) (closed° g2)))))

(define step° (orelse° adj-tac° (orelse° path-base-tac° path-rec-tac°)))

(pretty-print (μkanren-run (q -1 #t) ((then° path-rec-tac° (try° adj-tac°)) '(path a e) q)))
(pretty-print (μkanren-run (q 4 #t) ((repeat° step°) '(path a e) q)))
(pretty-print (μkanren-run (q 3 #t) ((repeat° step°) '(path a e) q) (closed° q)))
((cc (adj a α) (path α e)) (cc trueg (path b e)) (cc trueg (path c e)))
((path a e) (adj a e) (cc (adj a α) (path α e)) (cc trueg (path b e)))
((cc trueg (cc trueg trueg))
 (cc trueg (cc trueg trueg))
 (cc trueg (cc trueg (cc trueg (cc trueg (cc trueg trueg))))))

The open witness α of path-rec-tac° is chosen later by adj-tac°, just as T is in all_l. The first answer of repeat° is zero applications, (path a e). The book’s depth-first repeat would instead answer first with the maximal sequence, which here is the unprovable leftover adj a e. Interleaving enumerates all application lengths fairly. On the cyclic graph it produces the two three-edge proofs (a→b→d→ea{\to}b{\to}d{\to}e, a→c→d→ea{\to}c{\to}d{\to}e) and then a six-edge one around the cycle. A depth-first enumeration of all answers would never terminate here, and interleaving does not terminate either, but it keeps producing proofs. A script built from orelse and repeat is therefore complete under interleaving, while committed choice (orelse!, the cuts of goalreduce) needs (if° (take° 1 ...) ...). What is missing is maptac over allg. It needs a universal goal (a fresh eigenvariable) and the abstraction of that eigenvariable out of the result (Out t, a pattern). See Chapter 11.

8.2Computations over functional programs

Chapter 10 of the book turns to programming-language semantics. The object language miniFP is an untyped call-by-value λ\lambda-calculus with a conditional, a fixed point, booleans, integers and lists [MN p. 248]:

M::=x∣λx.M∣M N∣𝖼𝗈𝗇𝖽 M N P∣𝖿𝗂𝗑 x.M∣𝖼𝗇𝗌 M N∣𝗂 n∣𝗍𝗍∣𝖿𝖿∣𝗇𝗎𝗅𝗅∣𝖼𝗈𝗇𝗌∣𝖼𝖺𝗋∣… M ::= x\mid \lambda x.M\mid M\,N\mid \mathsf{cond}\,M\,N\,P\mid \mathsf{fix}\,x.M\mid \mathsf{cns}\,M\,N \mid \mathsf{i}\,n\mid \mathsf{tt}\mid\mathsf{ff}\mid\mathsf{null}\mid \mathsf{cons}\mid\mathsf{car}\mid\ldots
type abs    (tm -> tm) -> tm.          % function abstraction
type @      tm -> tm -> tm.            % application
infixl @ 4.                            % application is infix
type cond   tm -> tm -> tm -> tm.      % conditional
type fixpt  (tm -> tm) -> tm.          % recursive functions

The remaining constructors are first order: cns is the list value constructor, i injects integers, and constants such as cons, car, sum, equal have type tm. cons is a built-in function, applied with @. The encoding is untyped, so cons @ (i 4) @ (i 5) is a legal tm but not a valid program. Validity is a separate typing judgment. Four sample programs are named by prog [MN p. 249]. For instance:

prog "map" (fixpt map\ abs f\ abs l\
  cond (nullp @ l) null (cons @ (f @ (car @ l)) @
                                (map @ f @ (cdr @ l)))).

8.2.1Typing: hypotheses about bound variables

The four structural rules of simple typing are [MN p. 250]:

typeof (M @ N) A         :- typeof M (arr B A), typeof N B.
typeof (cond P Q R) A    :- typeof P bool, typeof Q A, typeof R A.
typeof (abs M) (arr A B) :- pi x\ typeof x A => typeof (M x) B.
typeof (fixpt M) A       :- pi x\ typeof x A => typeof (M x) A.

One axiom per constant follows, such as typeof car (arr (lst A) A). There is no clause for variables. Instead, when the abs clause enters the binder, it assumes a clause typeof x A for the fresh x. The book reports [MN p. 249–250] that typeof (abs w\ w) has type arr int int, arr bool bool, and even pi t\ typeof (abs w\ w) (arr t t). For the four programs it reports:

?- sigma Exp\ prog Name Exp, typeof Exp Ty.
Ty = arr int int.
Ty = arr A (arr (lst A) bool).
Ty = arr (lst A) (arr (lst A) (lst A)).
Ty = arr (arr A B) (arr (lst A) (lst B)).

Pitfall (polymorphic constants, monomorphic variables). The type variables of a constant’s axiom are renamed at each use of the clause, so each occurrence of car may get its own instance. The assumed clause typeof x A, by contrast, contains the outer logic variable A, which is not renamed, so all occurrences of x share one type. That is exactly simple typing. It is also why let-polymorphism is out of reach: “no simple extension to the program provided in Figure 10.3 can realize this algorithm” [MN p. 260].

Kanren angle (the classic miniKanren type inferencer is this program). Since every hypothesis is an atomic fact about a fresh variable, an explicit environment Γ\Gamma can replace =>. Variables are then named by Scheme symbols, and constants are wrapped as (c name) to keep the two apart. Sharing a logic variable inside Γ\Gamma is precisely the non-renaming of A. Wrapping each constant’s type variables in fresh° is the per-use renaming. Excerpt (the remaining constant clauses, and the four programs written with a helper @* for iterated application, are in the run file):

(define-relation (lookup° Γ x t)
  (fresh° (y u r)
    (=° Γ `((,y . ,u) . ,r))
    (cond° ((=° x y) (=° t u))
           ((≠° x y) (lookup° r x t)))))

(define-relation (typeof° Γ m t)
  (cond°
    ((symbol° m) (lookup° Γ m t))
    ((fresh° (M N B) (=° m `(@ ,M ,N)) (typeof° Γ M `(arr ,B ,t)) (typeof° Γ N B)))
    ((fresh° (P Q R) (=° m `(cond ,P ,Q ,R)) (typeof° Γ P 'bool) (typeof° Γ Q t) (typeof° Γ R t)))
    ((fresh° (x M A B) (=° m `(abs ,x ,M)) (=° t `(arr ,A ,B)) (typeof° `((,x . ,A) . ,Γ) M B)))
    ((fresh° (f M) (=° m `(fixpt ,f ,M)) (typeof° `((,f . ,t) . ,Γ) M t)))
    ((fresh° (n) (=° m `(i ,n)) (=° t 'int)))
    ((=° m '(c tt)) (=° t 'bool))
    ;; ... (c ff), (c null), (c equal), (c cons) ...
    ((fresh° (A) (=° m '(c car)) (=° t `(arr (lst ,A) ,A))))
    ;; ... (c cdr), (c nullp), (c consp), (c and), (c zerop), (c minus), (c sum)
    ))

(for-each (λ (p) (pretty-print (cons (car p) (μkanren-run (q -1 #t) (typeof° '() (cdr p) q)))))
  `((id . (abs w w)) (fib . ,fib) (mem . ,mem) (appnd . ,appnd) (map . ,map) (self . (abs w (@ w w)))))
(id (arr α α))
(fib (arr int int))
(mem (arr α (arr (lst α) bool)))
(appnd (arr (lst α) (arr (lst α) (lst α))))
(map (arr (arr α β) (arr (lst α) (lst β))))
(self)

These are the book’s types. Self-application has none, because (aux kanren micro)’s occurs check rejects B=B→AB = B\to A. Running the relation backwards enumerates inhabitants of a type:

(pretty-print (μkanren-run (q 5 #t) (typeof° '() q '(arr int int))))
((abs α α)
 (fixpt α α)
 (abs α (i β))
 (@ (abs α α) (abs β β))
 (abs α (fixpt β β)))

(Grounded answers omit the pending symbol° constraints on α, β.) Note the well-typed divergent term (fixpt α α). In the book’s clause order, depth-first search would try the application clause first and recurse on an ever larger function type. Interleaving gives every clause its turn. The named-binder encoding works here because typing never substitutes. Evaluation does, and needs more (see below).

8.2.2Big-step evaluation

The natural semanticsGilles Kahn. Natural semantics. In Proceedings of the Symposium on Theoretical Aspects of Computer Science, volume 247 of LNCS, pages 22–39, New York, 1987. Springer of miniFP is a relation M⇓VM\Downarrow V [MN p. 251–252]. Its structural core reads:

V a valueV⇓VM⇓FN⇓Uapply(F,U)⇓VM N⇓VM[𝖿𝗂𝗑 x.M/x]⇓V𝖿𝗂𝗑 x.M⇓VM[U/x]⇓Vapply(λx.M, U)⇓V \begin{gathered} \dfrac{V\text{ a value}}{V\Downarrow V} \qquad \dfrac{M\Downarrow F \qquad N\Downarrow U \qquad \mathrm{apply}(F,U)\Downarrow V}{M\,N\Downarrow V} \\[2ex] \dfrac{M[\mathsf{fix}\,x.M/x]\Downarrow V}{\mathsf{fix}\,x.M\Downarrow V} \qquad \dfrac{M[U/x]\Downarrow V}{\mathrm{apply}(\lambda x.M,\,U)\Downarrow V} \end{gathered}
val (abs _) & val (i _) & val tt & val ff & val null.
val (cns _ _) & val (spec _ _ _).

eval V V            :- val V.
eval (M @ N) V      :- eval M F, eval N U, apply F U V.
eval (fixpt R) V    :- eval (R (fixpt R)) V.
eval (cond C L R) V :- eval C B, if (B = tt) (eval L V) (eval R V).
eval F (spec I F nil) :- special I F.

apply (abs R) U V         :- eval (R U) V.
apply (spec 1 F Args) U V :- eval_spec F (U::Args) V.
apply (spec C F Args) U (spec D F (U::Args)) :- C > 1, D is C - 1.

Application of an abstraction “corresponds to a substitution that is realized elegantly through β\beta-conversion in the specification language” [MN p. 251]: eval (R U) V. A built-in F of arity nn evaluates to the partial application spec n F nil, which collects already evaluated arguments in reverse order until the δ\delta-rule eval_spec fires, for example eval_spec minus ((i N)::(i M)::nil) (i V) :- V is M - N. With these clauses prog "fib" F, eval (F @ (i 12)) V gives V = (i 144), and mapping fib over [9,4][9,4] gives (cns (i 34) (cns (i 3) null)) [MN p. 251–253]. Since eval_spec equal compares with λ\lambdaProlog’s =, which is equality of λ\lambda-terms up to αβη\alpha\beta\eta, eval (equal @ (abs x\x) @ (abs y\y)) V gives V = tt [MN p. 253]. This is “stronger” than a functional language, which cannot compare functions. (The book suggests replacing B = C by a first-order eq B C that only compares integers, booleans and lists. Since eq has no clause for abs and the test sits inside an if, the same query then gives V = ff, our notes observe.)

Tutorial (evaluating a small application). Take eval ((abs x\ cond x (i 1) (i 2)) @ tt) V. The clause for @ evaluates the function, which is a value and evaluates to itself, so F = abs x\ cond x (i 1) (i 2); it evaluates the argument tt to U = tt; then apply (abs R) U V calls eval (R U) V. Here R is the meta-level function x\ cond x (i 1) (i 2), so R U β\beta-reduces to cond tt (i 1) (i 2): object-level substitution has been done by the metalanguage. The cond clause evaluates tt to B = tt and takes the then branch, V = i 1.

New binding constructs fit the same pattern. The book’s bibliographic notes add let, with concrete let x = t in b represented as (let t (x\b)), and one clause [MN p. 259–260]: eval (let T R) V :- eval T U, eval (R U) V.

Pitfall (if is a commit, not logic). The conditional is defined with a cut [MN p. 137]:

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

It commits to the first proof of P. The book says it is used “only for convenience” and can be rewritten as (U = tt, G ; U = ff, H) when U is a boolean [MN p. 251]. The two readings differ on a non-boolean test. They also differ, more seriously, on an eigenvariable test: k = tt fails for a generic k, so if silently takes the else branch. This matters for mixed evaluation below.

8.2.3Evaluation contexts as meta-level functions

The reduction semantics of Felleisen and HiebMatthias Felleisen and Robert Hieb. The revised report on the syntactic theories of sequential control and state. Theoretical Computer Science, 103:235–271, 1992 splits a term into an evaluation context with a hole and the next redex: E[R]⟼E[N]E[R]\longmapsto E[N] when RR reduces to NN, with E::=[ ]∣𝖼𝗈𝗇𝖽 E N P∣E N∣V EE ::= [\,]\mid \mathsf{cond}\,E\,N\,P\mid E\,N\mid V\,E. In λ\lambdaProlog a context is simply a function tm -> tm, and plugging is application [MN p. 254]:

context R (x\ x) R :- redex R.
context (cond M N P) (x\ cond (E x) N P) R :-
    non_val M, context M E R.
context (M @ N) (x\ (E x) @ N) R :-
    non_val M, context M E R.
context (V @ M) (x\ V @ (E x)) R :-
    val V, non_val M, context M E R.

evalc V V :- val V.
evalc M V :- context M E R, reduce R N, evalc (E N) V.

redex, non_val and reduce are first-order tables (for example reduce ((abs R) @ N) (R N).). Each decomposition succeeds exactly once [MN p. 255]:

?- context (cond ((abs x\ ff) @ tt) (i 2) (i 3)) E R.
%  succeeds exactly once:  R = ((abs x\ ff) @ tt),  E = (W\ cond W (i 2) (i 3))

The output context x\ cond (E x) N P is built from the recursively computed E by abstraction. Every context answer is therefore a higher-order output.

8.2.4Partial evaluation: unfolding and mixed evaluation

Both evaluators unfold fixpt R into R (fixpt R). The query prog "map" (fixpt Body), Unfold = (Body (fixpt Body)) exhibits this as a source-to-source transformation [MN p. 255]. (The printed result is mis-parenthesized: @ f @ (cdr @ l) must apply the inner fixpt, not lie inside its body.) More interesting is mixed evaluation, which evaluates under a binder by treating the bound variable as an unknown value [MN p. 256]:

type mixeval  tm -> tm -> o.
mixeval (abs R) (abs S) :- pi k\ val k => eval (R k) (S k).

?- prog "appnd" App,
   eval (App @ (cons @ (i 1) @ (cons @ (i 5) @ null))) R,
   mixeval R S.

This “yields the single answer substitution, binding the variable S to” abs w\ cons @ (i 1) @ (cons @ (i 5) @ w) [MN p. 256]. (By the eval_spec cons clause the value form should be cns (i 1) (cns (i 5) w), the same function.) Append has been specialized away. Note (S k): a logic variable applied to an eigenvariable, the pattern case. Its solution abstracts k out of the computed value.

Proposition 8.3 ([MN p. 256]). If mixeval (abs R) (abs S) holds and val T is provable, then evaluating (R T) yields the value (S T).

The proof idea is the substitution property of ∀\forall and ⊃\supset: instantiate the generic derivation of eval (R k) (S k) at T and discharge val k with val T.

Pitfall (the proposition needs the logical reading). With the cut-based if, Proposition 8.3 fails. Our notes’ counterexample is mixeval (abs b\ cond b (i 1) (i 2)) S. The test if (k = tt) ... cannot unify the eigenvariable, so the else branch gives S = b\ i 2, but eval (cond tt (i 1) (i 2)) is i 1. With (B = tt, ... ; B = ff, ...) the conditional on k simply fails, and soundness holds. Failing on an eigenvariable means “unknown”, not “different”.

8.2.5CPS conversion and administrative redexes

Fischer’s call-by-value CPS transformationMichael J. Fischer. Lambda calculus schemata. ACM SIGPLAN Notices, 7(1):104–109, 1972 [MN p. 257] on the pure fragment is defined by ℱ\mathcal{F} on terms and Ψ\Psi on values (abstractions and variables). The marked λ¯\bar\lambda are the administrative abstractions:

ℱ[V]=λ¯k. (k  Ψ[V])ℱ[M N]=λ¯k. (ℱ[M]  λ¯m. (ℱ[N]  λ¯n. (m k n)))Ψ[x]=xΨ[λx.M]=λk. λx. (ℱ[M] k) \begin{aligned} \mathcal{F}[V] &= \bar\lambda k.\,(k\;\Psi[V])\\ \mathcal{F}[M\,N] &= \bar\lambda k.\,(\mathcal{F}[M]\;\bar\lambda m.\,(\mathcal{F}[N]\;\bar\lambda n.\,(m\,k\,n)))\\ \Psi[x] &= x\\ \Psi[\lambda x.M] &= \lambda k.\,\lambda x.\,(\mathcal{F}[M]\,k) \end{aligned}
type ftrans, phi  tm -> tm -> o.

ftrans (abs V) (abs k\ k @ U) :- phi (abs V) U.
ftrans (M @ N) (abs k\ P @ (abs m\ Q @ (abs n\ m @ k @ n))) :-
    ftrans M P, ftrans N Q.

phi (abs M) (abs k\ abs x\ (P x) @ k) :-
    pi x\ pi y\ ftrans x (abs k\ k @ y) => ftrans (M x) (P y).

Tutorial (where did the variable case go?). Neither ftrans nor phi has a clause for variables. When phi enters the binder of abs M, it creates a source variable x, a target variable y, and the local clause ftrans x (abs k\ k @ y). That clause is the equation ℱ[x]=λ¯k.(k Ψ[x])\mathcal{F}[x]=\bar\lambda k.(k\,\Psi[x]) for this one variable. The translated body is P y, a pattern, so P is the body abstracted over y, and abs x\ (P x) @ k re-binds it. The same device reappears in the λ\lambda-to-π\pi translation of Section 8.3.3: “one base case is assumed for every bound variable encountered” [MN p. 274].

On (λu.u)(λu.u)(\lambda u.u)(\lambda u.u) the book reports [MN p. 257]:

?- ftrans ((abs u\u) @ (abs u\u)) F.

F = (abs W1\ (abs (W2\ W2 @ abs W3\ abs W4\ abs (W5\ W5 @ W4) @ W3)) @
     (abs W2\ (abs (W3\ W3 @ abs W4\ abs W5\ abs (W6\ W6 @ W5) @ W4)) @
     (abs W3\ W2 @ W1 @ W3))).

To read it, let UU be Ψ[λu.u]\Psi[\lambda u.u] before any simplification, abs a\ abs b\ ((abs c\ c @ b) @ a). Then F is abs k\ (abs k1\ k1 @ U) @ (abs m\ (abs k2\ k2 @ U) @ (abs n\ m @ k @ n)), which is the application equation of ℱ\mathcal{F} with both sides instantiated by the value equation. The result contains many β\beta-redexes that exist “solely for the purpose of providing a compositional account of the transformation”. These are the administrative redexes. The two-phase version [MN p. 258] builds administrative abstractions with a separate constructor adm : (tm -> tm) -> tm and then reduces them away:

admred ((adm R) @ N) (R N).

red1 M N :- admred M N.
red1 (M @ N) (M' @ N) & red1 (N @ M) (N @ M') :- red1 M M'.
red1 (adm R) (abs S) & red1 (abs R) (abs S) :-
    pi x\ red1 (R x) (S x).

red M N :- red1 M P, !, red P N.
red M M.

?- ftrans ((abs x\x) @ (abs x\x)) T, red T S.
S = (abs W1\ (abs W2\ abs W3\ W2 @ W3) @ W1 @ (abs W2\ abs W3\ W2 @ W3)).

The ftrans/phi clauses are those above with adm for the marked λ¯\bar\lambda. The answer is λk. Ψ′ k Ψ′\lambda k.\,\Psi'\,k\,\Psi' with Ψ′=λk.λx.(k x)\Psi'=\lambda k.\lambda x.(k\,x). The cut in red is safe because administrative reduction is confluent and terminating.

Kanren angle (what functional meta-programs need). ∀\forall and ⊃\supset. Every hypothesis in this chapter is an atomic fact about a fresh variable: typeof x A, val k, ftrans x (abs k\ k @ y). A universal goal plus a scoped atomic hypothesis covers them all. The scope check is mostly invisible here, since no query lets an eigenvariable escape. Patterns. The outputs (S k) of mixeval, (P y) of phi, (S x) of red1 and the contexts x\ cond (E x) N P are pattern equations. Each means “abstract the eigenvariable out of the result”. Beyond patterns. (R U), (R (fixpt R)), (E N) are not patterns, but in the intended modes their heads are known, so they are plain β\beta-reductions. Running them backwards would need general higher-order unification. First-order alternatives. The book cites Hannan and Miller’s transformation of β\beta-based specifications into closure-based onesJohn Hannan and Dale Miller. From operational semantics to abstract machines. Mathematical Structures in Computer Science, 2(4):415–459, 1992. The standard relational miniKanren interpreter with environments and closures is that transformation applied to eval. It runs backwards, but values become closures, which changes equal on functions and rules out mixeval. Contexts can be defunctionalized into first-order frames with a structural plug relation. Conditionals. if (B = C) ... becomes a cond° of =° and ≠°, which is more relational than the book and works with unbound arguments. Under the module’s default generic reading (Definition 14.1), however, ≠° does decide k≠𝗍𝗍k\neq\mathsf{tt} for an eigenvariable kk, so a cond° of =° and ≠° reproduces the mixeval unsoundness. Under (fresh° (q) ...),

(∀° (k) (cond° ((=° k 'tt) (=° q 1)) ((≠° k 'tt) (=° q 2))))

answers (2). With (μkanren-λ-reading 'extensional) the disequality is kept and the conditional on kk fails, answering (), as soundness requires. Where a literal translation of a commit is wanted, (aux kanren micro)’s soft-cut if° needs take° 1. See Section 12.5 and Section 14.2.5.

8.3A process calculus: the π-calculus

The π\pi-calculusRobin Milner, Joachim Parrow, and David Walker. A calculus of mobile processes, part I. Information and Computation, 100(1):1–40, 1992 has the most delicate binders of the three applications. Names are bound by input and by restriction, and a restricted name can be sent out of its scope (scope extrusion). Chapter 11 of the book shows that λ\lambda-tree syntax treats this “naturally” [MN p. 261], and it also uses the calculus to expose a limit of the logic.

8.3.1Syntax and one-step transitions

Processes are P::=0∣P∣P∣P+P∣x(y).P∣x¯y.P∣[x=y].P∣τ.P∣(y)P∣ !PP ::= 0\mid P\mid P\mid P+P\mid x(y).P\mid \bar x y.P\mid [x=y].P\mid \tau.P\mid (y)P\mid\ !P, where yy is bound in x(y).Px(y).P and in (y)P(y)P. Free names are constants, and bound names are λ\lambda-variables [MN p. 262–263]:

kind name  type.
kind proc  type.
type null        proc.
type plus, par   proc -> proc -> proc.
type in          name -> (name -> proc) -> proc.
type out, match  name -> name -> proc -> proc.
type taup        proc -> proc.
type nu          (name -> proc) -> proc.
type bang        proc -> proc.

type a, b, c     name.
type example     int -> proc -> o.

example 1 (par (in b y\ null) (out b a null)).
example 2 (plus (in b y\ out b a null) (out b a (in b y\ null))).
example 3 (nu x\ par (in x y\ null) (out x a null)).
example 4 (nu x\ out a x null).
example 5 (in a y\ par (in y w\ null) (out b b null)).
example 6 (in a y\ plus (in y w\ out b b null)
                         (out b b (in y w\ null))).
example 7 (nu y\ out a y (par (in y w\ null) (out b b null))).
example 8 (nu y\ out a y (plus (in y w\ out b b null)
                               (out b b (in y w\ null)))).

For example, example 1 is (b(y).0)∣(b¯a.0)(b(y).0)\mid(\bar b a.0) and example 3 is (x)((x(y).0)∣(x¯a.0))(x)((x(y).0)\mid(\bar x a.0)). Actions are tau, the free output up x y (x¯y\bar x y) and the free input dn x y. A bound action is the partial application up x or dn x, of type name -> action. There are two transition predicates. one P A P' has a free action and a process as result. onep P A P' has a bound action and an abstracted continuation of type name -> proc. The book’s rules with binding side conditions are [MN p. 264–265]:

P→αP′(y)P→α(y)P′  res (y∉n(α))x(z).P→x(w)P{w/z}  input (w∉fn((z)P))P→x¯yP′(y)P→x¯(w)P′{w/y}  open (y≠x, w∉fn((y)P′))P→x¯(w)P′Q→x(w)Q′P∣Q→τ(w)(P′∣Q′)  close \begin{gathered} \dfrac{P\xrightarrow{\alpha}P'}{(y)P\xrightarrow{\alpha}(y)P'}\;\text{res}\ (y\notin n(\alpha)) \qquad \dfrac{}{x(z).P\xrightarrow{x(w)}P\{w/z\}}\;\text{input}\ (w\notin fn((z)P)) \\[2ex] \dfrac{P\xrightarrow{\bar x y}P'}{(y)P\xrightarrow{\bar x(w)}P'\{w/y\}}\;\text{open}\ (y\neq x,\ w\notin fn((y)P')) \qquad \dfrac{P\xrightarrow{\bar x(w)}P' \qquad Q\xrightarrow{x(w)}Q'}{P\mid Q\xrightarrow{\tau}(w)(P'\mid Q')}\;\text{close} \end{gathered}

Together with the binder-free rules (prefixes, match, sum, par, and the communication rule com), they become [MN p. 264]:

kind action  type.
type tau     action.
type up, dn  name -> name -> action.

type one   proc -> action -> proc -> o.
type onep  proc -> (name -> action) -> (name -> proc) -> o.

one  (taup P)      tau      P.
one  (out X Y P)   (up X Y) P.
onep (in X M)      (dn X)   M.
one  (match X X P) A P' :- one  P A P'.
onep (match X X P) A P' :- onep P A P'.
one  (plus P Q) A P'    :- one  P A P'; one  Q A P'.
onep (plus P Q) A P'    :- onep P A P'; onep Q A P'.
one  (par P Q) A (par P' Q) &
one  (par Q P) A (par Q P') :- one P A P'.
onep (par P Q) A (y\ par (P' y) Q) &
onep (par Q P) A (y\ par Q (P' y)) :- onep P A P'.
one  (nu P) A (nu P')           :- pi y\ one  (P y) A (P' y).
onep (nu P) A (x\ nu y\ P' y x) :- pi y\ onep (P y) A (P' y).
onep (nu P) (up X) P'           :-
        pi y\ one (P y) (up X y) (P' y).
one  (par P Q) tau (nu y\ par (P' y) (Q' y)) &
one  (par Q P) tau (nu y\ par (Q' y) (P' y)) :-
        onep P (up X) P', onep Q (dn X) Q'.
one  (par P Q) tau (par S (T Y)) :- one  P (up X Y) S,
                                    onep Q (dn X)   T.
one  (par P Q) tau (par (S Y) T) :- onep P (dn X) S,
                                    one  Q (up X Y) T.

Tutorial (where the side conditions went). res: in one (nu P) A (nu P') :- pi y\ one (P y) A (P' y), the variable A is quantified over the whole clause, outside the pi y. No legal instance can put y into A: “the side condition associated with the res rule is realized declaratively through a proper nesting of quantification” [MN p. 265]. input and open: the bound name is “represented by an explicit abstraction in the abstracted processes that result” [MN p. 266]. The input clause simply returns the abstraction M, so there is nothing to rename. open’s y≠xy\neq x holds because y is quantified inside the scope of X. close: the abstraction over the restricted name lies inside the scope of P' and Q', so the name cannot occur free in them [MN p. 266]. The input continuation stays abstract until a communication plugs the received name in, at (T Y) and (S Y). This is the late semantics.

The book animates the specification with queries [MN p. 266–267]:

?- example 1 P, one P A P'.
P = par (in b W\ null) (out b a null)
A = up b a
P' = par (in b W\ null) null;
P = par (in b W\ null) (out b a null)
A = tau
P' = par null null;
no

?- example 1 P, onep P A P'.
P = par (in b W\ null) (out b a null)
A = W\ dn b W
P' = W\ par null (out b a null);
no

For example 3 the query for one has a single answer, tau to nu W\ par null null [MN p. 267]: every visible action would mention the restricted name. Our notes also derive, by the same reading of the clauses, that example 4, (x)(a¯x.0)(x)(\bar a x.0), has no free transition (sending xx would leak it) but has the bound output A = W\ up a W, P' = W\ null by open.

Tutorial (three transitions, clause by clause). The τ\tau of example 1. The goal is one (par (in b y\ null) (out b a null)) tau P'. The first communication clause needs the left component to output, which an input cannot do. The second, one (par P Q) tau (par (S Y) T) :- onep P (dn X) S, one Q (up X Y) T, works: onep (in b y\ null) (dn X) S matches the input clause with X = b and S = y\ null; then one (out b a null) (up b Y) T matches the output clause with Y = a, T = null. The result par (S Y) T is par ((y\ null) a) null, which β\beta-reduces to par null null. The received name was plugged in only now, by the application (S Y): this is the late semantics.

Why example 3 has no visible action. The res clause asks pi y\ one (P y) A (P' y), with P y = par (in y z\ null) (out y a null). The output component offers up y a, so A = up y a would be needed. But A was created before the pi y, and the unifier refuses to bind it to a term that contains y. Only the internal communication, whose label tau does not mention y, survives.

Scope extrusion in example 4. one (nu x\ out a x null) A P' fails for the same reason (A = up a y is out of scope). The bound-output clause for open, onep (nu P) (up X) P' :- pi y\ one (P y) (up X y) (P' y), succeeds instead: the action pattern up X y already contains the fresh y, so only X = a is needed, and (P' y) = null is a pattern equation with the vacuous solution P' = W\ null. The extruded name is carried by the abstraction in the result, not by a free constant.

8.3.2Traces, may and must

Traces record sequences of actions. Bound outputs are continued with a generic name, while bound inputs are continued with a logic variable, “for an input action, we would want to consider different possible instantiations” [MN p. 268]:

kind trace  type.
type empty  trace.
type tr     action -> trace -> trace.
type trp    (name -> action) -> (name -> trace) -> trace.

type trace  proc -> trace -> o.
trace P empty.
trace P (tr Act Tr)     :- one P Act Q, trace Q Tr.
trace P (trp (up X) Tr) :- onep P (up X) Q,
                           pi x\ trace (Q x) (Tr x).
trace P (tr (dn X Y) Tr) :- onep P (dn X) Q, trace (Q Y) Tr.

For example 1 the query ?- example 1 P, trace P Tr. produces six traces [MN p. 268]:

empty
tr (up b a) empty
tr (up b a) (tr (dn b T) empty)
tr tau empty
tr (dn b T) empty
tr (dn b T) (tr (up b a) empty)

(The book prints trp (dn b T) in the last two lines. Its own clauses produce tr (dn b T), since only bound outputs build trp, and its later comptrace answers use tr (dn b T1).) Each input leaves a logic variable T: the trace says “some name was received”. The logic variable can be narrowed later by match. The query below enumerates exactly four traces [MN p. 268–269]:

?- trace (in a Y\ plus (match Y b (out Y Y null))
                       (match Y c (out Y Y null))) Tr.

empty
tr (dn a T) empty
tr (dn a b) (tr (up b b) empty)
tr (dn a c) (tr (up c c) empty)

After the input, the continuation is plus (match T b (out T T null)) (match T c ...). The clause one (match X X P) A P' can fire only if its two arguments unify, so it binds T := b in one branch and T := c in the other. Had the input been continued with a generic name (pi), both matches would have failed and the last two traces would be lost: “this process can do an unrestricted input and … if that input is chosen to be b or c, then further, distinct output actions can follow” [MN p. 269].

Definition 8.4 (may- and must-judgments; [MN p. 269]). A may-judgment asserts the existence of a computation path, so it corresponds to the existence of a proof. A must-judgment quantifies over all behaviours: a process can never do some action, all traces of PP are traces of QQ, PP is simulated by QQ.

“The style of logic specifications that we have described in this book does not, in general, provide declarative treatments of must-judgments. Negation-as-failure can be used, however, to capture or approximate some of these judgments” [MN p. 269]. Negation-as-failure is the cut-based predicate of [MN p. 137]:

type not  o -> o.
not P :- P, !, fail.
not P.

With it the book defines terminal processes, complete traces, separating traces and trace equivalence [MN p. 270]:

type possible, terminal  proc -> o.
type comptrace           proc -> trace -> o.
type separating_trace    proc -> proc -> trace -> o.
type trace_equiv         proc -> proc -> o.

possible P :- one P _ _ ; onep P _ _.
terminal P :- not (possible P).

comptrace P empty :- terminal P.
comptrace P (tr Act Tr)      :- one P Act Q, comptrace Q Tr.
comptrace P (tr (dn X Y) Tr) :- onep P (dn X) P',
                                comptrace (P' Y) Tr.
comptrace P (trp (up X) Tr)  :- onep P (up X) P',
                                pi x\ comptrace (P' x) (Tr x).

separating_trace P Q T :- trace P T,
                          not (trace Q T).
trace_equiv P Q :- not (separating_trace P Q _),
                   not (separating_trace Q P _).

A complete trace is one that cannot be extended: it may end with empty only at a process that can do nothing. Each of the four predicates hides a “for all” inside a not: terminal P says that no transition exists, trace_equiv that no trace separates. Examples 5 and 6 are separated, in one direction only, by an input of b followed by an internal step [MN p. 270–271]:

?- example 5 P, example 6 Q, separating_trace P Q T.
T = tr (dn a b) (tr tau empty)

Example 5 is a(y).((y(w).0)∣(b¯b.0))a(y).((y(w).0)\mid(\bar b b.0)). After the input, its two parallel components can communicate, but only on a common channel, so the communication clause unifies the received logic variable with b. Example 6, a(y).((y(w).b¯b.0)+(b¯b.y(w).0))a(y).((y(w).\bar b b.0)+(\bar b b.y(w).0)), offers the same two actions only in sequence, inside a choice, and can never make the internal step. The query in the other direction answers no. Examples 7 and 8 replace the input prefix by a bound output. They have no separating trace in either direction [MN p. 271], because the extruded name is generic and can never equal b.

An incorrect simulation. Trace equivalence is too coarse: x¯a.(y¯b.0+y¯c.0)\bar x a.(\bar y b.0+\bar y c.0) and (x¯a.y¯b.0+x¯a.y¯c.0)(\bar x a.\bar y b.0+\bar x a.\bar y c.0) are trace-equivalent, but after x¯a\bar x a the first can still choose between two outputs and the second cannot [MN p. 271]. The finer notion is simulation: “PP is simulated by QQ if whenever PP can perform an action and evolve into a process P′P', QQ can perform an identical action that transforms it into a process Q′Q' that simulates P′P'” [MN p. 271], read coinductively. The book attempts it with negation-as-failure and labels its own attempt incorrect [MN p. 272]:

type foreach2  (A -> B -> o) -> (A -> B -> o) -> o.
type sim       proc -> proc -> o.

foreach2 P Q :- not (sigma X\ sigma Y\ P X Y, not (Q X Y)).

sim P Q :- foreach2 (A\P'\ one P A P')
                    (A\P'\ sigma Q'\ one Q A Q', sim P' Q'),
           foreach2 (A\P'\ onep P A P')
                    (A\P'\ sigma Q'\ onep Q A Q',
                           pi x\ sim (P' x) (Q' x)).

The query

?- sim (in a x\ par (in x y\ null) (out c b null))
       (in a x\ plus (in x y\ out c b null) (out c b (in x y\ null))).
solved

answers solved, which is wrong. After receiving c on a, the first process can do a τ\tau and the second cannot. Diagnosis: “the universal quantifier in goals … has an intensional character: The generic goal must be derived by showing that an identical derivation exists for any of its instances. However, π\pi-calculus processes may have different evolutions for different instantiations of an input action” [MN p. 272]. What is needed is “a universal quantifier that has an extensional interpretation”. The bibliographic notes point to logics with definitionsRaymond McDowell and Dale Miller. Cut-elimination for a logic with definitions and induction. Theoretical Computer Science, 232:91–119, 2000, where ∀\forall is extensional, together with a separate generic quantifier ∇\nabla for namesDale Miller and Alwen Tiu. A proof theory for generic judgments. ACM Transactions on Computational Logic, 6(4):749–783, 2005 ([MN p. 275]).

Pitfall (one pi, two jobs). In λ\lambdaProlog, pi serves both as “a fresh name” (binders, where it is right) and as “for all instances” (must-judgments, where it is wrong). Negation-as-failure is “at best an ad hoc device” with uninstantiated variables [MN p. 273], and it needs finite failure, which replication can destroy.

8.3.3Replication, and the λ-calculus inside π

Replication !P!P, “the parallel composition of any number of copies of PP” [MN p. 262], adds four clauses [MN p. 273]:

one  (bang P) A (par P1 (bang P)) :- one P A P1.
onep (bang P) X (y\ par (M y) (bang P)) :- onep P X M.
one  (bang P) tau (par (par R (M Y)) (bang P)) :-
     onep P (dn X) M, one P (up X Y) R.
one  (bang P) tau (par (nu y\ par (M y) (N y)) (bang P)) :-
     onep P (up X) M, onep P (dn X) N.

A copy acts with a free action, a copy acts with a bound action, two copies communicate a free name, and two copies communicate an extruded one. In each case a fresh bang P remains. Milner’s call-by-name encodingRobin Milner. Functions as processes. In Automata, Languages and Programming, 17th International Colloquium, volume 443 of LNCS, pages 167–180, New York, 1990. Springer-Verlag sends arguments over a channel uu [MN p. 273]:

[ ⁣[x] ⁣](u)=x¯u.0[ ⁣[λxM] ⁣](u)=u(x).u(v).[ ⁣[M] ⁣](v)[ ⁣[M N] ⁣](u)=(v).([ ⁣[M] ⁣](v)∣(x).(v¯x.v¯u.!x(w).[ ⁣[N] ⁣](w))) \begin{aligned} [\![x]\!](u) &= \bar x u.0 \qquad\qquad [\![\lambda x M]\!](u) = u(x).u(v).[\![M]\!](v)\\ [\![M\,N]\!](u) &= (v).([\![M]\!](v)\mid(x).(\bar v x.\bar v u.!x(w).[\![N]\!](w))) \end{aligned}
type trans  tm -> (name -> proc) -> o.

trans (abs M) (u\ in u x\ in u v\ P x v) :-
    pi x\ pi y\ trans x (u\ out y u null) => trans (M x) (P y).

trans (app M N)
      (u\ nu v\ par (P v)
                    (nu x\ out v x (out v u (bang (in x Q))))) :-
    trans M P, trans N Q.

As in phi, the base case for variables is assumed as a local clause when the recursion enters a binder. The book checks the encoding by computing complete traces [MN p. 274]:

?- trans (abs w\ w) P, comptrace (P b) T.
P = u\ in u x\ in u y\ out x y null
T = tr (dn b T1) (tr (dn b T2) (tr (up T1 T2) empty));
no

For (app (abs w\ w) (abs w\ w)) the complete trace is tr tau (tr tau (tr tau (tr (dn b T1) (tr (dn b T2) (tr (up T1 T2) empty))))): three silent steps “corresponding to reduction of the term (λx x)(λx x)(\lambda x\,x)(\lambda x\,x) to λx x\lambda x\,x”, then the trace of the identity [MN p. 275].The printed process term for this query shadows a name and swaps the two par components, but the trace is unaffected.

Remark 8.5 (Lλ and πI; [MN p. 275]). “Almost all the one-step transition rules … are in the LλL_\lambda fragment”. The exceptions are the last two clauses of the one/onep program and the third replication clause, where an abstraction is applied to a received logic variable (T Y, S Y, M Y). Deleting them gives Sangiorgi’s π\piIDavide Sangiorgi. π\pi-calculus, internal mobility and agent-passing calculi. Theoretical Computer Science, 167(2):235–274, 1996, in which “only new names are bound to inputs”, so the metalogic needs only β0\beta_0-conversion.

Kanren angle (what the π-calculus needs). ∀\forall with a real scope check. Here the scope check is the whole point, because res, open and close hold only because outer variables cannot capture the fresh name. Without it, example 4 would perform the free output a¯x\bar a x and example 3 would perform up W a. A cheaper discipline, posting an absent° constraint on the clause’s own variables after each generic subgoal, is not enough. Our notes give the test trace (in a z\ nu x\ match z x (out b b null)) Tr. In λ\lambdaProlog it yields only empty and tr (dn a T) empty, because the received T, a variable hidden inside the process, may not become the restricted x. An absent-on-clause-variables port also yields tr (dn a T) (tr (up b b) empty). The check must live in unification. ⊃\supset. trans assumes atomic clauses about fresh variables, as in Section 8.2. Patterns. Abstracted continuations, (P' y) under pi y, and the trace abstraction (Tr x) are all pattern equations. Beyond patterns. (T Y) with Y a logic variable is outside LλL_\lambda. A faithful engine postpones it until T is known. A first-order locally nameless encoding turns it into a harmless structural “open” relation. Negation. not G is (if° (take° 1 G) ✗° ✓°). Without take° 1, (aux kanren micro)’s soft cut would map ✗° over every answer of G and diverge whenever G has infinitely many. Search. With bang, trace becomes an infinite but productive stream under interleaving, but negation still needs finite failure. Must-judgments. Our notes propose, beyond the book, to make the bound-input case of sim extensional by case analysis over the free names plus one fresh name. This is a finite substitute for the definitions-and-∇\nabla reading. See Chapter 11 for which of these the proposal adopts.

8.4Summary

  • One recipe for three domains. A judgment becomes a predicate. Object binders become meta λ\lambdas. Going under a binder means pi plus a hypothetical fact. Freshness and non-capture side conditions are then discharged by quantifier nesting.
  • Specification versus search. Direct translations are sound, but depth-first execution can loop (⊃L{\supset}L, # as a prover). A better calculus (Dyckhoff’s) gives a decision procedure. Programmable control (tactics and tacticals) moves the strategy into the program.
  • Logic variables as delayed choices. Witnesses of ∃R\exists R, all_l and path_rec_tac, and received names in traces, are chosen by unification at the leaves. The unifier must respect eigenvariable scope.
  • Cut and if are dangerous with logic variables and eigenvariables. They can lose completeness (the CL counterexample) or break soundness theorems (mixeval).
  • Must-judgments are beyond hohh. pi is intensional. Simulation needs an extensional ∀\forall (definitions) and a generic ∇\nabla.
  • Interleaving search makes naive calculi, prover modes and tactic scripts complete for answers, and it makes the classical prover complete without iterative deepening. It never provides termination.

The requirements, application by application (“atomic” means every assumed clause is an atomic fact, so an explicit context could replace =>):

application∀\forall (eigenvariables)⊃\supset (hypotheses)λ\lambda-term unification
Dyckhoff seqonly in the queryatomic, query onlynone: runs on (aux kanren micro) today
natural deduction #proof labels, ∀I\forall I, ∃E\exists Eatomic (p # A)patterns for completion, A' (f y) delayed
classical prv∀R\forall R, scope check vitalatomic (lit, bound)patterns (difference-list queue)
tacticsmaptac under allgnonepattern Out t; rest runs today
typeofunder abs, fixptatomicnone with named binders: runs today
eval, evalcnonenoneβ\beta with known heads; contexts as outputs
mixeval, CPSunder the binderatomicpatterns (S k), (P y)
π\pi transitions, tracesres/open/close, scope check vitalatomic (trans)patterns, plus non-LλL_\lambda (T Y)