AI Wiki中文/EN

Propositional logic: truth, entailment and proof

命题逻辑

Find countermodels and check a small proof language without confusing a valid conclusion with a valid submitted proof.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The alarm is on. Did the sensor fire?

A workshop rule says: if the sensor fires and power is available, the alarm turns on. Let S mean “the sensor fires,” P mean “power is available” and A mean “the alarm is on.” For this hypothetical, synchronous snapshot, the rule is (S∧P)→A(S\land P)\to A.

Knowing S and P lets us conclude A. Knowing A and P does not let us conclude S: the alarm may be on with the sensor silent without violating the stated rule. To rule that setting out, the model would need another premise. The three letters describe truth claims; their names do not make the alarm an exclusive effect of this sensor.

Propositional logic studies formulas built from whole statements and connectives such as AND, OR, NOT and implication. It helps separate an inference’s structure from the evidence supporting its premises. Our example makes that separation visible: a correct inference from an inaccurate sensor report can still describe the workshop incorrectly.

This chapter gives two executable checks. One examines every truth assignment and produces a counterexample when an entailment fails. The other checks a supplied chain of symbolic steps without examining possible worlds. They answer different questions: whether a conclusion follows, and whether this particular proof justifies it. The distinction between syntax and semantics is developed in Logic and Proof, chapter 6.

Formulas, truth and derivations are different objects

Fix a collection of atom names. An atom is an indivisible proposition for the purposes of this language. Starting from atoms and constants true/false, construct formulas recursively:

φ::=p∣⊤∣⊥∣¬φ∣(φ∧φ)∣(φ∨φ)∣(φ→φ)∣(φ↔φ).\varphi ::= p\mid\top\mid\bot\mid\lnot\varphi\mid(\varphi\land\varphi)\mid(\varphi\lor\varphi)\mid(\varphi\to\varphi)\mid(\varphi\leftrightarrow\varphi).

This grammar specifies syntax, not truth. It tells us how parentheses nest. In our code an atom is a nonempty string, constants are Python Booleans, and compound formulas are tagged tuples. The formula ('imp', ('and', 'S', 'P'), 'A') has an implication at its root. Merely putting the text S and P inside a string creates one atom; it does not create an AND node.

A valuation v assigns each atom either false or true. Extend it recursively to formulas. NOT flips truth, AND requires both operands, OR requires at least one, and biconditional requires equal truth values. Material implication p→qp\to q is false only when p is true and q is false. Logic and Proof, §6.1

pqANDORp → qp ↔ q
000011
010110
100100
111111

The alarm rule allows every setting except S=1, P=1, A=0. It says nothing about delays, alternative causes or intervention effects. A false antecedent makes the material implication true in that valuation; it does not provide evidence that the alarm would respond correctly if the sensor fired. Model time or causal behavior explicitly when those are the questions.

Let Γ\Gamma be a finite set of premises. Write v⊨Γv\models\Gamma when every premise is true under v. A model of Γ\Gamma is such a valuation. Semantic entailment means

Γ⊨φ⟺∀v  (v⊨Γ⇒v⊨φ).\Gamma\models\varphi\quad\Longleftrightarrow\quad\forall v\;(v\models\Gamma\Rightarrow v\models\varphi).

A countermodel is a valuation making all premises true and the conclusion false. One countermodel refutes entailment. If no valuation satisfies the premises, the condition holds for every conclusion: there is no countermodel. This is classical explosion at the semantic level, not evidence that every real-world claim is true. The program therefore reports how many premise models exist alongside the entailment result.

A formula is satisfiable if some valuation makes it true, valid or a tautology if every valuation does, contradictory if none does, and contingent if both true and false valuations exist. Two formulas are equivalent when they agree in every valuation. Equivalence entails each other in both directions; entailment in just one direction need not be equivalence. Relative to finite Γ\Gamma, the same countermodel condition gives

Γ⊨φ⟺(⋀γ∈Γγ)∧¬φ is unsatisfiable.\Gamma\models\varphi\quad\Longleftrightarrow\quad\left(\bigwedge_{\gamma\in\Gamma}\gamma\right)\land\lnot\varphi\text{ is unsatisfiable}.

