计算机科学 · 第 4 册 · 本科二年级

University Computer Science — Year 2

本书暂未推出简体中文版。现有版本:English。

University Computer Science — Year 2 · 本科二年级

24Predicate Logic and Formal Proofs

The town library has rules: a person with a book out is a member, a book is out to one person at most, every member has a friend. Each one speaks of all the people and some book, which propositional formulas cannot say. Written in a language with quantifiers, the rules can be checked against the town’s tables by a program:

RULES = [
    ("a person with a book out is a member",
     "forall x. (exists y. Out(x, y)) -> Member(x)"),
    ("a book is out to one person at most",
     "forall y. forall x. Out(x, y) -> forall z. Out(z, y) -> z = x"),
    ("what is out has been borrowed",
     "forall x. forall y. Out(x, y) -> Borrowed(x, y)"),
    ("every book has been borrowed",
     "forall y. Book(y) -> exists x. Borrowed(x, y)"),
    ("every member has a friend",
     "forall x. Member(x) -> exists y. Friend(x, y)"),
]

A = town()
print(f"{len(A.domain)} elements; {len(A.relations['Out'])} loans out now")
for words, text in RULES:
    A.atoms = 0
    bad = A.counterexamples(parse(text))
    print(f"{words}: {'holds' if not bad else 'fails'} ({A.atoms} atoms evaluated)")
    for vals in bad[:3]:
        print("   counterexample:", ", ".join(vals))
    if len(bad) > 3:
        print(f"   ... {len(bad)} in all")
Listing 24.1. Five rules about the library as formulas, each evaluated on the town’s tables, with the first counterexamples found code/bachelor-2/24-predicate-logic/listings/evaluate.py
$ python evaluate.py
200 elements; 22 loans out now
a person with a book out is a member: holds (37379 atoms evaluated)
a book is out to one person at most: fails (43826 atoms evaluated)
   counterexample: b28, p109
   counterexample: b28, p116
   counterexample: b5, p104
   ... 8 in all
what is out has been borrowed: holds (40022 atoms evaluated)
every book has been borrowed: holds (8452 atoms evaluated)
every member has a friend: fails (10541 atoms evaluated)
   counterexample: p102
   counterexample: p104
   counterexample: p106
   ... 41 in all
Output 24.1. Three rules hold; two fail. Four books are recorded as out to two people at once, and 41 members have no friend in the friendships table.

A check on the data says what holds today. Some rules hold for a better reason: they follow from others, in every possible town. If whoever has a book out is a member, and every member may borrow, then whoever has a book out may borrow, whatever the tables contain. This chapter defines the language of such rules, what it means for a formula to be true in a structure, and proofs: trees of small steps, each checked mechanically, with a theorem that a proved formula is true wherever its hypotheses are. It ends with two algorithmic tools of logic, unification and resolution, and a linear-time algorithm for 2-SAT.

You already know

The Year 1 volume: propositional formulas as trees, valuations, a model of a formula, satisfiability, logical consequence and equivalence; literals, clauses and CNF; the satisfiability problem and kk-SAT; strongly connected components of a directed graph, and Kosaraju’s algorithm, which finds them with two depth-first searches in linear time; structural induction. From mathematics: sets, relations, functions, tuples.

24.1 Syntax: terms, formulas, variables

Definition 24.1 (First-order signature, term, atomic formula)

A first-order signature is a set of function symbols and a set of predicate symbols, each with an arity, its number of arguments; a function symbol of arity 00 is a constant. Given an infinite set of variables, the terms are built by: a variable is a term; if ff has arity nn and t1,…,tnt_1, \dots, t_n are terms, f(t1,…,tn)f(t_1, \dots, t_n) is a term. An atomic formula is P(t1,…,tn)P(t_1, \dots, t_n) for a predicate symbol PP of arity nn, an equality t1=t2t_1 = t_2, or ⊥\bot (false).

The library’s signature has the constants p5, b3, …, the predicates Person\mathit{Person}, Member\mathit{Member} and Book\mathit{Book} of arity 1, and Out\mathit{Out}, Borrowed\mathit{Borrowed} and Friend\mathit{Friend} of arity 2. Arithmetic has the constant 00, the successor ss of arity 1 and ++ of arity 2, so s(0)+xs(0) + x is a term. A term names an object; an atomic formula says something about objects, and is true or false.

Definition 24.2 (First-order formula, quantifier)

The first-order formulas are built by: an atomic formula is a formula; if AA and BB are formulas and xx is a variable, ¬A\neg A, A∧BA \wedge B, A∨BA \vee B, A→BA \to B, ∀x A\forall x\, A and ∃x A\exists x\, A are formulas. The symbols ∀\forall (for all) and ∃\exists (there exists) are the quantifiers. Predicate logic is the study of these formulas.

As in the Year 1 volume, a formula is a tree, and brackets are only a way to write it on a line. The conventions are: ¬\neg binds tightest, then ∧\wedge, ∨\vee and →\to, which groups to the right; a quantifier reaches as far right as possible, so ∀x P(x)→Q(x)\forall x\, P(x) \to Q(x) is ∀x (P(x)→Q(x))\forall x\, (P(x) \to Q(x)). The listings write ~, &, |, ->, forall x. and exists x., and the library formulas.py reads and prints that text; its parser treats the names uu to zz, possibly followed by digits, as variables, and other lower-case names as constants.

Definition 24.3 (Free variable, bound variable, scope)

In ∀x A\forall x\, A and ∃x A\exists x\, A, the formula AA is the scope of the quantifier. An occurrence of xx is bound if it lies in the scope of a quantifier on xx, and then it is bound by the nearest such quantifier above it in the tree; otherwise it is free. The free variables of a formula are those with a free occurrence; a formula without any is a sentence.

The free variables are computed by structural induction, one line per case:

def free(e):
    """The free variables of a term or a formula."""
    match e:
        case Var(x):
            return {x}
        case Fun(_, args) | Pred(_, args):
            return set().union(*map(free, args))
        case Bot():
            return set()
        case Not(a):
            return free(a)
        case And(a, b) | Or(a, b) | Imp(a, b):
            return free(a) | free(b)
        case Forall(x, a) | Exists(x, a):
            return free(a) - {x}  # x is bound in its scope a
Listing 24.2. The free variables of a term or a formula; a quantifier removes its own variable code/bachelor-2/24-predicate-logic/listings/formulas.py

A formula’s truth depends on its free variables, as x<3x < 3 depends on xx; a sentence is simply true or false in a given world. In ∀x (R(x,y)→∃x P(x))\forall x\, (R(x, y) \to \exists x\, P(x)), the first xx is bound by ∀x\forall x, the second by ∃x\exists x, and yy is free:

The tree of x\, (R(x, y) x\, P(x)). A dashed arrow joins each bound occurrence to the quantifier that binds it: the nearest one above it on its own variable. The circled y is free.
The tree of ∀x (R(x,y)→∃x P(x))\forall x\, (R(x, y) \to \exists x\, P(x)). A dashed arrow joins each bound occurrence to the quantifier that binds it: the nearest one above it on its own variable. The circled yy is free.

Definition 24.4 (Substitution, capture-avoiding substitution)

The substitution A[t/x]A[t/x] replaces every free occurrence of xx in AA by the term tt. It is capture-avoiding when no variable of tt becomes bound by doing so: before entering the scope of a quantifier on a variable yy of tt, the bound yy is renamed to a variable used nowhere else.

Renaming a bound variable does not change a formula’s meaning, as ∑iai\sum_i a_i and ∑jaj\sum_j a_j are the same sum. Replacing without care does. With ss the successor, ∃y y=s(x)\exists y\, y = s(x) says that xx has a successor, which is true of every xx. Substituting yy for xx should say that yy has a successor; the careless copy says that some number is its own successor:

def subst(e, x, t):
    """e[t/x]: replace the free occurrences of x by t, renaming a bound variable that
    would capture a variable of t."""
    match e:
        case Var(y):
            return t if y == x else e
        case Fun(f, args):
            return Fun(f, tuple(subst(a, x, t) for a in args))
        case Pred(p, args):
            return Pred(p, tuple(subst(a, x, t) for a in args))
        case Bot():
            return e
        case Not(a):
            return Not(subst(a, x, t))
        case And(a, b) | Or(a, b) | Imp(a, b):
            return type(e)(subst(a, x, t), subst(b, x, t))
        case Forall(y, a) | Exists(y, a):
            if y == x or x not in free(a):
                return e  # no free x below: nothing to replace
            if y in free(t):  # y would capture t's y: rename it first
                z = fresh(y, free(t) | free(a) | {x})
                a, y = subst(a, y, Var(z)), z
            return type(e)(y, subst(a, x, t))
Listing 24.3. Capture-avoiding substitution: the bound variable is renamed when it would capture a variable of tt code/bachelor-2/24-predicate-logic/listings/formulas.py
$ python substitution_demo.py
phi       exists y. y = s(x)     free: ['x']  true for 0..4: [True, True, True, True, True]
naive     exists y. y = s(y)     free: []  true for 0..4: [False, False, False, False, False]
phi[y/x]  exists y1. y1 = s(y)   free: ['y']  true for 0..4: [True, True, True, True, True]
Output 24.2. In the integers modulo 5, the naive copy has lost its free variable and become false; the renamed substitution keeps the meaning.

24.2 Semantics: structures and truth

Definition 24.5 (Structure, variable assignment, satisfaction)

A structure A\mathcal{A} for a signature is a non-empty set DD, its domain, with a function fA:Dn→Df^{\mathcal{A}} : D^n \to D for each function symbol of arity nn and a relation PA⊆DnP^{\mathcal{A}} \subseteq D^n for each predicate symbol of arity nn. A variable assignment is a function ρ\rho from variables to DD. The value ⟦t⟧ρ\llbracket t \rrbracket_\rho of a term is ρ(x)\rho(x) for a variable and fA(⟦t1⟧ρ,…,⟦tn⟧ρ)f^{\mathcal{A}}(\llbracket t_1 \rrbracket_\rho, \dots, \llbracket t_n \rrbracket_\rho) for f(t1,…,tn)f(t_1, \dots, t_n). Satisfaction A,ρ⊨A\mathcal{A}, \rho \models A is defined by induction on AA:

  • A,ρ⊨P(t1,…,tn)\mathcal{A}, \rho \models P(t_1, \dots, t_n) when (⟦t1⟧ρ,…,⟦tn⟧ρ)∈PA(\llbracket t_1 \rrbracket_\rho, \dots, \llbracket t_n \rrbracket_\rho) \in P^{\mathcal{A}}; A,ρ⊨t1=t2\mathcal{A}, \rho \models t_1 = t_2 when the two values are equal; never A,ρ⊨⊥\mathcal{A}, \rho \models \bot;
  • the connectives as for valuations: A,ρ⊨A∧B\mathcal{A}, \rho \models A \wedge B when both hold, and so on;
  • A,ρ⊨∀x A\mathcal{A}, \rho \models \forall x\, A when A,ρ[x↦d]⊨A\mathcal{A}, \rho[x \mapsto d] \models A for every d∈Dd \in D, and A,ρ⊨∃x A\mathcal{A}, \rho \models \exists x\, A when it holds for at least one d∈Dd \in D, where ρ[x↦d]\rho[x \mapsto d] is ρ\rho changed at xx only.

Only the free variables of AA matter: if ρ\rho and ρ′\rho' agree on them, A,ρ⊨A\mathcal{A}, \rho \models A exactly when A,ρ′⊨A\mathcal{A}, \rho' \models A, by an induction on AA in which the quantifier case changes the assignment at the bound variable only. For a sentence the assignment does not matter, and one writes A⊨A\mathcal{A} \models A.

