---
title: "Predicate Logic and Formal Proofs"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 24
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/24-predicate-logic-and-formal-proofs
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 24 — Predicate 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](#def-b2-predicate-logic-formula), the rules can be checked against the town’s tables by a program:

```python
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](#def-b2-predicate-logic-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](#def-b2-predicate-logic-consequence) of a formula, satisfiability, logical consequence and equivalence; literals, clauses and CNF; the satisfiability problem and $k$-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 $0$ is a *constant*. Given an infinite set of *variables*, the *terms* are built by: a variable is a term; if $f$ has arity $n$ and $t_1, \dots, t_n$ are terms, $f(t_1, \dots, t_n)$ is a term. An *atomic formula* is $P(t_1, \dots, t_n)$ for a predicate symbol $P$ of arity $n$, an equality $t_1 = t_2$, or $\bot$ (false).

The library’s signature has the constants `p5`, `b3`, …, the predicates $\mathit{Person}$, $\mathit{Member}$ and $\mathit{Book}$ of arity 1, and $\mathit{Out}$, $\mathit{Borrowed}$ and $\mathit{Friend}$ of arity 2. Arithmetic has the constant $0$, the successor $s$ of arity 1 and $+$ of arity 2, so $s(0) + x$ is a term. A term names an object; an [atomic formula](#def-b2-predicate-logic-term) 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](#def-b2-predicate-logic-term) is a formula; if $A$ and $B$ are formulas and $x$ is a variable, $\neg A$, $A \wedge B$, $A \vee B$, $A \to B$, $\forall x\, A$ and $\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](#def-b2-predicate-logic-formula) reaches as far right as possible, so $\forall x\, P(x) \to Q(x)$ is $\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 $u$ to $z$, possibly followed by digits, as variables, and other lower-case names as constants.

**Definition 24.3 (Free variable, bound variable, scope).**

In $\forall x\, A$ and $\exists x\, A$, the formula $A$ is the *scope* of the [quantifier](#def-b2-predicate-logic-formula). An occurrence of $x$ is *bound* if it lies in the scope of a [quantifier](#def-b2-predicate-logic-formula) on $x$, and then it is bound by the nearest such [quantifier](#def-b2-predicate-logic-formula) 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](#def-b2-predicate-logic-free) are computed by structural induction, one line per case:

```python
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](#def-b2-predicate-logic-free) of a term or a formula; a [quantifier](#def-b2-predicate-logic-formula) removes its own variable code/bachelor-2/24-predicate-logic/listings/formulas.py*

A formula’s truth depends on its [free variables](#def-b2-predicate-logic-free), as $x < 3$ depends on $x$; a [sentence](#def-b2-predicate-logic-free) is simply true or false in a given world. In $\forall x\, (R(x, y) \to \exists x\, P(x))$, the first $x$ is [bound](#def-b2-predicate-logic-free) by $\forall x$, the second by $\exists x$, and $y$ is [free](#def-b2-predicate-logic-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.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-predicate-logic/fig-7f101a6d0306.svg)

*The tree of $\forall x\, (R(x, y) \to \exists x\, P(x))$. A dashed arrow joins each [bound](#def-b2-predicate-logic-free) occurrence to the [quantifier](#def-b2-predicate-logic-formula) that binds it: the nearest one above it on its own variable. The circled $y$ is [free](#def-b2-predicate-logic-free).*

**Definition 24.4 (Substitution, capture-avoiding substitution).**

The *substitution* $A[t/x]$ replaces every [free](#def-b2-predicate-logic-free) occurrence of $x$ in $A$ by the term $t$. It is *capture-avoiding* when no variable of $t$ becomes [bound](#def-b2-predicate-logic-free) by doing so: before entering the [scope](#def-b2-predicate-logic-free) of a [quantifier](#def-b2-predicate-logic-formula) on a variable $y$ of $t$, the [bound](#def-b2-predicate-logic-free) $y$ is renamed to a variable used nowhere else.

Renaming a [bound variable](#def-b2-predicate-logic-free) does not change a formula’s meaning, as $\sum_i a_i$ and $\sum_j a_j$ are the same sum. Replacing without care does. With $s$ the successor, $\exists y\, y = s(x)$ says that $x$ has a successor, which is true of every $x$. Substituting $y$ for $x$ should say that $y$ has a successor; the careless copy says that some number is its own successor:

```python
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](#def-b2-predicate-logic-substitution): the [bound variable](#def-b2-predicate-logic-free) is renamed when it would capture a variable of $t$ 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](#def-b2-predicate-logic-free) and become false; the renamed [substitution](#def-b2-predicate-logic-substitution) keeps the meaning.*

## 24.2 Semantics: structures and truth

**Definition 24.5 (Structure, variable assignment, satisfaction).**

A *structure* $\mathcal{A}$ for a signature is a non-empty set $D$, its *domain*, with a function $f^{\mathcal{A}} : D^n \to D$ for each function symbol of arity $n$ and a relation $P^{\mathcal{A}}
\subseteq D^n$ for each predicate symbol of arity $n$. A *variable assignment* is a function $\rho$ from variables to $D$. The value $\llbracket t \rrbracket_\rho$ of a term is $\rho(x)$ for a variable and $f^{\mathcal{A}}(\llbracket t_1 \rrbracket_\rho, \dots, \llbracket t_n \rrbracket_\rho)$ for $f(t_1, \dots, t_n)$. *Satisfaction* $\mathcal{A}, \rho \models A$ is defined by induction on $A$:

- $\mathcal{A}, \rho \models P(t_1, \dots, t_n)$ when $(\llbracket t_1 \rrbracket_\rho, \dots, \llbracket t_n \rrbracket_\rho) \in P^{\mathcal{A}}$ ; $\mathcal{A}, \rho \models t_1 = t_2$ when the two values are equal; never $\mathcal{A}, \rho \models \bot$ ;
- the connectives as for valuations: $\mathcal{A}, \rho \models A \wedge B$ when both hold, and so on;
- $\mathcal{A}, \rho \models \forall x\, A$ when $\mathcal{A}, \rho[x \mapsto d] \models A$ for every $d \in D$ , and $\mathcal{A}, \rho \models \exists x\, A$ when it holds for at least one $d \in D$ , where $\rho[x \mapsto d]$ is $\rho$ changed at $x$ only.

Only the [free variables](#def-b2-predicate-logic-free) of $A$ matter: if $\rho$ and $\rho'$ agree on them, $\mathcal{A}, \rho \models A$ exactly when $\mathcal{A}, \rho' \models A$, by an induction on $A$ in which the [quantifier](#def-b2-predicate-logic-formula) case changes the assignment at the [bound variable](#def-b2-predicate-logic-free) only. For a [sentence](#def-b2-predicate-logic-free) the assignment does not matter, and one writes $\mathcal{A} \models A$.

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

A [structure](#def-b2-predicate-logic-structure) $\mathcal{A}$ is a *model* of a set of [sentences](#def-b2-predicate-logic-free) $\Gamma$ when $\mathcal{A} \models B$ for every $B \in \Gamma$. A formula $A$ is *valid* when $\mathcal{A}, \rho \models A$ for every [structure](#def-b2-predicate-logic-structure) and every assignment. It is a *first-order logical consequence* of $\Gamma$, written $\Gamma \models A$, when every [structure](#def-b2-predicate-logic-structure) and assignment that satisfy all of $\Gamma$ satisfy $A$.

The definition reads like a program, and on a finite domain it is one. [Listing 24.4](#lst-b2-predicate-logic-structure) follows it line by line; the town is a [structure](#def-b2-predicate-logic-structure) whose domain holds the 120 people and the 80 books, with the relations read from the tables, and [Listing 24.1](#lst-b2-predicate-logic-evaluate) asked it about five [sentences](#def-b2-predicate-logic-free).

```python
    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](#def-b2-predicate-logic-structure), by induction on the formula code/bachelor-2/24-predicate-logic/listings/structures.py*

**Proposition 24.7 (Cost of evaluation).**

Let $A$ be a formula with $|A|$ nodes whose [quantifiers](#def-b2-predicate-logic-formula) are nested at most $q$ deep, and $\mathcal{A}$ a finite [structure](#def-b2-predicate-logic-structure) with domain $D$, in which a function or a relation is evaluated in constant time. The recursive evaluation of $\mathcal{A}, \rho \models A$ takes $\BigO(|D|^q \cdot |A| \cdot m)$ steps, where $m$ bounds the size of the [terms](#def-b2-predicate-logic-term).

**Proof.** A node of the tree of $A$ with $k$ [quantifiers](#def-b2-predicate-logic-formula) above it is evaluated at most once for each choice of values of those $k$ variables, so at most $|D|^k \leq |D|^q$ times. Each visit costs a constant, plus at most $m$ steps for the [terms](#def-b2-predicate-logic-term) of an [atomic formula](#def-b2-predicate-logic-term). Summing over the $|A|$ nodes gives the bound. ∎

The bound is exponential in $q$, not in $|A|$: a rule with three nested [quantifiers](#def-b2-predicate-logic-formula) on a domain of a thousand elements costs a billion visits. Transitivity has three, and on the order $<$ of $\{0, \dots, n-1\}$ the count of [atomic formulas](#def-b2-predicate-logic-term) grows as $n^3$:

```python
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](#def-b2-predicate-logic-term) 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/3$: every triple evaluates $R(x, y)$, half of them also $R(y, z)$, and the triples with $x < y < z$, a sixth, also $R(x, z)$.*

**In practice.**

A database query is a formula evaluated on a finite [structure](#def-b2-predicate-logic-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$ loop of [Proposition 24.7](#prop-b2-predicate-logic-evaluation-cost). Integrity constraints of a schema are [sentences](#def-b2-predicate-logic-free) of the same kind, checked on every change of the data.

The evaluation decides truth in *one* finite [structure](#def-b2-predicate-logic-structure). Consequence quantifies over *every* [structure](#def-b2-predicate-logic-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* $\Gamma \vdash A$ is a finite set of formulas $\Gamma$, the *hypotheses*, and a formula $A$, the conclusion; it claims that $A$ 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 $\Gamma \vdash A$ also for “some proof tree proves $\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](#def-b2-predicate-logic-formula) 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](#exo-b2-predicate-logic-11)).

*The rules of [natural deduction](#def-b2-predicate-logic-nd); $t$ is any term. Side conditions: $(*)$ $y$ is [free](#def-b2-predicate-logic-free) neither in $\Gamma$ nor in $\forall x\, A$; $(**)$ $y$ is [free](#def-b2-predicate-logic-free) neither in $\Gamma$, nor in $\exists x\, A$, nor in $C$.*

**Example 24.10 (Modus ponens and the syllogism).**

From $P \to Q$ and $P$, the rule $\to$e gives $Q$: this is *modus ponens*. From $P \to Q$ and $Q \to R$ the conclusion $P \to R$ needs a hypothesis that is later *discharged*: under the extra hypothesis $P$, two uses of $\to$e give $R$, and $\to$i turns “$R$ under $P$” into $P \to R$ with $P$ no longer among the hypotheses. With $\Gamma = \{P \to Q,\ Q \to R\}$:

${\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}}$ ${\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](#def-b2-predicate-logic-sequent) $\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 $\Delta = \{P \to Q,\ P \wedge \neg Q\}$:

${\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](#def-b2-predicate-logic-formula) enter, where no table exists.

## 24.4 The quantifier rules

The rule $\forall$e says that what holds of everything holds of any term $t$. From the rule $\forall x\,
\mathit{Member}(x) \to \mathit{MayBorrow}(x)$ it concludes that $\mathit{Member}(p5) \to \mathit{MayBorrow}(p5)$, and also, with a variable $y$ for $t$, that $\mathit{Member}(y) \to \mathit{MayBorrow}(y)$. The [substitution](#def-b2-predicate-logic-substitution) must avoid capture, or $\forall x\, \exists y\,
y = s(x)$ would give $\exists y\, y = s(y)$, as [Output 24.2](#out-b2-predicate-logic-substitution) showed.

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

**Example 24.12 (A universal from two universals).**

From $\forall x\, (P(x) \to Q(x))$ and $\forall x\, P(x)$ follows $\forall x\, Q(x)$. With $\Gamma$ the two hypotheses, both [sentences](#def-b2-predicate-logic-free), the variable $y$ is [free](#def-b2-predicate-logic-free) in none of them, and $\forall$i applies:

${\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](#def-b2-predicate-logic-formula) matters. $\exists x\, \forall y\, R(x, y) \vdash \forall y\, \exists x\, R(x, y)$ has a proof ([Exercise 24.10](#exo-b2-predicate-logic-10)): if one $x$ is related to every $y$, every $y$ has some $x$. The converse fails, and the way to show that a [sequent](#def-b2-predicate-logic-sequent) has no proof is a [structure](#def-b2-predicate-logic-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.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-predicate-logic/fig-acbb39f0dc79.svg)

*A [structure](#def-b2-predicate-logic-structure) with domain $\{0, 1\}$ and $R$ the equality. Every $y$ has an $x$ with $R(x, y)$, namely $y$ itself, so $\forall y\, \exists x\, R(x, y)$ is true; no $x$ is related to both $0$ and $1$, so $\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](#def-b2-predicate-logic-sequent) is a consequence: $\Gamma
\vdash A$ implies $\Gamma \models A$. It is *complete* when every consequence is provable: $\Gamma \models A$ implies $\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](#def-b2-predicate-logic-substitution), which says that substituting a term and changing the assignment are the same operation.

**Lemma 24.14 (Substitution).**

For every [structure](#def-b2-predicate-logic-structure), assignment $\rho$, [terms](#def-b2-predicate-logic-term) $s, t$, variable $x$ and formula $A$, with $d = \llbracket t
\rrbracket_\rho$:

$$
\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](#def-b2-predicate-logic-term), by induction on $s$. If $s$ is $x$, both sides are $d$. If $s$ is another variable $z$, both are $\rho(z)$. If $s = f(s_1, \dots, s_n)$, then $s[t/x] = f(s_1[t/x], \dots, s_n[t/x])$, and the induction hypothesis on each $s_i$ gives the equality of the arguments, so of the values of $f$. The statement on formulas follows by induction on $A$; its atomic case is the statement on [terms](#def-b2-predicate-logic-term), and its [quantifier](#def-b2-predicate-logic-formula) case is where capture avoidance is needed ([Exercise 24.12](#exo-b2-predicate-logic-12)). ∎

The test file `test_formulas.py` checks the property on 400 random formulas over a [structure](#def-b2-predicate-logic-structure) of three elements; the test fails at once if the renaming of [Listing 24.3](#lst-b2-predicate-logic-subst) is removed.

**Theorem 24.15 (Soundness of natural deduction).**

If $\Gamma \vdash A$ has a [proof tree](#def-b2-predicate-logic-sequent), then $\Gamma \models A$.

**Proof.** By induction on the [proof tree](#def-b2-predicate-logic-sequent): assuming that the premises of its last rule are consequences, so is its conclusion. Fix a [structure](#def-b2-predicate-logic-structure) $\mathcal{A}$ and an assignment $\rho$ satisfying every formula of $\Gamma$; we show $\mathcal{A}, \rho
\models A$ for each rule.

- hyp : $A \in \Gamma$ , and $\rho$ satisfies $\Gamma$ .
- $\wedge$ i : by induction $\rho$ satisfies $A$ and $B$ , so $A \wedge B$ . The eliminations of $\wedge$ and the introductions of $\vee$ are as direct.
- $\to$ e : $\rho$ satisfies $A \to B$ and $A$ , so $B$ . The rules $\neg$ i and $\neg$ e are the same argument with $\neg A$ read as $A \to \bot$ , and $\bot$ e holds because no $\rho$ satisfies $\bot$ .
- raa : if $\rho$ did not satisfy $A$ , it would satisfy $\Gamma \cup \{\neg A\}$ , hence $\bot$ by induction, which is impossible.
- $\forall$ e : $\rho$ satisfies $\forall x\, A$ , so $\rho[x \mapsto \llbracket t \rrbracket_\rho]$ satisfies $A$ , and $\rho$ satisfies $A[t/x]$ by [Lemma 24.14](#lem-b2-predicate-logic-substitution) .
- $\forall$ i : let $d \in D$ and $\rho' = \rho[y \mapsto d]$ . As $y$ is not [free](#def-b2-predicate-logic-free) in $\Gamma$ , $\rho'$ satisfies $\Gamma$ , so by induction it satisfies $A[y/x]$ , and by the lemma, with $\llbracket y \rrbracket_{\rho'} = d$ , $\rho'[x \mapsto d]$ satisfies $A$ . If $y = x$ , this assignment is $\rho[x \mapsto d]$ . Otherwise $y$ is not [free](#def-b2-predicate-logic-free) in $\forall x\, A$ , so not in $A$ , and $\rho'[x \mapsto d]$ agrees with $\rho[x \mapsto d]$ on the [free variables](#def-b2-predicate-logic-free) of $A$ . In both cases $\rho[x \mapsto d]$ satisfies $A$ , for every $d$ : $\rho$ satisfies $\forall x\, A$ .

The rules $\to$i and $\vee$e are [Exercise 24.8](#exo-b2-predicate-logic-8), and the rules of $\exists$ follow the pattern of those of $\forall$. ∎

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

**Theorem 24.16 (Completeness).**

If $\Gamma \models A$, then $\Gamma \vdash A$ has a [proof tree](#def-b2-predicate-logic-sequent) in [natural deduction](#def-b2-predicate-logic-nd).

**Proof.** *Admitted at this level.* ∎

The proof builds, from a set of formulas that proves nothing false, a [structure](#def-b2-predicate-logic-structure) that satisfies all of them, made of the [terms](#def-b2-predicate-logic-term) 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](#def-b2-predicate-logic-sequent), and if $\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](#def-b2-predicate-logic-nd) and the [sequent](#def-b2-predicate-logic-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](#def-b2-predicate-logic-sequent) calculus, a variant in which every rule acts on the hypotheses or on the conclusion of a [sequent](#def-b2-predicate-logic-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](#def-b2-predicate-logic-sequent), decides whether every node follows from its children by a rule of the system, side conditions included. If it accepts, the root [sequent](#def-b2-predicate-logic-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](#def-b2-predicate-logic-formula) 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.

```python
        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 $i$ with the extra hypothesis $A$ code/bachelor-2/24-predicate-logic/listings/checker.py*

```python
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](#ex-b2-predicate-logic-forall), and a $\forall$-introduction on a variable [free](#def-b2-predicate-logic-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](#def-b2-predicate-logic-substitution), 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](#def-b2-predicate-logic-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 \vee L$ and $C' \vee \neg L$ conclude $C \vee C'$, is such a rule, and a set of clauses is unsatisfiable exactly when it derives the empty clause. In [predicate logic](#def-b2-predicate-logic-formula) a clause $\neg \mathit{Out}(x, y) \vee \mathit{Member}(x)$ stands for its universal closure, and the literal $\mathit{Member}(x)$ should cancel $\neg\mathit{Member}(p5)$ after replacing $x$ by $p5$. The replacement is found by unification.

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

A [substitution](#def-b2-predicate-logic-substitution) $\sigma$, replacing finitely many variables by [terms](#def-b2-predicate-logic-term) at the same time, is a *unifier* of $s$ and $t$ when $s\sigma = t\sigma$. It is a *most general unifier* when every unifier $\tau$ is $\sigma$ followed by another [substitution](#def-b2-predicate-logic-substitution): $\tau =
\sigma\theta$ for some $\theta$. The *occurs check* refuses to bind a variable $x$ to a term other than $x$ that contains $x$.

**Method 24.19 (Robinson’s unification).**

Keep a list of equations to solve, initially $s = t$, and a [substitution](#def-b2-predicate-logic-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 $x$: fail if $x$ occurs in the other side $u$, otherwise add $x \mapsto u$ to $\sigma$. If both are $f(s_1, \dots, s_n)$ and $f(t_1, \dots,
t_n)$ with the same symbol, replace the equation by $s_i = t_i$ for each $i$. Otherwise, with two different symbols, fail. When the list is empty, return $\sigma$.

```python
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](#def-b2-predicate-logic-unification) stops $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](#def-b2-predicate-logic-unification) found through a chain of bindings, a clash of constants, a failed [occurs check](#def-b2-predicate-logic-unification), and a second success.*

**Theorem 24.20 (Robinson).**

[Method 24.19](#met-b2-predicate-logic-unify) terminates. If $s$ and $t$ have a [unifier](#def-b2-predicate-logic-unification), it returns a [most general unifier](#def-b2-predicate-logic-unification); 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](#def-b2-predicate-logic-substitution) $\tau$ unifies $s$ and $t$ 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(\vec s) = f(\vec t)$ by its arguments, does not change the solutions. Adding $x \mapsto u$, when $x$ does not occur in $u$, does not either: $\tau$ solves $x = u$ exactly when $\tau(x) = u\tau$, that is when $x \mapsto u$ followed by $\tau$ is $\tau$.

*Failures*: two different symbols at the roots never become equal under a [substitution](#def-b2-predicate-logic-substitution); and if $x$ occurs in $u
\neq x$, then $u\tau$ is strictly larger than $\tau(x)$ for every $\tau$, so $x = u$ has no solution. By the invariant, $s$ and $t$ then have no [unifier](#def-b2-predicate-logic-unification).

*Termination*: a binding removes the variable $x$ from all later equations, since they are walked through $\sigma$, and the [occurs check](#def-b2-predicate-logic-unification) 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 = 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 = x$ with $u$ 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 $s$ and $t$; every [unifier](#def-b2-predicate-logic-unification) $\tau$ satisfies $\sigma\tau = \tau$, so $\sigma$ is most general. ∎

**Definition 24.21 (Resolvent, resolution).**

Let $C_1 \vee L_1$ and $C_2 \vee \neg L_2$ be two clauses, their variables renamed so that they share none, with $L_1$ and $L_2$ [atomic formulas](#def-b2-predicate-logic-term) on the same predicate and $\sigma$ a [most general unifier](#def-b2-predicate-logic-unification) of $L_1$ and $L_2$. Their *resolvent* is $(C_1 \vee C_2)\sigma$. When two literals $L$ and $L'$ of the same sign in a clause $C \vee L \vee L'$ have a [most general unifier](#def-b2-predicate-logic-unification) $\sigma$, the clause $(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.

```python
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](#def-b2-predicate-logic-resolution): two literals of the same sign made one code/bachelor-2/24-predicate-logic/listings/unify.py*

A [resolvent](#def-b2-predicate-logic-resolution) is a consequence of its two clauses, and a [factor](#def-b2-predicate-logic-resolution) of its clause, so a refutation proves that the set has no [model](#def-b2-predicate-logic-consequence). 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](#def-b2-predicate-logic-consequence) has a refutation. His rule resolves several literals at once, which builds factoring in; binary [resolvents](#def-b2-predicate-logic-resolution) alone are not enough, and [Exercise 24.3](#exo-b2-predicate-logic-3) gives two clauses with no [model](#def-b2-predicate-logic-consequence) 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](#def-b2-predicate-logic-resolution) proves that `p5` may borrow. Each new clause names its two parents and the [unifier](#def-b2-predicate-logic-unification); 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](#def-b2-predicate-logic-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](#def-b2-predicate-logic-term).

## 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 $x_1, \dots, x_n$ is the directed graph whose $2n$ vertices are the literals $x_k$ and $\neg x_k$, with two edges $\neg a \to b$ and $\neg b \to a$ for each clause $a \vee b$ (where $\neg\neg x$ is $x$).

An edge $\ell \to m$ says that every [model](#def-b2-predicate-logic-consequence) making $\ell$ true makes $m$ true, so a path does too. The formula $(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.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-predicate-logic/fig-e1dd6998d8cc.svg)

*The [implication graph](#def-b2-predicate-logic-implication-graph) of the four clauses on $x_1, x_2$: each clause $a \vee b$ gives the edges $\neg a \to b$ and $\neg b \to a$. All four literals are in one strongly connected component, so $x_1$ implies $\neg
x_1$ and $\neg x_1$ implies $x_1$.*

**Theorem 24.23 (2-SAT in linear time).**

A 2-CNF formula is unsatisfiable if and only if, for some variable $x$, the literals $x$ and $\neg x$ lie in the same strongly connected component of its [implication graph](#def-b2-predicate-logic-implication-graph). Satisfiability, and a [model](#def-b2-predicate-logic-consequence) when there is one, are found in time linear in the number of variables and clauses.

**Proof.** If $x$ and $\neg x$ share a component, there are paths $x \leadsto \neg x$ and $\neg x \leadsto x$. A [model](#def-b2-predicate-logic-consequence) making $x$ true makes $\neg x$ true along the first, and one making $x$ false makes $x$ true along the second: there is no [model](#def-b2-predicate-logic-consequence).

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(\ell)$ for the number of the component of $\ell$. Make $\ell$ true when $c(\ell) > c(\neg \ell)$; exactly one of $x$, $\neg x$ is true since their numbers differ. Suppose a clause $a \vee b$ had both literals false: $c(a) < c(\neg a)$ and $c(b) <
c(\neg b)$. The edges $\neg a \to b$ and $\neg b \to a$ give $c(\neg a) \leq c(b)$ and $c(\neg b) \leq c(a)$, so $c(a) <
c(\neg a) \leq c(b) < c(\neg b) \leq c(a)$, a contradiction. The assignment is a [model](#def-b2-predicate-logic-consequence).

The graph has $2n$ 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. ∎

```python
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](#def-b2-predicate-logic-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*

```python
        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](#thm-b2-predicate-logic-2sat), and the [model](#def-b2-predicate-logic-consequence) 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: $x_k$ says that talk $k$ is in the big room, two talks with a speaker in common must be in different rooms ($x_j \vee x_k$ and $\neg x_j \vee \neg x_k$), and a talk that needs the big room’s screen gives the clause $x_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 \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](#def-b2-predicate-logic-free) of $\forall x\, R(x, y)$; $(\forall x\, P(x)) \to P(x)$; $\exists x\, \forall y\, R(x, y)
\wedge R(y, z)$; $\forall x\, ((\exists x\, P(x)) \to Q(x, f(y)))$; $\exists y\, (y = f(x) \wedge \forall x\, \neg R(x,
y))$. Then run `exo_free.py` and compare.

**Solution of Exercise 24.1.**

In order: $\{y\}$; $\{x\}$, from the $x$ of $P(x)$ outside the brackets; $\{z\}$, since the [scope](#def-b2-predicate-logic-free) of $\forall y$ runs to the end and binds the $y$ of $R(y, z)$; $\{y\}$, the $x$ of $Q(x, f(y))$ being [bound](#def-b2-predicate-logic-free) by the outer $\forall x$; $\{x\}$, from $f(x)$, the later $x$ being [bound](#def-b2-predicate-logic-free) by $\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](#def-b2-predicate-logic-free) of the five formulas.*

**Exercise 24.2 ★.**

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

**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](#def-b2-predicate-logic-substitution) made by `replace`.*

The first two are right: the [bound](#def-b2-predicate-logic-free) $y$ of the first formula is not touched because $z$ does not occur under it, and in the second $x$ is [bound](#def-b2-predicate-logic-free), so nothing is replaced. The third is wrong. “$x$ has a friend” with $y$ for $x$ should say “$y$ has a friend”, $\exists y_1\, \mathit{Friend}(y, y_1)$; `replace` enters the [scope](#def-b2-predicate-logic-free) of $\exists y$ with the term $y$ and the $y$ is captured, giving “someone is their own friend”. The correction is the [quantifier](#def-b2-predicate-logic-formula) case of [Listing 24.3](#lst-b2-predicate-logic-subst): return $e$ when $x$ is not [free](#def-b2-predicate-logic-free) below, and rename the [bound variable](#def-b2-predicate-logic-free) first when it occurs in $t$. 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)$ with $P(y, f(a))$; $P(x, f(x))$ with $P(f(y), y)$; $P(x, y, z)$ with $P(y,
z, a)$; $P(g(x), x)$ with $P(f(y), a)$. Check with `exo_unify.py`. Then show that the two clauses $P(x) \vee
P(y)$ and $\neg P(x) \vee \neg P(y)$ have no [model](#def-b2-predicate-logic-consequence), that binary [resolvents](#def-b2-predicate-logic-resolution) alone, however often repeated, only ever give clauses of two literals, and find a refutation that uses [factors](#def-b2-predicate-logic-resolution). Check with `factor_demo.py`.

**Solution of Exercise 24.3.**

First pair: $y = f(x)$ from the first arguments, then $f(x) = f(a)$, so $x = a$: both become $P(f(a), f(a))$. Second: $x = f(y)$, then $f(f(y)) = y$, which the [occurs check](#def-b2-predicate-logic-unification) refuses: no [unifier](#def-b2-predicate-logic-unification). Third: $x = y$, $y = z$, $z = a$, all three become $a$: $P(a, a, a)$. Fourth: $g(x) = f(y)$ is a clash of symbols: no [unifier](#def-b2-predicate-logic-unification).

```
$ 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](#def-b2-predicate-logic-structure), the first says that every element is in $P$ (take $x = y$), the second that none is, and the domain is not empty, so there is no [model](#def-b2-predicate-logic-consequence). Every clause derived by binary [resolvents](#def-b2-predicate-logic-resolution) has two literals on $P$, with two different variables: true of both clauses at the start, and a [resolvent](#def-b2-predicate-logic-resolution) 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 = 2$ literals, never 0, and up to renaming only the three clauses of the output appear. With [factors](#def-b2-predicate-logic-resolution), $P(x) \vee P(y)$ gives $P(x)$ (unify the two literals), $\neg P(x) \vee \neg P(y)$ gives $\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](#def-b2-predicate-logic-resolution) refute at once.*

**Exercise 24.4 ★.**

Draw the [implication graph](#def-b2-predicate-logic-implication-graph) of $(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 $\neg
x_1 \vee \neg x_3$ is added, and then also $x_1 \vee x_3$? Check with `exo_twosat.py`.

**Solution of Exercise 24.4.**

The clauses give the edges $\neg x_1 \to x_2$, $\neg x_2 \to x_1$; $x_1 \to x_3$, $\neg x_3 \to \neg x_1$; $x_2 \to \neg
x_3$, $x_3 \to \neg x_2$; $x_3 \to x_1$, $\neg x_1 \to \neg x_3$. There are two components: $A = \{x_1, x_3, \neg x_2\}$ (the cycle $x_1 \to x_3 \to \neg x_2 \to x_1$) and its mirror $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 $A$ true gives $x_1 = x_3 = 1$, $x_2 = 0$, and making $B$ true gives the other [model](#def-b2-predicate-logic-consequence).

The clause $\neg x_1 \vee \neg x_3$ adds $x_1 \to \neg x_3$ and $x_3 \to \neg x_1$, edges from $A$ to $B$. Now $B$ comes after $A$ and is made true: $x_1 = x_3 = 0$, $x_2 = 1$. The clause $x_1 \vee x_3$ adds $\neg x_1 \to x_3$ and $\neg x_3
\to x_1$, from $B$ to $A$; the two components merge, $x_1$ and $\neg x_1$ are in one, and the formula is unsatisfiable: its clauses say $x_1 \leftrightarrow x_3$ and $x_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](#def-b2-predicate-logic-free) $\forall x\, \exists y\, R(x, y)$, $\neg \exists x\, R(x, x)$ and $\exists y\, \forall x\, \neg
R(x, y)$, say which hold in: $\mathbb{Z}/3$ with $R(x, y)$ when $y = x + 1$; $\{0, 1, 2\}$ with $R$ the order $<$; $\{0, 1\}$ with $R$ the relation $\neq$. Check with `exo_three.py`.

**Solution of Exercise 24.5.**

In $\mathbb{Z}/3$ with the successor: every $x$ has a successor, true; no $x$ is its own successor, true; every $y$ is the successor of something, so the third is false. In $\{0, 1, 2\}$ with $<$: $2$ has nothing above it, so the first is false; $<$ is irreflexive, true; $0$ has nothing below it, true. In $\{0, 1\}$ with $\neq$: each element has the other, true; irreflexive, true; each $y$ 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](#def-b2-predicate-logic-structure), then the truth of the three [sentences](#def-b2-predicate-logic-free) 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](#def-b2-predicate-logic-structure) that answers, then the strongest correct conclusion its steps support.

**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\}$, $\mathit{Member} = \mathit{MayBorrow} = \{0\}$ and $\rho(y) =
0$: the hypotheses $\forall x\, (\mathit{Member}(x) \to \mathit{MayBorrow}(x))$ and $\mathit{Member}(y)$ are true, and $\forall x\, \mathit{MayBorrow}(x)$ is false because of $1$. The steps above the last one are correct and prove $\mathit{MayBorrow}(y)$: what is known of one member is that this member may borrow. The $y$ of the hypothesis is not arbitrary, which is what the side condition checks.

**Exercise 24.7 ★★.**

Write a [proof tree](#def-b2-predicate-logic-sequent) of $\neg(P \vee Q) \vdash \neg P \wedge \neg Q$, then write it as data for the checker.

**Solution of Exercise 24.7.**

Write $\Gamma = \{\neg(P \vee Q)\}$. Under the extra hypothesis $P$, $\vee$i $_1$ gives $P \vee Q$, and $\neg$e with the hypothesis $\neg(P \vee Q)$ gives $\bot$; $\neg$i discharges $P$ and gives $\Gamma
\vdash \neg P$. The same with $Q$ and $\vee$i $_2$ gives $\Gamma \vdash \neg Q$, and $\wedge$i ends:

${\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}}$

```python
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](#out-b2-predicate-logic-exo-proofs)) code/bachelor-2/24-predicate-logic/listings/proofs_more.py*

**Exercise 24.8 ★★.**

Complete the proof of [Theorem 24.15](#thm-b2-predicate-logic-soundness) with the cases of $\to$i and $\vee$e .

**Solution of Exercise 24.8.**

Fix a [structure](#def-b2-predicate-logic-structure) and an assignment $\rho$ that satisfies $\Gamma$.

$\to$i : by induction $\Gamma, A \models B$. If $\rho$ satisfies $A$, it satisfies all of $\Gamma \cup \{A\}$, so it satisfies $B$; if it does not satisfy $A$, it satisfies $A \to B$ anyway. In both cases $\rho \models A \to B$.

$\vee$e : by induction $\Gamma \models A \vee B$, $\Gamma, A \models C$ and $\Gamma, B \models C$. So $\rho$ satisfies $A$ or $B$. In the first case it satisfies $\Gamma \cup \{A\}$, hence $C$; in the second it satisfies $\Gamma
\cup \{B\}$, hence $C$.

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 $\exists$i and $\exists$e , through its argument `extra`, which maps a rule’s name to a function receiving the step, the hypotheses, `sub` and `need`.

**Solution of Exercise 24.9.**

```python
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$; $\exists$e 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 $\exists$e has three parts. If $y$ were [free](#def-b2-predicate-logic-free) in $C$, the conclusion would say something about the witness that leaves the [scope](#def-b2-predicate-logic-free) of the reasoning; if it were [free](#def-b2-predicate-logic-free) in a hypothesis, the witness would not be arbitrary; if it were [free](#def-b2-predicate-logic-free) in $\exists x\, A$, then $A[y/x]$ would confuse it with another variable of $A$. Each of them, removed, lets the checker accept a false conclusion: for the second, $P(y), \exists x\, \neg P(x) \vdash \bot$.

**Exercise 24.10 ★★★.**

Prove $\exists x\, \forall y\, R(x, y) \vdash \forall y\, \exists x\, R(x, y)$ and check the proof with [Exercise 24.9](#exo-b2-predicate-logic-9). Try the same plan for the converse: which side condition stops it, and why must something stop it?

**Solution of Exercise 24.10.**

Let $v$ be arbitrary; from $\exists x\, \forall y\, R(x, y)$, take a witness $u$ with $\forall y\, R(u, y)$; then $R(u,
v)$ by $\forall$e , so $\exists x\, R(x, v)$ by $\exists$i ; $\exists$e concludes it from the hypothesis ($u$ is [free](#def-b2-predicate-logic-free) neither in the conclusion nor in the hypothesis), and $\forall$i on $v$ gives $\forall y\, \exists x\, R(x, y)$.

```python
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](#exo-b2-predicate-logic-7), [24.10](#exo-b2-predicate-logic-10) and [24.11](#exo-b2-predicate-logic-11); the converse attempt is rejected.*

For the converse, the plan takes a $v$, gets $\exists x\, R(x, v)$, and works with a witness $u$ under the hypothesis $R(u, v)$; to conclude $\exists x\, \forall y\, R(x, y)$ it needs $\forall y\, R(u, y)$, and generalising $R(u, v)$ on $v$ is refused: $v$ is [free](#def-b2-predicate-logic-free) in the hypothesis $R(u, v)$. The witness depends on $v$. Something must stop every attempt: the two-element [structure](#def-b2-predicate-logic-structure) of [Section 24.4](#sec-24-4) satisfies the hypothesis and not the conclusion, and by [Theorem 24.15](#thm-b2-predicate-logic-soundness) no proof exists.

**Exercise 24.11 ★★★.**

Prove $\vdash P \vee \neg P$ in [natural deduction](#def-b2-predicate-logic-nd), 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 \vee
\neg P$ lacks, or argue from the shape of a proof that ends with $\vee$i .

**Solution of Exercise 24.11.**

Assume $\neg(P \vee \neg P)$ and aim at $\bot$. Under the further hypothesis $P$, $\vee$i $_1$ gives $P \vee
\neg P$, which contradicts the first hypothesis, so $\neg$i gives $\neg P$. Then $\vee$i $_2$ gives $P
\vee \neg P$ again, the contradiction is $\bot$, and raa discharges $\neg(P \vee \neg P)$.

```python
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, \tfrac12, 1\}$: $\wedge$ is the minimum, $\vee$ the maximum, $\bot$ is $0$, $a \to b$ is $1$ if $a \leq b$ and $b$ otherwise, and $\neg a$ is $a \to 0$, so $1$ if $a = 0$ and $0$ otherwise. Call $\Gamma \vdash A$ *[valid](#def-b2-predicate-logic-consequence)* 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 $A$. Every rule except raa turns [valid](#def-b2-predicate-logic-consequence) premises into a [valid](#def-b2-predicate-logic-consequence) conclusion; for instance for $\to$i , if $\min(\gamma, a) \leq b$ and $a > b$, then $\gamma \leq b$, which is the value of $a \to b$, and for $\vee$e , $\gamma = \max(\min(\gamma, a), \min(\gamma,
b)) \leq c$ when $\gamma \leq \max(a, b)$. With $P = \tfrac12$, $P \vee \neg P$ has the value $\max(\tfrac12, 0) =
\tfrac12 < 1$, so $\vdash P \vee \neg P$ is not [valid](#def-b2-predicate-logic-consequence), and no proof without raa reaches it. raa itself fails the test: $\neg\neg P$ has the value $1$ when $P = \tfrac12$. The logic without raa is called intuitionistic.

**Exercise 24.12 ★★★.**

Prove the formula part of [Lemma 24.14](#lem-b2-predicate-logic-substitution) by induction on $A$, with the [substitution](#def-b2-predicate-logic-substitution) of [Listing 24.3](#lst-b2-predicate-logic-subst). Where is the renaming used?

**Solution of Exercise 24.12.**

By induction on the number of connectives and [quantifiers](#def-b2-predicate-logic-formula) of $A$, which renaming a variable does not change; write $d =
\llbracket t \rrbracket_\rho$. [Atomic formulas](#def-b2-predicate-logic-term): by the part on [terms](#def-b2-predicate-logic-term), the arguments of $P$ have the same values on both sides. Connectives: $(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](#def-b2-predicate-logic-formula), $\forall y\, B$ (the case of $\exists$ is identical). If $y = x$, or if $x$ is not [free](#def-b2-predicate-logic-free) in $B$, the [substitution](#def-b2-predicate-logic-substitution) returns the formula unchanged; $x$ is not [free](#def-b2-predicate-logic-free) in it, so $\rho$ and $\rho[x \mapsto d]$ agree on its [free variables](#def-b2-predicate-logic-free) and give it the same truth. Otherwise, if $y$ is not [free](#def-b2-predicate-logic-free) in $t$: $\rho \models \forall y\, B[t/x]$ iff for every $e$, $\rho[y \mapsto e] \models B[t/x]$; the value of $t$ under $\rho[y
\mapsto e]$ is still $d$ because $y$ is not in $t$, so by induction this is $\rho[y \mapsto e][x \mapsto d] \models
B$, which is $\rho[x \mapsto d][y \mapsto e] \models B$ since $x \neq y$; that is $\rho[x \mapsto d] \models \forall y\,
B$.

If $y$ is [free](#def-b2-predicate-logic-free) in $t$, the program first renames: $\forall y\, B$ becomes $\forall z\, B[z/y]$ with $z$ [free](#def-b2-predicate-logic-free) nowhere. The two have the same truth under every assignment: $\rho[z \mapsto e] \models B[z/y]$ iff, by induction ($B$ is smaller than $A$), $\rho[z \mapsto e][y \mapsto e] \models B$, iff $\rho[y \mapsto e] \models B$ since $z$ is not [free](#def-b2-predicate-logic-free) in $B$. The previous case applies to $\forall z\, B[z/y]$, as $z$ is not in $t$. The renaming is used here, and only here: without it, the value of $t$ would change under $\rho[y \mapsto e]$, and the step “still $d$” fails, which is the capture of [Output 24.2](#out-b2-predicate-logic-substitution).

## 24.10 Problem: Checking the library’s rules

**Problem 24.1.**

Weekend problem — Checking the library’s rules

The library keeps three rules: $H_1$, whoever has a book out is a member; $H_2$, every member may borrow; $H_3$, a book that is out has been borrowed by that person. It would like to know which other rules follow from them: $C_1$, whoever has a book out may borrow; $C_2$, whoever has a book out is a member and has borrowed it; $C_3$, whoever may not borrow is not a member; $C_4$, every member has a book out.

```python
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 $C_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](#def-b2-predicate-logic-structure) found among the 4096 on two elements.*

**Part I — The rules as sentences.**

1. Write $H_1$ , $H_2$ , $H_3$ and $C_1$ to $C_4$ as [sentences](#def-b2-predicate-logic-free) over $\mathit{Out}$ , $\mathit{Member}$ , $\mathit{MayBorrow}$ and $\mathit{Borrowed}$ .
2. $H_1$ is written $\forall x\, \forall y\, (\mathit{Out}(x, y) \to \mathit{Member}(x))$ in the program, and $\forall x\, ((\exists y\, \mathit{Out}(x, y)) \to \mathit{Member}(x))$ in [Listing 24.1](#lst-b2-predicate-logic-evaluate) . Prove that the two are equivalent.
3. What are the [free variables](#def-b2-predicate-logic-free) of $\mathit{Out}(x, y) \to \mathit{Member}(x)$ ? Why must the rules be [sentences](#def-b2-predicate-logic-free) ?
4. Write “a book is out to one person at most” as a [sentence](#def-b2-predicate-logic-free) , and explain each [quantifier](#def-b2-predicate-logic-formula) .
5. The [sentence](#def-b2-predicate-logic-free) $\forall x\, \exists y\, \mathit{Out}(x, y) \to \mathit{Member}(x)$ is not $H_1$ . Put its brackets and say what it means.
6. How many nested [quantifiers](#def-b2-predicate-logic-formula) do $C_2$ and the rule of question 4 have, and what does [Proposition 24.7](#prop-b2-predicate-logic-evaluation-cost) predict for their cost on the town?

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

7. Which of the five rules of [Listing 24.1](#lst-b2-predicate-logic-evaluate) hold in the town?
8. The rule “out to one person at most” has 8 counterexamples. Why 8, for 4 books?
9. What does a counterexample to that rule say about the loans table, and what should the library do about it?
10. The rule “every member has a friend” fails 41 times. Is this an error in the data?
11. Why does the town satisfy $H_1$ and $H_3$ although nobody proved them about the town?
12. 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.**

13. Draw the [proof tree](#def-b2-predicate-logic-sequent) of $C_1$ from [Listing 24.12](#lst-b2-predicate-logic-library) .
14. Why are the two uses of $\forall$ i in the proof of $C_1$ allowed?
15. Write a proof of $C_2$ that uses the proof of $\mathit{Out}(x, y) \vdash \mathit{Member}(x)$ as a part.
16. Write a proof of $C_3$ . Which rule for $\neg$ does it use, and which hypothesis does it discharge?
17. Count the steps of your proof of $C_1$ and compare with the output.
18. The proof of $C_1$ proves the [sequent](#def-b2-predicate-logic-sequent) for $x$ and $y$ and then generalises. Why can it not instead prove $\mathit{MayBorrow}(p5)$ and generalise from $p5$ ?

**Part IV — Checked mechanically, and a countermodel.**

19. What does the checker’s acceptance of $C_1$ to $C_3$ prove, by [Theorem 24.15](#thm-b2-predicate-logic-soundness) ?
20. Describe the [structure](#def-b2-predicate-logic-structure) found for $C_4$ in words: a library, a member, no loan.
21. Why does this [structure](#def-b2-predicate-logic-structure) prove that no proof of $C_4$ from $H_1$ to $H_3$ exists?
22. Is there a countermodel with a domain of one element? Why did the program search two?
23. The program tries [structures](#def-b2-predicate-logic-structure) in a fixed order. How many [structures](#def-b2-predicate-logic-structure) on two elements are there for these four predicates, and how long would the search take on three elements?
24. Prove $C_1$ by resolution, writing $H_1$ , $H_2$ and the negation of $C_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 of Problem 24.1.**

**1.** In the order of the statement:

$$
\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*}
$$

$$
C_2 = \forall x\, \forall y\, (\mathit{Out}(x, y) \to \mathit{Member}(x) \wedge \mathit{Borrowed}(x, y)).
$$

**2.** Fix $x$. If $\mathit{Out}(x, y) \to \mathit{Member}(x)$ holds for every $y$ and some $y$ has $\mathit{Out}(x, y)$, then $\mathit{Member}(x)$. Conversely, if $(\exists y\, \mathit{Out}(x, y)) \to
\mathit{Member}(x)$ and $\mathit{Out}(x, y)$ for a given $y$, then the left side holds, so $\mathit{Member}(x)$. The argument uses that $y$ is not [free](#def-b2-predicate-logic-free) in $\mathit{Member}(x)$.

**3.** $x$ and $y$. A formula with [free variables](#def-b2-predicate-logic-free) is true or false only once they have values; a rule must hold of everyone, so its variables are all quantified.

**4.** $\forall y\, \forall x\, (\mathit{Out}(x, y) \to \forall z\, (\mathit{Out}(z, y) \to z = x))$: for every book $y$ and every person $x$ who has it out, every person $z$ who has it out is $x$.

**5.** It reads $\forall x\, \exists y\, (\mathit{Out}(x, y) \to \mathit{Member}(x))$, since a [quantifier](#def-b2-predicate-logic-formula) reaches as far right as possible: for every $x$ there is a $y$ that $x$ does not have out, or $x$ is a member. With 200 elements and at most a few books out per person, it is true of everyone and says nothing.

**6.** $C_2$ has 2 nested [quantifiers](#def-b2-predicate-logic-formula), the rule of question 4 has 3. The bound gives $200^3 = 8 \times 10^6$ visits for the second; the output reports 43,826 [atomic formulas](#def-b2-predicate-logic-term), because the implication stops at a false $\mathit{Out}(x, y)$: 40,000 pairs $(y, x)$ are visited, and the inner $\forall z$ runs only for the 22 loans that are out, about 200 visits each.

**7.** $H_1$ (as “a person with a book out is a member”), $H_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)$ for which the body is false: $2 \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$ for the naive evaluation.

**13.** With $\Gamma = \{H_1, H_2, H_3\}$ and $\Delta = \Gamma \cup \{\mathit{Out}(x, y)\}$: $\Delta \vdash
\mathit{Member}(x) \to \mathit{MayBorrow}(x)$ by hyp and $\forall$e ; $\Delta \vdash \mathit{Out}(x, y)
\to \mathit{Member}(x)$ by hyp and two $\forall$e ; $\Delta \vdash \mathit{Out}(x, y)$ by hyp ; $\to$e twice gives $\Delta \vdash \mathit{Member}(x)$, then $\Delta \vdash \mathit{MayBorrow}(x)$; $\to$i gives $\Gamma \vdash \mathit{Out}(x, y) \to \mathit{MayBorrow}(x)$, and $\forall$i on $y$, then on $x$, gives $C_1$.

**14.** Both are applied after $\to$i has discharged $\mathit{Out}(x, y)$, so the hypotheses are $H_1$, $H_2$, $H_3$, [sentences](#def-b2-predicate-logic-free) in which no variable is [free](#def-b2-predicate-logic-free); and the conclusions $\forall y\, (\dots)$ and $C_1$ have neither $y$ nor $x$ [free](#def-b2-predicate-logic-free).

**15.** Under $\Delta$, the proof of question 13 gives $\mathit{Member}(x)$; hyp , two $\forall$e on $H_3$ and $\to$e give $\mathit{Borrowed}(x, y)$; $\wedge$i joins them; then $\to$i and two $\forall$i . This is `C2` in `library.py`, 14 steps.

**16.** Under $\neg\mathit{MayBorrow}(x)$ and $\mathit{Member}(x)$: $\forall$e on $H_2$ and $\to$e give $\mathit{MayBorrow}(x)$, and $\neg$e gives $\bot$. Then $\neg$i discharges $\mathit{Member}(x)$, $\to$i discharges $\neg\mathit{MayBorrow}(x)$, and $\forall$i on $x$ ends.

**17.** Eleven: three hyp , three $\forall$e , two $\to$e , one $\to$i , two $\forall$i , as in the output.

**18.** $\forall$i generalises a variable, not a constant: $p5$ names one person, of whom the data might say anything, and $\mathit{MayBorrow}(p5)$ needs the fact $\mathit{Out}(p5, b3)$, which is not about everyone. The proof with $x$ and $y$ uses only the rules.

**19.** $H_1, H_2, H_3 \models C_i$ for $i = 1, 2, 3$: in every [structure](#def-b2-predicate-logic-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 $0$, who may borrow, has nothing out and has borrowed nothing; element $1$ is neither a member nor allowed to borrow. The three rules hold, and $C_4$ fails because of $0$.

**21.** If a proof of $C_4$ existed, by [Theorem 24.15](#thm-b2-predicate-logic-soundness) $C_4$ would hold in every [model](#def-b2-predicate-logic-consequence) of the rules, and this [structure](#def-b2-predicate-logic-structure) is one where it does not.

**22.** Yes: the domain $\{0\}$ with $\mathit{Member} = \mathit{MayBorrow} = \{0\}$ and $\mathit{Out} =
\mathit{Borrowed} = \emptyset$. The program searches a fixed domain of two elements for all four [sentences](#def-b2-predicate-logic-free) alike; a domain of one would also have been enough here.

**23.** A binary relation on two elements is one of $2^4 = 16$ sets, a unary one of $2^2 = 4$: $16 \cdot 16 \cdot 4
\cdot 4 = 4096$. On three elements: $2^9 \cdot 2^9 \cdot 2^3 \cdot 2^3 = 16{,}777{,}216$ [structures](#def-b2-predicate-logic-structure), 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 $\neg\mathit{Out}(x, y) \vee \mathit{Member}(x)$ and $\neg\mathit{Member}(x) \vee
\mathit{MayBorrow}(x)$. The negation of $C_1$ is $\exists x\, \exists y\, (\mathit{Out}(x, y) \wedge
\neg\mathit{MayBorrow}(x))$; naming the two witnesses by new constants $a$ and $b$ gives the clauses $\mathit{Out}(a,
b)$ and $\neg\mathit{MayBorrow}(a)$. As in [Output 24.6](#out-b2-predicate-logic-refute): $\mathit{Member}(a)$ from the first and third, $\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.