The empty conjunction is true. The definitions and reduction can also be checked in Stanford, lesson 3, sections 3.2–3.6. This identity explains how a SAT solver can answer a logical entailment question after a semantics-preserving encoding. For ordinary classical entailment, adding premises cannot destroy an existing entailment: the set of permitted valuations only shrinks. It may shrink to the empty set, which is why checking consistency remains useful.

A proof system instead provides syntactic rules. Write Γ⊢Rφ\Gamma\vdash_{\mathcal R}\varphi when a derivation using rule set R\mathcal R concludes φ\varphi from Γ\Gamma. Conjunction introduction builds p∧qp\land q from p and q; conjunction elimination extracts either part; modus ponens obtains q from p→qp\to q and p. These are among the natural-deduction rules discussed in Logic and Proof, §§3.1 and 3.3.

Our checker implements those rules plus citing a stated premise. It permits only backward references to earlier proof lines. Every line remains under the same global premises; it has no temporary assumption scopes or assumption discharge. This is a deliberately small proof language, not the whole natural-deduction calculus.

Its soundness has a short induction. Fix any valuation satisfying all global premises. A cited premise is true. An AND formed from earlier true lines is true, either component of a true AND is true, and a true implication with a true antecedent has a true consequent. Thus every accepted line is true in that valuation, including the final conclusion. Backward references make this induction possible; allowing a line to justify itself would break the argument.

Return a countermodel or validate the supplied steps

The complete Python 3.10+ program uses only the standard library. names validates finite formula trees and collects atom names; lists, integer constants such as 0 and 1, unknown operator tags and wrong arities are rejected as formulas. Atom strings are case-sensitive and have no reserved meaning. value is an internal evaluator for validated trees and full Boolean assignments, not a separately validated input interface.

analyze(premises, goal) checks every assignment to the sorted union of atoms appearing in either the premises or the goal. False precedes True. It returns whether entailment holds, the count of premise models over that union, the first countermodel if one exists, and the number of assignments examined. It does not stop at the first countermodel, because the count is meant to be complete. Adding a fresh atom only in the goal can multiply the premise-model count without changing the premises themselves.

The countermodel sentinel is None. The empty dictionary {} is a real valuation for a language with no atoms, so testing its truthiness would confuse a counterexample with no counterexample. This boundary appears in the output below.

A proof line is (rule, conclusion, references). References are a tuple of zero-based earlier line indices, with Boolean and out-of-range indices rejected. Modus ponens takes the implication’s line first and the antecedent’s line second. Malformed syntax, unsupported rules or an unjustified step raise ValueError. A fully well-formed sequence returns True only if its final conclusion is structurally identical to the requested goal. An empty proof or a valid sequence ending elsewhere returns False. No return value searches for another proof.

from itertools import product

ARITY = {'not': 1, 'and': 2, 'or': 2, 'imp': 2, 'iff': 2}


def names(formulas):
    todo, found = list(formulas), set()
    while todo:
        f = todo.pop()
        if type(f) is bool:
            continue
        if type(f) is str and f:
            found.add(f)
        elif (type(f) is tuple and f and type(f[0]) is str
              and f[0] in ARITY and len(f) == ARITY[f[0]] + 1):
            todo.extend(f[1:])
        else:
            raise ValueError('use a nonempty atom, Boolean constant, or operator tuple')
    return sorted(found)


def value(f, assignment):
    # Internal evaluator: validated syntax and a complete Boolean assignment.
    if type(f) is bool:
        return f
    if type(f) is str:
        return assignment[f]
    op, *children = f
    a = value(children[0], assignment)
    if op == 'not':
        return not a
    b = value(children[1], assignment)
    return {'and': a and b, 'or': a or b, 'imp': (not a) or b,
            'iff': a == b}[op]