Definition 24.6 (Model, valid formula, first-order logical consequence)

A structure A\mathcal{A} is a model of a set of sentences Γ\Gamma when A⊨B\mathcal{A} \models B for every B∈ΓB \in \Gamma. A formula AA is valid when A,ρ⊨A\mathcal{A}, \rho \models A for every structure and every assignment. It is a first-order logical consequence of Γ\Gamma, written Γ⊨A\Gamma \models A, when every structure and assignment that satisfy all of Γ\Gamma satisfy AA.

The definition reads like a program, and on a finite domain it is one. Listing 24.4 follows it line by line; the town is a structure whose domain holds the 120 people and the 80 books, with the relations read from the tables, and Listing 24.1 asked it about five sentences.

    def value(self, t, env):
        match t:
            case Var(x):
                return env[x]
            case Fun(c, ()) if c not in self.functions:
                return c  # a constant names itself
            case Fun(f, args):
                return self.functions[f](*(self.value(a, env) for a in args))

    def holds(self, f, env=None):
        """A, env |= f, by induction on f; the connectives stop as soon as they know."""
        env = env or {}
        match f:
            case Pred(p, args):
                self.atoms += 1
                vals = tuple(self.value(a, env) for a in args)
                return vals[0] == vals[1] if p == "=" else vals in self.relations[p]
            case Bot():
                return False
            case Not(a):
                return not self.holds(a, env)
            case And(a, b):
                return self.holds(a, env) and self.holds(b, env)
            case Or(a, b):
                return self.holds(a, env) or self.holds(b, env)
            case Imp(a, b):
                return not self.holds(a, env) or self.holds(b, env)
            case Forall(x, a):
                return all(self.holds(a, {**env, x: d}) for d in self.domain)
            case Exists(x, a):
                return any(self.holds(a, {**env, x: d}) for d in self.domain)
Listing 24.4. The value of a term and the satisfaction relation on a finite structure, by induction on the formula code/bachelor-2/24-predicate-logic/listings/structures.py

Proposition 24.7 (Cost of evaluation)

Let AA be a formula with ∣A∣|A| nodes whose quantifiers are nested at most qq deep, and A\mathcal{A} a finite structure with domain DD, in which a function or a relation is evaluated in constant time. The recursive evaluation of A,ρ⊨A\mathcal{A}, \rho \models A takes O⁡(∣D∣q⋅∣A∣⋅m)\BigO(|D|^q \cdot |A| \cdot m) steps, where mm bounds the size of the terms.

Proof. A node of the tree of AA with kk quantifiers above it is evaluated at most once for each choice of values of those kk variables, so at most ∣D∣k≤∣D∣q|D|^k \leq |D|^q times. Each visit costs a constant, plus at most mm steps for the terms of an atomic formula. Summing over the ∣A∣|A| nodes gives the bound. ∎

The bound is exponential in qq, not in ∣A∣|A|: a rule with three nested quantifiers on a domain of a thousand elements costs a billion visits. Transitivity has three, and on the order << of {0,…,n−1}\{0, \dots, n-1\} the count of atomic formulas grows as n3n^3:

phi = parse("forall x. forall y. forall z. R(x, y) & R(y, z) -> R(x, z)")
print(" |D|     |D|^3      atoms  atoms/|D|^3  holds")
for n in [10, 20, 40, 80]:
    less = {(a, b) for a in range(n) for b in range(n) if a < b}
    A = Structure(range(n), {"R": less})
    ok = A.holds(phi)
    print(f"{n:4} {n ** 3:9} {A.atoms:10} {A.atoms / n ** 3:12.2f}  {ok}")
Listing 24.5. Atomic formulas evaluated to check that << is transitive, for growing domains code/bachelor-2/24-predicate-logic/listings/cost.py
$ python cost.py
 |D|     |D|^3      atoms  atoms/|D|^3  holds
  10      1000       1570         1.57  True
  20      8000      12940         1.62  True
  40     64000     105080         1.64  True
  80    512000     846960         1.65  True
Output 24.3. The ratio tends to 5/35/3: every triple evaluates R(x,y)R(x, y), half of them also R(y,z)R(y, z), and the triples with x<y<zx < y < z, a sixth, also R(x,z)R(x, z).

In practice

A database query is a formula evaluated on a finite structure: the tables are the relations. The rule “a book is out to one person at most” becomes a query for its counterexamples, two loans of the same book, neither returned, by two different members, and a database runs it with indexes rather than with the ∣D∣3|D|^3 loop of Proposition 24.7. Integrity constraints of a schema are sentences of the same kind, checked on every change of the data.

The evaluation decides truth in one finite structure. Consequence quantifies over every structure, including infinite ones, and no program can try them all. A rule that follows from others needs another kind of evidence: a proof.

24.3 Natural deduction

Definition 24.8 (Sequent, inference rule, proof tree)

A sequent Γ⊢A\Gamma \vdash A is a finite set of formulas Γ\Gamma, the hypotheses, and a formula AA, the conclusion; it claims that AA follows from Γ\Gamma. An inference rule gives a sequent, its conclusion, from zero or more sequents, its premises, possibly under a side condition. A proof tree is a tree of sequents in which every node follows from its children by a rule; it proves the sequent at its root. One writes Γ⊢A\Gamma \vdash A also for “some proof tree proves Γ⊢A\Gamma \vdash A”.

Definition 24.9 (Natural deduction, introduction rule, elimination rule)

Natural deduction is the system of rules drawn below. Each connective and quantifier has introduction rules, which conclude a formula with that symbol at its root, and elimination rules, which use such a formula among the premises. The rule raa (reductio ad absurdum) makes it classical logic; without it, the logic is intuitionistic (Exercise 24.11).

 Γ⊢A hyp (A∈Γ)Γ⊢AΓ⊢BΓ⊢A∧B ∧iΓ⊢A∧BΓ⊢A ∧e1Γ⊢A∧BΓ⊢B ∧e2Γ⊢AΓ⊢A∨B ∨i1Γ⊢BΓ⊢A∨B ∨i2Γ⊢A∨BΓ,A⊢CΓ,B⊢CΓ⊢C ∨eΓ,A⊢BΓ⊢A→B →iΓ⊢A→BΓ⊢AΓ⊢B →eΓ,A⊢⊥Γ⊢¬A ¬iΓ⊢AΓ⊢¬AΓ⊢⊥ ¬eΓ⊢⊥Γ⊢A ⊥eΓ,¬A⊢⊥Γ⊢A raaΓ⊢A[y/x]Γ⊢∀x A ∀i (∗)Γ⊢∀x AΓ⊢A[t/x] ∀eΓ⊢A[t/x]Γ⊢∃x A ∃iΓ⊢∃x AΓ,A[y/x]⊢CΓ⊢C ∃e (∗∗)\begin{gather*}{\dfrac{\ }{\Gamma \vdash A}\,\scriptstyle\text{hyp}}\ (A \in \Gamma) \qquad {\dfrac{\Gamma \vdash A \qquad \Gamma \vdash B}{\Gamma \vdash A \wedge B}\,\scriptstyle\text{$\wedge$i}} \qquad {\dfrac{\Gamma \vdash A \wedge B}{\Gamma \vdash A}\,\scriptstyle\text{$\wedge$e$_1$}} \qquad {\dfrac{\Gamma \vdash A \wedge B}{\Gamma \vdash B}\,\scriptstyle\text{$\wedge$e$_2$}} \\ {\dfrac{\Gamma \vdash A}{\Gamma \vdash A \vee B}\,\scriptstyle\text{$\vee$i$_1$}} \\[2ex] {\dfrac{\Gamma \vdash B}{\Gamma \vdash A \vee B}\,\scriptstyle\text{$\vee$i$_2$}} \qquad {\dfrac{\Gamma \vdash A \vee B \qquad \Gamma, A \vdash C \qquad \Gamma, B \vdash C}{\Gamma \vdash C}\,\scriptstyle\text{$\vee$e}} \\ {\dfrac{\Gamma, A \vdash B}{\Gamma \vdash A \to B}\,\scriptstyle\text{$\to$i}} \qquad {\dfrac{\Gamma \vdash A \to B \qquad \Gamma \vdash A}{\Gamma \vdash B}\,\scriptstyle\text{$\to$e}} \qquad {\dfrac{\Gamma, A \vdash \bot}{\Gamma \vdash \neg A}\,\scriptstyle\text{$\neg$i}} \\[2ex] {\dfrac{\Gamma \vdash A \qquad \Gamma \vdash \neg A}{\Gamma \vdash \bot}\,\scriptstyle\text{$\neg$e}} \\ {\dfrac{\Gamma \vdash \bot}{\Gamma \vdash A}\,\scriptstyle\text{$\bot$e}} \qquad {\dfrac{\Gamma, \neg A \vdash \bot}{\Gamma \vdash A}\,\scriptstyle\text{raa}} \qquad {\dfrac{\Gamma \vdash A[y/x]}{\Gamma \vdash \forall x\, A}\,\scriptstyle\text{$\forall$i}}\ (*) \\[2ex] {\dfrac{\Gamma \vdash \forall x\, A}{\Gamma \vdash A[t/x]}\,\scriptstyle\text{$\forall$e}} \\ {\dfrac{\Gamma \vdash A[t/x]}{\Gamma \vdash \exists x\, A}\,\scriptstyle\text{$\exists$i}} \qquad {\dfrac{\Gamma \vdash \exists x\, A \qquad \Gamma, A[y/x] \vdash C}{\Gamma \vdash C}\,\scriptstyle\text{$\exists$e}}\ (**)\end{gather*}
The rules of natural deduction; tt is any term. Side conditions: (∗)(*) yy is free neither in Γ\Gamma nor in ∀x A\forall x\, A; (∗∗)(**) yy is free neither in Γ\Gamma, nor in ∃x A\exists x\, A, nor in CC.

Example 24.10 (Modus ponens and the syllogism)

From P→QP \to Q and PP, the rule →\toe gives QQ: this is modus ponens. From P→QP \to Q and Q→RQ \to R the conclusion P→RP \to R needs a hypothesis that is later discharged: under the extra hypothesis PP, two uses of →\toe give RR, and →\toi turns “RR under PP” into P→RP \to R with PP no longer among the hypotheses. With Γ={P→Q, Q→R}\Gamma = \{P \to Q,\ Q \to R\}:

 P→Q,P⊢P→Q hyp P→Q,P⊢P hypP→Q,P⊢Q →e{\dfrac{{\dfrac{\ }{P \to Q, P \vdash P \to Q}\,\scriptstyle\text{hyp}} \qquad {\dfrac{\ }{P \to Q, P \vdash P}\,\scriptstyle\text{hyp}}}{P \to Q, P \vdash Q}\,\scriptstyle\text{$\to$e}}  Γ,P⊢Q→R hyp Γ,P⊢P→Q hyp Γ,P⊢P hypΓ,P⊢Q →eΓ,P⊢R →eΓ⊢P→R →i{\dfrac{{\dfrac{{\dfrac{\ }{\Gamma, P \vdash Q \to R}\,\scriptstyle\text{hyp}} \qquad {\dfrac{{\dfrac{\ }{\Gamma, P \vdash P \to Q}\,\scriptstyle\text{hyp}} \qquad {\dfrac{\ }{\Gamma, P \vdash P}\,\scriptstyle\text{hyp}}}{\Gamma, P \vdash Q}\,\scriptstyle\text{$\to$e}}}{\Gamma, P \vdash R}\,\scriptstyle\text{$\to$e}}}{\Gamma \vdash P \to R}\,\scriptstyle\text{$\to$i}}

