Module contents
Lesson 16 of 23Core 110 min

First-order inference: unification and resolution

From knowledge-based agents to automated theorem proving. Starting with first-order semantics, reduce logical consequence to refutation through clausal form and Skolemization, Herbrand’s theorem, unification and resolution with refutational completeness, and the given-clause loop used by modern provers such as Vampire and E.

After this lesson you can

  • Describe a knowledge-based agent architecture and logical consequence as a decision mechanism.
  • Convert first-order formulas to clausal form with Skolemization.
  • Implement unification with an occurs check and resolution with factoring.
  • Explain Herbrand’s theorem and the semidecidability of first-order logic.
  • Build a prover with the given-clause loop and compare selection strategies.

Before you start

Motivation: an agent that decides by proving

Earlier lessons in this topic solved problems whose structure was fixed in advance: a state graph, a game tree, a finite set of variables with domains. This lesson asks a different question. A system has knowledge written as formulas (access-control rules, simplified physics of a video game, axioms of a mathematical theory) and wants to know whether something follows from it. We are not looking for a path or assignment: we are looking for a proof.

The classic architecture is the knowledge-based agent (Russell and Norvig, chapter 7). It has a knowledge base KB\mathrm{KB}, a set of formulas, and two operations:

  • TELL(KB,φ)\mathrm{TELL}(\mathrm{KB}, \varphi) adds formula φ\varphi: a domain rule or percept (“square (2,1)(2, 1) is breezy”).
  • ASK(KB,α)\mathrm{ASK}(\mathrm{KB}, \alpha) asks whether α\alpha is a logical consequence of the base, KB⊨α\mathrm{KB} \models \alpha: whether α\alpha is true in every model of KB\mathrm{KB}.

At each instant the agent performs TELL\mathrm{TELL} with what it perceives, ASK\mathrm{ASK} about a useful action (“is square (2,2)(2, 2) safe?”), and acts on the answer. The separation matters: knowledge is declarative and the decision mechanism is general. Changing behavior means changing formulas, not code. The idea reappears in expert systems, Prolog, ontologies and, with another engine, the previous lesson’s program verifiers.

AIMA’s testbed is the wumpus world: a cave of 4×44\times 4 squares with pits and a monster. The agent sees nothing; it perceives a breeze if a neighboring square has a pit and a stench if the wumpus is in a neighbor. World rules are formulas, for example

∀c  (Brisa(c)↔∃v (Vecina(v,c)∧Pozo(v))),\forall c\;\big(\mathit{Brisa}(c) \leftrightarrow \exists v\,(\mathit{Vecina}(v, c) \land \mathit{Pozo}(v))\big),

and “may I step on cc?” is ASK(KB,¬Pozo(c)∧¬Wumpus(c))\mathrm{ASK}(\mathrm{KB}, \lnot\mathit{Pozo}(c) \land \lnot\mathit{Wumpus}(c)). In a finite cave the answer can be computed by model checking: enumerate all worlds compatible with the percepts and see whether α\alpha holds in all. This is AIMA’s example after two percepts: no breeze at (1,1)(1, 1), breeze at (2,1)(2, 1).

[ ]ASK by model checking in the wumpus worldBrowser
from itertools import product

# El mundo de wumpus de AIMA tras dos percepciones: sin brisa en (1,1), brisa en (2,1).
# Variables: P[c] = hay pozo en la casilla c. Solo importan las casillas de la frontera.
frontera = [(1, 2), (2, 2), (3, 1)]
vecinas = {(1, 1): [(1, 2), (2, 1)], (2, 1): [(1, 1), (2, 2), (3, 1)]}

def kb(P):
    brisa = lambda c: any(P.get(v, False) for v in vecinas[c])
    # TELL: reglas de la brisa en las dos casillas visitadas + percepciones + (1,1) y (2,1) sin pozo
    return (not brisa((1, 1))) and brisa((2, 1))

modelos = []
for valores in product([False, True], repeat=len(frontera)):
    P = dict(zip(frontera, valores))
    if kb(P):
        modelos.append(P)
print(f"{2 ** len(frontera)} mundos posibles, {len(modelos)} modelos de KB:")
for P in modelos:
    print("   pozos en", [c for c in frontera if P[c]])

def ask(alfa):
    """KB |= alfa  si y solo si alfa es cierta en todos los modelos de KB."""
    return all(alfa(P) for P in modelos)

print("KB |= ¬P(1,2):", ask(lambda P: not P[(1, 2)]))
print("KB |= ¬P(2,2):", ask(lambda P: not P[(2, 2)]), "  KB |= P(2,2):", ask(lambda P: P[(2, 2)]))
print("KB |= P(2,2) ∨ P(3,1):", ask(lambda P: P[(2, 2)] or P[(3, 1)]))

Of 8 possible worlds, 3 models remain. In all three (1,2)(1, 2) is clear, so KB⊨¬P1,2\mathrm{KB} \models \lnot P_{1,2}; neither P2,2P_{2,2} nor ¬P2,2\lnot P_{2,2} follows, because the base does not know where the pit causing the breeze is, though it knows it is at (2,2)(2, 2) or (3,1)(3, 1).

InteractiveA logical agent in the wumpus world
1,1nothing2,1breeze3,1pit4,11,2stench2,2safe3,24,21,3wumpus2,33,34,31,42,43,44,4
  • visited
  • entailed safe
  • proven pit
  • proven wumpus
  • undecided frontier