def analyze(premises, goal):
    if type(premises) not in (tuple, list):
        raise ValueError('premises must be a finite tuple or list')
    premises = tuple(premises)
    variables = names((*premises, goal))
    compatible, countermodel = 0, None
    for row in product((False, True), repeat=len(variables)):
        assignment = dict(zip(variables, row))
        if all(value(p, assignment) for p in premises):
            compatible += 1
            if not value(goal, assignment) and countermodel is None:
                countermodel = assignment.copy()
    return dict(entailed=countermodel is None, premise_models=compatible,
                countermodel=countermodel, assignments=2**len(variables))


def check_proof(premises, goal, proof):
    if type(premises) not in (tuple, list) or type(proof) not in (tuple, list):
        raise ValueError('premises and proof must be finite tuples or lists')
    premises = tuple(premises)
    names((*premises, goal))
    conclusions = []
    for line in proof:
        if type(line) is not tuple or len(line) != 3 or type(line[0]) is not str:
            raise ValueError('each line is (rule, conclusion, earlier line indices)')
        rule, conclusion, refs = line
        names((conclusion,))
        if (type(refs) is not tuple or any(type(i) is not int or
                not 0 <= i < len(conclusions) for i in refs)):
            raise ValueError('references must be zero-based earlier lines, not booleans')
        inputs = [conclusions[i] for i in refs]
        if rule == 'premise':
            ok = not refs and conclusion in premises
        elif rule == 'and-intro':
            ok = len(inputs) == 2 and conclusion == ('and', *inputs)
        elif rule in ('and-left', 'and-right'):
            side = 1 if rule == 'and-left' else 2
            ok = (len(inputs) == 1 and type(inputs[0]) is tuple
                  and inputs[0][0] == 'and' and conclusion == inputs[0][side])
        elif rule == 'mp':
            ok = len(inputs) == 2 and inputs[0] == ('imp', inputs[1], conclusion)
        else:
            raise ValueError('unsupported proof rule')
        if not ok:
            raise ValueError('rule does not justify this conclusion')
        conclusions.append(conclusion)
    return bool(conclusions) and conclusions[-1] == goal


S, P, A = 'S', 'P', 'A'
rule = ('imp', ('and', S, P), A)
premises = (rule, S, P)
proof = (
    ('premise', rule, ()),
    ('premise', S, ()),
    ('premise', P, ()),
    ('and-intro', ('and', S, P), (1, 2)),
    ('mp', A, (0, 3)),
)
print('alarm:', analyze(premises, A))
print('proof:', check_proof(premises, A, proof))
print('reverse:', analyze((rule, A, P), S))
print('missing power:', analyze((rule, S), A))
print('inconsistent:', analyze((S, ('not', S)), A))
print('no atoms:', analyze((), False))
print('tautology:', analyze((), ('or', S, ('not', S))))
print('empty proof:', check_proof((), ('or', S, ('not', S)), ()))

The alarm argument has one premise model over the three atoms, and A is true there. Its supplied proof is:

LineConclusionReason
0(S ∧ P) → APremise
1SPremise
2PPremise
3S ∧ PAND introduction, lines 1 and 2
4AModus ponens, lines 0 and 3

For the reverse inference, premises (rule, A, P) have two models. The first countermodel is {'A': True, 'P': True, 'S': False}. With (rule, S) and goal A, there are three premise models, including the countermodel {'A': False, 'P': False, 'S': True}. Missing power prevents the rule from forcing the alarm on.

Contradictory premises (S, not S) have zero models. The analyzer reports entailment of A, while still exposing the empty premise set of models. With no atoms and goal False, there is one valuation, {}, which is a countermodel. Finally, S OR NOT S is true under both one-atom valuations, but the empty proof does not establish it in our checker.

Let n be the number of distinct atoms and C the combined tree size of premises and goal, counting repeated occurrences separately. With constant-cost atom/hash operations, validation and sorting take O(1+C+nlog⁡(2+n))O(1+C+n\log(2+n)), and analysis takes O(2n(1+n+C))O(2^n(1+n+C)) time. It stores one current valuation and at most one countermodel, not the full truth table; input plus working storage is O(1+C+n)O(1+C+n). Python recursion depth and the exponential number of valuations limit practical inputs. Shared tuple objects do not receive memoized evaluation; use the expanded tree size in these bounds.