Example 24.11 (No counterexample)

The sequent ⊢(P→Q)→¬(P∧¬Q)\vdash (P \to Q) \to \neg(P \wedge \neg Q) says that an implication has no counterexample. Read from the bottom: to prove an implication, assume its left side; to prove a negation, assume the formula and reach ⊥\bot. With Δ={P→Q, P∧¬Q}\Delta = \{P \to Q,\ P \wedge \neg Q\}:

 Δ⊢P→Q hyp Δ⊢P∧¬Q hypΔ⊢P ∧e1Δ⊢Q →e Δ⊢P∧¬Q hypΔ⊢¬Q ∧e2Δ⊢⊥ ¬eP→Q⊢¬(P∧¬Q) ¬i⊢(P→Q)→¬(P∧¬Q) →i{\dfrac{{\dfrac{{\dfrac{{\dfrac{{\dfrac{\ }{\Delta \vdash P \to Q}\,\scriptstyle\text{hyp}} \qquad {\dfrac{{\dfrac{\ }{\Delta \vdash P \wedge \neg Q}\,\scriptstyle\text{hyp}}}{\Delta \vdash P}\,\scriptstyle\text{$\wedge$e$_1$}}}{\Delta \vdash Q}\,\scriptstyle\text{$\to$e}} \qquad {\dfrac{{\dfrac{\ }{\Delta \vdash P \wedge \neg Q}\,\scriptstyle\text{hyp}}}{\Delta \vdash \neg Q}\,\scriptstyle\text{$\wedge$e$_2$}}}{\Delta \vdash \bot}\,\scriptstyle\text{$\neg$e}}}{P \to Q \vdash \neg(P \wedge \neg Q)}\,\scriptstyle\text{$\neg$i}}}{\vdash (P \to Q) \to \neg(P \wedge \neg Q)}\,\scriptstyle\text{$\to$i}}

Every proposition proved so far is also a tautology, as the truth tables of the Year 1 volume would confirm. The proof says more than the table: it is a finite object that a reader, or a program, checks step by step, and the same rules continue to work once quantifiers enter, where no table exists.

24.4 The quantifier rules

The rule ∀\foralle says that what holds of everything holds of any term tt. From the rule ∀x Member(x)→MayBorrow(x)\forall x\, \mathit{Member}(x) \to \mathit{MayBorrow}(x) it concludes that Member(p5)→MayBorrow(p5)\mathit{Member}(p5) \to \mathit{MayBorrow}(p5), and also, with a variable yy for tt, that Member(y)→MayBorrow(y)\mathit{Member}(y) \to \mathit{MayBorrow}(y). The substitution must avoid capture, or ∀x ∃y y=s(x)\forall x\, \exists y\, y = s(x) would give ∃y y=s(y)\exists y\, y = s(y), as Output 24.2 showed.

The rule ∀\foralli is the mathematician’s “let yy be arbitrary”: if A[y/x]A[y/x] has been proved about a yy of which the hypotheses say nothing, the same proof works for every value of yy, so ∀x A\forall x\, A holds. The side condition is what “arbitrary” means. Without it, from the hypothesis P(y)P(y), “this person is a member”, one would conclude ∀x P(x)\forall x\, P(x), “everyone is”. The rules for ∃\exists are mirror images: ∃\existsi needs one witness tt, and ∃\existse reasons about a witness yy that nothing else mentions.

Example 24.12 (A universal from two universals)

From ∀x (P(x)→Q(x))\forall x\, (P(x) \to Q(x)) and ∀x P(x)\forall x\, P(x) follows ∀x Q(x)\forall x\, Q(x). With Γ\Gamma the two hypotheses, both sentences, the variable yy is free in none of them, and ∀\foralli applies:

 Γ⊢∀x (P(x)→Q(x)) hypΓ⊢P(y)→Q(y) ∀e Γ⊢∀x P(x) hypΓ⊢P(y) ∀eΓ⊢Q(y) →eΓ⊢∀x Q(x) ∀i{\dfrac{{\dfrac{{\dfrac{{\dfrac{\ }{\Gamma \vdash \forall x\, (P(x) \to Q(x))}\,\scriptstyle\text{hyp}}}{\Gamma \vdash P(y) \to Q(y)}\,\scriptstyle\text{$\forall$e}} \qquad {\dfrac{{\dfrac{\ }{\Gamma \vdash \forall x\, P(x)}\,\scriptstyle\text{hyp}}}{\Gamma \vdash P(y)}\,\scriptstyle\text{$\forall$e}}}{\Gamma \vdash Q(y)}\,\scriptstyle\text{$\to$e}}}{\Gamma \vdash \forall x\, Q(x)}\,\scriptstyle\text{$\forall$i}}

The order of quantifiers matters. ∃x ∀y R(x,y)⊢∀y ∃x R(x,y)\exists x\, \forall y\, R(x, y) \vdash \forall y\, \exists x\, R(x, y) has a proof (Exercise 24.10): if one xx is related to every yy, every yy has some xx. The converse fails, and the way to show that a sequent has no proof is a structure in which its hypotheses are true and its conclusion false:

A structure with domain \0, 1\ and R the equality. Every y has an x with R(x, y), namely y itself, so y\, x\, R(x, y) is true; no x is related to both 0 and 1, so x\, y\, R(x, y) is false.
A structure with domain {0,1}\{0, 1\} and RR the equality. Every yy has an xx with R(x,y)R(x, y), namely yy itself, so ∀y ∃x R(x,y)\forall y\, \exists x\, R(x, y) is true; no xx is related to both 00 and 11, so ∃x ∀y R(x,y)\exists x\, \forall y\, R(x, y) is false.

24.5 Soundness and completeness

Definition 24.13 (Soundness, completeness)

A proof system is sound when every provable sequent is a consequence: Γ⊢A\Gamma \vdash A implies Γ⊨A\Gamma \models A. It is complete when every consequence is provable: Γ⊨A\Gamma \models A implies Γ⊢A\Gamma \vdash A.

Soundness makes a proof worth having; completeness says that the rules miss nothing. The proof of soundness uses one fact about substitution, which says that substituting a term and changing the assignment are the same operation.

Lemma 24.14 (Substitution)

For every structure, assignment ρ\rho, terms s,ts, t, variable xx and formula AA, with d=⟦t⟧ρd = \llbracket t \rrbracket_\rho:

⟦s[t/x]⟧ρ=⟦s⟧ρ[x↦d]andA,ρ⊨A[t/x]  ⟺  A,ρ[x↦d]⊨A.\llbracket s[t/x] \rrbracket_\rho = \llbracket s \rrbracket_{\rho[x \mapsto d]} \qquad\text{and}\qquad \mathcal{A}, \rho \models A[t/x] \iff \mathcal{A}, \rho[x \mapsto d] \models A.

Proof. For terms, by induction on ss. If ss is xx, both sides are dd. If ss is another variable zz, both are ρ(z)\rho(z). If s=f(s1,…,sn)s = f(s_1, \dots, s_n), then s[t/x]=f(s1[t/x],…,sn[t/x])s[t/x] = f(s_1[t/x], \dots, s_n[t/x]), and the induction hypothesis on each sis_i gives the equality of the arguments, so of the values of ff. The statement on formulas follows by induction on AA; its atomic case is the statement on terms, and its quantifier case is where capture avoidance is needed (Exercise 24.12). ∎

The test file test_formulas.py checks the property on 400 random formulas over a structure of three elements; the test fails at once if the renaming of Listing 24.3 is removed.

Theorem 24.15 (Soundness of natural deduction)

If Γ⊢A\Gamma \vdash A has a proof tree, then Γ⊨A\Gamma \models A.

