本书暂未推出简体中文版。现有版本: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")
$ 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
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 -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 is a constant. Given an infinite set of variables, the terms are built by: a variable is a term; if has arity and are terms, is a term. An atomic formula is for a predicate symbol of arity , an equality , or (false).
The library’s signature has the constants p5, b3, …, the predicates , and of arity 1, and , and of arity 2. Arithmetic has the constant , the successor of arity 1 and of arity 2, so 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 and are formulas and is a variable, , , , , and are formulas. The symbols (for all) and (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: binds tightest, then , and , which groups to the right; a quantifier reaches as far right as possible, so is . The listings write ~, &, |, ->, forall x. and exists x., and the library formulas.py reads and prints that text; its parser treats the names to , possibly followed by digits, as variables, and other lower-case names as constants.
Definition 24.3 (Free variable, bound variable, scope)
In and , the formula is the scope of the quantifier. An occurrence of is bound if it lies in the scope of a quantifier on , 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
A formula’s truth depends on its free variables, as depends on ; a sentence is simply true or false in a given world. In , the first is bound by , the second by , and is free:
Definition 24.4 (Substitution, capture-avoiding substitution)
The substitution replaces every free occurrence of in by the term . It is capture-avoiding when no variable of becomes bound by doing so: before entering the scope of a quantifier on a variable of , the bound is renamed to a variable used nowhere else.
Renaming a bound variable does not change a formula’s meaning, as and are the same sum. Replacing without care does. With the successor, says that has a successor, which is true of every . Substituting for should say that 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))
$ 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]
24.2 Semantics: structures and truth
Definition 24.5 (Structure, variable assignment, satisfaction)
A structure for a signature is a non-empty set , its domain, with a function for each function symbol of arity and a relation for each predicate symbol of arity . A variable assignment is a function from variables to . The value of a term is for a variable and for . Satisfaction is defined by induction on :
- when ; when the two values are equal; never ;
- the connectives as for valuations: when both hold, and so on;
- when for every , and when it holds for at least one , where is changed at only.
Only the free variables of matter: if and agree on them, exactly when , by an induction on in which the quantifier case changes the assignment at the bound variable only. For a sentence the assignment does not matter, and one writes .
Definition 24.6 (Model, valid formula, first-order logical consequence)
A structure is a model of a set of sentences when for every . A formula is valid when for every structure and every assignment. It is a first-order logical consequence of , written , when every structure and assignment that satisfy all of satisfy .
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)
Proposition 24.7 (Cost of evaluation)
Let be a formula with nodes whose quantifiers are nested at most deep, and a finite structure with domain , in which a function or a relation is evaluated in constant time. The recursive evaluation of takes steps, where bounds the size of the terms.
Proof. A node of the tree of with quantifiers above it is evaluated at most once for each choice of values of those variables, so at most times. Each visit costs a constant, plus at most steps for the terms of an atomic formula. Summing over the nodes gives the bound. ∎
The bound is exponential in , not in : 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 the count of atomic formulas grows as :
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}")
$ 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
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 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 is a finite set of formulas , the hypotheses, and a formula , the conclusion; it claims that follows from . 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 also for “some proof tree proves ”.
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).
Example 24.10 (Modus ponens and the syllogism)
From and , the rule e gives : this is modus ponens. From and the conclusion needs a hypothesis that is later discharged: under the extra hypothesis , two uses of e give , and i turns “ under ” into with no longer among the hypotheses. With :
Example 24.11 (No counterexample)
The sequent 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 . With :
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 e says that what holds of everything holds of any term . From the rule it concludes that , and also, with a variable for , that . The substitution must avoid capture, or would give , as Output 24.2 showed.
The rule i is the mathematician’s “let be arbitrary”: if has been proved about a of which the hypotheses say nothing, the same proof works for every value of , so holds. The side condition is what “arbitrary” means. Without it, from the hypothesis , “this person is a member”, one would conclude , “everyone is”. The rules for are mirror images: i needs one witness , and e reasons about a witness that nothing else mentions.
Example 24.12 (A universal from two universals)
From and follows . With the two hypotheses, both sentences, the variable is free in none of them, and i applies:
The order of quantifiers matters. has a proof (Exercise 24.10): if one is related to every , every has some . 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:
24.5 Soundness and completeness
Definition 24.13 (Soundness, completeness)
A proof system is sound when every provable sequent is a consequence: implies . It is complete when every consequence is provable: implies .
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 , terms , variable and formula , with :
Proof. For terms, by induction on . If is , both sides are . If is another variable , both are . If , then , and the induction hypothesis on each gives the equality of the arguments, so of the values of . The statement on formulas follows by induction on ; 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 has a proof tree, then .
Proof. By induction on the proof tree: assuming that the premises of its last rule are consequences, so is its conclusion. Fix a structure and an assignment satisfying every formula of ; we show for each rule.
- hyp: , and satisfies .
- i: by induction satisfies and , so . The eliminations of and the introductions of are as direct.
- e: satisfies and , so . The rules i and e are the same argument with read as , and e holds because no satisfies .
- raa: if did not satisfy , it would satisfy , hence by induction, which is impossible.
- e: satisfies , so satisfies , and satisfies by Lemma 24.14.
- i: let and . As is not free in , satisfies , so by induction it satisfies , and by the lemma, with , satisfies . If , this assignment is . Otherwise is not free in , so not in , and agrees with on the free variables of . In both cases satisfies , for every : satisfies .
The rules i and e are Exercise 24.8, and the rules of follow the pattern of those of . ∎
The side condition of i appears in the proof exactly where it is used: changing 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 and not , 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 , then 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 and are the same relation. They do not give an algorithm deciding it: one can enumerate all proof trees, and if 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)
sub(i, A) checks premise with the extra hypothesis code/bachelor-2/24-predicate-logic/listings/checker.pyALL = (["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"))
$ 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
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 and conclude , is such a rule, and a set of clauses is unsatisfiable exactly when it derives the empty clause. In predicate logic a clause stands for its universal closure, and the literal should cancel after replacing by . The replacement is found by unification.
Definition 24.18 (Unifier, most general unifier, occurs check)
A substitution , replacing finitely many variables by terms at the same time, is a unifier of and when . It is a most general unifier when every unifier is followed by another substitution: for some . The occurs check refuses to bind a variable to a term other than that contains .
Method 24.19 (Robinson’s unification)
Keep a list of equations to solve, initially , and a substitution , initially empty. Repeatedly take an equation and apply to both sides. If they are equal, drop it. If one side is a variable : fail if occurs in the other side , otherwise add to . If both are and with the same symbol, replace the equation by for each . Otherwise, with two different symbols, fail. When the list is empty, return .
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
walk applies the bindings found so far; the occurs check stops 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))
Theorem 24.20 (Robinson)
Method 24.19 terminates. If and have a unifier, it returns a most general unifier; otherwise it fails.
Proof. Write for followed by , with applied until no variable of ’s domain is left. Invariant: a substitution unifies and if and only if and solves every equation of the list. It holds at the start, with empty. Dropping an equation with equal sides, or replacing by its arguments, does not change the solutions. Adding , when does not occur in , does not either: solves exactly when , that is when followed by is .
Failures: two different symbols at the roots never become equal under a substitution; and if occurs in , then is strictly larger than for every , so has no solution. By the invariant, and then have no unifier.
Termination: a binding removes the variable from all later equations, since they are walked through , 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 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 with not a variable) decreases at each step in lexicographic order.
Result: when the list is empty, itself satisfies , since no variable of ’s domain occurs in what gives, and so by the invariant unifies and ; every unifier satisfies , so is most general. ∎
Definition 24.21 (Resolvent, resolution)
Let and be two clauses, their variables renamed so that they share none, with and atomic formulas on the same predicate and a most general unifier of and . Their resolvent is . When two literals and of the same sign in a clause have a most general unifier , the clause 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
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)
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 is the directed graph whose vertices are the literals and , with two edges and for each clause (where is ).
An edge says that every model making true makes true, so a path does too. The formula forbids each of the four assignments, and its graph has a single strongly connected component:
Theorem 24.23 (2-SAT in linear time)
A 2-CNF formula is unsatisfiable if and only if, for some variable , the literals and 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 and share a component, there are paths and . A model making true makes true along the first, and one making false makes 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 for the number of the component of . Make true when ; exactly one of , is true since their numbers differ. Suppose a clause had both literals false: and . The edges and give and , so , a contradiction. The assignment is a model.
The graph has 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)
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
The talks of a two-room meeting are a 2-SAT instance: says that talk is in the big room, two talks with a speaker in common must be in different rooms ( and ), and a talk that needs the big room’s screen gives the clause .
$ 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
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 ; ; ; ; . Then run exo_free.py and compare.
Solution
Solution of Exercise 24.1.
In order: ; , from the of outside the brackets; , since the scope of runs to the end and binds the of ; , the of being bound by the outer ; , from , the later being bound by .
$ 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']
Exercise 24.2 ★
The function replace of exo_capture.py is meant to compute . 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)
replace.The first two are right: the bound of the first formula is not touched because does not occur under it, and in the second is bound, so nothing is replaced. The third is wrong. “ has a friend” with for should say “ has a friend”, ; replace enters the scope of with the term and the is captured, giving “someone is their own friend”. The correction is the quantifier case of Listing 24.3: return when is not free below, and rename the bound variable first when it occurs in . The function has a second defect: has no left field, so replace fails on it.
Exercise 24.3 ★
Predict the result of unifying with ; with ; with ; with . Check with exo_unify.py. Then show that the two clauses and 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: from the first arguments, then , so : both become . Second: , then , which the occurs check refuses: no unifier. Third: , , , all three become : . Fourth: 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
The two clauses: in a structure, the first says that every element is in (take ), 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 , 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 literals, never 0, and up to renaming only the three clauses of the output appear. With factors, gives (unify the two literals), gives , 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
Exercise 24.4 ★
Draw the implication graph of and find its strongly connected components. Is the formula satisfiable? What changes when the clause is added, and then also ? Check with exo_twosat.py.
Solution
Solution of Exercise 24.4.
The clauses give the edges , ; , ; , ; , . There are two components: (the cycle ) and its mirror , 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 true gives , , and making true gives the other model.
The clause adds and , edges from to . Now comes after and is made true: , . The clause adds and , from to ; the two components merge, and are in one, and the formula is unsatisfiable: its clauses say and .
$ 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
Exercise 24.5 ★★
For the three sentences , and , say which hold in: with when ; with the order ; with the relation . Check with exo_three.py.
Solution
Solution of Exercise 24.5.
In with the successor: every has a successor, true; no is its own successor, true; every is the successor of something, so the third is false. In with : has nothing above it, so the first is false; is irreflexive, true; has nothing below it, true. In with : each element has the other, true; irreflexive, true; each 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
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
The conclusion is not a consequence. Take , and : the hypotheses and are true, and is false because of . The steps above the last one are correct and prove : what is known of one member is that this member may borrow. The of the hypothesis is not arbitrary, which is what the side condition checks.
Exercise 24.7 ★★
Write a proof tree of , then write it as data for the checker.
Solution
Solution of Exercise 24.7.
Write . Under the extra hypothesis , i gives , and e with the hypothesis gives ; i discharges and gives . The same with and i gives , and i ends:
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)")))))
Exercise 24.8 ★★
Complete the proof of Theorem 24.15 with the cases of i and e.
Solution
Solution of Exercise 24.8.
Fix a structure and an assignment that satisfies .
i: by induction . If satisfies , it satisfies all of , so it satisfies ; if it does not satisfy , it satisfies anyway. In both cases .
e: by induction , and . So satisfies or . In the first case it satisfies , hence ; in the second it satisfies , hence .
In both rules the hypothesis added in a premise is exactly what the case analysis on provides; this is the meaning of discharging it.
Exercise 24.9 ★★
Extend the checker with the rules i and e, 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 side condition of e has three parts. If were free in , 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 , then would confuse it with another variable of . Each of them, removed, lets the checker accept a false conclusion: for the second, .
Exercise 24.10 ★★★
Prove 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 be arbitrary; from , take a witness with ; then by e, so by i; e concludes it from the hypothesis ( is free neither in the conclusion nor in the hypothesis), and i on gives .
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"))
$ 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
For the converse, the plan takes a , gets , and works with a witness under the hypothesis ; to conclude it needs , and generalising on is refused: is free in the hypothesis . The witness depends on . 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 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 lacks, or argue from the shape of a proof that ends with i.
Solution
Solution of Exercise 24.11.
Assume and aim at . Under the further hypothesis , i gives , which contradicts the first hypothesis, so i gives . Then i gives again, the contradiction is , and raa discharges .
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)"))))
raa is needed. Give each formula a value in : is the minimum, the maximum, is , is if and otherwise, and is , so if and otherwise. Call valid when, for every choice of values of the variables, the minimum of the values of (1 if is empty) is at most the value of . Every rule except raa turns valid premises into a valid conclusion; for instance for i, if and , then , which is the value of , and for e, when . With , has the value , so is not valid, and no proof without raa reaches it. raa itself fails the test: has the value when . The logic without raa is called intuitionistic.
Exercise 24.12 ★★★
Prove the formula part of Lemma 24.14 by induction on , 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 , which renaming a variable does not change; write . Atomic formulas: by the part on terms, the arguments of have the same values on both sides. Connectives: , and the induction hypothesis applies to each side; the other connectives are the same.
Quantifiers, (the case of is identical). If , or if is not free in , the substitution returns the formula unchanged; is not free in it, so and agree on its free variables and give it the same truth. Otherwise, if is not free in : iff for every , ; the value of under is still because is not in , so by induction this is , which is since ; that is .
If is free in , the program first renames: becomes with free nowhere. The two have the same truth under every assignment: iff, by induction ( is smaller than ), , iff since is not free in . The previous case applies to , as is not in . The renaming is used here, and only here: without it, the value of would change under , and the step “still ” 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: , whoever has a book out is a member; , every member may borrow; , a book that is out has been borrowed by that person. It would like to know which other rules follow from them: , whoever has a book out may borrow; , whoever has a book out is a member and has borrowed it; , whoever may not borrow is not a member; , 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")
$ 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
Part I — The rules as sentences.
- Write , , and to as sentences over , , and .
- is written in the program, and in Listing 24.1. Prove that the two are equivalent.
- What are the free variables of ? Why must the rules be sentences?
- Write “a book is out to one person at most” as a sentence, and explain each quantifier.
- The sentence is not . Put its brackets and say what it means.
- How many nested quantifiers do 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.
- Which of the five rules of Listing 24.1 hold in the town?
- The rule “out to one person at most” has 8 counterexamples. Why 8, for 4 books?
- What does a counterexample to that rule say about the loans table, and what should the library do about it?
- The rule “every member has a friend” fails 41 times. Is this an error in the data?
- Why does the town satisfy and although nobody proved them about the town?
- 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.
- Draw the proof tree of from Listing 24.12.
- Why are the two uses of i in the proof of allowed?
- Write a proof of that uses the proof of as a part.
- Write a proof of . Which rule for does it use, and which hypothesis does it discharge?
- Count the steps of your proof of and compare with the output.
- The proof of proves the sequent for and and then generalises. Why can it not instead prove and generalise from ?
Part IV — Checked mechanically, and a countermodel.
- What does the checker’s acceptance of to prove, by Theorem 24.15?
- Describe the structure found for in words: a library, a member, no loan.
- Why does this structure prove that no proof of from to exists?
- Is there a countermodel with a domain of one element? Why did the program search two?
- 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?
- Prove by resolution, writing , and the negation of 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:
2. Fix . If holds for every and some has , then . Conversely, if and for a given , then the left side holds, so . The argument uses that is not free in .
3. and . 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. : for every book and every person who has it out, every person who has it out is .
5. It reads , since a quantifier reaches as far right as possible: for every there is a that does not have out, or is a member. With 200 elements and at most a few books out per person, it is true of everyone and says nothing.
6. has 2 nested quantifiers, the rule of question 4 has 3. The bound gives visits for the second; the output reports 43,826 atomic formulas, because the implication stops at a false : 40,000 pairs are visited, and the inner runs only for the 22 loans that are out, about 200 visits each.
7. (as “a person with a book out is a member”), (“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 for which the body is false: .
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 for the naive evaluation.
13. With and : by hyp and e; by hyp and two e; by hyp; e twice gives , then ; i gives , and i on , then on , gives .
14. Both are applied after i has discharged , so the hypotheses are , , , sentences in which no variable is free; and the conclusions and have neither nor free.
15. Under , the proof of question 13 gives ; hyp, two e on and e give ; i joins them; then i and two i. This is C2 in library.py, 14 steps.
16. Under and : e on and e give , and e gives . Then i discharges , i discharges , and i on ends.
17. Eleven: three hyp, three e, two e, one i, two i, as in the output.
18. i generalises a variable, not a constant: names one person, of whom the data might say anything, and needs the fact , which is not about everyone. The proof with and uses only the rules.
19. for : 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 , who may borrow, has nothing out and has borrowed nothing; element is neither a member nor allowed to borrow. The three rules hold, and fails because of .
21. If a proof of existed, by Theorem 24.15 would hold in every model of the rules, and this structure is one where it does not.
22. Yes: the domain with and . 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 sets, a unary one of : . On three elements: 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 and . The negation of is ; naming the two witnesses by new constants and gives the clauses and . As in Output 24.6: from the first and third, 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.
本章定义的术语
- First-order formula, quantifier
- First-order signature, term, atomic formula
- Free variable, bound variable, scope
- Implication graph
- Model, valid formula, first-order logical consequence
- Natural deduction, introduction rule, elimination rule
- Proof checker
- Resolvent, resolution
- Sequent, inference rule, proof tree
- Soundness, completeness
- Structure, variable assignment, satisfaction
- Substitution, capture-avoiding substitution
- Unifier, most general unifier, occurs check