The proof checker does no valuation enumeration. For a valid certificate with r lines, m premises, maximum formula size L, and total supplied formula-tree size T, a conservative time bound is O(1+Tlog⁡(2+T)+r(m+1)L)O(1+T\log(2+T)+r(m+1)L). Valid rules reference at most two earlier lines. The bound includes repeated syntax validation, sorted atom collection, structural equality and the linear scan of premises used by premise. Including the input, space is O(1+T+r+m)O(1+T+r+m). This straightforward implementation is not claimed to be a linear-time proof checker.

A rejected proof is not a refuted conclusion

Soundness says that provable conclusions are entailed; completeness says that every entailed conclusion has a proof in the specified system. These are properties of a system relative to its semantics, not labels awarded because some examples pass. A full classical natural-deduction system can be sound and complete; this small checker implements only a subset of its rules. Logic and Proof, §6.3

Our subset is incomplete. With no premises, no first line can be justified: the premise rule has nothing to cite, and every other rule needs earlier lines. Yet S OR NOT S is valid. A checker refusing an attempted derivation therefore need not mean the conclusion is false or not entailed. Even a complete proof system would not make every incorrect submitted proof valid.

Do not swap implication with its converse. From p→qp\to q and q, inferring p is the fallacy of affirming the consequent; p=false, q=true refutes it. By contrast, contraposition p→q≡¬q→¬pp\to q\equiv\lnot q\to\lnot p agrees under every classical valuation. Neither identity by itself identifies a cause.

Not knowing p is different from having the premise NOT p. The classical valuation assumes a truth value, but an observer may not know which valuations remain possible. If the current premises allow both p=true and p=false, neither p nor NOT p is entailed. A database or rule engine that treats every missing fact as false adopts an additional convention. That convention is absent here.

This propositional language has no variables ranging over objects, quantifiers, arithmetic theory or time indices with built-in meaning. Naming an atom all_sensors_work does not give the checker access to individual sensors. SMT and first-order logic add different kinds of structure.

Find the missing premise or the broken proof step

  1. Use only the workshop rule and S as premises. Give a countermodel to A. Add P and explain why the countermodel disappears. Does this establish a causal effect of supplying power?
  2. Someone submits lines premise: rule, premise: A, premise: P, then uses modus ponens to conclude S. Explain the exact failed match. Supply a correct five-line proof of A from (rule, S, P).
  3. What does the analyzer say about goal A from (S, not S)? What does it say about goal False with no premises and no atoms? Explain why if not countermodel would be a bug.
  4. Prove semantic equivalence of p→qp\to q and ¬q→¬p\lnot q\to\lnot p using all four rows. Does the checker have to accept an empty proof of that equivalence? If Γ⊨A\Gamma\models A, can adding one more premise make entailment of A fail in this classical semantics?
Worked answers

Answer 1: S=true, P=false, A=false satisfies the rule and S while falsifying A. Adding P excludes this valuation; S and P make the rule’s antecedent true, so all remaining premise models make A true. This is a consequence of the encoded rule, not an intervention experiment or proof that the rule accurately describes the device.

Answer 2: Modus ponens needs an implication whose consequent is the desired conclusion and a separate line identical to its antecedent. The displayed rule has consequent A and antecedent S AND P, not consequent S and antecedent A. Lines 0–4 in the table above provide the valid proof. Neither reversing the references nor renaming the rule makes the proposed reverse inference sound.

Answer 3: The contradictory premises have zero models and entail A vacuously. The empty-premise, atom-free case has one valuation {} and does not entail False. An empty dictionary is falsy in Python, so truthiness would incorrectly hide this actual countermodel; use identity with None.

Answer 4: In row order (p,q)=00,01,10,11, both implications evaluate to 1,1,0,1. The analyzer can establish that equivalence, but our checker rejects an empty proof and lacks rules to prove any closed theorem. Adding premises shrinks the allowed valuation set, so it cannot introduce a countermodel to an already entailed A. It can make the premises inconsistent, which affects how useful that result is.

Test a proof checker by trying to make it accept a bad step