Proof. By induction on the proof tree: assuming that the premises of its last rule are consequences, so is its conclusion. Fix a structure A\mathcal{A} and an assignment ρ\rho satisfying every formula of Γ\Gamma; we show A,ρ⊨A\mathcal{A}, \rho \models A for each rule.

  • hyp: A∈ΓA \in \Gamma, and ρ\rho satisfies Γ\Gamma.
  • ∧\wedgei: by induction ρ\rho satisfies AA and BB, so A∧BA \wedge B. The eliminations of ∧\wedge and the introductions of ∨\vee are as direct.
  • →\toe: ρ\rho satisfies A→BA \to B and AA, so BB. The rules ¬\negi and ¬\nege are the same argument with ¬A\neg A read as A→⊥A \to \bot, and ⊥\bote holds because no ρ\rho satisfies ⊥\bot.
  • raa: if ρ\rho did not satisfy AA, it would satisfy Γ∪{¬A}\Gamma \cup \{\neg A\}, hence ⊥\bot by induction, which is impossible.
  • ∀\foralle: ρ\rho satisfies ∀x A\forall x\, A, so ρ[x↦⟦t⟧ρ]\rho[x \mapsto \llbracket t \rrbracket_\rho] satisfies AA, and ρ\rho satisfies A[t/x]A[t/x] by Lemma 24.14.
  • ∀\foralli: let d∈Dd \in D and ρ′=ρ[y↦d]\rho' = \rho[y \mapsto d]. As yy is not free in Γ\Gamma, ρ′\rho' satisfies Γ\Gamma, so by induction it satisfies A[y/x]A[y/x], and by the lemma, with ⟦y⟧ρ′=d\llbracket y \rrbracket_{\rho'} = d, ρ′[x↦d]\rho'[x \mapsto d] satisfies AA. If y=xy = x, this assignment is ρ[x↦d]\rho[x \mapsto d]. Otherwise yy is not free in ∀x A\forall x\, A, so not in AA, and ρ′[x↦d]\rho'[x \mapsto d] agrees with ρ[x↦d]\rho[x \mapsto d] on the free variables of AA. In both cases ρ[x↦d]\rho[x \mapsto d] satisfies AA, for every dd: ρ\rho satisfies ∀x A\forall x\, A.

The rules →\toi and ∨\veee are Exercise 24.8, and the rules of ∃\exists follow the pattern of those of ∀\forall. ∎

The side condition of ∀\foralli appears in the proof exactly where it is used: changing yy must leave the hypotheses true. Soundness also gives the method for showing that a sequent has no proof. The structure of the previous figure satisfies ∀y ∃x R(x,y)\forall y\, \exists x\, R(x, y) and not ∃x ∀y R(x,y)\exists x\, \forall y\, R(x, y), so the second is not a consequence of the first, and by soundness no proof tree, however long, derives it.

Theorem 24.16 (Completeness)

If Γ⊨A\Gamma \models A, then Γ⊢A\Gamma \vdash A has a proof tree in natural deduction.

Proof. Admitted at this level. ∎

The proof builds, from a set of formulas that proves nothing false, a structure that satisfies all of them, made of the terms themselves; it is longer than the chapter allows. Together the two theorems say that ⊢\vdash and ⊨\models are the same relation. They do not give an algorithm deciding it: one can enumerate all proof trees, and if Γ⊨A\Gamma \models A a proof will appear, but if not, the search never ends. No algorithm decides first-order consequence in general; Book 5 develops the methods that prove such impossibility results.

History

Gottlob Frege published the Begriffsschrift in 1879, a formula language for logic modelled on that of arithmetic, in which quantified variables first appear in their modern role. Natural deduction and the sequent calculus were introduced by Gerhard Gentzen in a paper of 1935, both to make formal proofs look like the reasoning of mathematicians; the sequent calculus, a variant in which every rule acts on the hypotheses or on the conclusion of a sequent, was the form in which he proved that proofs can be put in a normal form. Kurt Gödel published the completeness of first-order logic in 1930.

24.6 Proof checkers

Definition 24.17 (Proof checker)

A proof checker is a program that, given a proof tree, decides whether every node follows from its children by a rule of the system, side conditions included. If it accepts, the root sequent is proved.

A checker does not search for proofs; it only checks that each step is one of the rules, which is easy. In checker.py a proof is a tree of steps, each with its rule, the formula it concludes, the proofs of its premises, and for the quantifier rules the variable or term involved. The hypotheses are not stored in the tree: check receives them, and passes the extended set to the premises of the rules that add one.

        case "or_e":  # from A | B, and C both from A and from B, conclude C
            need(isinstance(above[0], Or), "the first premise is not a disjunction")
            need(above[1] == goal == above[2], "the cases do not both give the goal")
            return 1 + sub(0) + sub(1, above[0].left) + sub(2, above[0].right)
        case "imp_i":  # from B under the hypothesis A, conclude A -> B
            need(isinstance(goal, Imp) and above[0] == goal.right, "not A -> B from B")
            return 1 + sub(0, goal.left)
        case "imp_e":  # modus ponens
            need(above[0] == Imp(above[1], goal), "the premises are not A -> B and A")
            return 1 + sub(0) + sub(1)
        case "not_i":  # from false under the hypothesis A, conclude ~A
            need(isinstance(goal, Not) and above[0] == Bot(), "not ~A from false")
            return 1 + sub(0, goal.body)
        case "not_e":
            need(goal == Bot() and above[1] == Not(above[0]), "premises not A, ~A")
            return 1 + sub(0) + sub(1)
        case "bot_e":
            need(above[0] == Bot(), "the premise is not false")
            return 1 + sub(0)
        case "raa":  # reductio: from false under ~A, conclude A
            need(above[0] == Bot(), "the premise is not false")
            return 1 + sub(0, Not(goal))
        case "forall_i":  # from A[y/x], y free in no hypothesis, conclude forall x. A
            need(isinstance(goal, Forall) and isinstance(p.term, Var), "no variable")
            y = p.term.name
            need(above[0] == subst(goal.body, goal.var, p.term), f"not A[{y}/x]")
            need(y not in free(goal), f"{y} is free in the conclusion")
            need(all(y not in free(h) for h in gamma), f"{y} is free in a hypothesis")
            return 1 + sub(0)
        case "forall_e":  # from forall x. A, conclude A[t/x]
            need(isinstance(above[0], Forall), "the premise is not universal")
            need(goal == subst(above[0].body, above[0].var, p.term), "not A[t/x]")
            return 1 + sub(0)
Listing 24.6. The checker’s rules for ∨\vee, →\to, ¬\neg, ⊥\bot and ∀\forall; sub(i, A) checks premise ii with the extra hypothesis AA code/bachelor-2/24-predicate-logic/listings/checker.py
ALL = (["forall x. P(x) -> Q(x)", "forall x. P(x)"],
       s("forall_i", "forall x. Q(x)",
         s("imp_e", "Q(y)",
           s("forall_e", "P(y) -> Q(y)", s("hyp", "forall x. P(x) -> Q(x)"), term="y"),
           s("forall_e", "P(y)", s("hyp", "forall x. P(x)"), term="y")),
         term="y"))

WRONG_ALL = (["P(y)"],  # one element has the property, so all do?
             s("forall_i", "forall x. P(x)", s("hyp", "P(y)"), term="y"))
Listing 24.7. Two proofs as data: the proof of Example 24.12, and a ∀\forall-introduction on a variable free in the hypothesis code/bachelor-2/24-predicate-logic/listings/proofs.py
$ python check_demo.py
P -> Q, P |- Q
   accepted: 3 steps checked
P -> Q, Q -> R |- P -> R
   accepted: 6 steps checked
 |- (P -> Q) -> ~(P & ~Q)
   accepted: 9 steps checked
forall x. P(x) -> Q(x), forall x. P(x) |- forall x. Q(x)
   accepted: 6 steps checked
P(y) |- forall x. P(x)
   rejected: forall_i giving forall x. P(x): y is free in a hypothesis
Output 24.4. The four proofs of this chapter are accepted. The last one is rejected, and the checker names the side condition it breaks.

Each step is checked once, and its checks are comparisons of formulas and substitutions, so a checker runs in time polynomial in the size of the proof. A proof can be enormous and found by any means, by a person, by a search program or by guessing; it is trusted because a small program, which can itself be read and tested, accepts it.

Facts as of 2026

A proof assistant is a proof checker with a language for writing proofs and tools that fill in their routine steps. Lean is an open-source programming language and proof assistant, with Mathlib, a large library of formalised mathematics built by its community. The Rocq Prover, formerly the Coq Proof Assistant, is another. Both check proofs in type theories richer than the logic of this chapter, in which a proof is a program and the formula it proves is its type.

24.7 Unification and resolution

A program that searches for proofs needs a rule that applies blindly. Propositional resolution, from C∨LC \vee L and C′∨¬LC' \vee \neg L conclude C∨C′C \vee C', is such a rule, and a set of clauses is unsatisfiable exactly when it derives the empty clause. In predicate logic a clause ¬Out(x,y)∨Member(x)\neg \mathit{Out}(x, y) \vee \mathit{Member}(x) stands for its universal closure, and the literal Member(x)\mathit{Member}(x) should cancel ¬Member(p5)\neg\mathit{Member}(p5) after replacing xx by p5p5. The replacement is found by unification.

Definition 24.18 (Unifier, most general unifier, occurs check)

A substitution σ\sigma, replacing finitely many variables by terms at the same time, is a unifier of ss and tt when sσ=tσs\sigma = t\sigma. It is a most general unifier when every unifier τ\tau is σ\sigma followed by another substitution: τ=σθ\tau = \sigma\theta for some θ\theta. The occurs check refuses to bind a variable xx to a term other than xx that contains xx.

Method 24.19 (Robinson’s unification)

Keep a list of equations to solve, initially s=ts = t, and a substitution σ\sigma, initially empty. Repeatedly take an equation and apply σ\sigma to both sides. If they are equal, drop it. If one side is a variable xx: fail if xx occurs in the other side uu, otherwise add x↦ux \mapsto u to σ\sigma. If both are f(s1,…,sn)f(s_1, \dots, s_n) and f(t1,…,tn)f(t_1, \dots, t_n) with the same symbol, replace the equation by si=tis_i = t_i for each ii. Otherwise, with two different symbols, fail. When the list is empty, return σ\sigma.

def walk(t, sigma):
    """t with the bindings of sigma applied, all the way down."""
    match t:
        case Var(x) if x in sigma:
            return walk(sigma[x], sigma)
        case Fun(f, args):
            return Fun(f, tuple(walk(a, sigma) for a in args))
    return t


def unify(s, t, sigma=None):
    """A most general unifier of s and t extending sigma, as a dict, or None."""
    sigma = dict(sigma or {})
    todo = [(s, t)]
    while todo:
        a, b = (walk(u, sigma) for u in todo.pop())
        match a, b:
            case _ if a == b:
                continue
            case Var(x), _:
                if x in free(b):
                    return None  # the occurs check: x = f(x) has no finite solution
                sigma[x] = b
            case _, Var(_):
                todo.append((b, a))
            case Fun(f, xs), Fun(g, ys) if f == g and len(xs) == len(ys):
                todo.extend(zip(xs, ys))
            case _:
                return None  # two different function symbols: a clash
    return sigma
Listing 24.8. Unification: walk applies the bindings found so far; the occurs check stops x=f(x)x = f(x) code/bachelor-2/24-predicate-logic/listings/unify.py
$ python unify_demo.py
P(x, f(y)) and P(g(z), f(x)): {x := g(z), y := g(z)}; both become P(g(z), f(g(z)))
Q(x, x) and Q(a, b): no unifier
R(x) and R(f(x)): no unifier
S(x, h(y)) and S(h(z), x): {x := h(z), y := z}; both become S(h(z), h(z))
Output 24.5. Four pairs: a unifier found through a chain of bindings, a clash of constants, a failed occurs check, and a second success.

Theorem 24.20 (Robinson)

Method 24.19 terminates. If ss and tt have a unifier, it returns a most general unifier; otherwise it fails.

Proof. Write στ\sigma\tau for σ\sigma followed by τ\tau, with σ\sigma applied until no variable of σ\sigma’s domain is left. Invariant: a substitution τ\tau unifies ss and tt if and only if στ=τ\sigma\tau = \tau and τ\tau solves every equation of the list. It holds at the start, with σ\sigma empty. Dropping an equation with equal sides, or replacing f(s⃗)=f(t⃗)f(\vec s) = f(\vec t) by its arguments, does not change the solutions. Adding x↦ux \mapsto u, when xx does not occur in uu, does not either: τ\tau solves x=ux = u exactly when τ(x)=uτ\tau(x) = u\tau, that is when x↦ux \mapsto u followed by τ\tau is τ\tau.

Failures: two different symbols at the roots never become equal under a substitution; and if xx occurs in u≠xu \neq x, then uτu\tau is strictly larger than τ(x)\tau(x) for every τ\tau, so x=ux = u has no solution. By the invariant, ss and tt then have no unifier.

Termination: a binding removes the variable xx from all later equations, since they are walked through σ\sigma, and the occurs check ensures it never comes back, so at most as many bindings as variables happen; between two bindings, each decomposition removes a function symbol from the list, dropping an equation with equal sides removes that equation, and turning u=xu = x round only changes its order. The triple (number of unbound variables, number of symbols in the list, variables included, number of equations of the form u=xu = x with uu not a variable) decreases at each step in lexicographic order.

Result: when the list is empty, σ\sigma itself satisfies σσ=σ\sigma\sigma = \sigma, since no variable of σ\sigma’s domain occurs in what σ\sigma gives, and so by the invariant σ\sigma unifies ss and tt; every unifier τ\tau satisfies στ=τ\sigma\tau = \tau, so σ\sigma is most general. ∎

Definition 24.21 (Resolvent, resolution)

Let C1∨L1C_1 \vee L_1 and C2∨¬L2C_2 \vee \neg L_2 be two clauses, their variables renamed so that they share none, with L1L_1 and L2L_2 atomic formulas on the same predicate and σ\sigma a most general unifier of L1L_1 and L2L_2. Their resolvent is (C1∨C2)σ(C_1 \vee C_2)\sigma. When two literals LL and L′L' of the same sign in a clause C∨L∨L′C \vee L \vee L' have a most general unifier σ\sigma, the clause (C∨L)σ(C \vee L)\sigma is a factor of it. Resolution is the proof system with these two rules, resolvents and factors; a refutation of a set of clauses derives the empty clause from it.

def factors(c):
    """Every factor of a clause: two of its literals of the same sign made equal."""
    for (sign, p, args), (sign2, p2, args2) in combinations(sorted(c, key=repr), 2):
        if p != p2 or sign != sign2:
            continue
        sigma = unify(Fun("", args), Fun("", args2))
        if sigma is not None:  # the two literals become one
            yield frozenset((sg, q, tuple(walk(a, sigma) for a in xs))
                            for sg, q, xs in c), sigma
Listing 24.9. Factors: two literals of the same sign made one code/bachelor-2/24-predicate-logic/listings/unify.py

A resolvent is a consequence of its two clauses, and a factor of its clause, so a refutation proves that the set has no model. To prove a goal from some rules, one refutes the rules together with the negation of the goal. Robinson proved the converse in 1965: a set of clauses with no model has a refutation. His rule resolves several literals at once, which builds factoring in; binary resolvents alone are not enough, and Exercise 24.3 gives two clauses with no model from which they never reach the empty clause. A whole proof is found by trying all pairs, as refute.py does for “p5 may borrow”:

$ python refute.py
(1) ~Out(x, y) | Member(x)
(2) ~Member(x) | MayBorrow(x)
(3) Out(p5, b3)
(4) ~MayBorrow(p5)
(5) ~Out(x', y') | MayBorrow(x')   from (1) and (2) with x := x'
(6) Member(p5)   from (1) and (3) with x' := p5, y' := b3
(7) ~Member(p5)   from (2) and (4) with x' := p5
(8) MayBorrow(p5)   from (3) and (5) with x' := p5, y' := b3
(9) ~Out(p5, y')   from (4) and (5) with x' := p5
(10) the empty clause   from (6) and (7)
Output 24.6. Resolution proves that p5 may borrow. Each new clause names its two parents and the unifier; clause (5) chains the two rules into one before any fact is used.

Robinson published unification and resolution together in 1965, for a logic oriented towards machines rather than towards people. Resolution on clauses with at most one positive literal, Horn clauses, is the engine of logic programming, and unification reappears in Book 5, where the types of a program are inferred by solving equations between type terms.

24.8 2-SAT and the implication graph

Satisfiability has a case solved in linear time. For three literals per clause no algorithm much faster than the search of the Year 1 volume is known; with two, each clause is a pair of implications.

Definition 24.22 (Implication graph)

The implication graph of a 2-CNF formula over x1,…,xnx_1, \dots, x_n is the directed graph whose 2n2n vertices are the literals xkx_k and ¬xk\neg x_k, with two edges ¬a→b\neg a \to b and ¬b→a\neg b \to a for each clause a∨ba \vee b (where ¬¬x\neg\neg x is xx).

An edge ℓ→m\ell \to m says that every model making ℓ\ell true makes mm true, so a path does too. The formula (x1∨x2)∧(¬x1∨x2)∧(x1∨¬x2)∧(¬x1∨¬x2)(x_1 \vee x_2) \wedge (\neg x_1 \vee x_2) \wedge (x_1 \vee \neg x_2) \wedge (\neg x_1 \vee \neg x_2) forbids each of the four assignments, and its graph has a single strongly connected component:

The implication graph of the four clauses on x_1, x_2: each clause a b gives the edges a b and b a. All four literals are in one strongly connected component, so x_1 implies x_1 and x_1 implies x_1.
The implication graph of the four clauses on x1,x2x_1, x_2: each clause a∨ba \vee b gives the edges ¬a→b\neg a \to b and ¬b→a\neg b \to a. All four literals are in one strongly connected component, so x1x_1 implies ¬x1\neg x_1 and ¬x1\neg x_1 implies x1x_1.

Theorem 24.23 (2-SAT in linear time)

A 2-CNF formula is unsatisfiable if and only if, for some variable xx, the literals xx and ¬x\neg x lie in the same strongly connected component of its implication graph. Satisfiability, and a model when there is one, are found in time linear in the number of variables and clauses.

Proof. If xx and ¬x\neg x share a component, there are paths x⇝¬xx \leadsto \neg x and ¬x⇝x\neg x \leadsto x. A model making xx true makes ¬x\neg x true along the first, and one making xx false makes xx true along the second: there is no model.

Conversely, suppose no variable shares a component with its negation. Number the components in a topological order of the graph of components, so that every edge goes from a component to the same or a later one, and write c(ℓ)c(\ell) for the number of the component of ℓ\ell. Make ℓ\ell true when c(ℓ)>c(¬ℓ)c(\ell) > c(\neg \ell); exactly one of xx, ¬x\neg x is true since their numbers differ. Suppose a clause a∨ba \vee b had both literals false: c(a)<c(¬a)c(a) < c(\neg a) and c(b)<c(¬b)c(b) < c(\neg b). The edges ¬a→b\neg a \to b and ¬b→a\neg b \to a give c(¬a)≤c(b)c(\neg a) \leq c(b) and c(¬b)≤c(a)c(\neg b) \leq c(a), so c(a)<c(¬a)≤c(b)<c(¬b)≤c(a)c(a) < c(\neg a) \leq c(b) < c(\neg b) \leq c(a), a contradiction. The assignment is a model.

The graph has 2n2n vertices and twice as many edges as clauses; Kosaraju’s algorithm finds its components in linear time, and numbers them in a topological order as it goes. ∎

def solve(n, clauses):
    """Variables 1..n; a literal is k or -k; a clause (a, b) means a | b.
    Returns a satisfying assignment {k: bool}, or the variable and its component."""
    def node(lit):  # the vertex of x_k is 2k - 2, that of ~x_k is 2k - 1
        return 2 * (abs(lit) - 1) + (lit < 0)

    succ = [[] for _ in range(2 * n)]
    pred = [[] for _ in range(2 * n)]
    for a, b in clauses:  # a | b gives ~a -> b and ~b -> a
        for u, v in [(node(-a), node(b)), (node(-b), node(a))]:
            succ[u].append(v)
            pred[v].append(u)
Listing 24.10. The implication graph: two edges per clause, and the reversed edges for the second search of Kosaraju’s algorithm code/bachelor-2/24-predicate-logic/listings/twosat.py
        count += 1  # components numbered in a topological order of the graph
    for k in range(1, n + 1):
        if comp[node(k)] == comp[node(-k)]:
            return None, k
    # x_k is true when its component comes after that of ~x_k in topological order
    return {k: comp[node(k)] > comp[node(-k)] for k in range(1, n + 1)}, None
Listing 24.11. The test of Theorem 24.23, and the model read from the order of the components code/bachelor-2/24-predicate-logic/listings/twosat.py

The talks of a two-room meeting are a 2-SAT instance: xkx_k says that talk kk is in the big room, two talks with a speaker in common must be in different rooms (xj∨xkx_j \vee x_k and ¬xj∨¬xk\neg x_j \vee \neg x_k), and a talk that needs the big room’s screen gives the clause xk∨xkx_k \vee x_k.

$ python twosat_demo.py
as planned: 1:big 2:small 3:big 4:small 5:big 6:big
   by trying all 64 assignments: 2 satisfy it
with talk 6: no plan: x1, ~x1 in one strongly connected component
   by trying all 64 assignments: 0 satisfy it
Output 24.7. A plan for the five talks, then none once a sixth talk shares speakers with talk 4 and cannot be in the big room with talk 1; all 64 assignments confirm both. Talk 6 is in no clause of the first formula, so its one plan counts twice: 2=1×22 = 1 \times 2.

The algorithm is due to Bengt Aspvall, Michael Plass and Robert Tarjan, in 1979. It is the reason why 2-SAT, unlike 3-SAT, appears inside other algorithms as a routine step.

24.9 Exercises

Exercise 24.1 ★

Give the free variables of ∀x R(x,y)\forall x\, R(x, y); (∀x P(x))→P(x)(\forall x\, P(x)) \to P(x); ∃x ∀y R(x,y)∧R(y,z)\exists x\, \forall y\, R(x, y) \wedge R(y, z); ∀x ((∃x P(x))→Q(x,f(y)))\forall x\, ((\exists x\, P(x)) \to Q(x, f(y))); ∃y (y=f(x)∧∀x ¬R(x,y))\exists y\, (y = f(x) \wedge \forall x\, \neg R(x, y)). Then run exo_free.py and compare.

Solution

Solution of Exercise 24.1.

In order: {y}\{y\}; {x}\{x\}, from the xx of P(x)P(x) outside the brackets; {z}\{z\}, since the scope of ∀y\forall y runs to the end and binds the yy of R(y,z)R(y, z); {y}\{y\}, the xx of Q(x,f(y))Q(x, f(y)) being bound by the outer ∀x\forall x; {x}\{x\}, from f(x)f(x), the later xx being bound by ∀x\forall x.

$ python exo_free.py
forall x. R(x, y)                             free: ['y']
(forall x. P(x)) -> P(x)                      free: ['x']
exists x. forall y. R(x, y) & R(y, z)         free: ['z']
forall x. (exists x. P(x)) -> Q(x, f(y))      free: ['y']
exists y. y = f(x) & forall x. ~R(x, y)       free: ['x']
Output 24.9. The free variables of the five formulas.

Exercise 24.2 ★

The function replace of exo_capture.py is meant to compute A[t/x]A[t/x]. Which of its three results is wrong, and why? Correct the function.

Solution

Solution of Exercise 24.2.

$ python exo_capture.py
(Friend(x, z) & exists y. Friend(x, y))[y/z] = Friend(x, y) & (exists y. Friend(x, y))
(forall x. Friend(x, z))[y/x] = forall x. Friend(x, z)
(exists y. Friend(x, y))[y/x] = exists y. Friend(y, y)
Output 24.10. The three substitutions made by replace.

The first two are right: the bound yy of the first formula is not touched because zz does not occur under it, and in the second xx is bound, so nothing is replaced. The third is wrong. “xx has a friend” with yy for xx should say “yy has a friend”, ∃y1 Friend(y,y1)\exists y_1\, \mathit{Friend}(y, y_1); replace enters the scope of ∃y\exists y with the term yy and the yy is captured, giving “someone is their own friend”. The correction is the quantifier case of Listing 24.3: return ee when xx is not free below, and rename the bound variable first when it occurs in tt. The function has a second defect: ⊥\bot has no left field, so replace fails on it.

Exercise 24.3 ★

Predict the result of unifying P(f(x),y)P(f(x), y) with P(y,f(a))P(y, f(a)); P(x,f(x))P(x, f(x)) with P(f(y),y)P(f(y), y); P(x,y,z)P(x, y, z) with P(y,z,a)P(y, z, a); P(g(x),x)P(g(x), x) with P(f(y),a)P(f(y), a). Check with exo_unify.py. Then show that the two clauses P(x)∨P(y)P(x) \vee P(y) and ¬P(x)∨¬P(y)\neg P(x) \vee \neg P(y) have no model, that binary resolvents alone, however often repeated, only ever give clauses of two literals, and find a refutation that uses factors. Check with factor_demo.py.

Solution

Solution of Exercise 24.3.

First pair: y=f(x)y = f(x) from the first arguments, then f(x)=f(a)f(x) = f(a), so x=ax = a: both become P(f(a),f(a))P(f(a), f(a)). Second: x=f(y)x = f(y), then f(f(y))=yf(f(y)) = y, which the occurs check refuses: no unifier. Third: x=yx = y, y=zy = z, z=az = a, all three become aa: P(a,a,a)P(a, a, a). Fourth: g(x)=f(y)g(x) = f(y) is a clash of symbols: no unifier.

$ python exo_unify.py
P(f(x), y) and P(y, f(a)): both become P(f(a), f(a))
P(x, f(x)) and P(f(y), y): no unifier
P(x, y, z) and P(y, z, a): both become P(a, a, a)
P(g(x), x) and P(f(y), a): no unifier
Output 24.11. The four pairs of the exercise.

The two clauses: in a structure, the first says that every element is in PP (take x=yx = y), the second that none is, and the domain is not empty, so there is no model. Every clause derived by binary resolvents has two literals on PP, with two different variables: true of both clauses at the start, and a resolvent of two such clauses unifies one literal of each, which binds one variable to another of the other clause, and keeps the two remaining literals, whose variables are still different (they come from clauses renamed apart). So n+m−2=2n + m - 2 = 2 literals, never 0, and up to renaming only the three clauses of the output appear. With factors, P(x)∨P(y)P(x) \vee P(y) gives P(x)P(x) (unify the two literals), ¬P(x)∨¬P(y)\neg P(x) \vee \neg P(y) gives ¬P(x)\neg P(x), and these two resolve to the empty clause.

$ python factor_demo.py
binary resolution alone:
  (1) P(x1) | P(x2)
  (2) ~P(x1) | ~P(x2)
  (3) P(x1) | ~P(x2)   from (1) and (2)
  3 clauses: nothing new, no refutation
with factoring:
  (1) P(x1) | P(x2)
  (2) ~P(x1) | ~P(x2)
  (3) P(x1)   factor of (1)
  (4) ~P(x1)   factor of (2)
  (5) P(x1) | ~P(x2)   from (1) and (2)
  (6) the empty clause   from (3) and (4)
  6 clauses: refuted
Output 24.12. Binary resolution saturates without a refutation; factors refute at once.

Exercise 24.4 ★

Draw the implication graph of (x1∨x2)∧(¬x1∨x3)∧(¬x2∨¬x3)∧(¬x3∨x1)(x_1 \vee x_2) \wedge (\neg x_1 \vee x_3) \wedge (\neg x_2 \vee \neg x_3) \wedge (\neg x_3 \vee x_1) and find its strongly connected components. Is the formula satisfiable? What changes when the clause ¬x1∨¬x3\neg x_1 \vee \neg x_3 is added, and then also x1∨x3x_1 \vee x_3? Check with exo_twosat.py.

Solution

Solution of Exercise 24.4.

The clauses give the edges ¬x1→x2\neg x_1 \to x_2, ¬x2→x1\neg x_2 \to x_1; x1→x3x_1 \to x_3, ¬x3→¬x1\neg x_3 \to \neg x_1; x2→¬x3x_2 \to \neg x_3, x3→¬x2x_3 \to \neg x_2; x3→x1x_3 \to x_1, ¬x1→¬x3\neg x_1 \to \neg x_3. There are two components: A={x1,x3,¬x2}A = \{x_1, x_3, \neg x_2\} (the cycle x1→x3→¬x2→x1x_1 \to x_3 \to \neg x_2 \to x_1) and its mirror B={¬x1,¬x3,x2}B = \{\neg x_1, \neg x_3, x_2\}, with no edge between them. No variable shares a component with its negation, so the formula is satisfiable, and either component may come last: making AA true gives x1=x3=1x_1 = x_3 = 1, x2=0x_2 = 0, and making BB true gives the other model.

The clause ¬x1∨¬x3\neg x_1 \vee \neg x_3 adds x1→¬x3x_1 \to \neg x_3 and x3→¬x1x_3 \to \neg x_1, edges from AA to BB. Now BB comes after AA and is made true: x1=x3=0x_1 = x_3 = 0, x2=1x_2 = 1. The clause x1∨x3x_1 \vee x_3 adds ¬x1→x3\neg x_1 \to x_3 and ¬x3→x1\neg x_3 \to x_1, from BB to AA; the two components merge, x1x_1 and ¬x1\neg x_1 are in one, and the formula is unsatisfiable: its clauses say x1↔x3x_1 \leftrightarrow x_3 and x1≠x3x_1 \neq x_3.

$ python exo_twosat.py
[(1, 2), (-1, 3), (-2, -3), (-3, 1)] -> {1: True, 2: False, 3: True}
[(1, 2), (-1, 3), (-2, -3), (-3, 1), (-1, -3)] -> {1: False, 2: True, 3: False}
[(1, 2), (-1, 3), (-2, -3), (-3, 1), (-1, -3), (1, 3)] -> unsatisfiable, x1 with ~x1
Output 24.13. The three formulas of the exercise.

Exercise 24.5 ★★

For the three sentences ∀x ∃y R(x,y)\forall x\, \exists y\, R(x, y), ¬∃x R(x,x)\neg \exists x\, R(x, x) and ∃y ∀x ¬R(x,y)\exists y\, \forall x\, \neg R(x, y), say which hold in: Z/3\mathbb{Z}/3 with R(x,y)R(x, y) when y=x+1y = x + 1; {0,1,2}\{0, 1, 2\} with RR the order <<; {0,1}\{0, 1\} with RR the relation ≠\neq. Check with exo_three.py.

Solution

Solution of Exercise 24.5.

In Z/3\mathbb{Z}/3 with the successor: every xx has a successor, true; no xx is its own successor, true; every yy is the successor of something, so the third is false. In {0,1,2}\{0, 1, 2\} with <<: 22 has nothing above it, so the first is false; << is irreflexive, true; 00 has nothing below it, true. In {0,1}\{0, 1\} with ≠\neq: each element has the other, true; irreflexive, true; each yy differs from the other element, so the third is false.

$ python exo_three.py
Z/3, R(x, y) when y = x + 1     True  True  False
{0, 1, 2}, R(x, y) when x < y   False  True  True
{0, 1}, R(x, y) when x != y     True  True  False
Output 24.14. Each structure, then the truth of the three sentences in it.

Exercise 24.6 ★★

The checker rejects the proof of exo_forall_bug.py. Is its conclusion a consequence of its hypotheses? Give a structure that answers, then the strongest correct conclusion its steps support.

Solution

Solution of Exercise 24.6.

$ python exo_forall_bug.py
rejected: forall_i giving forall x. MayBorrow(x): y is free in a hypothesis
Output 24.15. The checker names the broken side condition.

The conclusion is not a consequence. Take D={0,1}D = \{0, 1\}, Member=MayBorrow={0}\mathit{Member} = \mathit{MayBorrow} = \{0\} and ρ(y)=0\rho(y) = 0: the hypotheses ∀x (Member(x)→MayBorrow(x))\forall x\, (\mathit{Member}(x) \to \mathit{MayBorrow}(x)) and Member(y)\mathit{Member}(y) are true, and ∀x MayBorrow(x)\forall x\, \mathit{MayBorrow}(x) is false because of 11. The steps above the last one are correct and prove MayBorrow(y)\mathit{MayBorrow}(y): what is known of one member is that this member may borrow. The yy of the hypothesis is not arbitrary, which is what the side condition checks.

Exercise 24.7 ★★

Write a proof tree of ¬(P∨Q)⊢¬P∧¬Q\neg(P \vee Q) \vdash \neg P \wedge \neg Q, then write it as data for the checker.

Solution

Solution of Exercise 24.7.

Write Γ={¬(P∨Q)}\Gamma = \{\neg(P \vee Q)\}. Under the extra hypothesis PP, ∨\veei1_1 gives P∨QP \vee Q, and ¬\nege with the hypothesis ¬(P∨Q)\neg(P \vee Q) gives ⊥\bot; ¬\negi discharges PP and gives Γ⊢¬P\Gamma \vdash \neg P. The same with QQ and ∨\veei2_2 gives Γ⊢¬Q\Gamma \vdash \neg Q, and ∧\wedgei ends:

 Γ,P⊢P hypΓ,P⊢P∨Q ∨i1 Γ,P⊢¬(P∨Q) hypΓ,P⊢⊥ ¬eΓ⊢¬P ¬i⋯Γ⊢¬Q ¬iΓ⊢¬P∧¬Q ∧i{\dfrac{{\dfrac{{\dfrac{{\dfrac{{\dfrac{\ }{\Gamma, P \vdash P}\,\scriptstyle\text{hyp}}}{\Gamma, P \vdash P \vee Q}\,\scriptstyle\text{$\vee$i$_1$}} \qquad {\dfrac{\ }{\Gamma, P \vdash \neg(P \vee Q)}\,\scriptstyle\text{hyp}}}{\Gamma, P \vdash \bot}\,\scriptstyle\text{$\neg$e}}}{\Gamma \vdash \neg P}\,\scriptstyle\text{$\neg$i}} \qquad {\dfrac{\cdots}{\Gamma \vdash \neg Q}\,\scriptstyle\text{$\neg$i}}}{\Gamma \vdash \neg P \wedge \neg Q}\,\scriptstyle\text{$\wedge$i}}

DE_MORGAN = (["~(P | Q)"],
             s("and_i", "~P & ~Q",
               s("not_i", "~P",
                 s("not_e", "false", s("or_i1", "P | Q", s("hyp", "P")),
                   s("hyp", "~(P | Q)"))),
               s("not_i", "~Q",
                 s("not_e", "false", s("or_i2", "P | Q", s("hyp", "Q")),
                   s("hyp", "~(P | Q)")))))
The proof as data; the checker accepts it in 11 steps (first lines of Output 24.16) code/bachelor-2/24-predicate-logic/listings/proofs_more.py

Exercise 24.8 ★★

Complete the proof of Theorem 24.15 with the cases of →\toi and ∨\veee.

Solution

Solution of Exercise 24.8.

Fix a structure and an assignment ρ\rho that satisfies Γ\Gamma.

→\toi: by induction Γ,A⊨B\Gamma, A \models B. If ρ\rho satisfies AA, it satisfies all of Γ∪{A}\Gamma \cup \{A\}, so it satisfies BB; if it does not satisfy AA, it satisfies A→BA \to B anyway. In both cases ρ⊨A→B\rho \models A \to B.

∨\veee: by induction Γ⊨A∨B\Gamma \models A \vee B, Γ,A⊨C\Gamma, A \models C and Γ,B⊨C\Gamma, B \models C. So ρ\rho satisfies AA or BB. In the first case it satisfies Γ∪{A}\Gamma \cup \{A\}, hence CC; in the second it satisfies Γ∪{B}\Gamma \cup \{B\}, hence CC.

In both rules the hypothesis added in a premise is exactly what the case analysis on ρ\rho provides; this is the meaning of discharging it.

Exercise 24.9 ★★

Extend the checker with the rules ∃\existsi and ∃\existse, through its argument extra, which maps a rule’s name to a function receiving the step, the hypotheses, sub and need.

Solution

Solution of Exercise 24.9.

def exists_i(p, gamma, sub, need):  # from A[t/x], conclude exists x. A
    need(isinstance(p.goal, Exists), "not an existential")
    need(len(p.premises) == 1 and p.term is not None, "needs one premise, a term")
    need(p.premises[0].goal == subst(p.goal.body, p.goal.var, p.term), "not A[t/x]")
    return 1 + sub(0)


def exists_e(p, gamma, sub, need):
    """From exists x. A, and C under the hypothesis A[y/x], conclude C, when y is free
    neither in exists x. A, nor in C, nor in another hypothesis."""
    need(len(p.premises) == 2 and isinstance(p.term, Var), "2 premises, a variable")
    some, y = p.premises[0].goal, p.term.name
    need(isinstance(some, Exists), "the first premise is not an existential")
    need(p.premises[1].goal == p.goal, "the second premise does not give the goal")
    need(y not in free(some) | free(p.goal), f"{y} is free in the conclusion")
    need(all(y not in free(h) for h in gamma), f"{y} is free in a hypothesis")
    return 1 + sub(0) + sub(1, subst(some.body, some.var, Var(y)))


EXISTS = {"exists_i": exists_i, "exists_e": exists_e}
The two rules of ∃\exists; ∃\existse checks its second premise with the hypothesis on the witness added code/bachelor-2/24-predicate-logic/listings/exists_rules.py

The side condition of ∃\existse has three parts. If yy were free in CC, the conclusion would say something about the witness that leaves the scope of the reasoning; if it were free in a hypothesis, the witness would not be arbitrary; if it were free in ∃x A\exists x\, A, then A[y/x]A[y/x] would confuse it with another variable of AA. Each of them, removed, lets the checker accept a false conclusion: for the second, P(y),∃x ¬P(x)⊢⊥P(y), \exists x\, \neg P(x) \vdash \bot.

Exercise 24.10 ★★★

Prove ∃x ∀y R(x,y)⊢∀y ∃x R(x,y)\exists x\, \forall y\, R(x, y) \vdash \forall y\, \exists x\, R(x, y) and check the proof with Exercise 24.9. Try the same plan for the converse: which side condition stops it, and why must something stop it?

Solution

Solution of Exercise 24.10.

Let vv be arbitrary; from ∃x ∀y R(x,y)\exists x\, \forall y\, R(x, y), take a witness uu with ∀y R(u,y)\forall y\, R(u, y); then R(u,v)R(u, v) by ∀\foralle, so ∃x R(x,v)\exists x\, R(x, v) by ∃\existsi; ∃\existse concludes it from the hypothesis (uu is free neither in the conclusion nor in the hypothesis), and ∀\foralli on vv gives ∀y ∃x R(x,y)\forall y\, \exists x\, R(x, y).

SWAP = (["exists x. forall y. R(x, y)"],
        s("forall_i", "forall y. exists x. R(x, y)",
          s("exists_e", "exists x. R(x, v)",
            s("hyp", "exists x. forall y. R(x, y)"),
            s("exists_i", "exists x. R(x, v)",
              s("forall_e", "R(u, v)", s("hyp", "forall y. R(u, y)"), term="v"),
              term="u"),
            term="u"),
          term="v"))

CONVERSE = (["forall y. exists x. R(x, y)"],  # an attempt; the checker refuses a step
            s("exists_e", "exists x. forall y. R(x, y)",
              s("forall_e", "exists x. R(x, v)",
                s("hyp", "forall y. exists x. R(x, y)"), term="v"),
              s("exists_i", "exists x. forall y. R(x, y)",
                s("forall_i", "forall y. R(u, y)", s("hyp", "R(u, v)"), term="v"),
                term="u"),
              term="u"))
The proof, and the same plan tried for the converse code/bachelor-2/24-predicate-logic/listings/proofs_more.py
$ python exo_proofs.py
~(P | Q) |- ~P & ~Q
   accepted: 11 steps checked
exists x. forall y. R(x, y) |- forall y. exists x. R(x, y)
   accepted: 6 steps checked
forall y. exists x. R(x, y) |- exists x. forall y. R(x, y)
   rejected: forall_i giving forall y. R(u, y): v is free in a hypothesis
 |- P | ~P
   accepted: 9 steps checked
Output 24.16. The proofs of Exercises 24.7, 24.10 and 24.11; the converse attempt is rejected.

For the converse, the plan takes a vv, gets ∃x R(x,v)\exists x\, R(x, v), and works with a witness uu under the hypothesis R(u,v)R(u, v); to conclude ∃x ∀y R(x,y)\exists x\, \forall y\, R(x, y) it needs ∀y R(u,y)\forall y\, R(u, y), and generalising R(u,v)R(u, v) on vv is refused: vv is free in the hypothesis R(u,v)R(u, v). The witness depends on vv. Something must stop every attempt: the two-element structure of Section 24.4 satisfies the hypothesis and not the conclusion, and by Theorem 24.15 no proof exists.

Exercise 24.11 ★★★

Prove ⊢P∨¬P\vdash P \vee \neg P in natural deduction, and check the proof. Explain why every proof of it uses raa: find a reading of the rules other than raa under which each rule preserves a property that P∨¬PP \vee \neg P lacks, or argue from the shape of a proof that ends with ∨\veei.

Solution

Solution of Exercise 24.11.

Assume ¬(P∨¬P)\neg(P \vee \neg P) and aim at ⊥\bot. Under the further hypothesis PP, ∨\veei1_1 gives P∨¬PP \vee \neg P, which contradicts the first hypothesis, so ¬\negi gives ¬P\neg P. Then ∨\veei2_2 gives P∨¬PP \vee \neg P again, the contradiction is ⊥\bot, and raa discharges ¬(P∨¬P)\neg(P \vee \neg P).

EXCLUDED_MIDDLE = ([],
                   s("raa", "P | ~P",
                     s("not_e", "false",
                       s("or_i2", "P | ~P",
                         s("not_i", "~P",
                           s("not_e", "false", s("or_i1", "P | ~P", s("hyp", "P")),
                             s("hyp", "~(P | ~P)")))),
                       s("hyp", "~(P | ~P)"))))
The proof as data; it is accepted in 9 steps code/bachelor-2/24-predicate-logic/listings/proofs_more.py

raa is needed. Give each formula a value in {0,12,1}\{0, \tfrac12, 1\}: ∧\wedge is the minimum, ∨\vee the maximum, ⊥\bot is 00, a→ba \to b is 11 if a≤ba \leq b and bb otherwise, and ¬a\neg a is a→0a \to 0, so 11 if a=0a = 0 and 00 otherwise. Call Γ⊢A\Gamma \vdash A valid when, for every choice of values of the variables, the minimum of the values of Γ\Gamma (1 if Γ\Gamma is empty) is at most the value of AA. Every rule except raa turns valid premises into a valid conclusion; for instance for →\toi, if min⁡(γ,a)≤b\min(\gamma, a) \leq b and a>ba > b, then γ≤b\gamma \leq b, which is the value of a→ba \to b, and for ∨\veee, γ=max⁡(min⁡(γ,a),min⁡(γ,b))≤c\gamma = \max(\min(\gamma, a), \min(\gamma, b)) \leq c when γ≤max⁡(a,b)\gamma \leq \max(a, b). With P=12P = \tfrac12, P∨¬PP \vee \neg P has the value max⁡(12,0)=12<1\max(\tfrac12, 0) = \tfrac12 < 1, so ⊢P∨¬P\vdash P \vee \neg P is not valid, and no proof without raa reaches it. raa itself fails the test: ¬¬P\neg\neg P has the value 11 when P=12P = \tfrac12. The logic without raa is called intuitionistic.

Exercise 24.12 ★★★

Prove the formula part of Lemma 24.14 by induction on AA, with the substitution of Listing 24.3. Where is the renaming used?

Solution

Solution of Exercise 24.12.

By induction on the number of connectives and quantifiers of AA, which renaming a variable does not change; write d=⟦t⟧ρd = \llbracket t \rrbracket_\rho. Atomic formulas: by the part on terms, the arguments of PP have the same values on both sides. Connectives: (A∧B)[t/x]=A[t/x]∧B[t/x](A \wedge B)[t/x] = A[t/x] \wedge B[t/x], and the induction hypothesis applies to each side; the other connectives are the same.

Quantifiers, ∀y B\forall y\, B (the case of ∃\exists is identical). If y=xy = x, or if xx is not free in BB, the substitution returns the formula unchanged; xx is not free in it, so ρ\rho and ρ[x↦d]\rho[x \mapsto d] agree on its free variables and give it the same truth. Otherwise, if yy is not free in tt: ρ⊨∀y B[t/x]\rho \models \forall y\, B[t/x] iff for every ee, ρ[y↦e]⊨B[t/x]\rho[y \mapsto e] \models B[t/x]; the value of tt under ρ[y↦e]\rho[y \mapsto e] is still dd because yy is not in tt, so by induction this is ρ[y↦e][x↦d]⊨B\rho[y \mapsto e][x \mapsto d] \models B, which is ρ[x↦d][y↦e]⊨B\rho[x \mapsto d][y \mapsto e] \models B since x≠yx \neq y; that is ρ[x↦d]⊨∀y B\rho[x \mapsto d] \models \forall y\, B.

If yy is free in tt, the program first renames: ∀y B\forall y\, B becomes ∀z B[z/y]\forall z\, B[z/y] with zz free nowhere. The two have the same truth under every assignment: ρ[z↦e]⊨B[z/y]\rho[z \mapsto e] \models B[z/y] iff, by induction (BB is smaller than AA), ρ[z↦e][y↦e]⊨B\rho[z \mapsto e][y \mapsto e] \models B, iff ρ[y↦e]⊨B\rho[y \mapsto e] \models B since zz is not free in BB. The previous case applies to ∀z B[z/y]\forall z\, B[z/y], as zz is not in tt. The renaming is used here, and only here: without it, the value of tt would change under ρ[y↦e]\rho[y \mapsto e], and the step “still dd” fails, which is the capture of Output 24.2.

24.10 Problem: Checking the library’s rules

Problem 24.1

Weekend problem — Checking the library’s rules

The library keeps three rules: H1H_1, whoever has a book out is a member; H2H_2, every member may borrow; H3H_3, a book that is out has been borrowed by that person. It would like to know which other rules follow from them: C1C_1, whoever has a book out may borrow; C2C_2, whoever has a book out is a member and has borrowed it; C3C_3, whoever may not borrow is not a member; C4C_4, every member has a book out.

H1 = "forall x. forall y. Out(x, y) -> Member(x)"
H2 = "forall x. Member(x) -> MayBorrow(x)"
H3 = "forall x. forall y. Out(x, y) -> Borrowed(x, y)"
RULES = [H1, H2, H3]


def out_member():  # Out(x, y) |- Member(x), from H1
    return s("imp_e", "Member(x)",
             s("forall_e", "Out(x, y) -> Member(x)",
               s("forall_e", "forall y. Out(x, y) -> Member(x)", s("hyp", H1),
                 term="x"),
               term="y"),
             s("hyp", "Out(x, y)"))


C1 = s("forall_i", "forall x. forall y. Out(x, y) -> MayBorrow(x)",
       s("forall_i", "forall y. Out(x, y) -> MayBorrow(x)",
         s("imp_i", "Out(x, y) -> MayBorrow(x)",
           s("imp_e", "MayBorrow(x)",
             s("forall_e", "Member(x) -> MayBorrow(x)", s("hyp", H2), term="x"),
             out_member())),
         term="y"),
       term="x")
Listing 24.12. The three rules and the proof of C1C_1, as data for the checker code/bachelor-2/24-predicate-logic/listings/library.py
$ python library.py
C1 proved from the rules, 11 steps checked
C2 proved from the rules, 14 steps checked
C3 proved from the rules, 9 steps checked
in all: 3 consequences, 34 steps
C4 does not follow: structure 6 of 4096 on {0, 1} is a model
   of the rules, Member = [(0,)], MayBorrow = [(0,)],
   Out = [], Borrowed = []; C4 is false
Output 24.8. Three consequences proved and checked; the fourth refuted by a structure found among the 4096 on two elements.

Part I — The rules as sentences.

  1. Write H1H_1, H2H_2, H3H_3 and C1C_1 to C4C_4 as sentences over Out\mathit{Out}, Member\mathit{Member}, MayBorrow\mathit{MayBorrow} and Borrowed\mathit{Borrowed}.
  2. H1H_1 is written ∀x ∀y (Out(x,y)→Member(x))\forall x\, \forall y\, (\mathit{Out}(x, y) \to \mathit{Member}(x)) in the program, and ∀x ((∃y Out(x,y))→Member(x))\forall x\, ((\exists y\, \mathit{Out}(x, y)) \to \mathit{Member}(x)) in Listing 24.1. Prove that the two are equivalent.
  3. What are the free variables of Out(x,y)→Member(x)\mathit{Out}(x, y) \to \mathit{Member}(x)? Why must the rules be sentences?
  4. Write “a book is out to one person at most” as a sentence, and explain each quantifier.
  5. The sentence ∀x ∃y Out(x,y)→Member(x)\forall x\, \exists y\, \mathit{Out}(x, y) \to \mathit{Member}(x) is not H1H_1. Put its brackets and say what it means.
  6. How many nested quantifiers do C2C_2 and the rule of question 4 have, and what does Proposition 24.7 predict for their cost on the town?

Part II — The rules on the town’s data.

  1. Which of the five rules of Listing 24.1 hold in the town?
  2. The rule “out to one person at most” has 8 counterexamples. Why 8, for 4 books?
  3. What does a counterexample to that rule say about the loans table, and what should the library do about it?
  4. The rule “every member has a friend” fails 41 times. Is this an error in the data?
  5. Why does the town satisfy H1H_1 and H3H_3 although nobody proved them about the town?
  6. Rewrite the rule of question 4 as a search for its counterexamples by one pass over the loans, and give its cost.

Part III — Proofs in natural deduction.

  1. Draw the proof tree of C1C_1 from Listing 24.12.
  2. Why are the two uses of ∀\foralli in the proof of C1C_1 allowed?
  3. Write a proof of C2C_2 that uses the proof of Out(x,y)⊢Member(x)\mathit{Out}(x, y) \vdash \mathit{Member}(x) as a part.
  4. Write a proof of C3C_3. Which rule for ¬\neg does it use, and which hypothesis does it discharge?
  5. Count the steps of your proof of C1C_1 and compare with the output.
  6. The proof of C1C_1 proves the sequent for xx and yy and then generalises. Why can it not instead prove MayBorrow(p5)\mathit{MayBorrow}(p5) and generalise from p5p5?

Part IV — Checked mechanically, and a countermodel.

  1. What does the checker’s acceptance of C1C_1 to C3C_3 prove, by Theorem 24.15?
  2. Describe the structure found for C4C_4 in words: a library, a member, no loan.
  3. Why does this structure prove that no proof of C4C_4 from H1H_1 to H3H_3 exists?
  4. Is there a countermodel with a domain of one element? Why did the program search two?
  5. The program tries structures in a fixed order. How many structures on two elements are there for these four predicates, and how long would the search take on three elements?
  6. Prove C1C_1 by resolution, writing H1H_1, H2H_2 and the negation of C1C_1 as clauses, and state the result: 3 rules proved in 34 checked steps, and a two-element countermodel for the one that does not follow.
Solution

Solution of Problem 24.1.

1. In the order of the statement:

H1=∀x ∀y (Out(x,y)→Member(x)),H2=∀x (Member(x)→MayBorrow(x)),H3=∀x ∀y (Out(x,y)→Borrowed(x,y)),C1=∀x ∀y (Out(x,y)→MayBorrow(x)),C3=∀x (¬MayBorrow(x)→¬Member(x)),C4=∀x (Member(x)→∃y Out(x,y)),\begin{align*} H_1 &= \forall x\, \forall y\, (\mathit{Out}(x, y) \to \mathit{Member}(x)), & H_2 &= \forall x\, (\mathit{Member}(x) \to \mathit{MayBorrow}(x)),\\ H_3 &= \forall x\, \forall y\, (\mathit{Out}(x, y) \to \mathit{Borrowed}(x, y)), & C_1 &= \forall x\, \forall y\, (\mathit{Out}(x, y) \to \mathit{MayBorrow}(x)),\\ C_3 &= \forall x\, (\neg\mathit{MayBorrow}(x) \to \neg\mathit{Member}(x)), & C_4 &= \forall x\, (\mathit{Member}(x) \to \exists y\, \mathit{Out}(x, y)), \end{align*}
C2=∀x ∀y (Out(x,y)→Member(x)∧Borrowed(x,y)).C_2 = \forall x\, \forall y\, (\mathit{Out}(x, y) \to \mathit{Member}(x) \wedge \mathit{Borrowed}(x, y)).

2. Fix xx. If Out(x,y)→Member(x)\mathit{Out}(x, y) \to \mathit{Member}(x) holds for every yy and some yy has Out(x,y)\mathit{Out}(x, y), then Member(x)\mathit{Member}(x). Conversely, if (∃y Out(x,y))→Member(x)(\exists y\, \mathit{Out}(x, y)) \to \mathit{Member}(x) and Out(x,y)\mathit{Out}(x, y) for a given yy, then the left side holds, so Member(x)\mathit{Member}(x). The argument uses that yy is not free in Member(x)\mathit{Member}(x).

3. xx and yy. A formula with free variables is true or false only once they have values; a rule must hold of everyone, so its variables are all quantified.

4. ∀y ∀x (Out(x,y)→∀z (Out(z,y)→z=x))\forall y\, \forall x\, (\mathit{Out}(x, y) \to \forall z\, (\mathit{Out}(z, y) \to z = x)): for every book yy and every person xx who has it out, every person zz who has it out is xx.

5. It reads ∀x ∃y (Out(x,y)→Member(x))\forall x\, \exists y\, (\mathit{Out}(x, y) \to \mathit{Member}(x)), since a quantifier reaches as far right as possible: for every xx there is a yy that xx does not have out, or xx is a member. With 200 elements and at most a few books out per person, it is true of everyone and says nothing.

6. C2C_2 has 2 nested quantifiers, the rule of question 4 has 3. The bound gives 2003=8×106200^3 = 8 \times 10^6 visits for the second; the output reports 43,826 atomic formulas, because the implication stops at a false Out(x,y)\mathit{Out}(x, y): 40,000 pairs (y,x)(y, x) are visited, and the inner ∀z\forall z runs only for the 22 loans that are out, about 200 visits each.

7. H1H_1 (as “a person with a book out is a member”), H3H_3 (“what is out has been borrowed”) and “every book has been borrowed”.

8. Each of the 4 books is out to two people, and each of the two is a pair (y,x)(y, x) for which the body is false: 2×4=82 \times 4 = 8.

9. Two loans of the same copy, neither returned: one of the two return dates is missing, or two copies share a number. The library should look at the loans and correct the table, or record copies separately.

10. No. Nothing requires a member to have a friend recorded; the table holds 50 friendships, and a rule that fails on the data is either a wrong rule or a sign of bad data. Here it is the rule.

11. Because the tables were built so: every loan is by a member, and a loan that is out is in the loans table. Holding on the data says nothing of another town or of tomorrow’s tables; a proof from the rules would.

12. Go through the loans once; for each loan without a return date, add its member to a set kept per book in a dictionary; report the books whose set has two members. This is linear in the number of loans, against ∣D∣3|D|^3 for the naive evaluation.

13. With Γ={H1,H2,H3}\Gamma = \{H_1, H_2, H_3\} and Δ=Γ∪{Out(x,y)}\Delta = \Gamma \cup \{\mathit{Out}(x, y)\}: Δ⊢Member(x)→MayBorrow(x)\Delta \vdash \mathit{Member}(x) \to \mathit{MayBorrow}(x) by hyp and ∀\foralle; Δ⊢Out(x,y)→Member(x)\Delta \vdash \mathit{Out}(x, y) \to \mathit{Member}(x) by hyp and two ∀\foralle; Δ⊢Out(x,y)\Delta \vdash \mathit{Out}(x, y) by hyp; →\toe twice gives Δ⊢Member(x)\Delta \vdash \mathit{Member}(x), then Δ⊢MayBorrow(x)\Delta \vdash \mathit{MayBorrow}(x); →\toi gives Γ⊢Out(x,y)→MayBorrow(x)\Gamma \vdash \mathit{Out}(x, y) \to \mathit{MayBorrow}(x), and ∀\foralli on yy, then on xx, gives C1C_1.

14. Both are applied after →\toi has discharged Out(x,y)\mathit{Out}(x, y), so the hypotheses are H1H_1, H2H_2, H3H_3, sentences in which no variable is free; and the conclusions ∀y (… )\forall y\, (\dots) and C1C_1 have neither yy nor xx free.

15. Under Δ\Delta, the proof of question 13 gives Member(x)\mathit{Member}(x); hyp, two ∀\foralle on H3H_3 and →\toe give Borrowed(x,y)\mathit{Borrowed}(x, y); ∧\wedgei joins them; then →\toi and two ∀\foralli. This is C2 in library.py, 14 steps.

16. Under ¬MayBorrow(x)\neg\mathit{MayBorrow}(x) and Member(x)\mathit{Member}(x): ∀\foralle on H2H_2 and →\toe give MayBorrow(x)\mathit{MayBorrow}(x), and ¬\nege gives ⊥\bot. Then ¬\negi discharges Member(x)\mathit{Member}(x), →\toi discharges ¬MayBorrow(x)\neg\mathit{MayBorrow}(x), and ∀\foralli on xx ends.

17. Eleven: three hyp, three ∀\foralle, two →\toe, one →\toi, two ∀\foralli, as in the output.

18. ∀\foralli generalises a variable, not a constant: p5p5 names one person, of whom the data might say anything, and MayBorrow(p5)\mathit{MayBorrow}(p5) needs the fact Out(p5,b3)\mathit{Out}(p5, b3), which is not about everyone. The proof with xx and yy uses only the rules.

19. H1,H2,H3⊨CiH_1, H_2, H_3 \models C_i for i=1,2,3i = 1, 2, 3: in every structure, every town, every state of the tables, in which the three rules hold, the three consequences hold too.

20. The library has one member, element 00, who may borrow, has nothing out and has borrowed nothing; element 11 is neither a member nor allowed to borrow. The three rules hold, and C4C_4 fails because of 00.

21. If a proof of C4C_4 existed, by Theorem 24.15 C4C_4 would hold in every model of the rules, and this structure is one where it does not.

22. Yes: the domain {0}\{0\} with Member=MayBorrow={0}\mathit{Member} = \mathit{MayBorrow} = \{0\} and Out=Borrowed=∅\mathit{Out} = \mathit{Borrowed} = \emptyset. The program searches a fixed domain of two elements for all four sentences alike; a domain of one would also have been enough here.

23. A binary relation on two elements is one of 24=162^4 = 16 sets, a unary one of 22=42^2 = 4: 16⋅16⋅4⋅4=409616 \cdot 16 \cdot 4 \cdot 4 = 4096. On three elements: 29⋅29⋅23⋅23=16,777,2162^9 \cdot 2^9 \cdot 2^3 \cdot 2^3 = 16{,}777{,}216 structures, 4096 times more, each costing more evaluations; the number grows exponentially with the square of the domain’s size, and a search for countermodels tries the smallest domains first.

24. The clauses are ¬Out(x,y)∨Member(x)\neg\mathit{Out}(x, y) \vee \mathit{Member}(x) and ¬Member(x)∨MayBorrow(x)\neg\mathit{Member}(x) \vee \mathit{MayBorrow}(x). The negation of C1C_1 is ∃x ∃y (Out(x,y)∧¬MayBorrow(x))\exists x\, \exists y\, (\mathit{Out}(x, y) \wedge \neg\mathit{MayBorrow}(x)); naming the two witnesses by new constants aa and bb gives the clauses Out(a,b)\mathit{Out}(a, b) and ¬MayBorrow(a)\neg\mathit{MayBorrow}(a). As in Output 24.6: Member(a)\mathit{Member}(a) from the first and third, ¬Member(a)\neg\mathit{Member}(a) from the second and fourth, then the empty clause. The result: 3 rules proved in 34 checked steps, and a two-element countermodel for the one that does not follow.

本章定义的术语

在术语表中查看全部 1050 个术语