Inductive definitions, structural induction and fixed points
Program data such as lists, trees, formulas and ASTs are defined inductively and their properties proved by structural induction. Well-founded induction generalizes this, and an inductive set is the least fixed point of a monotone operator (Knaster–Tarski), the same idea behind termination of data-flow analysis.
After this lesson you can
- Define inductive sets with constructors and closure, and functions by structural recursion
- Prove properties of lists, trees and formulas by structural induction covering every constructor
- Justify recursive function termination using a measure on a well-founded relation
- State and prove Knaster–Tarski and calculate least fixed points by Kleene iteration
- Implement a simple data-flow analysis as a least fixed-point computation
Before you start
Motivation: guarantees for infinitely many trees
A compiler does not see your program as text. First it converts it into an abstract syntax tree (AST), and thereafter everything is a function traversing trees: the type checker, the optimizer replacing 2 * 3 with 6, the code generator. A security static analyzer does the same and also traverses the control-flow graph looking for paths by which untrusted data reach a SQL query. A byte pair encoding (BPE) tokenizer defines its vocabulary by repeatedly applying a merge rule. A SAT solver receives formulas, which are trees too.
The guarantees we want from these tools always have the same form: something holds for every tree. The optimizer preserves the meaning of every expression. The normal-form converter terminates for every formula. The analyzer terminates for every program and misses no dangerous flow. No test suite covers infinitely many trees, so these guarantees are theorems, almost all proved using one technique: structural induction.
This lesson builds it from the ground up and takes it to practical applications:
- Inductive definitions. What exactly “the set of formulas” or “the set of binary trees” means, and why “and nothing else” is not decorative.
- Structural recursion and induction. Why functions on trees can be defined with one equation per constructor, and why one case per constructor proves a property of all of them.
- Well-founded induction. The general principle encompassing induction on and structural induction, and a tool for proving recursive functions terminate: a decreasing measure.
- Fixed points. An inductively defined set is the least fixed point of a monotone operator (Knaster–Tarski), calculated by iteration from the empty set (Kleene iteration). This is exactly what data-flow analysis does and why it terminates.
Inductive definitions
In the first lesson you defined formulas as “the smallest set of strings containing variables and closed under connectives,” and in the fifth used induction on . Both are cases of one scheme.
is closed, so the family is nonempty, and intersections of closed sets are closed: is the smallest closed set. These are the three clauses of every textbook inductive definition without intersections: base elements belong (base clause), constructors stay inside (inductive clauses), and nothing else belongs (extremal clause). The last says “smallest.”
Examples important in computer science:
| Set | Base | Constructors | BNF notation |
|---|---|---|---|
| Naturals | |||
| Lists over | , one per | ||
| Full binary trees | |||
| Arithmetic expressions | numbers and | , | |
| Propositional formulas | variables, , | , | lesson 1 grammar |
For lists, each gives a unary constructor ; if is infinite there are infinitely many constructors, and that is fine: each one’s arity must be finite. Intersection is a top-down definition: it does not say how elements are obtained. An equivalent bottom-up description by stages is what a program uses.
Proof
Stages grow. , and if , everything constructs from elements of it also constructs from elements of : . This is weak induction on .
Each stage lies in . Induct on : , and if , then because contains and is closed. Thus .
The union is closed. It contains . If , each is in some stage ; as stages grow, all are in with , and thus . Since is the smallest closed set, .
∎The last part crucially uses finite constructor arity: finitely many premises always fit in a finite stage. With infinitely many premises (“if are in , then is in ”) the union of stages need not be closed, and transfinite stages are needed. This returns with Kleene iteration.
The number of the first stage containing is its rank: the number of levels in its best derivation. For full binary trees the rank of is its height plus one, and stages contain , , , trees: each stage is the leaf plus all pairs of trees from the previous one, .
The extremal clause and junk objects
What is lost without “and nothing else”? The definition no longer determines a set. Base and inductive clauses hold for any closed set, and many exist: all alphabet strings, containing junk such as )p¬(; or, if formulas are read as trees and the universe permits infinite trees, all formula trees, finite and infinite, including , its own negation. A program that “proves” something for all formulas without using the extremal clause reasons about those objects too. In fixed points we will see that choosing the smallest or largest closed set distinguishes finite objects (induction) from infinite ones (coinduction).
Unique parsing: free generation
To prove things about the definition suffices. To define functions on more is needed: each element must be built in one way.
Equivalently every is either a base element or for a unique constructor and unique arguments. For fully parenthesized formulas this is lesson 1’s unique parsing theorem, which needed a prefix lemma. In programming-language data types (Python dataclass, Rust enum, Haskell or Lean algebraic types), free generation holds by construction: an Add(a, b) value records exactly the constructor and arguments used.
Without it things really fail. Generate from with and . This is a valid inductive definition (the smallest subset of containing 0 and closed under and is ), but not free: , so a base element is also a constructor image. Now try to “define” , , , intending to count steps. These equations force and , contradicting : no function satisfies them.
Structural recursion
Such a function is defined by structural recursion: one equation per constructor, with each recursive call on an immediate constructor argument. The general version lets also use the themselves, not just , and is proved similarly.
Proof
Existence. Construct the graph of as an inductive set. Let be the smallest set containing pairs such that, if for , then . We must show is a function, meaning the set of with exactly one such that is all of . Since is the smallest closed set, it suffices to show contains and is closed.
- Base. . If also with , would still satisfy the rules: only the base rule produces pairs with first component , because is not a constructor image. This contradicts minimality of .
- Constructor. Let with each and unique value . Then . If with another , remove it: the only rule that could require it is for a constructor with . By free generation, and , and since the premises can only be , forcing rather than . Again would not be smallest.
Thus , and := the unique with satisfies the equations by construction.
Uniqueness. If and satisfy the equations, contains and is closed: if they agree on the , they agree on because both equal of the same arguments. Hence it is all of .
∎The proof uses free generation in exactly one place: guaranteeing an element cannot be obtained by two routes yielding different values. This is the failure in the example.
By the theorem, each definition below on arithmetic expressions is legitimate; compiler evaluation is the fourth:
Here is an environment assigning each variable a number, and is the value of in it. The number of internal nodes is . For formulas, besides valuation from lesson 1, the most important operation is substitution , replacing every occurrence of variable with formula :
In code structural recursion is a match with one case per constructor. If one is missing, Python never complains: match finds no case and silently returns None (a type checker like mypy or Pyright can warn if you close the match with assert_never). Rust, Haskell or Lean detect it at compile time (exhaustiveness checking), the automated version of “do not forget an induction case.”
Structural induction
Proof
Let . By 1, . By 2, if , then (because is closed) and satisfies : is closed. Since is the smallest closed set, .
∎This is structural induction: one case per base element and constructor, with the property assumed for immediate arguments in each constructor case (the induction hypothesis, IH). Notice what the proof does not use: free generation. The extremal clause suffices for proof; defining functions also needs unique parsing. With , base and constructor , the principle literally is weak induction.
Construct expressions and watch the proof work. Each node shows a structural function’s value, calculated only from its children. With the proof layer each node is colored by whether it satisfies the property; selecting a node highlights the IH on its children and checks the step numerically.
What you should have seen:
- The proof does not depend on the tree constructed. The case list is the same for five and seventeen nodes: each case reasons about a generic constructor with arbitrary children satisfying IH. Thus a finite proof covers infinitely many trees.
- Adding a constructor requires adding a case. “Leaves = internal nodes + 1” holds for the grammar with and , and fails with unary minus: has one leaf and one internal node. The old proof was not wrong; it simply no longer covers every constructor. The size property survives: its new case, , is provable.
- A case that fails in general constructs a counterexample. If the step for constructor does not follow from IH, applying to an element satisfying normally yields one that does not. The minimum counterexample highlighted by the interactive always has the problematic constructor at its root.
Two theorems used by compilers
Proof
By structural induction on , with , and fixed.
- : .
- (or a constant): and , since changes only at .
- : .
- : the connective uses the same evaluation table on both sides, and by IH .
The key consequence is replacement of equivalents: if , then , because for each the modified valuations and are the same. Thus every equivalence law can be applied to a subformula anywhere without changing the whole’s meaning. This justifies each normal-form conversion step and each optimizer rewrite.
Well-founded induction
Weak, strong and structural induction share a skeleton: a “smaller than” relation lets us assume for everything smaller when proving . All that is required is that the relation disallow infinite descent. Recall from the previous lesson that on is well-founded if every nonempty subset of has a -minimal element, with nothing in the subset below it.
Proof
Suppose not, and let . By well-foundedness has a minimal element . Every lies outside (otherwise would not be minimal), so satisfies . The hypothesis then gives , contradicting .
∎This is the minimal-counterexample argument from lesson 5 in abstract form: well-founded induction. There is no separate base case: for a minimal element of the hypothesis “” is empty, and must be proved unaided. The converse holds too: if the principle holds for every , the relation is well-founded (apply it to “ is not in ” for without a minimal element). Thus well-founded induction is exactly what well-foundedness permits.
| Relation | Induction obtained |
|---|---|
| on | weak |
| on | strong |
| in a freely generated set | structural (immediate argument is well-founded: rank strictly decreases; without free generation cycles may occur, as and in the example) |
| proper subterm | strong structural: assume for all subtrees, not just children |
| lexicographic order on | on pairs: if , or and |
| for | by measure: most used for termination |
Lexicographic order on is well-founded though an element like has infinitely many below, : in a nonempty subset take the least first coordinate, then the least second among pairs with it. There can be no infinite descending chain. Lexicographic order of words over , dictionary order, is not well-founded: .
Well-founded recursion and termination measures
Like structural induction, well-founded induction has a function-defining twin: if is well-founded, an equation defining using only values with determines a unique function . The proof copies structural recursion with well-founded induction in place of structural induction. For programs the practical consequence is a termination criterion:
Proof
By well-founded induction on , well-founded because every nonempty set of values has a minimum in . Let be “f(x) terminates.” If every call with smaller measure terminates, f(x) makes finitely many direct calls, all on smaller-measure arguments, which terminate by hypothesis; its own work terminates too. Hence f(x) terminates.
can take values in any well-founded order, not just . Three examples of increasing difficulty:
- Euclid. if , and . Measure decreases because . The next lesson’s variant function is this idea applied to a loop.
- Ackermann. , , . No simple natural measure works: in the last equation the outer call receives a gigantic second argument. But decreases lexicographically in all three calls: , and regardless of second coordinate.
- Collatz. , if is even and if odd. No decreasing measure is known, and whether terminates for every has been open since 1937. The recursion follows a relation () whose well-foundedness is unknown.
A measure for negation normal form
The normal-form conversion from lesson 1 pushes negations toward variables. A natural rewriting-system implementation applies a law and calls again on the result:
This is not structural recursion: is not a subformula of , but a new formula. It is larger by one node. Termination needs a measure decreasing in all five equations.
The interactive’s family is , and . Write and and compare De Morgan’s two calls:
The difference is independent of and , yielding an exact condition: the measure decreases in all De Morgan calls if and only if . Three consequences:
- No additive measure works. With (each node adds fixed weight, like size), the condition is , impossible with nonnegative weights. Structurally, De Morgan changes one negation to two, and a sum of weights cannot penalize that.
- Doubling is insufficient if negation has weight. With and all weights 1, the difference is : the measure stays equal in each De Morgan step, and a measure that does not strictly decrease proves nothing.
- With , and it works. De Morgan drops 1. Double negation drops from to . Splitting drops from to or . This adds for each variable and binary connective, where counts negations above it; negations add nothing. Pushing a negation below a binary connective drops that connective’s weight from to , while everything below retains its number of negations above and hence its weight.
If is written directly, , the calls are on and , with fewer nodes than , and size suffices. The same function written differently needs a different termination proof. The lab also shows what happens with , which requires weighting the antecedent more.
Fixed points: the smallest closed set
Return to stages, . “ is closed” uses the same operator: is closed if and only if . And is monotone: if , everything built from can be built from , so . The inductive set is a fixed point of , and a special one. For the generality needed in program analysis, work in a complete lattice: a partial order where every subset has supremum and infimum . In particular it has a minimum and maximum . The model example is , with union as supremum and intersection as infimum.
The proof of the formula takes four steps, which you do. The proof is the same with order reversed.
Step 1 of 4. Why does exist?
An inductive set is a least fixed point
Apply the theorem to and operator . The pre-fixed points of are exactly the closed sets, so
This equality reorganizes everything above:
- The inductive definition is a least fixed point: says every element of is a base element or constructor applied to elements of (nothing else), and is closed.
- Structural induction is the exercise’s final sentence, Park’s principle: if , then . Checking induction cases checks that is pre-fixed.
- Stages are the iteration . Their union being the least fixed point is a separate theorem, valid for any lattice with the appropriate assumption.
Proof
- because is least; applying monotone , implies . If is any fixed point, , and if , then . In particular all terms lie below .
- Let . By continuity, (removing the first term does not change the supremum). So is fixed and, by 1, lies below all others.
- If for , there would be a strictly increasing chain of elements. Thus there is a first with , a fixed point and, by 1, the least.
The operator of a definition with finite-arity constructors is continuous: an element of is built from finitely many arguments, all in some in the chain, so belongs to . Thus stages exhaust the inductive set, the theorem at the lesson’s beginning seen from here.
Without continuity iteration may fall short. Take , a complete lattice, and , . It is monotone. Iteration from traverses all naturals with supremum , but : the Kleene limit is not even fixed, and needs one step beyond infinity. This is what happens with the earlier infinite-premise rule.
Least and greatest: induction and coinduction
The same operator may have very different fixed points. Take the universe of finite and infinite binary trees and . Its least fixed point is the finite trees: those built in finitely many steps. Its greatest fixed point is the whole universe, because every tree, finite or infinite, is a leaf or node with two trees beneath it. Objects in the greatest fixed point can be deconstructed step by step forever without contradiction, and are reasoned about using the dual principle, coinduction: if , then . Haskell lazy lists, streams and nonterminating processes such as servers are coinductive objects. “And nothing else” is precisely the choice of the least.
Data-flow analysis as a least fixed point
Now the promised application. Taint analysis is a defense: it marks data from untrusted inputs as tainted and checks whether any reaches a sensitive operation (a sink: a SQL query, a system command, an eval) without passing through a sanitizer. This underlies SQL-injection warnings in many static analyzers; its correctness and termination are theorems from this lesson. Consider:
u = input() # 1 fuente no confiable
q = "SELECT …" # 2
n = 0 # 3
while n < 3: # 4
q = q + t # 5 (t vale "" en la primera vuelta)
t = u # 6
n = n + 1 # 7
db.execute(q) # 8 sumidero: la consulta llega a la base de datos
On the first pass t is still clean when concatenated to q; on the second it already contains the input. Does input reach the query? The analysis answers without running anything.
The lattice. For each control-flow graph node , is the set of variables that may be tainted on exit from . An analysis state is a vector , ordered by componentwise inclusion. This is the complete lattice , of height : each strictly increasing step adds at least one variable to some node.
Transfer functions. Each statement transforms the incoming tainted set into the outgoing one:
and a sanitizer behaves like a constant. All three are monotone: if , removing preserves inclusion, and if touches a variable of , it touches one of too.
The equations. A node’s input is the union of its predecessors’ outputs (a may analysis: one path suffices), and the initial node’s input is empty. Together, with
is monotone because union and each are. Knaster–Tarski gives a least fixed point, and as the lattice has finite height, Kleene iteration , reaches it in at most 32 steps.
What you should have seen:
- The trajectory only rises. At loop header (node 4), the tainted set follows : input reaches
ton the first loop andqon the second. Iteration stabilizes in 13 steps, far below bound 32, anddb.execute(q)receives taintedq: the analyzer correctly warns. - The loop taints
q. Without the back edge,q = q + truns only with cleant, the fixed point has noqat the sink, and iteration ends in 8 steps. With a sanitizertis never tainted, nor isq. - Statement order changes step count, not the result. Swapping lines 5 and 6 taints
qon the first pass: the least fixed point is the same, reached in 9 steps. - The greatest fixed point gives false alarms. From , iteration decreases to , which marks
ntainted:n = n + 1justifies taint ofnusing the existing taint ofn, circular reasoning excluded by the least fixed point. With a sanitizer it is worse: the greatest fixed point marksqatdb.execute(q), giving a false warning. - Without monotonicity there are no guarantees. The faulty transfer “two tainted inputs cancel” ( tainted if exactly one of and is) is not monotone: , but and . The trajectory rises and falls, the state repeats with period 8 and iteration never terminates.
Why the least fixed point is the right answer
Both fixed points are sound: neither misses a real flow. A real flow is a concrete program path, and induction on path length shows taint accumulated at each node lies in for any with ; in particular for both fixed points. The difference is precision. The least fixed point contains only what can be derived from sources in finitely many steps, just as an inductive set contains only what can be constructed in finitely many steps. The greatest admits circular justifications. For a may analysis, the useful answer is the least fixed point: the most precise sound solution.
Not every analysis wants the least under . In a must analysis such as “definitely initialized variables,” a node’s input is the intersection of predecessor outputs, and the useful answer is the greatest fixed point under . Reverse the order and it is the least, as program-analysis textbooks present it: always a least fixed point in the appropriate lattice. This appears in the exercises.
Worklist: do not recalculate what has not changed
Parallel iteration recalculates all 8 nodes at each step even if only one changes. Real analyzers use a worklist: keep pending nodes, recalculate one at a time, and if its output changes add its successors.
Proof
Two invariants by induction on updates. (a) : true for , and if true before updating node , monotonicity gives . (b) : true for ; updating makes the new value , so grows, and monotonicity makes grow too, maintaining (b) at every node. By (b), each update strictly increases the vector, so there are at most as many as the lattice height; each update adds finitely many nodes to the list, so the algorithm terminates. At termination no node is pending, and a nonpending node satisfies (it was recalculated after its predecessors’ last change, or they never changed). Thus is fixed and by (a) the least.
∎Implementation from scratch
First arithmetic expressions as an inductive data type, with each function defined by structural recursion (one match case per constructor). The properties proved above are checked exhaustively for every expression up to a size: the inductive definition read as a stage-by-stage generator.
from dataclasses import dataclass
import itertools, random
@dataclass(frozen=True)
class Num:
v: int
@dataclass(frozen=True)
class Var:
name: str
@dataclass(frozen=True)
class Add:
a: object
b: object
@dataclass(frozen=True)
class Mul:
a: object
b: object
# Recursión estructural: un caso por constructor, llamadas solo sobre los hijos
def size(e):
match e:
case Num() | Var(): return 1
case Add(a, b) | Mul(a, b): return 1 + size(a) + size(b)
def height(e):
match e:
case Num() | Var(): return 0
case Add(a, b) | Mul(a, b): return 1 + max(height(a), height(b))
def leaves(e):
match e:
case Num() | Var(): return 1
case Add(a, b) | Mul(a, b): return leaves(a) + leaves(b)
def evaluate(e, env):
match e:
case Num(v): return v
case Var(name): return env[name]
case Add(a, b): return evaluate(a, env) + evaluate(b, env)
case Mul(a, b): return evaluate(a, env) * evaluate(b, env)
def show(e):
match e:
case Num(v): return str(v)
case Var(name): return name
case Add(a, b): return f"({show(a)} + {show(b)})"
case Mul(a, b): return f"({show(a)} * {show(b)})"
def fold(e):
"""Plegado de constantes y elementos neutros, de abajo arriba."""
match e:
case Num() | Var():
return e
case Add(a, b) | Mul(a, b):
a, b = fold(a), fold(b)
suma = isinstance(e, Add)
if isinstance(a, Num) and isinstance(b, Num):
return Num(a.v + b.v if suma else a.v * b.v)
neutro = Num(0 if suma else 1)
if a == neutro: return b
if b == neutro: return a
return Add(a, b) if suma else Mul(a, b)
ATOMS = [Num(0), Num(1), Num(2), Var("x")]
_memo = {}
def exprs_of_size(n):
"""Todas las expresiones con exactamente n nodos: la gramática como generador."""
if n not in _memo:
if n == 1:
out = list(ATOMS)
else:
out = [C(a, b) for i in range(1, n - 1)
for a in exprs_of_size(i) for b in exprs_of_size(n - 1 - i) for C in (Add, Mul)]
_memo[n] = out
return _memo[n]
total = 0
for n in range(1, 8, 2): # con constructores binarios el tamaño es impar
for e in exprs_of_size(n):
assert leaves(e) == (size(e) - leaves(e)) + 1 # hojas = internos + 1
assert size(e) <= 2 ** (height(e) + 1) - 1 # tamaño frente a altura
f = fold(e)
assert size(f) <= size(e) and fold(f) == f # no crece y es idempotente
assert all(evaluate(f, {"x": x}) == evaluate(e, {"x": x}) for x in (-2, 0, 1, 3))
total += len(exprs_of_size(n))
print(f"tamaño {n}: {len(exprs_of_size(n)):6d} expresiones, todas comprueban las cuatro propiedades")
print("total comprobadas:", total)
e = Add(Mul(Num(1), Add(Var("x"), Num(0))), Mul(Num(2), Num(3)))
print(show(e), " -> ", show(fold(e)))Exhaustive checking does not replace proof (it covers 10,788 expressions, not infinitely many), but is the best safety net while writing code: a missing case in fold appears at the first size using it. Now formulas. checked wraps a recursive function and raises an error if any recursive call fails to decrease the measure; since internal calls of nnf_raw look up global name nnf at execution, reassigning nnf monitors them all.
@dataclass(frozen=True)
class Atom:
name: str
@dataclass(frozen=True)
class Not:
a: object
@dataclass(frozen=True)
class And:
a: object
b: object
@dataclass(frozen=True)
class Or:
a: object
b: object
@dataclass(frozen=True)
class Imp:
a: object
b: object
SYM = {And: "∧", Or: "∨", Imp: "→"}
def sf(f):
match f:
case Atom(n): return n
case Not(a): return "¬" + sf(a)
case _: return f"({sf(f.a)} {SYM[type(f)]} {sf(f.b)})"
def ev(f, v):
match f:
case Atom(n): return v[n]
case Not(a): return not ev(a, v)
case And(a, b): return ev(a, v) and ev(b, v)
case Or(a, b): return ev(a, v) or ev(b, v)
case Imp(a, b): return (not ev(a, v)) or ev(b, v)
def subst(f, p, g):
"""f[g/p] por recursión estructural."""
match f:
case Atom(n): return g if n == p else f
case Not(a): return Not(subst(a, p, g))
case _: return type(f)(subst(f.a, p, g), subst(f.b, p, g))
def fsize(f):
match f:
case Atom(): return 1
case Not(a): return 1 + fsize(a)
case _: return 1 + fsize(f.a) + fsize(f.b)
def mu(f):
"""μ(p) = 1, μ(¬φ) = 2μ(φ), μ(φ∘ψ) = μ(φ) + μ(ψ) + 1 para ∧ y ∨, y μ(φ→ψ) = 2μ(φ) + μ(ψ) + 2."""
match f:
case Atom(): return 1
case Not(a): return 2 * mu(a)
case Imp(a, b): return 2 * mu(a) + mu(b) + 2
case _: return mu(f.a) + mu(f.b) + 1
def nnf_raw(f):
"""Forma normal negativa por reescritura: aplica una ley y vuelve a llamar a nnf."""
match f:
case Atom() | Not(Atom()): return f
case And(a, b): return And(nnf(a), nnf(b))
case Or(a, b): return Or(nnf(a), nnf(b))
case Imp(a, b): return nnf(Or(Not(a), b))
case Not(Not(a)): return nnf(a)
case Not(And(a, b)): return nnf(Or(Not(a), Not(b)))
case Not(Or(a, b)): return nnf(And(Not(a), Not(b)))
case Not(Imp(a, b)): return nnf(And(a, Not(b)))
def checked(fn, measure):
"""Envuelve una función recursiva: cada llamada debe tener medida menor que la que la hizo."""
stack = []
def wrapper(f):
if stack and not measure(f) < measure(stack[-1]):
raise AssertionError(f"no decrece: nnf({sf(stack[-1])}) llama a nnf({sf(f)}), "
f"{measure(stack[-1])} -> {measure(f)}")
stack.append(f)
try:
return fn(f)
finally:
stack.pop()
return wrapper
def is_nnf(f):
match f:
case Atom() | Not(Atom()): return True
case And(a, b) | Or(a, b): return is_nnf(a) and is_nnf(b)
case _: return False
ATOMS_F = [Atom("p"), Atom("q")]
_fm = {}
def formulas_of_size(n):
if n not in _fm:
out = list(ATOMS_F) if n == 1 else [Not(a) for a in formulas_of_size(n - 1)]
out += [C(a, b) for i in range(1, n - 1) for a in formulas_of_size(i)
for b in formulas_of_size(n - 1 - i) for C in (And, Or, Imp)]
_fm[n] = out
return _fm[n]
VALS = [dict(zip("pq", bits)) for bits in itertools.product([False, True], repeat=2)]
# 1. Con el tamaño como medida, la reescritura de De Morgan lo hace crecer
nnf = checked(nnf_raw, fsize)
try:
nnf(Not(And(Atom("p"), Not(Or(Atom("q"), Atom("r"))))))
except AssertionError as err:
print("tamaño:", err)
# 2. Con μ, todas las llamadas decrecen: comprobación exhaustiva hasta tamaño 7
nnf = checked(nnf_raw, mu)
cuenta = 0
for n in range(1, 8):
for f in formulas_of_size(n):
g = nnf(f)
assert is_nnf(g) and all(ev(g, v) == ev(f, v) for v in VALS), sf(f)
cuenta += 1
print("fórmulas comprobadas hasta tamaño 7:", cuenta, [len(formulas_of_size(n)) for n in range(1, 8)])
# 3. Lema de sustitución: v(φ[ψ/p]) = v[p ↦ v(ψ)](φ)
psis = [Atom("q"), Not(Atom("p")), Imp(Atom("q"), Atom("p")), And(Atom("p"), Not(Atom("q")))]
ok = all(ev(subst(f, "p", g), v) == ev(f, {**v, "p": ev(g, v)})
for n in range(1, 6) for f in formulas_of_size(n) for g in psis for v in VALS)
print("lema de sustitución en", sum(len(formulas_of_size(n)) for n in range(1, 6)) * len(psis) * 4, "casos:", ok)
# 4. Por encima, fórmulas aleatorias más grandes con cuatro variables
rng = random.Random(0)
def rand_f(d):
if d == 0 or rng.random() < 0.15:
return Atom(rng.choice("pqrs"))
k = rng.choice("NNAOI")
if k == "N":
return Not(rand_f(d - 1))
return {"A": And, "O": Or, "I": Imp}[k](rand_f(d - 1), rand_f(d - 1))
VALS4 = [dict(zip("pqrs", bits)) for bits in itertools.product([False, True], repeat=4)]
grandes = [rand_f(7) for _ in range(300)]
for f in grandes:
g = nnf(f)
assert is_nnf(g) and all(ev(g, v) == ev(f, v) for v in VALS4)
print("300 fórmulas aleatorias, tamaño medio", round(sum(map(fsize, grandes)) / 300, 1), ": correctas y μ decrece siempre")With nnf checked, conjunctive normal form is another structural recursion, now over formulas in negation normal form: a clause is a set of literals and disjunction distributes clauses, as in lesson 1. Equivalence is proved by structural induction on NNF; here it is checked.
def cnf(f):
"""CNF de una fórmula en NNF, como lista de cláusulas (frozensets de literales)."""
match f:
case Atom() | Not(Atom()): return [frozenset([f])]
case And(a, b): return cnf(a) + cnf(b)
case Or(a, b): return [ca | cb for ca in cnf(a) for cb in cnf(b)]
raise ValueError("la entrada debe estar en forma normal negativa")
def ev_cnf(cls, v):
return all(any(ev(lit, v) for lit in c) for c in cls)
cuenta = 0
for n in range(1, 7):
for f in formulas_of_size(n):
cls = cnf(nnf(f))
assert all(isinstance(l, Atom) or (isinstance(l, Not) and isinstance(l.a, Atom)) for c in cls for l in c)
assert all(ev_cnf(cls, v) == ev(f, v) for v in VALS), sf(f)
cuenta += 1
print("CNF correcta en", cuenta, "fórmulas")
f = Not(Imp(Or(Atom("p"), Atom("q")), And(Atom("r"), Not(Atom("p")))))
print(sf(f), "\n NNF:", sf(nnf(f)), "\n CNF:", [sorted(sf(l) for l in c) for c in cnf(nnf(f))])Now fixed points. kleene iterates from until nothing changes; it shows full binary tree stages, constructs a bounded inductive set (balanced-parenthesis strings of length ), and brute-force checks Knaster–Tarski in a small lattice by enumerating its 256 elements.
def kleene(F, bottom, max_steps=10_000):
x, chain = bottom, [bottom]
for _ in range(max_steps):
y = F(x)
if y == x:
return x, chain
x = y
chain.append(x)
raise RuntimeError("no se estabiliza")
# Etapas de los árboles binarios llenos: Φ(X) = {hoja} ∪ {nodo(l, r) : l, r ∈ X}
def Phi_trees(X):
return frozenset(["hoja"]) | frozenset(("nodo", l, r) for l in X for r in X)
X = frozenset()
etapas = []
for n in range(1, 6):
X = Phi_trees(X)
etapas.append(len(X))
print("|Φⁿ(∅)| para n = 1..5:", etapas)
# Paréntesis equilibrados de longitud ≤ 8: Φ(X) = {ε} ∪ {"(" a ")" b : a, b ∈ X}, recortado
def Phi_par(X, L=8):
return frozenset([""]) | frozenset("(" + a + ")" + b for a in X for b in X if len(a) + len(b) + 2 <= L)
D, chain = kleene(Phi_par, frozenset())
print("paréntesis: punto fijo en", len(chain) - 1, "pasos;", len(D), "cadenas; por longitud:",
[sum(1 for s in D if len(s) == k) for k in range(0, 9, 2)])
# Knaster-Tarski por fuerza bruta en P({0..7}), con una regla circular 5 -> 1
U = range(8)
def Phi_c(X):
return frozenset([0]) | frozenset(n + 2 for n in X if n + 2 < 8) | (frozenset([1]) if 5 in X else frozenset())
subsets = [frozenset(c) for r in range(9) for c in itertools.combinations(U, r)]
prefijos = [S for S in subsets if Phi_c(S) <= S]
fijos = [S for S in subsets if Phi_c(S) == S]
postfijos = [S for S in subsets if S <= Phi_c(S)]
inf_pre = frozenset.intersection(*prefijos)
sup_post = frozenset().union(*postfijos)
lfp, _ = kleene(Phi_c, frozenset())
print("puntos prefijos:", len(prefijos), "| puntos fijos:", [sorted(S) for S in fijos])
print("ínfimo de los prefijos:", sorted(inf_pre), "= Kleene desde ∅:", sorted(lfp), "->", inf_pre == lfp)
print("supremo de los postfijos:", sorted(sup_post), "= mayor punto fijo:", sup_post == max(fijos, key=len))Odd numbers form a cycle of justifications ( and ) not fed from : they are in the greatest fixed point and not the least, like variable n in taint analysis. Finally the analyzer. Parallel iteration is the interactive’s; the worklist counts transfer-function evaluations. Then in a smaller program (4 nodes, 3 variables, states), all states are enumerated to find all fixed points and check Kleene’s result lies below every one.
from collections import deque
def transfer(stmt, T):
kind = stmt[0]
if kind == "source": return T | {stmt[1]}
if kind in ("const", "sanitize"): return T - {stmt[1]}
if kind == "assign":
x, deps = stmt[1], stmt[2]
return (T - {x}) | ({x} if any(d in T for d in deps) else frozenset())
return T
def F(prog, edges, X):
"""Un paso de Kleene en paralelo: todos los nodos a partir del estado anterior."""
preds = [[a for a, b in edges if b == i] for i in range(len(prog))]
return tuple(transfer(prog[i], frozenset().union(*[X[j] for j in preds[i]])) for i in range(len(prog)))
def jacobi(prog, edges, vars_, top=False):
X = tuple(frozenset(vars_ if top else ()) for _ in prog)
k = 0
while (Y := F(prog, edges, X)) != X:
X, k = Y, k + 1
return X, k
def worklist(prog, edges):
preds = [[a for a, b in edges if b == i] for i in range(len(prog))]
succs = [[b for a, b in edges if a == i] for i in range(len(prog))]
X = [frozenset()] * len(prog)
work, evals = deque(range(len(prog))), 0
while work:
i = work.popleft()
new = transfer(prog[i], frozenset().union(*[X[j] for j in preds[i]]))
evals += 1
if new != X[i]:
X[i] = new
work.extend(s for s in succs[i] if s not in work)
return tuple(X), evals
V4 = ("u", "t", "q", "n")
PROG = [("source", "u"), ("const", "q"), ("const", "n"), ("nop",),
("assign", "q", ("q", "t")), ("assign", "t", ("u",)), ("assign", "n", ("n",)), ("nop",)]
EDGES = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 3), (3, 7)]
def fmt(X, vars_=V4):
return " ".join("".join(v for v in vars_ if v in s) or "∅" for s in X)
lfp, pasos = jacobi(PROG, EDGES, V4)
wl, evals = worklist(PROG, EDGES)
gfp, _ = jacobi(PROG, EDGES, V4, top=True)
print("menor punto fijo:", fmt(lfp), f"| {pasos} pasos en paralelo ({pasos * len(PROG)} evaluaciones)")
print("lista de trabajo: ", fmt(wl), f"| {evals} evaluaciones | mismo resultado: {wl == lfp}")
print("mayor punto fijo:", fmt(gfp))
SAN = list(PROG); SAN[5] = ("sanitize", "t", ("u",))
print("con saneador, menor:", fmt(jacobi(SAN, EDGES, V4)[0]), "| mayor:", fmt(jacobi(SAN, EDGES, V4, top=True)[0]))
# Todos los puntos fijos de un programa pequeño: a = input(); while ...: c = c + 1; b = a
small = [("source", "a"), ("nop",), ("assign", "c", ("c",)), ("assign", "b", ("a",))]
small_edges = [(0, 1), (1, 2), (2, 3), (3, 1)]
V3 = ("a", "b", "c")
sets = [frozenset(c) for r in range(4) for c in itertools.combinations(V3, r)]
fixed = [X for X in itertools.product(sets, repeat=4) if F(small, small_edges, X) == X]
lo, _ = jacobi(small, small_edges, V3)
hi, _ = jacobi(small, small_edges, V3, top=True)
below_all = all(all(a <= b for a, b in zip(lo, X)) for X in fixed)
above_all = all(all(b <= a for a, b in zip(hi, X)) for X in fixed)
print(f"programa pequeño: {len(fixed)} puntos fijos de 4096 estados")
print(" Kleene desde ⊥:", fmt(lo, V3), "| por debajo de todos:", below_all)
print(" Kleene desde ⊤:", fmt(hi, V3), "| por encima de todos:", above_all)Both strategies reach the same least fixed point, guaranteed by chaotic iteration, but with very different cost: 13 parallel steps are 104 transfer-function evaluations, while the worklist needs 16. In the small program only 2 of 4096 states are fixed points, and loop variable c in c = c + 1 distinguishes them: clean in the least, tainted in the greatest.
The professional version
Python has its own inductive tree type: module ast. ast.NodeTransformer is prewritten structural recursion traversing the tree and calling visit_<Constructor> at each node. Constant folding fits in one class. To check it we do not use eval, which would execute arbitrary code if the string came from outside, but our own evaluator accepting only known constructors, another structural recursion.
import ast, operator
OPS = {ast.Add: operator.add, ast.Mult: operator.mul, ast.Sub: operator.sub}
class Plegado(ast.NodeTransformer):
def visit_BinOp(self, node):
self.generic_visit(node) # primero los hijos: de abajo arriba
if isinstance(node.left, ast.Constant) and isinstance(node.right, ast.Constant) and type(node.op) in OPS:
return ast.copy_location(ast.Constant(OPS[type(node.op)](node.left.value, node.right.value)), node)
return node
def valor(node, env):
"""Evaluador seguro: solo constantes numéricas, variables y + − ×. Cualquier otro nodo es un error."""
match node:
case ast.Expression(body): return valor(body, env)
case ast.Constant(value) if isinstance(value, int): return value
case ast.Name(id): return env[id]
case ast.BinOp(l, op, r) if type(op) in OPS: return OPS[type(op)](valor(l, env), valor(r, env))
raise ValueError(f"nodo no permitido: {ast.dump(node)}")
src = "(2 * 3) + x * (4 - 1)"
arbol = ast.parse(src, mode="eval")
plegado = Plegado().visit(ast.parse(src, mode="eval"))
print(ast.unparse(arbol), " -> ", ast.unparse(plegado))
print("nodos:", sum(1 for _ in ast.walk(arbol)), "->", sum(1 for _ in ast.walk(plegado)))
# Comprobación: todas las expresiones de tamaño ≤ 5 de la primera celda y una muestra de las de tamaño 7
muestra = exprs_of_size(1) + exprs_of_size(3) + exprs_of_size(5) + random.Random(1).sample(exprs_of_size(7), 1500)
for e in muestra:
t = ast.parse(show(e), mode="eval")
p = Plegado().visit(ast.parse(show(e), mode="eval"))
assert all(valor(t, {"x": x}) == valor(p, {"x": x}) for x in (-2, 0, 3))
print("plegado de ast correcto en", len(muestra), "expresiones")For logic, sympy has to_nnf and to_cnf, with simplifications the classroom version lacks. Comparing two large formulas by truth table always costs rows; satisfiable uses a DPLL solver, exponential in the worst case too but much faster in practice, and two formulas are equivalent if the negation of their biconditional is unsatisfiable.
import sympy
from sympy.logic.boolalg import to_nnf, to_cnf, Equivalent
from sympy.logic.inference import satisfiable
S = {n: sympy.Symbol(n) for n in "pqrs"}
def to_sympy(f):
match f:
case Atom(n): return S[n]
case Not(a): return sympy.Not(to_sympy(a))
case And(a, b): return sympy.And(to_sympy(a), to_sympy(b))
case Or(a, b): return sympy.Or(to_sympy(a), to_sympy(b))
case Imp(a, b): return sympy.Implies(to_sympy(a), to_sympy(b))
medianas = [rand_f(4) for _ in range(6)]
for f in medianas:
nuestra = to_sympy(nnf(f))
suya = to_nnf(to_sympy(f), simplify=False)
iguales = not satisfiable(sympy.Not(Equivalent(nuestra, suya)))
print(f"tamaño {fsize(f):3d}: nnf propia con {sympy.count_ops(nuestra):3d} operaciones, "
f"sympy {sympy.count_ops(suya):3d}, equivalentes: {iguales}")
print(to_cnf(to_sympy(Not(Imp(Or(Atom("p"), Atom("q")), And(Atom("r"), Not(Atom("p")))))), simplify=True))In professional practice, all three threads of the lesson have mature tools:
- Proof assistants. In Lean or Coq, declaring an inductive type automatically generates recursion and induction principles, one case per constructor, and the checker rejects a recursive function unless it sees an argument decreasing structurally or is given a well-founded measure. The first volume of Software Foundations teaches exactly this mechanically. Return to it with proof assistants at the end of the module.
- Program analysis in Datalog. Many analyzers express equations as logical rules and leave the least fixed point to a specialized engine. This lesson’s taint analysis fits four rules:
in(N, V) :- edge(M, N), out(M, V).,out(N, X) :- source(N, X).,out(N, V) :- in(N, V), not defines(N, V).andout(N, X) :- in(N, Y), uses(N, X, Y).The engine applies rules until no new fact is derived: Kleene iteration with a worklist. - Security static analyzers. Commercial and open-source tools warning of SQL injection or command execution with external data calculate this same least fixed point at scale with many refinements (call-context sensitivity, library models, declared sanitizers). Warnings start real mitigation: parameterized queries instead of string concatenation, input validation at the boundary and least privilege at the sink.
Common mistakes
Exercises
Step 1 of 4. How do you set up the proof?
Step 1 of 5. What statement do you prove by structural induction?
More than one answer may be correct.
More than one answer may be correct.
nnf(f) for formulas with Var, Not, And, Or and Imp, and a measure mu(f) returning an integer and strictly decreasing in every recursive call made by your nnf. The result must be equivalent and in negation normal form: no Imp and Not only before variables. Tests trace your function: whenever nnf calls itself they check that mu of the new argument is less than mu of the caller argument. Write it by rewriting (apply a law and call again on the result): this makes the measure the difficult part.from dataclasses import dataclass
@dataclass(frozen=True)
class Var:
name: str
@dataclass(frozen=True)
class Not:
a: object
@dataclass(frozen=True)
class And:
a: object
b: object
@dataclass(frozen=True)
class Or:
a: object
b: object
@dataclass(frozen=True)
class Imp:
a: object
b: object
def mu(f):
"""Medida de terminación: entero >= 0 que baja en cada llamada recursiva de nnf."""
pass
def nnf(f):
"""Forma normal negativa. Llama a nnf recursivamente (por su nombre)."""
passtransfer(stmt, T) receives a statement and frozenset of variables tainted on entry and returns the outgoing set; statements are tuples ('source', x), ('const', x), ('assign', x, deps), ('sanitize', x, deps) (that is, x = escape(deps)) and ('nop',). is_monotone(f, universe) must exhaustively check whether universe implies . analyze is already written (worklist iteration) and uses your transfer. Tests use the lesson program.from itertools import combinations
def transfer(stmt, T):
"""Variables contaminadas tras ejecutar stmt si a la entrada lo están las de T (frozensets)."""
pass
def is_monotone(f, universe):
"""True si S ⊆ T ⊆ universe implica f(S) ⊆ f(T)."""
pass
def analyze(stmts, edges):
"""Kleene con lista de trabajo. Devuelve OUT[i] (frozenset) para cada nodo i."""
preds = {i: [a for a, b in edges if b == i] for i in range(len(stmts))}
succs = {i: [b for a, b in edges if a == i] for i in range(len(stmts))}
out = [frozenset()] * len(stmts)
work = list(range(len(stmts)))
while work:
i = work.pop(0)
IN = frozenset().union(*[out[p] for p in preds[i]])
new = transfer(stmts[i], IN)
if new != out[i]:
out[i] = new
work.extend(s for s in succs[i] if s not in work)
return outSummary
- Inductive definition: base, constructors and ‘nothing else’; the set is the intersection of closed sets and also the union of stages for finite-arity constructors.
- Structural recursion: well-defined under free generation (unique parsing); without it innocent-looking equations can have no solution.
- Structural induction: one case per constructor with induction hypotheses on arguments; free generation is unnecessary, but every case is needed.
- Well-founded induction: encompasses weak, strong and structural induction; gives termination by measure, possibly requiring lexicographic orders beyond or nonadditive weights.
- Knaster–Tarski and Kleene: every monotone function on a complete lattice has least and greatest fixed points; with continuity or finite height, iteration from reaches the least. A may analysis’s least fixed point is the most precise sound solution; the greatest permits circular justifications.