For the analyzer, generate small formulas and compute their truth sets through a different representation. Check entailment by set containment and compare the reported first countermodel and premise-model count. Test false goals with no atoms, fresh atoms appearing only in the goal, empty or contradictory premises, and equivalences whose syntax trees differ.

For the checker, generate correctly instantiated rules and verify that every accepted line is true in every model of its declared premises. Then mutate a premise, a reference, an operator or the final goal. An accepted result is meaningful only if invalid certificates are rejected too. The repository tests exercise all five rules as well as self-reference, forward reference, altered conclusions and an omitted premise.

The formula representation, workshop example, analyzer, restricted checker and tests are original. The linked textbook provides terminology and rule descriptions; no textbook puzzle, image, proof script or implementation is reproduced. The checker is not a Lean kernel, and passing its Python tests is not a machine-checked metatheoretic proof. Its short soundness argument and explicit incompleteness example delimit what it does. Use the SAT chapter for CNF and satisfiability encodings, while keeping semantic entailment distinct from the choice of a solver or proof language.

Make a prediction, then check

The checker rejects a submitted proof, but the complete truth table finds no countermodel to the conclusion. What follows?

Choose one answer

Learning objectives

  • Distinguish formula syntax, valuation, entailment and derivation; use countermodels for converse errors, ignorance versus negation, inconsistent premises and reduction to SAT.
  • Implement full semantic analysis and a five-rule certificate checker, prove the small rule set sound but incomplete, and handle empty valuations, invalid references and a mismatched final goal.

Prerequisites & connections

This article can be used as an entry point.

Explore related knowledge →

References

  1. Logic and Proof: 6. Semantics of Propositional Logic
    Jeremy Avigad; Joseph Hua; Robert Y. Lewis; Floris van Doorn
  2. Logic and Proof: 3. Natural Deduction for Propositional Logic
    Jeremy Avigad; Joseph Hua; Robert Y. Lewis; Floris van Doorn
  3. Introduction to Logic: Lesson 3 — Propositional Analysis
    Stanford Introduction to Logic course team

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent finite-state oracles, bilingual review and second-agent cross-checks; not independent human peer review.

  • Reread both locales: three display equations, two numerical/proof tables, complete Python, six anchors and four answered exercises correspond. Distinguishes material from causal/counterfactual claims, premise models from real-world truth, entailment from submitted certificates, and full classical natural deduction from the incomplete five-rule subset.
  • Eight tests passed:4,096 pairs-of-premises/goal combinations from16 two-atom truth functions against integer-world-set semantics, including SAT reduction;256 equivalence/bidirectional-entailment cases;800 random syntax trees and premise monotonicity;1,024 rule instances with independent per-line soundness checks; invalid tags/references/premises/conclusions, the empty-world countermodel, contradictions, fresh-atom counts, unparsed atom strings and bilingual code identity.
  • Recomputed one alarm premise model, two converse premise models and three with missing power; inconsistent premises have zero models and vacuous entailment, while an atom-free false goal has actual countermodel{} rather than None. Code retains only the first countermodel while completing counts. Proof checking does no search; False/errors do not refute entailment. Complexity includes expanded trees, name sorting, structural equality and premise scans.
  • Read both complete articles, example.py, metadata and all eight author tests; no substantive defect. Checked material implication versus causal/converse claims, entailment versus a submitted proof, the five-rule soundness induction and incompleteness without assumption discharge. False means a valid sequence ends elsewhere or is empty, while ValueError rejects that submission; neither is a semantic refutation.
  • The independent reference translates formulas to algebraic normal form over GF(2) with x²=x, using neither author per-valuation recursive Boolean evaluation nor the author-test set of possible worlds. For 2,400 seeded cases with zero through six atoms, depth at most four and zero through four premises, compared original goals, shared duplicate conjunctions, false-antecedent implications and added goal/inconsistent premises: 9,600 complete results. Entailment is determined by a zero countermodel polynomial; counts and first countermodels are independently evaluated from that polynomial. All pass, including Chinese, spaced and operator-named atoms.
  • The certificate reference uses generic pattern unification with explicit metavariables for the four inference schemas and separately checks premise citation, without reusing the target checker’s rule branches. Across 512 triples from eight formulas, each checks four rules, a valid-prefix final-goal comparison and premise citation. Also perturbed conclusions/self-references/rule names on every line of 300 eight-line proofs, changed final goals, removed premises and checked eight empty proofs. All 11,180 True/False/ValueError classifications agree. All 2,702 line occurrences in returned-True certificates are independently entailed under the polynomial semantics.
  • Reran all eight author tests successfully. Confirmed alarm/converse/missing-power counts 1/2/3, zero models for inconsistency, the real atom-free countermodel {} versus None, and counts over the current premises∪goal atom universe. Reviewed expanded tree size, repeated validation/sorting, structural comparison and premise scans: the conservative time/space bounds hold for valid certificates as stated, without claiming that bound for arbitrary malicious certificates.
  • Both Python blocks exactly match example.py; three display equations, six stable anchors and four answers correspond, with review written. Independently compiled strict KaTeX/MDX and actually rendered React static HTML: three displays/four strong answer labels per language, without KaTeX errors or unrendered emphasis outside code. Wrote only /tmp reference and review files; no author/repository edits, whole-site or browser acceptance.
  • Promotion preserves full prose, equations, program and exercises. Test loading alone changes from temporary drafts to repository articles; implementation and oracle logic are unchanged. Final review binds both MDX SHA-256 hashes.
  • With SMT completed in the same group, linked directly to its article in both locales and restricted the pending wording to first-order logic. Only navigation/publication wording changed; mathematics, code and exercises did not.
  • After group publication, reread the navigation paragraph and changed completed first-order logic, unification or resolution directory entries to their articles, removing stale pending wording. Algorithms, derivations, prior sources and exercises are unchanged; final MDX hashes bind this scoped navigation revision.