The KB entails that (2,2) is safe: in the only remaining model there is no pit or wumpus there.
What the KB knows
Rules: Breeze(c) ⟺ ∃v (Neighbor(v, c) ∧ Pit(v)); Stench(c) ⟺ ∃v (Neighbor(v, c) ∧ Wumpus(v)); exactly one wumpus.
Percepts: (1,1) ¬B ¬S; (2,1) B ¬S; (1,2) ¬B S.
KB models1
Proven safe (frontier)(2,2)
Proven dangerspit (3,1), wumpus (1,3)
The world is AIMA figure 7.2. The agent has visited (1,1)(1,1), (2,1)(2,1) and (1,2)(1,2): the KB deduces that (2,2)(2,2) is safe, there is a pit at (3,1)(3,1) and the wumpus is at (1,3)(1,3). Each ASK answer enumerates all compatible worlds (frontier pits and the single wumpus's location) and checks whether the claim holds in all. Click the logical agent step several times: how far does it get from logical consequences alone? Then try stepping on an orange square, which the KB does not guarantee, and show the real world.

If you continue with the logical agent, eventually no frontier square is guaranteed safe: logic does not decide which risk is smaller, and the agent gets stuck. Probability handles that limit (AIMA devotes chapter 12 to the same world). But there is an earlier, more serious problem: model checking works only when models can be enumerated. With infinite domains (natural numbers, lists, program states) or simply large ones, enumeration is impossible. We need a syntactic procedure manipulating first-order formulas and guaranteed by semantics: sound (what it derives follows) and complete (it derives everything that follows). Propositional logic already provides it: resolution and its refutational completeness. This lesson lifts it to first order.

Entailment as refutation

The first step turns “does α\alpha follow?” into “is this set contradictory?”.

Proof

If Γ⊨α\Gamma \models \alpha and M\mathcal{M} were a model of Γ∪{¬α}\Gamma \cup \{\lnot\alpha\}, then M⊨α\mathcal{M} \models \alpha because it models Γ\Gamma and M⊨¬α\mathcal{M} \models \lnot\alpha: impossible. Conversely, if Γ∪{¬α}\Gamma \cup \{\lnot\alpha\} has no models, every model of Γ\Gamma makes ¬α\lnot\alpha false, that is, α\alpha true.

∎

A refutation prover therefore negates the conjecture, adds it to the axioms and seeks an explicit contradiction: the empty clause □\square. The rest of the lesson builds the pieces: turn formulas into clauses, understand why looking at “instances” suffices (Herbrand), find suitable instances without guessing (unification), combine them (resolution) and organize the search (the given-clause loop).

From formulas to clauses

Resolution works on clauses: disjunctions of literals, with all variables implicitly universally quantified. A clause like ¬miembro(U,G)∨¬permiso(G,R)∨puede_leer(U,R)\lnot\mathit{miembro}(U, G) \lor \lnot\mathit{permiso}(G, R) \lor \mathit{puede\_leer}(U, R) means ∀U ∀G ∀R (… )\forall U\,\forall G\,\forall R\,(\dots). A set of clauses is read as their conjunction. Getting there from any formula takes five steps.

  1. Eliminate →\to and ↔\leftrightarrow: φ→ψ\varphi \to \psi becomes ¬φ∨ψ\lnot\varphi \lor \psi.
  2. Negation normal form (NNF): push negations to atoms using De Morgan and the quantifier laws ¬∀x φ≡∃x ¬φ\lnot\forall x\,\varphi \equiv \exists x\,\lnot\varphi and ¬∃x φ≡∀x ¬φ\lnot\exists x\,\varphi \equiv \forall x\,\lnot\varphi.
  3. Rename bound variables so each quantifier has its own.
  4. Skolemize: eliminate each ∃\exists by replacing its variable with a new term.
  5. Conjunctive normal form: remove ∀\forall (now implicit) and distribute ∨\lor over ∧\land, as in propositional CNF.

Steps 1 through 3 and 5 produce equivalent formulas. Step 4 does not, and is the interesting one.

Skolemization

In ∀x ∃y ama(y,x)\forall x\,\exists y\,\mathit{ama}(y, x) (“everyone has someone who loves them”), the yy that exists depends on xx. If we name that dependency with a new function symbol ss, “the one who loves xx”, formula ∀x ama(s(x),x)\forall x\,\mathit{ama}(s(x), x) has no existential quantifiers.

The proof is short and you will reconstruct it in the guided exercise at the end: in one direction the Skolem term is a witness; in the other, interpret ss as a function choosing a witness for each value of xix_i (the axiom of choice if the domain is infinite). Lack of equivalence is no obstacle: the refutation theorem asks only whether Γ∪{¬α}\Gamma \cup \{\lnot\alpha\} is unsatisfiable, which Skolemization preserves. What matters is negating before Skolemizing: existential quantifiers in the conjecture become universal when negated.

Take the first sentence of the AIMA problem used as an example: “anyone who loves all animals is loved by someone”.

To fit the formulas, abbreviate animal\mathit{animal} as AA and ama\mathit{ama} as MM.

∀x [∀y (A(y)→M(x,y))→∃y M(y,x)]\begin{aligned} \forall x\,\big[&\forall y\,(A(y) \to M(x, y)) \\ &\to \exists y\,M(y, x)\big] \end{aligned}
The sentence in first order. The two y variables are distinct.
1/5

F(x)F(x) is “an animal that xx does not love” (if one exists) and G(x)G(x) is “someone who loves xx”. The lab’s clausal-form cell does exactly this and returns the same two clauses, with FF and GG named sk2 and sk3; when the loop cell clausifies the problem again, they are named sk14 and sk15 because the fresh-name counter is global. Those are the names in the interactives.

Step 5 has a known trap: distribution can multiply size. (a1∧b1)∨⋯∨(an∧bn)(a_1 \land b_1) \lor \dots \lor (a_n \land b_n) produces 2n2^n clauses. Real clausifiers name subformulas with new predicates, the same idea as Tseitin encoding in SAT, obtaining linear size while again preserving only satisfiability (Nonnengart and Weidenbach, Computing small clause normal forms, in the Handbook of Automated Reasoning, 2001). They then apply simplifications like SAT preprocessing: remove tautologies, subsumed clauses and pure literals.

The Herbrand universe: reducing to infinitely many propositional problems

We have a set of clauses SS and want to know whether it is unsatisfiable. By definition we must check that no structure satisfies it, and structures are infinite in number and can have domains of any size. Jacques Herbrand (1930 thesis) observed that a very specific kind of structure, built from the syntax itself, suffices.

A Herbrand interpretation is thus a propositional valuation of ground atoms. With the chain p(a)p(a), ¬p(X)∨p(f(X))\lnot p(X) \lor p(f(X)), ¬p(f(f(a)))\lnot p(f(f(a))), the universe is {a,f(a),f(f(a)),… }\{a, f(a), f(f(a)), \dots\}, and ground instances of the second clause are ¬p(a)∨p(f(a))\lnot p(a) \lor p(f(a)), ¬p(f(a))∨p(f(f(a)))\lnot p(f(a)) \lor p(f(f(a))), and so on.

Proof

A Herbrand model is a model. Conversely, let M⊨S\mathcal{M} \models S. Define the Herbrand interpretation H\mathcal{H} making a ground atom AA true exactly when M⊨A\mathcal{M} \models A (evaluating its ground terms in M\mathcal{M}). Take a clause C∈SC \in S with variables x1,…,xmx_1, \dots, x_m and an assignment of ground terms t1,…,tm∈Ht_1, \dots, t_m \in H to those variables. Since M\mathcal{M} satisfies ∀x1⋯∀xm C\forall x_1 \cdots \forall x_m\,C, it particularly satisfies instance C[xi:=ti]C[x_i := t_i] (with values tiMt_i^{\mathcal{M}}), so some literal of that instance is true in M\mathcal{M}, and by construction also in H\mathcal{H}. Since the domain of H\mathcal{H} is exactly HH, this says H⊨∀x1⋯∀xm C\mathcal{H} \models \forall x_1 \cdots \forall x_m\,C.

∎

The proof uses two things worth noticing: clauses are universal (hence Skolemization was needed) and there is no equality (with ==, atom a=ba = b could be true in M\mathcal{M} and the Herbrand interpretation, treating aa and bb as distinct terms, would not respect it; quotienting by a congruence fixes this, as the equality calculi below do).

Proof

Let G(S)G(S) be the set of all ground instances of SS over HH. A Herbrand interpretation satisfies SS if and only if, viewed as a valuation of the base, it satisfies all propositional clauses of G(S)G(S): the final line of the preceding proof. By the previous theorem, SS is unsatisfiable if and only if it has no Herbrand model, that is, if and only if G(S)G(S) is propositionally unsatisfiable. By the compactness theorem of propositional logic (a possibly infinite set is unsatisfiable if and only if some finite subset is), this occurs if and only if some finite subset of G(S)G(S) is unsatisfiable.

∎

This is Herbrand’s theorem in the form used by provers. It suggests an immediate procedure, proposed by Gilmore (1960) and, with a much better propositional algorithm, Davis and Putnam (1960), the direct predecessor of DPLL: for k=0,1,2,…k = 0, 1, 2, \dots, generate all ground instances over HkH_k and pass them to a propositional solver; if they are ever unsatisfiable, stop.

InteractiveHerbrand saturation
1. ama(sk15(V0), V0) ∨ animal(sk14(V0))
2. ¬ama(V0, sk14(V0)) ∨ ama(sk15(V0), V0)
3. ¬ama(V0, V1) ∨ ¬animal(V2) ∨ ¬mata(V1, V2)
4. ama(jack, V0) ∨ ¬animal(V0)
5. mata(curiosidad, tuna) ∨ mata(jack, tuna)
6. gato(tuna)
7. animal(V0) ∨ ¬gato(V0)
8. ¬mata(curiosidad, tuna)
110¹10²10³10⁴level 042level 1·level 2level 3level 4level 5
  • satisfiable instances
  • unsatisfiable: refutation
  • finite, complete universe
Level 0: 42 satisfiable instances. Proceed to the next level.
H₀ (3 terms)
jack, tuna, curiosidad
level 0
Ground terms in HkH_k3
Ground instances42
Level verdictsatisfiable
Each bar is a level kk: its length is the number of ground instances over HkH_k (logarithmic scale), and its color the answer from DPLL on them. Everything is calculated in your browser. With the AIMA problem, contradiction appears at level 1 with 768 instances, and the minimal core extracted by the interactive has only 8: compare them with the resolution refutation below. Try Schubert's steamroller: how many instances are needed at level 1? Then choose satisfiable sets: with a function symbol the procedure can never stop; without functions, the universe ends and it does answer ‘satisfiable’.

Semidecidability

Gilmore’s procedure terminates with “unsatisfiable” exactly when SS is unsatisfiable. If SS is satisfiable and has a function symbol, the universe is infinite, every level is satisfiable and the procedure never stops. This proves part of a central result:

Semidecidability is what you just saw: clausify Γ∪{¬α}\Gamma \cup \{\lnot\alpha\} and saturate by levels. Undecidability is the undecidability of first-order logic seen in computability, by reduction from the halting problem. The practical consequence is that a first-order prover cannot guarantee termination on a false conjecture: silence means nothing. There are decidable islands. The most useful is the Bernays–Schönfinkel class (prefix ∃∗∀∗\exists^*\forall^*, no functions), which after Skolemization has no functions, has a finite Herbrand universe, and is the EPR class recognized and decided by provers, as in the figure’s “no functions” example.

Gilmore quickly bogs down, as the figure shows: Schubert’s steamroller, a lab problem, needs 23,742 ground instances at level 1, while resolution proves it by generating 215 clauses. The flaw is fundamental: the procedure guesses terms (all of HkH_k) instead of calculating which are needed. In AIMA, only 8 of the 768 level-1 instances are needed, and they contain very specific terms, such as sk14(jack)\mathit{sk14}(\mathit{jack}) or sk15(jack)\mathit{sk15}(\mathit{jack}). Robinson’s idea (1965) was never to instantiate more than needed: defer term choice until an inference needs it, then choose the most general possible instance. That operation is unification.

Unification

f(X,g(Y))f(X, g(Y)) and f(h(Z),g(X))f(h(Z), g(X)) have many unifiers: {X↦h(a),Y↦h(a),Z↦a}\{X \mapsto h(a), Y \mapsto h(a), Z \mapsto a\} is one; {X↦h(Z),Y↦h(Z)}\{X \mapsto h(Z), Y \mapsto h(Z)\} is most general, and the former is obtained by composing it with {Z↦a}\{Z \mapsto a\}. The mgu is unique up to variable renaming. Unification calculates that mgu or establishes that none exists.

The Martelli–Montanari algorithm

Robinson gave the first algorithm in 1965, recursive on terms. Martelli and Montanari (1982) reformulated it as a system of rules on an equation set E={s1≐t1,… }E = \{s_1 \doteq t_1, \dots\} transformed until in solved form {x1≐t1,…,xn≐tn}\{x_1 \doteq t_1, \dots, x_n \doteq t_n\}, with distinct xix_i and none appearing in any tjt_j. That solved form, read as a substitution, is the mgu. There are six rules:

RuleIf EE containsReplace with
Delete trivialt≐tt \doteq tnothing
Decomposef(s1,…,sn)≐f(t1,…,tn)f(s_1, \dots, s_n) \doteq f(t_1, \dots, t_n)s1≐t1,…,sn≐tns_1 \doteq t_1, \dots, s_n \doteq t_n
Conflictf(… )≐g(… )f(\dots) \doteq g(\dots) with f≠gf \neq g or different aritiesfailure
Orientt≐xt \doteq x with tt not a variablex≐tx \doteq t
Occursx≐tx \doteq t with xx in tt and t≠xt \neq xfailure
Eliminate variablex≐tx \doteq t with xx not in tt and xx in the rest of EEx≐tx \doteq t and E′{x↦t}E' \{x \mapsto t\} in the rest
Proof

The rules preserve unifiers. Call U(E)U(E) the set of substitutions unifying every equation in EE. Delete trivial, decompose and orient do not change it, since f(s⃗)θ=f(t⃗)θf(\vec s)\theta = f(\vec t)\theta is equivalent to siθ=tiθs_i\theta = t_i\theta for every ii. Nor does variable elimination: if xθ=tθx\theta = t\theta, then uθ=u{x↦t}θu\theta = u\{x \mapsto t\}\theta for every term uu, so θ\theta unifies the rest before substitution if and only if it does afterward. Conflict rightly fails because terms with different heads cannot be made equal by any substitution. So does occurs: if xx occurs strictly inside tt, the size of tθt\theta exceeds that of xθx\theta for every θ\theta.

Termination. Associate with EE the triple (n1,n2,n3)(n_1, n_2, n_3): number of unsolved variables (those appearing in EE without being left side of a solved equation), total symbol count of EE and number of equations t≐xt \doteq x with tt not a variable. Variable elimination solves xx and creates no new variables: it reduces n1n_1. Decomposition and trivial deletion add no variables and remove symbols: they reduce n2n_2 without increasing n1n_1. Orientation leaves n1n_1 and n2n_2 equal and reduces n3n_3. Lexicographic order on N3\N^3 is well founded.

The result is an mgu. When no rule applies and there is no failure, EE is in solved form {xi≐ti}\{x_i \doteq t_i\} and σ={xi↦ti}\sigma = \{x_i \mapsto t_i\} unifies it (xix_i do not appear in tjt_j). If θ∈U(E)\theta \in U(E), then xiθ=tiθ=xiσθx_i\theta = t_i\theta = x_i\sigma\theta, and for other variables yσθ=yθy\sigma\theta = y\theta: hence θ=σθ\theta = \sigma\theta. Since U(E)=U({s≐t})U(E) = U(\{s \doteq t\}), σ\sigma is more general than any unifier of ss and tt.

∎
InteractiveUnification step by step
s = f(X, g(Y))
fXgY
t = f(h(Z), g(X))
fhZgX
start. Start with a system containing one equation.
Pending equations E
f(X, g(Y)) ≐ f(h(Z), g(X))
Solved substitution σ
{ }
Final result: a most general unifier exists.
step 0 / 5
Rulestart
Bindings in σ0
Common instance: tree · distinct subterms6 · 4
Martelli–Montanari on the two terms you enter: the current rule applies to the first equation of E, and its position is highlighted in both trees. Already solved equations x≐tx \doteq t are set aside in substitution σ (the text's solved form, written separately). At the end, the tree of the common instance. With the initial example, go through the steps from the start. Then choose ‘X and f(X)’ and disable the occurs check: what term should X be? Choose ‘Exponential growth’ and compare the two common-instance readings: tree nodes versus distinct subterms.

The occurs check

The occurs rule is most often forgotten and causes most damage. Without it, X≐f(X)X \doteq f(X) is “solved” with X↦f(X)X \mapsto f(X), meaningful only if XX is the infinite term f(f(f(⋯ )))f(f(f(\cdots))). Worse, it produces false proofs. Clauses p(X,X)p(X, X) and ¬p(Y,f(Y))\lnot p(Y, f(Y)) are jointly satisfiable (in the naturals, with pp equality and ff successor: every number equals itself and none equals its successor). Without an occurs check, p(X,X)p(X, X) and p(Y,f(Y))p(Y, f(Y)) “unify” by accepting cyclic binding Y↦f(Y)Y \mapsto f(Y), and resolution derives □\square: an unsound prover. The lab’s unification cell and the interactive below show this with “p(X, X) and p(Y, f(Y))”.

Prolog omits the check by default for efficiency: unifying a variable with a term takes constant instead of linear time. The ISO standard offers unify_with_occurs_check/2 to those needing it, and serious provers, which cannot afford incorrect answers, always perform it.

Cost

The naive recursive algorithm can take exponential time. The classic example is

p(X1,X2,…,Xn)≐p(f(X0,X0),f(X1,X1),…,f(Xn−1,Xn−1)),p(X_1, X_2, \dots, X_n) \doteq p(f(X_0, X_0), f(X_1, X_1), \dots, f(X_{n-1}, X_{n-1})),

whose mgu binds XnX_n to a complete tree of depth nn with 2n+1−12^{n+1} - 1 nodes. If terms are represented as trees, merely writing the result is exponential. With directed acyclic graphs sharing subterms, the same result uses n+1n + 1 nodes: the figure’s “distinct subterms” reading shows this. Paterson and Wegman (1978) gave a linear-time algorithm over that representation, and Martelli and Montanari a practically efficient one based on multiequations. Real provers use shared representations and triangular substitutions (bindings are stored unapplied and followed when read, as in the lab’s unificar), and above all index terms to avoid attempting unifications that will fail.

First-order resolution

With unification, the propositional resolution rule lifts without changing form.

First-order resolution is the calculus with those two rules. Robinson formulated one rule unifying several literals from each premise at once; today’s usual presentation separates it into binary resolution and factoring, equivalent and easier to implement.

Proof

Clauses are universally quantified, so M\mathcal{M} also satisfies their instances (C∨L)σ(C \lor L)\sigma and (D∨¬L′)σ(D \lor \lnot L')\sigma, in which Lσ=L′σL\sigma = L'\sigma. For each variable assignment, either LσL\sigma is true and some literal of DσD\sigma is true, or it is false and some literal of CσC\sigma is true. Factoring is an instance of its premise with two literals merged. □\square has no models.

∎

The two conditions in the definition are not details: without either, the calculus ceases to be complete.

  • Rename variables. p(X)p(X) and ¬p(f(X))\lnot p(f(X)) form an unsatisfiable set (the first says everything satisfies pp; the second, nothing of form f(⋅)f(\cdot) does). But without separating variables one must unify p(X)p(X) with p(f(X))p(f(X)), prevented by the occurs check. Renaming the second to ¬p(f(X′))\lnot p(f(X')), mgu {X↦f(X′)}\{X \mapsto f(X')\} yields □\square in one step. The XX of one clause and another’s are distinct variables because each clause has its own ∀\forall.
  • Factor. {p(X)∨p(Y), ¬p(U)∨¬p(V)}\{p(X) \lor p(Y),\ \lnot p(U) \lor \lnot p(V)\} is unsatisfiable (the first implies ∀x p(x)\forall x\,p(x) and the second ∀x ¬p(x)\forall x\,\lnot p(x)). But every binary resolvent between two-literal clauses has two literals: □\square never appears. Factoring the first into p(X)p(X) and the second into ¬p(U)\lnot p(U) produces it in one step. The lab saturates the set without factoring and checks this: it stays with two-literal clauses.

Refutational completeness

The argument has two parts and is the model for almost all completeness proofs in automated deduction.

  1. Ground level. By Herbrand’s theorem, some finite set GG of ground instances of SS is propositionally unsatisfiable. By completeness of propositional resolution, there is a refutation of GG.
  2. Lifting lemma. If C′C' and D′D' are instances of CC and DD, and R′R' is a propositional resolvent of C′C' and D′D', then there is a resolvent RR of CC and DD (perhaps after factoring either) of which R′R' is an instance. The reason: the literal resolved upon in C′C' comes from one or more literals of CC made equal by instantiation; a factor of CC merges them, and the resolution mgu is more general than the substitution producing C′C' and D′D', so that substitution factors through it.

Applying the lemma step by step to the ground refutation, from leaves to root, yields a first-order refutation of which the ground one is an instance; and the only clause of which □\square is an instance is □\square. Notice each condition’s role: renaming allows CC and DD to be instantiated independently, as at ground level, and factoring is necessary because a ground instance can merge literals distinct in CC.

InteractiveBuild the refutation
  • axiom
  • negated conjecture
  • resolvent
  • factor
Resolve 8 with 4 (variables of the second have a prime):
Derived steps0
Clauses8
Statusnot yet refuted
Click two clauses (the second clause's variables are primed during resolution) and choose the literal pair: see the unifier and resolvent, or why the step is invalid. Initially the negated conjecture and access-control read rule are selected: add that resolvent and continue to the empty clause, which draws the refutation tree. Try the AIMA base (you will need a resolvent whose two literals coincide after substitution), ‘Factoring needed’ (can you reach □ without factoring?) and ‘Renaming needed’ with the ‘Rename variables’ switch off and on. You can edit the base: remove the template's permission and ask the prover for the proof.

There is a delicate moment in the AIMA base. Resolving ama(jack,X)∨¬animal(X)\mathit{ama}(\mathit{jack}, X) \lor \lnot\mathit{animal}(X) with ¬ama(Y,F(Y))∨ama(G(Y),Y)\lnot\mathit{ama}(Y, F(Y)) \lor \mathit{ama}(G(Y), Y) and then with animal(F(Y))∨ama(G(Y),Y)\mathit{animal}(F(Y)) \lor \mathit{ama}(G(Y), Y) produces ama(G(jack),jack)∨ama(G(jack),jack)\mathit{ama}(G(\mathit{jack}), \mathit{jack}) \lor \mathit{ama}(G(\mathit{jack}), \mathit{jack}): the same literal twice, a single literal as a set. This is “trivial” factoring (with the empty unifier), always done when clauses are treated as sets. The result is exactly instance sk15(jack)\mathit{sk15}(\mathit{jack}) that appeared in the Herbrand core: resolution found on its own the terms Gilmore had to guess.

Strategies and the given-clause loop

Completeness is not efficiency. Brute-force saturation (all resolvents of all pairs, repeatedly) generates enormous amounts of useless clauses. Three families of ideas control this, and all three have completeness traps.

Restrict inferences.

  • Set of support (Wos, Robinson and Carson, 1965): divide SS into axioms AA and a support TT (usually the negated conjecture), and forbid resolving two clauses not descended from TT. If AA is satisfiable, it remains complete: the contradiction must pass through TT. This focuses search on the conjecture instead of exploring consequences of axioms.
  • Ordered resolution with selection (Bachmair and Ganzinger, in the Handbook of Automated Reasoning, 2001): resolve only on certain literals of each clause. A selection function may choose a negative literal of each clause having one; then that clause resolves only on it, and clauses without negative literals only on maximal literals for a fixed term order. Selecting all negatives gives Robinson’s positive resolution. The lab version selects the heaviest negative literal and leaves all literals of positive clauses eligible (equivalent to an empty order, which only adds inferences relative to any admissible order), and factors only positive clauses. It is complete and prunes heavily: with one selected literal, the steamroller’s 8-literal clause resolves on one instead of eight.

Delete redundancy. A clause is a tautology if it contains LL and ¬L\lnot L: it adds nothing. Clause CC subsumes DD if Cσ⊆DC\sigma \subseteq D for some σ\sigma (as literal sets) and CC has no more literals than DD: then DD follows from CC and is weaker, so it can be deleted. Forward subsumption discards new clauses subsumed by old ones; backward subsumption, old clauses subsumed by a new one. The size condition is not cosmetic: p(X)∨p(Y)p(X) \lor p(Y) subsumes p(Z)p(Z) as a set (with X,Y↦ZX, Y \mapsto Z), its own factor; if allowed, factoring would be useless and completeness lost.

Order the search. This is the given-clause loop.

The loop

The given-clause algorithm, popularized by William McCune’s Otter prover and used with variations by E and Vampire, maintains two lists:

  • Processed PP: clauses that have already made all inferences among themselves.
  • Pending UU: generated clauses not yet involved in any inference.

Initially everything is in UU (or, with set of support, axioms in PP and the negated conjecture in UU). Each iteration:

  1. Choose the given clause GG from UU using a heuristic.
  2. If one of PP subsumes GG, discard it and return to 1. Otherwise delete from PP those subsumed by GG.
  3. Move GG to PP and generate all inferences between GG and clauses of PP (including itself), and factors of GG.
  4. For each new clause: if □\square, finish with a proof; if a tautology or subsumed by one of PP, discard it; otherwise add it to UU.

If UU empties without □\square, the set is saturated: with a complete calculus this proves satisfiability. The key invariant is that all inferences between clauses in PP have already been made, avoiding repeated work. There are two variants: in Otter, pending clauses also simplify and subsume new ones; in DISCOUNT (Denzinger, Kronenburg and Schulz, 1997), used by E, pending clauses are passive and only processed ones are used, saving memory and time when UU grows to millions of clauses. The lab implements the latter.

Selection heuristic. Selecting by age (oldest) is fair: every clause is eventually selected, so with a complete calculus the loop is complete, but searches breadth-first and gets lost. Selecting by weight (symbol count, shortest) pursues small clauses, which approach □\square and subsume the most. With a finite signature it is also theoretically fair, since up to renaming only finitely many clauses have each weight; but that number grows quickly, and a needed heavy clause can wait many iterations. Common practice mixes them: Otter calls it pick_given_ratio, and value 4 selects four by weight and one by age, so the oldest pending clause never waits more than five selections. Vampire adds its limited-resource strategy (Riazanov and Voronkov, 2003): near the time limit it discards clauses it estimates it can no longer process.

InteractiveThe given-clause loop
Empty clause after 169 given clauses: the proof uses 65 clauses.
Given clause (round 1)
[1] lobo(sk31) · weight 2
New this round (0)
no inference possible with the processed clauses
Next pending, ordered by weight
[3] zorro(sk33) · weight 2
[5] ave(sk35) · weight 2
[7] oruga(sk37) · weight 2
[9] caracol(sk39) · weight 2
[10] grano(sk40) · weight 2
[0] animal(V0) ∨ ¬lobo(V0) · weight 4
[2] animal(V0) ∨ ¬zorro(V0) · weight 4
[4] animal(V0) ∨ ¬ave(V0) · weight 4
… and 17 more
  • processed
  • pending
  • generated
With these refinements, the three choices (budget: 1500 generated):
choiceresultgivengeneratedweightproof169215mixed 4:1proof216296ageproof10301478
  • kept
  • discarded (subsumed or tautology)
  • given clause
given 1 / 169
Choose by
Given · generated1 · 0
Kept · subsumed0 · 0
Processed · pending1 · 25
The lab loop runs in your browser with the same rules and tie-breaks (totals match the cell table). Top: current iteration's given clause; left: what it generates (discarded items crossed out); right: pending clauses in selection order; bottom: list sizes. Start with the already-solved steamroller by weight and traverse from the beginning. Switch to age and compare the table below. Disable negative selection (unrestricted binary resolution), then enable it together with set of support: what does the prover answer and why should you not believe it? Finish with the false conjecture about an order without a minimum.

The lab quantifies what the figure shows on Schubert’s steamroller (26 clauses, largest with 8 literals). With negative selection, weight finds the proof with 169 given and 215 generated clauses; the 4:1 mix, with 216 and 296; age, with 1030 and 1478. Without selection, with a budget of 1500 generated clauses, none succeeds. The steamroller has a history because unrefined resolution provers stalled on it: Walther (1984) solved it with many-sorted resolution, avoiding inferences between incompatible object classes; Stickel (1986) later collected formulations and solutions, and Pelletier included it as problem 47 in his collection of 75 test problems (1986).

Equality on one page

Nearly all mathematics, and much verification, needs equality. Treating it as another predicate requires adding its axioms: reflexivity, symmetry, transitivity and, for every function and predicate symbol, congruence (x=y→f(x)=f(y)x = y \to f(x) = f(y), x=y∧p(x)→p(y)x = y \land p(x) \to p(y)). It is sound and complete, and disastrous in practice: transitivity and congruences resolve with almost everything.

The alternative is a special rule. Paramodulation (Robinson and Wos, 1969) uses equality to rewrite within another clause: from C∨s=tC \lor s = t and D[u]D[u], with uu a subterm unifiable with ss via σ\sigma, derive (C∨D[t])σ(C \lor D[t])\sigma. It is still very prolific because it rewrites both directions at any position. Superposition (Bachmair and Ganzinger, 1994) restricts it with a term reduction ordering, such as Knuth–Bendix or lexicographic path ordering: rewrite only a larger term to a smaller one, only in maximal literals and never inside variables. It is complete and at the heart of E, Vampire and SPASS. With it comes demodulation: oriented equalities act as rewrite rules simplifying all clauses, and a unit equality such as x+0=xx + 0 = x eliminates a whole family of clauses at once.

The best-known success is the Robbins conjecture, open since the 1930s: are all Robbins algebras Boolean? McCune’s EQP prover, based on associative and commutative paramodulation, found the proof in 1996 (McCune, Solution of the Robbins problem, Journal of Automated Reasoning, 1997). In the SMT solvers of lesson 13, quantifier-free equality is decided with congruence closure, much cheaper; superposition is needed when equality occurs under quantifiers.

Automated provers and proof assistants

First-order automated provers (Vampire, E, Prover9, SPASS, iProver) receive a problem in a standard format, Sutcliffe’s TPTP, and return a proof or give up. They compete annually in CASC, and all saturation engines use what you just built: clausal form, unification, resolution or superposition, subsumption and a given-clause loop with heuristics, term indexing and, in Vampire, a portfolio of strategies tried in turns with allocated time (Kovács and Voronkov, 2013). Their strength is search: they find lemma combinations in seconds that would take a person time to see. Their limits are semidecidability and combinatorial explosion: they do not reason well by induction, invent auxiliary definitions or handle problems whose proofs are long and conceptual.

Proof assistants (Lean, Isabelle, Coq, now Rocq), seen in discrete mathematics’ proof assistants, reverse the division. A person writes the proof structure and a small kernel checks each step in a much more expressive logic (higher order, dependent types, induction). Automation comes through tactics: simp rewrites, omega decides integer linear arithmetic, aesop searches for proofs, decide evaluates. The bridge is hammers: Isabelle’s Sledgehammer translates the goal and hundreds of relevant lemmas to first order, calls E, Vampire or SMT solvers, and using the list of lemmas used, reconstructs the proof inside Isabelle with Metis, a resolution prover whose inferences the kernel checks. Thus an external program that need not be trusted does the search, and the kernel verifies. Lean 4 tools in the same direction include Duper, a superposition prover producing Lean proof terms.

The current frontier combines both with learning: models choosing the given clause or relevant lemmas, and language models proposing tactics checked by an assistant. You will see this in learning-guided theorem proving in the topic’s last lesson, and language-model-based automated theorem proving. If you keep to this lesson’s Horn part (clauses with one positive literal, like all access-control clauses), the next lesson, logic programming, turns it into a programming language: Prolog’s SLD resolution is resolution with selection on Horn clauses and depth-first search.

Lab: a resolution prover from scratch

We will build all of the above in about four hundred lines of Python: terms and unification, clausal form, resolution with factoring and subsumption, and the given-clause loop. Terms are tuples: a variable is a string beginning with a capital letter ('X') and a compound term or constant is a tuple with the symbol and arguments (('f', 'X', ('a',))).

[ ]Terms and unification with an occurs checkBrowser
# Términos como tuplas: una variable es un str que empieza por mayúscula ('X', 'Y1');
# una constante o un término compuesto es una tupla (símbolo, arg1, ..., argn): ('a',), ('f', 'X', ('a',)).
def es_var(t):
    return isinstance(t, str)

def resolver(t, s):
    """Sigue la cadena de ligaduras de una variable en la sustitución triangular s."""
    while es_var(t) and t in s:
        t = s[t]
    return t

def aparece(v, t, s):
    """Comprobación de ocurrencia: ¿aparece la variable v en t (bajo s)?"""
    t = resolver(t, s)
    if es_var(t):
        return t == v
    return any(aparece(v, a, s) for a in t[1:])

def unificar(a, b, s=None, ocurrencia=True):
    """Extiende s hasta unificar a y b. Devuelve la sustitución (triangular) o None."""
    s = dict(s or {})
    pendientes = [(a, b)]
    while pendientes:
        x, y = pendientes.pop()
        x, y = resolver(x, s), resolver(y, s)
        if x == y:
            continue                                   # eliminar ecuación trivial
        if es_var(x) or es_var(y):
            if not es_var(x):
                x, y = y, x                            # orientar: variable a la izquierda
            if ocurrencia and aparece(x, y, s):
                return None                            # X = f(... X ...): no hay unificador
            s[x] = y                                   # eliminar variable
        elif x[0] != y[0] or len(x) != len(y):
            return None                                # conflicto de símbolos
        else:
            pendientes.extend(zip(x[1:], y[1:]))       # descomponer
    return s

def aplicar(t, s):
    t = resolver(t, s)
    if es_var(t):
        return t
    return (t[0],) + tuple(aplicar(a, s) for a in t[1:])

def renombrar_t(t, ren):
    """Sustitución simultánea de un solo paso (para renombrar variables: no encadena)."""
    if es_var(t):
        return ren.get(t, t)
    return (t[0],) + tuple(renombrar_t(a, ren) for a in t[1:])

def texto(t):
    if es_var(t):
        return t
    return t[0] if len(t) == 1 else f"{t[0]}({', '.join(texto(a) for a in t[1:])})"

def mgu(a, b, ocurrencia=True):
    s = unificar(a, b, ocurrencia=ocurrencia)
    if s is None:
        return None
    return {v: texto(aplicar(v, s)) for v in s}        # forma resuelta (idempotente)

t1, t2 = ('f', 'X', ('g', 'Y')), ('f', ('h', 'Z'), ('g', 'X'))
print(texto(t1), "=", texto(t2), "  mgu:", mgu(t1, t2))
print("X = f(X):", mgu('X', ('f', 'X')), "   sin comprobación:", unificar('X', ('f', 'X'), ocurrencia=False))
# (aplicar esa sustitución a X no termina: X -> f(X) -> f(f(X)) -> ...)
print("f(a, X) = g(Y):", mgu(('f', ('a',), 'X'), ('g', 'Y')))

# Sin comprobación de ocurrencia, una «prueba» falsa: p(X, X) y ¬p(Y, f(Y)) no son contradictorias
# (en los naturales, con p la igualdad y f el sucesor, las dos son ciertas), pero se «unifican».
s = unificar(('p', 'X', 'X'), ('p', 'Y', ('f', 'Y')), ocurrencia=False)
print("p(X,X) frente a p(Y,f(Y)) sin comprobación:", s, " ¿ciclo? Y ->", s.get('Y'))

# Términos que crecen exponencialmente: p(X1..Xn) = p(f(X0,X0), ..., f(X_{n-1},X_{n-1}))
def tam(t):
    return 1 if es_var(t) else 1 + sum(tam(a) for a in t[1:])
for n in (5, 10, 15):
    izq = ('p',) + tuple(f'X{i}' for i in range(1, n + 1))
    der = ('p',) + tuple(('f', f'X{i}', f'X{i}') for i in range(n))
    s = unificar(izq, der)
    print(f"n = {n:2d}: {len(s)} ligaduras; tamaño de X{n} aplicado: {tam(aplicar(f'X{n}', s))} nodos")

unificar is Robinson’s version with triangular substitution: it stores X↦YX \mapsto Y and Y↦f(Z)Y \mapsto f(Z) without composing them, and resolver follows the chain when reading. It is the same logic as Martelli–Montanari (each branch is one of its rules, commented alongside) without the cost of substituting into every equation at every step. The output confirms three things: the example’s mgu binds XX and YY to h(Z)h(Z); without an occurs check Y↦f(Y)Y \mapsto f(Y) is accepted; and in the exponential family there are only nn bindings, but the applied term has 2n+1−12^{n+1} - 1 nodes (65535 with n=15n = 15). Triangular representation avoids writing it.

Now clausal form. The parser reads TPTP’s FOF syntax (~, &, |, =>, <=>, ![X]: for all, ?[X]: exists), as real provers do.

[ ]Clausal form: NNF, Skolemization and CNFBrowser
import re

# Sintaxis FOF de TPTP: ~ & | => <=>, ![X,Y]: (para todo), ?[X]: (existe).
# Variables en mayúscula; constantes, funciones y predicados en minúscula.
TOKEN = re.compile(r"\s*(<=>|=>|[()\[\],:~&|!?]|[A-Za-z_][A-Za-z0-9_]*)")

def parsear(texto_formula):
    tk, pos, s = [], 0, texto_formula.strip()
    while pos < len(s):
        m = TOKEN.match(s, pos)
        if not m:
            raise SyntaxError(f"no entiendo {s[pos:pos + 12]!r}")
        tk.append(m.group(1))
        pos = m.end()
    i = 0
    def mira():
        return tk[i] if i < len(tk) else None
    def toma(esperado=None):
        nonlocal i
        t = tk[i]
        if esperado and t != esperado:
            raise SyntaxError(f"esperaba {esperado!r} y encontré {t!r}")
        i += 1
        return t
    def termino():
        nombre = toma()
        if mira() != '(':
            return nombre if nombre[0].isupper() else (nombre,)
        toma('(')
        args = [termino()]
        while mira() == ',':
            toma(',')
            args.append(termino())
        toma(')')
        return (nombre, *args)
    def unitaria():
        t = mira()
        if t == '~':
            toma()
            return ('no', unitaria())
        if t in ('!', '?'):
            toma(); toma('[')
            vs = [toma()]
            while mira() == ',':
                toma(',')
                vs.append(toma())
            toma(']'); toma(':')
            f = unitaria()
            for v in reversed(vs):
                f = ('todo' if t == '!' else 'existe', v, f)
            return f
        if t == '(':
            toma('(')
            f = binaria()
            toma(')')
            return f
        return ('atomo', termino())
    def binaria():
        f = unitaria()
        op = mira()
        if op in ('&', '|'):
            while mira() == op:
                toma()
                f = ('y' if op == '&' else 'o', f, unitaria())
        elif op in ('=>', '<=>'):
            toma()
            f = ('implica' if op == '=>' else 'equivale', f, unitaria())
        return f
    f = binaria()
    if i != len(tk):
        raise SyntaxError(f"sobra {' '.join(tk[i:])}")
    return f

def fnn(f, positiva=True):
    """Forma normal negativa: sin => ni <=>, y negaciones solo delante de átomos."""
    k = f[0]
    if k == 'atomo':
        return f if positiva else ('no', f)
    if k == 'no':
        return fnn(f[1], not positiva)
    if k == 'implica':
        return fnn(('o', ('no', f[1]), f[2]), positiva)
    if k == 'equivale':
        return fnn(('y', ('implica', f[1], f[2]), ('implica', f[2], f[1])), positiva)
    if k in ('y', 'o'):
        op = k if positiva else {'y': 'o', 'o': 'y'}[k]
        return (op, fnn(f[1], positiva), fnn(f[2], positiva))
    q = k if positiva else {'todo': 'existe', 'existe': 'todo'}[k]   # ¬∀ = ∃¬ y ¬∃ = ∀¬
    return (q, f[1], fnn(f[2], positiva))

contador = [0]
def nuevo(prefijo):
    contador[0] += 1
    return f"{prefijo}{contador[0]}"

def skolemizar(f, universales=(), ren=None):
    """Sobre la FNN: renombra cada variable ligada y cambia cada ∃ por un término de Skolem
    cuyos argumentos son las variables universales en cuyo alcance está."""
    ren = ren or {}
    k = f[0]
    if k == 'atomo':
        return ('atomo', renombrar_t(f[1], ren))
    if k == 'no':
        return ('no', skolemizar(f[1], universales, ren))
    if k in ('y', 'o'):
        return (k, skolemizar(f[1], universales, ren), skolemizar(f[2], universales, ren))
    if k == 'todo':
        v = nuevo('X')
        return skolemizar(f[2], universales + (v,), {**ren, f[1]: v})
    termino_skolem = (nuevo('sk'),) + universales          # k = 'existe'
    return skolemizar(f[2], universales, {**ren, f[1]: termino_skolem})

def fnc(f):
    """Fórmula sin cuantificadores en FNN -> lista de cláusulas (listas de literales (signo, átomo))."""
    k = f[0]
    if k == 'atomo':
        return [[(True, f[1])]]
    if k == 'no':
        return [[(False, f[1][1])]]
    if k == 'y':
        return fnc(f[1]) + fnc(f[2])
    return [a + b for a in fnc(f[1]) for b in fnc(f[2])]   # distributividad de ∨ sobre ∧

def variables(t, acc):
    if es_var(t):
        if t not in acc:
            acc.append(t)
    else:
        for a in t[1:]:
            variables(a, acc)
    return acc

def normalizar(literales, s=None):
    """Aplica s, quita literales repetidos, ordena y renombra las variables a V0, V1, ..."""
    s = s or {}
    clave = lambda l: (texto(l[1]), l[0])
    lits = sorted({(sg, aplicar(a, s)) for sg, a in literales}, key=clave)
    vs = []
    for _, a in lits:
        variables(a, vs)
    ren = {v: f"V{i}" for i, v in enumerate(vs)}
    return tuple(sorted(((sg, renombrar_t(a, ren)) for sg, a in lits), key=clave))

def tautologia(C):
    return any((not sg, a) in C for sg, a in C)

def clausular(formula, conjetura=False):
    f = parsear(formula)
    if conjetura:
        f = ('no', f)                                      # refutación: se niega la conjetura
    cls = [normalizar(c) for c in fnc(skolemizar(fnn(f)))]
    return [c for c in dict.fromkeys(cls) if not tautologia(c)]

def texto_clausula(C):
    return ' ∨ '.join(('' if sg else '¬') + texto(a) for sg, a in C) if C else '□'

# El problema de AIMA: ¿mató Curiosidad al gato Tuna?
CURIOSIDAD = [
    "![X]: ((![Y]: (animal(Y) => ama(X, Y))) => (?[Y]: ama(Y, X)))",   # quien ama a todos los animales es amado por alguien
    "![X]: ((?[Z]: (animal(Z) & mata(X, Z))) => (![Y]: ~ama(Y, X)))",  # quien mata a un animal no es amado por nadie
    "![X]: (animal(X) => ama(jack, X))",                                # Jack ama a todos los animales
    "mata(jack, tuna) | mata(curiosidad, tuna)",
    "gato(tuna)",
    "![X]: (gato(X) => animal(X))",
]
CONJETURA_CURIOSIDAD = "mata(curiosidad, tuna)"

for f in CURIOSIDAD + [CONJETURA_CURIOSIDAD]:
    cls = clausular(f, conjetura=(f == CONJETURA_CURIOSIDAD))
    print(f"{f}\n    -> " + "\n    -> ".join(texto_clausula(c) for c in cls))

# El error típico: Skolem sin argumentos. ∀x ∃y ama(y, x) («todos tienen a alguien que los ama»)
# NO es lo mismo que ama(c, x) («hay uno que ama a todos»).
print("\ncorrecta:", [texto_clausula(c) for c in clausular("![X]: ?[Y]: ama(Y, X)")])
print("otro orden:", [texto_clausula(c) for c in clausular("?[Y]: ![X]: ama(Y, X)")])

Skolemization works directly on NNF, without prenex form: it carries the list of universals whose scope contains the current formula, exactly the Skolem term arguments. The first sentence gives the two clauses of the derivation above; the second, ¬ama(V0,V1)∨¬animal(V2)∨¬mata(V1,V2)\lnot\mathit{ama}(V_0, V_1) \lor \lnot\mathit{animal}(V_2) \lor \lnot\mathit{mata}(V_1, V_2), without Skolem functions, because its ∃z\exists z is in an implication antecedent and becomes universal. The last two lines distinguish quantifier orders: ∀∃\forall\exists gives a function of XX; ∃∀\exists\forall, a constant.

Now resolution, factoring and subsumption.

[ ]Binary resolution, factoring and subsumptionBrowser
def renombrar(C, sufijo):
    """Variables nuevas para C: las de cada cláusula son independientes (separar variables)."""
    vs = []
    for _, a in C:
        variables(a, vs)
    ren = {v: v + sufijo for v in vs}
    return tuple((sg, renombrar_t(a, ren)) for sg, a in C)

from functools import lru_cache

@lru_cache(maxsize=None)
def elegibles(C, seleccion):
    """Índices de los literales sobre los que se puede resolver. Con selección negativa,
    si C tiene literales negativos solo cuenta uno (el de más peso); si no, todos."""
    if seleccion:
        negativos = [i for i, (sg, _) in enumerate(C) if not sg]
        if negativos:
            return (max(negativos, key=lambda i: (peso_t(C[i][1]), -i)),)
    return tuple(range(len(C)))

def resolventes(C, D, seleccion=False):
    """Todas las resolventes binarias de C y D (D con variables renombradas)."""
    pares = [(i, j) for i in elegibles(C, seleccion) for j in elegibles(D, seleccion)
             if C[i][0] != D[j][0] and C[i][1][0] == D[j][1][0]]   # signos opuestos, mismo predicado
    if not pares:
        return
    D = renombrar(D, "'")
    for i, j in pares:
        s = unificar(C[i][1], D[j][1])
        if s is not None:
            yield normalizar(C[:i] + C[i + 1:] + D[:j] + D[j + 1:], s)

def factores(C, seleccion=False):
    """Factores de C: unifica dos literales del mismo signo y quita uno."""
    if seleccion and any(not sg for sg, _ in C):
        return                                  # con selección solo se factorizan las positivas
    for i in range(len(C)):
        for j in range(i + 1, len(C)):
            (si, ai), (sj, aj) = C[i], C[j]
            if si == sj and ai[0] == aj[0]:
                s = unificar(ai, aj)
                if s is not None:
                    yield normalizar(C[:j] + C[j + 1:], s)

def encajar(p, t, s):
    """Emparejamiento: liga solo las variables del patrón p; las de t son constantes."""
    if es_var(p):
        if p in s:
            return s if s[p] == t else None
        return {**s, p: t}
    if es_var(t) or p[0] != t[0] or len(p) != len(t):
        return None
    for a, b in zip(p[1:], t[1:]):
        s = encajar(a, b, s)
        if s is None:
            return None
    return s

@lru_cache(maxsize=None)
def firma(C):
    return frozenset((sg, a[0]) for sg, a in C)

def subsume(C, D):
    """C subsume a D si Cσ ⊆ D para alguna σ y C no tiene más literales que D."""
    if len(C) > len(D) or not firma(C) <= firma(D):
        return False                            # filtro barato: signos y predicados
    def busca(i, s):
        if i == len(C):
            return True
        sc, ac = C[i]
        for sd, ad in D:
            if sc == sd and ac[0] == ad[0]:
                s2 = encajar(ac, ad, s)
                if s2 is not None and busca(i + 1, s2):
                    return True
        return False
    return busca(0, {})

def peso_t(t):
    return 1 if es_var(t) else 1 + sum(peso_t(a) for a in t[1:])

def peso(C):
    return sum(peso_t(a) for _, a in C)

cl = lambda s: normalizar([(not l.strip().startswith('~'), parsear(l.strip().lstrip('~'))[1])
                           for l in s.split('|')])

# 1. Sin renombrar, p(X) y ¬p(f(X)) no resuelven (X = f(X) falla); renombrando, sí.
C, D = cl("p(X)"), cl("~p(f(X))")
print("sin renombrar:", unificar(C[0][1], D[0][1]), "  renombrando:", [texto_clausula(r) for r in resolventes(C, D)])

# 2. La factorización es necesaria: {p(X) ∨ p(Y), ¬p(U) ∨ ¬p(V)} es insatisfacible...
A, B = cl("p(X) | p(Y)"), cl("~p(U) | ~p(V)")
def saturar(clausulas, con_factores, maximo=60):
    S = list(dict.fromkeys(clausulas))
    nuevas = True
    while nuevas and len(S) < maximo:
        nuevas = False
        for C in list(S):
            hijos = [R for D in list(S) for R in resolventes(C, D)]
            if con_factores:
                hijos += list(factores(C))
            for R in hijos:
                if not tautologia(R) and not any(subsume(E, R) for E in S):
                    S.append(R); nuevas = True
                    if not R:
                        return S
    return S
for con in (False, True):
    S = saturar([A, B], con)
    print(f"factorización={con}: {len(S)} cláusulas, ¿vacía? {() in S}, tamaños {sorted({len(c) for c in S})}")

# 3. Subsunción: p(X) ∨ p(Y) «subsume como conjunto» a su propio factor p(X), pero no cuenta:
print("p(X)∨p(Y) subsume a p(Z)?", subsume(A, cl("p(Z)")), "  p(Z) subsume a p(a) ∨ q(b)?", subsume(cl("p(Z)"), cl("p(a) | q(b)")))

The three checks reproduce the resolution section’s arguments. Without renaming, p(X)p(X) and p(f(X))p(f(X)) do not unify; renaming yields □\square. Without factoring, saturation of {p(X)∨p(Y),¬p(U)∨¬p(V)}\{p(X) \lor p(Y), \lnot p(U) \lor \lnot p(V)\} ends with 2 clauses, all two-literal and without □\square: a saturated unsatisfiable set, concrete proof that the calculus without factoring is incomplete. With factoring □\square appears. Subsumption respects the size condition.

The given-clause loop, with three selection heuristics and refinements as options:

[ ]The given-clause loopBrowser
import heapq
from collections import Counter

def demostrar(axiomas, negadas, eleccion='peso', proporcion=4, soporte=False, seleccion=True,
              subsuncion=True, max_generadas=5000):
    """Bucle de la cláusula dada (variante DISCOUNT). Devuelve (prueba o None, estadísticas, motivo)."""
    info = []                         # id -> (cláusula, padres)
    procesadas = []
    por_peso, por_edad, vivas = [], [], set()
    st = Counter()
    def pendiente(C, padres):
        info.append((C, padres)); cid = len(info) - 1
        vivas.add(cid)
        heapq.heappush(por_peso, (peso(C), cid))
        heapq.heappush(por_edad, cid)
    for C in axiomas:
        if soporte:                   # conjunto de soporte: los axiomas no se resuelven entre sí
            info.append((C, 'axioma')); procesadas.append(len(info) - 1)
        else:
            pendiente(C, 'axioma')
    for C in negadas:
        pendiente(C, 'conjetura negada')
    n = 0
    while vivas:
        if st['generadas'] >= max_generadas:
            return None, st, 'presupuesto agotado'
        por_edad_ahora = eleccion == 'edad' or (eleccion == 'mixta' and n % (proporcion + 1) == proporcion)
        cola = por_edad if por_edad_ahora else por_peso
        while True:
            x = heapq.heappop(cola)
            cid = x if por_edad_ahora else x[1]
            if cid in vivas:
                break
        vivas.discard(cid); n += 1
        G = info[cid][0]
        if subsuncion and any(subsume(info[p][0], G) for p in procesadas):
            st['subsumidas'] += 1
            continue
        st['dadas'] += 1
        if subsuncion:                # subsunción hacia atrás: G elimina procesadas más débiles
            quedan = [p for p in procesadas if not subsume(G, info[p][0])]
            st['eliminadas'] += len(procesadas) - len(quedan)
            procesadas = quedan
        procesadas.append(cid)
        hijos = [(F, (cid,)) for F in factores(G, seleccion)]
        for p in procesadas:
            hijos += [(R, (cid, p)) for R in resolventes(G, info[p][0], seleccion)]
        for R, padres in hijos:
            st['generadas'] += 1
            if not R:
                info.append((R, padres))
                return (len(info) - 1, info), st, 'refutación'
            if tautologia(R):
                st['tautologías'] += 1
            elif subsuncion and any(subsume(info[p][0], R) for p in procesadas):
                st['subsumidas'] += 1
            else:
                st['retenidas'] += 1
                pendiente(R, padres)
    return None, st, 'saturado sin cláusula vacía'

def imprimir_prueba(prueba):
    cid, info = prueba
    usados, pila = [], [cid]
    while pila:
        c = pila.pop()
        if c in usados:
            continue
        usados.append(c)
        if isinstance(info[c][1], tuple):
            pila.extend(info[c][1])
    for c in sorted(usados):
        C, padres = info[c]
        origen = padres if isinstance(padres, str) else 'de ' + ', '.join(f'[{p}]' for p in padres)
        print(f"  [{c}] {texto_clausula(C):55s} {origen}")
    return len(usados)

def clausular_problema(axiomas, conjetura):
    return [c for f in axiomas for c in clausular(f)], clausular(conjetura, conjetura=True)

ax, neg = clausular_problema(CURIOSIDAD, CONJETURA_CURIOSIDAD)
prueba, st, motivo = demostrar(ax, neg)
print(motivo, dict(st))
print("cláusulas en la prueba:", imprimir_prueba(prueba))

ACCESO = [
    "miembro(ana, desarrollo)",
    "hereda(desarrollo, plantilla)",
    "![U, G, H]: ((miembro(U, G) & hereda(G, H)) => miembro(U, H))",
    "![U, G, R]: ((miembro(U, G) & permiso(G, R)) => puede_leer(U, R))",
    "![G, R, D]: ((permiso(G, D) & dentro(R, D)) => permiso(G, R))",
    "permiso(plantilla, documentos)",
    "dentro(informe, documentos)",
]
ax2, neg2 = clausular_problema(ACCESO, "puede_leer(ana, informe)")
prueba, st, motivo = demostrar(ax2, neg2)
print("\ncontrol de accesos:", motivo, dict(st))
print("cláusulas en la prueba:", imprimir_prueba(prueba))
# Sin el permiso de la plantilla la conjetura es falsa y el conjunto se satura
prueba, st, motivo = demostrar([c for c in ax2 if 'plantilla' not in texto_clausula(c) or 'hereda' in texto_clausula(c)], neg2)
print("sin permiso(plantilla, documentos):", motivo, dict(st))

The AIMA proof uses 15 clauses: the 8 starting ones and 7 resolvents, the same found by hand in the refutation figure, and the loop finds it generating only 12 clauses. Access control works too: 7 resolvents chain group and permission inheritance. Without fact permiso(plantilla, documentos) the conjecture no longer follows, and as the problem has no functions (not even Skolem functions), the loop saturates: with complete negative selection, this proves the conjecture does not follow.

[ ]Schubert’s steamroller: refinements and heuristicsBrowser
import time

APISONADORA = [
    "![X]: (lobo(X) => animal(X))", "?[X]: lobo(X)",
    "![X]: (zorro(X) => animal(X))", "?[X]: zorro(X)",
    "![X]: (ave(X) => animal(X))", "?[X]: ave(X)",
    "![X]: (oruga(X) => animal(X))", "?[X]: oruga(X)",
    "![X]: (caracol(X) => animal(X))", "?[X]: caracol(X)",
    "?[X]: grano(X)", "![X]: (grano(X) => planta(X))",
    # todo animal come todas las plantas, o come todos los animales mucho menores que él que comen alguna planta
    "![X]: (animal(X) => ((![Y]: (planta(Y) => come(X, Y))) | (![Y]: ((animal(Y) & menor(Y, X) & (?[Z]: (planta(Z) & come(Y, Z)))) => come(X, Y)))))",
    "![X, Y]: ((ave(Y) & (caracol(X) | oruga(X))) => menor(X, Y))",
    "![X, Y]: ((ave(X) & zorro(Y)) => menor(X, Y))",
    "![X, Y]: ((zorro(X) & lobo(Y)) => menor(X, Y))",
    "![X, Y]: ((lobo(X) & (zorro(Y) | grano(Y))) => ~come(X, Y))",
    "![X, Y]: ((ave(X) & oruga(Y)) => come(X, Y))",
    "![X, Y]: ((ave(X) & caracol(Y)) => ~come(X, Y))",
    "![X]: ((oruga(X) | caracol(X)) => (?[Y]: (planta(Y) & come(X, Y))))",
]
CONJETURA_APISONADORA = "?[X, Y]: (animal(X) & animal(Y) & (?[Z]: (grano(Z) & come(Y, Z) & come(X, Y))))"

ax3, neg3 = clausular_problema(APISONADORA, CONJETURA_APISONADORA)
print(len(ax3) + len(neg3), "cláusulas; la más larga tiene", max(len(c) for c in ax3), "literales:")
print("   ", texto_clausula(max(ax3, key=len)))

def fila(nombre, eleccion, seleccion, soporte=False, presupuesto=5000):
    t0 = time.perf_counter()
    prueba, st, motivo = demostrar(ax3, neg3, eleccion=eleccion, seleccion=seleccion, soporte=soporte,
                                   max_generadas=presupuesto)
    print(f"{nombre:10s} {eleccion:6s} {'sí' if soporte else 'no':8s} {motivo:28s} "
          f"{st['dadas']:6d} {st['generadas']:9d} {st['retenidas']:9d} {st['subsumidas']:10d} {time.perf_counter() - t0:6.2f}")
    return prueba

print(f"{'resolución':10s} {'elige':6s} {'soporte':8s} {'resultado':28s} {'dadas':>6s} {'generadas':>9s} {'retenidas':>9s} {'subsumidas':>10s} {'s':>6s}")
for eleccion in ('peso', 'mixta', 'edad'):
    fila('selección', eleccion, True)
fila('selección', 'peso', True, soporte=True)

prueba, st, motivo = demostrar(ax3, neg3, eleccion='peso', seleccion=True)
print()
print("la prueba por peso usa", imprimir_prueba(prueba), "cláusulas")

The table summarizes the strategies section: 169, 216 and 1030 given clauses for weight, mix and age, and false saturation from combining with set of support. The proof follows a person’s reasoning: the bird eats plants (because it does not eat snails, which are small and eat plants), so it eats grain; the wolf does not eat grain, so it eats every small animal that eats plants, and since it does not eat the fox, the fox does not eat plants; therefore the fox eats small animals that eat plants, including the bird. The fox eats an animal that eats grain.

Without selection, with unrestricted binary resolution, the same budget is exhausted:

[ ]Without refinements, and with a false conjectureBrowser
for eleccion in ('peso', 'mixta', 'edad'):
    fila('binaria', eleccion, False, presupuesto=1500)

# Una conjetura falsa cuyo contraejemplo es infinito: un orden estricto sin máximo, ¿tiene mínimo?
ORDEN = ["![X]: ~r(X, X)", "![X, Y, Z]: ((r(X, Y) & r(Y, Z)) => r(X, Z))", "![X]: ?[Y]: r(X, Y)"]
ax4, neg4 = clausular_problema(ORDEN, "?[X]: ![Y]: ~r(Y, X)")
for presupuesto in (200, 400, 800):
    prueba, st, motivo = demostrar(ax4, neg4, max_generadas=presupuesto)
    print(f"orden sin mínimo, presupuesto {presupuesto}: {motivo}, {st['dadas']} dadas, {st['retenidas']} retenidas")

Binary resolution does not reach the proof with 1500 generated clauses under any of the three choices; by age it generates them with just 49 given clauses, because each produces dozens of resolvents. The last part is the common mistake of expecting the prover to stop. “Every strict order without a maximum has a minimum element” is false (the integers with << have no minimum), but all its countermodels are infinite: a strict order without a maximum on a finite set is impossible. The loop generates r(X,s(X))r(X, s(X)), r(X,s(s(X)))r(X, s(s(X))), r(s′(X),X)r(s'(X), X)… endlessly, and doubling the budget only increases retained clauses. No budget turns that silence into an answer.

Finally, return to Herbrand with the same pieces: generate levels of HH, instantiate and pass the instances to a minimal DPLL.

[ ]Herbrand saturation (Gilmore) with DPLLBrowser
from itertools import product

def firma_de(clausulas):
    """Constantes y funciones (con aridad) que aparecen en los argumentos de los átomos."""
    cons, funs = set(), set()
    def mira(t):
        if es_var(t):
            return
        (cons if len(t) == 1 else funs).add((t[0], len(t) - 1))
        for a in t[1:]:
            mira(a)
    for C in clausulas:
        for _, a in C:
            for t in a[1:]:
                mira(t)
    return sorted(cons) or [('c0', 0)], sorted(funs)    # sin constantes, se añade una

def herbrand(clausulas, nivel):
    """H_k: términos cerrados de profundidad <= k."""
    cons, funs = firma_de(clausulas)
    H = {(c,) for c, _ in cons}
    for _ in range(nivel):
        H |= {(f,) + args for f, n in funs for args in product(sorted(H), repeat=n)}
    return sorted(H, key=lambda t: (len(texto(t)), texto(t)))

def variables_de(C):
    vs = []
    for _, a in C:
        variables(a, vs)
    return vs

def instancias(clausulas, H):
    out = set()
    for C in clausulas:
        vs = variables_de(C)
        for valores in product(H, repeat=len(vs)):
            s = dict(zip(vs, valores))
            out.add(frozenset((sg, texto(aplicar(a, s))) for sg, a in C))
    return out

def dpll(F):
    """F: conjunto de cláusulas proposicionales (frozensets de (signo, átomo)). ¿Satisfacible?"""
    F = set(F)
    while True:                                          # propagación unitaria
        if frozenset() in F:
            return False
        unit = next((next(iter(C)) for C in F if len(C) == 1), None)
        if unit is None:
            break
        F = {C - {(not unit[0], unit[1])} for C in F if unit not in C}
    if not F:
        return True
    sg, at = next(iter(next(iter(F))))
    return any(dpll(F | {frozenset([(v, at)])}) for v in (True, False))

def gilmore(clausulas, max_nivel=5, max_instancias=20000):
    for k in range(max_nivel + 1):
        H = herbrand(clausulas, k)
        n = sum(len(H) ** len(variables_de(C)) for C in clausulas)
        if n > max_instancias:
            print(f"   nivel {k}: |H| = {len(H)}, harían falta {n} instancias: me paro (¿satisfacible? no lo sé)")
            return
        sat = dpll(instancias(clausulas, H))
        print(f"   nivel {k}: |H| = {len(H):4d}, {n:6d} instancias, {'satisfacibles' if sat else 'INSATISFACIBLES'}")
        if not sat:
            return k
        if len(herbrand(clausulas, k + 1)) == len(H):
            print("   el universo de Herbrand es finito y ya está entero: el conjunto es satisfacible")
            return

problemas = {
    "insatisfacible": ["p(a)", "~p(X) | p(f(X))", "~p(f(f(a)))"],
    "satisfacible con funciones": ["p(a)", "~p(X) | p(f(X))", "~q(a)"],
    "satisfacible sin funciones": ["p(a) | q(b)", "~p(X) | r(X, b)", "~r(a, Y) | ~q(Y)"],
    "comprobación de ocurrencia": ["p(X, X)", "~p(Y, f(Y))"],
}
for nombre, cls in problemas.items():
    print(nombre + ":")
    gilmore([cl(c) for c in cls])
print("curiosidad (AIMA), en forma clausal:")
gilmore(ax + neg)
print("apisonadora de Schubert:")
gilmore(ax3 + neg3, max_instancias=30000)

The numbers are those of the Herbrand figure: the chain is refuted at level 1, as is the AIMA base (9 terms, 768 instances), and the steamroller needs 23,742 level-1 instances versus 215 clauses generated by the loop with selection. The “occurs check” set, {p(X,X),¬p(Y,f(Y))}\{p(X, X), \lnot p(Y, f(Y))\}, is satisfiable at every level: semantic confirmation that □\square produced by unification without checking was false.

Compare with real provers

The next cell writes the same problems in TPTP format and solves them with Vampire or E if installed (find them on each project’s page; neither is distributed by pip), and always with Z3, the SMT solver from lessons 13 and 14, which accepts quantifiers and handles them by instantiation instead of resolution. It adds two false conjectures: one with a finite countermodel and the order without a minimum.

[ ]The same problems with Z3 (and Vampire or E if installed)Local GPU
import re, shutil, subprocess, tempfile, time
from pathlib import Path
import z3

ACCESO = [
    "miembro(ana, desarrollo)", "hereda(desarrollo, plantilla)",
    "![U, G, H]: ((miembro(U, G) & hereda(G, H)) => miembro(U, H))",
    "![U, G, R]: ((miembro(U, G) & permiso(G, R)) => puede_leer(U, R))",
    "![G, R, D]: ((permiso(G, D) & dentro(R, D)) => permiso(G, R))",
    "permiso(plantilla, documentos)", "dentro(informe, documentos)",
]
CURIOSIDAD = [
    "![X]: ((![Y]: (animal(Y) => ama(X, Y))) => (?[Y]: ama(Y, X)))",
    "![X]: ((?[Z]: (animal(Z) & mata(X, Z))) => (![Y]: ~ama(Y, X)))",
    "![X]: (animal(X) => ama(jack, X))",
    "mata(jack, tuna) | mata(curiosidad, tuna)", "gato(tuna)", "![X]: (gato(X) => animal(X))",
]
APISONADORA = [
    "![X]: (lobo(X) => animal(X))", "?[X]: lobo(X)", "![X]: (zorro(X) => animal(X))", "?[X]: zorro(X)",
    "![X]: (ave(X) => animal(X))", "?[X]: ave(X)", "![X]: (oruga(X) => animal(X))", "?[X]: oruga(X)",
    "![X]: (caracol(X) => animal(X))", "?[X]: caracol(X)", "?[X]: grano(X)", "![X]: (grano(X) => planta(X))",
    "![X]: (animal(X) => ((![Y]: (planta(Y) => come(X, Y))) | (![Y]: ((animal(Y) & menor(Y, X) & (?[Z]: (planta(Z) & come(Y, Z)))) => come(X, Y)))))",
    "![X, Y]: ((ave(Y) & (caracol(X) | oruga(X))) => menor(X, Y))",
    "![X, Y]: ((ave(X) & zorro(Y)) => menor(X, Y))",
    "![X, Y]: ((zorro(X) & lobo(Y)) => menor(X, Y))",
    "![X, Y]: ((lobo(X) & (zorro(Y) | grano(Y))) => ~come(X, Y))",
    "![X, Y]: ((ave(X) & oruga(Y)) => come(X, Y))",
    "![X, Y]: ((ave(X) & caracol(Y)) => ~come(X, Y))",
    "![X]: ((oruga(X) | caracol(X)) => (?[Y]: (planta(Y) & come(X, Y))))",
]
PROBLEMAS = {
    "acceso": (ACCESO, "puede_leer(ana, informe)"),
    "curiosidad": (CURIOSIDAD, "mata(curiosidad, tuna)"),
    "apisonadora": (APISONADORA, "?[X, Y]: (animal(X) & animal(Y) & (?[Z]: (grano(Z) & come(Y, Z) & come(X, Y))))"),
    "conjetura falsa": (ACCESO, "puede_leer(ana, nominas)"),
    # orden estricto sin máximo: solo tiene modelos infinitos. ¿Tiene un elemento mínimo? En N sí, en Z no.
    "sin modelo finito": (["![X]: ~r(X, X)", "![X, Y, Z]: ((r(X, Y) & r(Y, Z)) => r(X, Z))", "![X]: ?[Y]: r(X, Y)"],
                          "?[X]: ![Y]: ~r(Y, X)"),
}

def tptp(axiomas, conjetura):
    lineas = [f"fof(a{i}, axiom, {f})." for i, f in enumerate(axiomas)]
    return "\n".join(lineas + [f"fof(objetivo, conjecture, {conjetura})."]) + "\n"

# --- De la sintaxis FOF de TPTP a Z3 (un solo tipo U, funciones y predicados no interpretados) ---
U = z3.DeclareSort('U')
def a_z3(texto_formula, simbolos):
    tk = re.findall(r"<=>|=>|[()\[\],:~&|!?]|[A-Za-z_][A-Za-z0-9_]*", texto_formula)
    pos = [0]
    def mira():
        return tk[pos[0]] if pos[0] < len(tk) else None
    def toma():
        pos[0] += 1
        return tk[pos[0] - 1]
    def termino(ligadas, es_atomo=False):
        nombre = toma()
        args = []
        if mira() == '(':
            toma(); args.append(termino(ligadas))
            while mira() == ',':
                toma(); args.append(termino(ligadas))
            toma()
        if nombre in ligadas:
            return ligadas[nombre]
        clave = (nombre, len(args), es_atomo)
        if clave not in simbolos:
            rango = z3.BoolSort() if es_atomo else U
            simbolos[clave] = z3.Function(nombre, *([U] * len(args)), rango) if args else z3.Const(nombre, rango)
        f = simbolos[clave]
        return f(*args) if args else f
    def unitaria(lig):
        t = mira()
        if t == '~':
            toma(); return z3.Not(unitaria(lig))
        if t in ('!', '?'):
            toma(); toma()
            vs = [toma()]
            while mira() == ',':
                toma(); vs.append(toma())
            toma(); toma()
            nuevas = {v: z3.Const(f"{v}_{len(simbolos)}_{pos[0]}", U) for v in vs}
            cuerpo = unitaria({**lig, **nuevas})
            return (z3.ForAll if t == '!' else z3.Exists)(list(nuevas.values()), cuerpo)
        if t == '(':
            toma(); f = binaria(lig); toma(); return f
        return termino(lig, es_atomo=True)
    def binaria(lig):
        f = unitaria(lig)
        op = mira()
        if op in ('&', '|'):
            partes = [f]
            while mira() == op:
                toma(); partes.append(unitaria(lig))
            return z3.And(partes) if op == '&' else z3.Or(partes)
        if op in ('=>', '<=>'):
            toma(); g = unitaria(lig)
            return z3.Implies(f, g) if op == '=>' else f == g
        return f
    return binaria({})

carpeta = Path(tempfile.mkdtemp())
externos = {nombre: shutil.which(nombre) for nombre in ("vampire", "eprover")}
print("demostradores externos encontrados:", {k: v for k, v in externos.items() if v} or "ninguno")
for nombre, (axiomas, conjetura) in PROBLEMAS.items():
    fichero = carpeta / f"{nombre.replace(' ', '_')}.p"
    fichero.write_text(tptp(axiomas, conjetura), encoding="utf-8")
    simbolos = {}
    s = z3.Solver()
    s.set("timeout", 5000)
    for f in axiomas:
        s.add(a_z3(f, simbolos))
    s.add(z3.Not(a_z3(conjetura, simbolos)))
    t0 = time.perf_counter()
    r = s.check()
    dt = time.perf_counter() - t0
    est = s.statistics()
    inst = est.get_key_value("quant instantiations") if "quant instantiations" in est.keys() else 0
    veredicto = {"unsat": "teorema (refutación)", "sat": "no es teorema (hay modelo)"}.get(str(r), str(r))
    print(f"{nombre:17s} Z3: {veredicto:28s} {dt * 1000:7.1f} ms   instanciaciones de cuantificadores: {inst}")
    if str(r) == "sat":
        print("    tamaño del universo del contramodelo:", len(s.model().get_universe(U)))
    for prog, ruta in externos.items():
        if not ruta:
            continue
        orden = [ruta, "--mode", "casc", "-t", "10", str(fichero)] if prog == "vampire" else \
                [ruta, "--auto", "--soft-cpu-limit=10", "-s", str(fichero)]
        t0 = time.perf_counter()
        salida = subprocess.run(orden, capture_output=True, text=True, timeout=60).stdout
        estado = re.search(r"SZS status (\w+)", salida)
        print(f"    {prog}: {estado.group(1) if estado else '?'} en {time.perf_counter() - t0:.2f} s")
print("\nficheros TPTP en", carpeta)
print(tptp(*PROBLEMAS["acceso"]))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In our run (without Vampire or E installed), Z3 refutes all three theorems in milliseconds, with 5, 17 and 339 quantifier instantiations for access control, AIMA and the steamroller; exact numbers depend on the Z3 version. For the false access-control conjecture it finds a finite countermodel of 6 elements: its model-based quantifier instantiation engine (MBQI, lesson 14) builds candidate models and, if they fit, answers “not a theorem”, which our loop only achieves when it saturates. With the order without a minimum it exhausts 5 seconds and returns unknown: there is no finite model to find and no instantiation leads to contradiction. Semidecidability from another engine’s perspective. Compare with your prover: for the steamroller, 339 instances in Z3 versus 215 clauses generated by the loop with selection and 23,742 Gilmore ground instances. If you install Vampire, line SZS status Theorem is the standard TPTP verdict; CounterSatisfiable indicates a false conjecture with a countermodel found.

Common mistakes

Exercises

QuizMost general unifiers
Which statements about most general unifiers are correct? Uppercase letters are variables.

More than one answer may be correct.

NumericSize of the Herbrand universe
A clause set has constants aa and bb, a unary function ff and a binary function gg, with no other function symbols. How many terms are in H2H_2, level 2 of its Herbrand universe?
ProofSkolemization preserves satisfiability, not equivalence
Prove: Let φ=∀x ∃y ψ(x,y)\varphi = \forall x\,\exists y\,\psi(x, y), with ψ\psi having no other free variables, and φsk=∀x ψ(x,s(x))\varphi^{\mathrm{sk}} = \forall x\,\psi(x, s(x)), with ss a function symbol absent from ψ\psi. Then φ\varphi is satisfiable if and only if φsk\varphi^{\mathrm{sk}} is, but in general φ⊭φsk\varphi \not\models \varphi^{\mathrm{sk}}.
0
We work with structures M\mathcal{M} for the signature of ψ\psi, extended with ss when needed.

Step 1 of 4. How do you prove that if M⊨φsk\mathcal{M} \models \varphi^{\mathrm{sk}}, then M⊨φ\mathcal{M} \models \varphi?

ProofGuided refutation: can Ana read the report?
Prove: With clauses (1) miembro(ana,desarrollo)\mathit{miembro}(\mathit{ana}, \mathit{desarrollo}), (2) hereda(desarrollo,plantilla)\mathit{hereda}(\mathit{desarrollo}, \mathit{plantilla}), (3) ¬miembro(U,G)∨¬hereda(G,H)∨miembro(U,H)\lnot\mathit{miembro}(U, G) \lor \lnot\mathit{hereda}(G, H) \lor \mathit{miembro}(U, H), (4) ¬miembro(U,G)∨¬permiso(G,R)∨puede_leer(U,R)\lnot\mathit{miembro}(U, G) \lor \lnot\mathit{permiso}(G, R) \lor \mathit{puede\_leer}(U, R), (5) ¬permiso(G,D)∨¬dentro(R,D)∨permiso(G,R)\lnot\mathit{permiso}(G, D) \lor \lnot\mathit{dentro}(R, D) \lor \mathit{permiso}(G, R), (6) permiso(plantilla,documentos)\mathit{permiso}(\mathit{plantilla}, \mathit{documentos}) and (7) dentro(informe,documentos)\mathit{dentro}(\mathit{informe}, \mathit{documentos}), prove puede_leer(ana,informe)\mathit{puede\_leer}(\mathit{ana}, \mathit{informe}) by resolution.
0
Add negated conjecture (8) ¬puede_leer(ana,informe)\lnot\mathit{puede\_leer}(\mathit{ana}, \mathit{informe}) and seek the empty clause. Rename variables of each clause before use.

Step 1 of 4. Where do you begin?

QuizA false conjecture
You run a complete resolution prover with fair selection on Γ∪{¬α}\Gamma \cup \{\lnot\alpha\}, where Γ⊭α\Gamma \not\models \alpha. What can happen?

More than one answer may be correct.

QuizCompleteness of refinements
For Schubert's steamroller, which statements are correct?

More than one answer may be correct.

CodeUnification by transforming equations
Implement unify(t1, t2) using the Martelli–Montanari algorithm: maintain a list of pending equations and an idempotent substitution in solved form (no bound variable appears in values). Return a variable → term dictionary with the most general unifier, or None if none exists. Terms are as in the lab: a variable is a str starting with an uppercase letter and a compound term or constant is a tuple (símbolo, *argumentos). Tests check direct and indirect cycles, shared variables, symbol and arity conflicts, idempotence, and 300 random pairs compared with a reference mgu up to renaming.
def es_var(t):
  return isinstance(t, str)

def unify(t1, t2):
  """Unificador más general idempotente de t1 y t2, o None."""
  E = [(t1, t2)]       # ecuaciones pendientes
  sigma = {}           # sustitución resuelta
  # tu código: aplica las reglas (eliminar trivial, orientar, ocurrencia,
  # eliminar variable, conflicto, descomponer) hasta vaciar E
  return None
Shift+Enter to run

Summary

Key idea
A first-order prover reduces “does α follow?” to “is KB with ¬α contradictory?”, converts everything to clauses with Skolemization, and searches for the empty clause by resolution: unification calculates, rather than guesses, the instances Herbrand’s theorem guarantees exist.
  • A knowledge-based agent separates what it knows (TELL) from how it decides (ASK, logical entailment). Model checking works only for small finite domains; syntactic refutation works whenever the conjecture follows.
  • Clausal form uses NNF, renaming, Skolemization (with universals dominating each existential as arguments) and CNF. It preserves satisfiability, not equivalence, so negate the conjecture first.
  • Herbrand’s theorem: a clause set is unsatisfiable if and only if some finite set of its ground instances is. This gives a procedure terminating on theorems that may not terminate otherwise: first-order entailment is semidecidable and undecidable.
  • Unification computes the mgu or detects none exists. Without the occurs check the prover becomes unsound; with terms as trees the result may be exponential, hence shared subterms.
  • Binary resolution plus factoring on clauses with separated variables is sound and refutationally complete (lifting lemma). Omitting renaming or factoring makes it incomplete.
  • Real provers use a given-clause loop with refinements (selection, orders, set of support), redundancy deletion (subsumption) and a heuristic mixing weight and age. On the steamroller, selection and weight make the difference between 215 generated clauses and not succeeding with 1500.
  • Equality uses superposition, paramodulation restricted by a term order. Proof assistants use these provers as oracles and check their work with a small kernel.