Source locations checked:

  • Logic and Proof: 6. Semantics of Propositional Logic · Read lines2–19 for syntax/semantics, 20–58 for valuations and connective meaning, 59–78 for material versus counterfactual implication, 152–167 for all-valuation truth tables, and 168–189 for soundness/completeness, entailment from hypotheses and induction. Own finite five-rule language is explicitly incomplete and is not a Lean kernel.
  • Logic and Proof: 3. Natural Deduction for Propositional Logic · Read sections3.1 and3.3, lines7–42 for formulas, proof assumptions, earlier-line format and discharge; 132–145 for MP/conjunction elimination, backward/forward reasoning and hypothesis scopes. The Python subset has one fixed global premise context and no discharge or temporary scopes; own proof lines and counterexamples are checked independently.
  • Introduction to Logic: Lesson 3 — Propositional Analysis · Actually opened lesson3 section page after chapter-host502 errors. Read3.2 lines14–18,3.3 lines20–36,3.4 lines38–56,3.5 lines74–84 and3.6 lines87–91. Verified partition of formulas, bidirectional entailment/equivalence, inconsistency entailing all conclusions and Gamma plus not-goal unsatisfiability. Course scenarios and tables are not reproduced.
  • Logic and Proof: 6. Semantics of Propositional Logic · Independently opened official Logic and Proof chapter 6. Read §6.1 lines 2–78 for syntax/semantics, two-valued valuations and material versus counterfactual implication, and §6.2–6.3 lines 152–189 for truth tables, soundness/completeness, hypotheses and induction. Confirmed that completeness is for the full stated calculus and is not transferred to the five-rule Python checker.
  • Logic and Proof: 3. Natural Deduction for Propositional Logic · Independently opened chapter 3, reading §3.1 lines 7–42 on assumptions, conjunction introduction, earlier-line presentations, discharge and substitution; §3.3 lines 132–145 on MP/conjunction elimination and hypothesis scopes. Read textual rules, not diagram-image inspection or execution of Lean examples.
  • Introduction to Logic: Lesson 3 — Propositional Analysis · Independently opened official lesson 3 section URL successfully. Read §§3.2–3.6, lines 14–94: validity/contingency/unsatisfiability, equivalence and bidirectional entailment, consistency, vacuous consequence and Gamma plus negated goal unsatisfiability. The article’s semantics matches these definitions. No publication-date or course-example reproduction claim.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.