Module contents
Lesson 7 of 22Core 105 min

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 N\N 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 N\N. Both are cases of one scheme.

UU is closed, so the family is nonempty, and intersections of closed sets are closed: II 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:

SetBaseConstructorsBNF notation
Naturals N\N00suc⁡(n)\operatorname{suc}(n)n::=0∣suc⁡(n)n ::= 0 \mid \operatorname{suc}(n)
Lists over AA[ ][\,]cons⁡(a,ℓ)\operatorname{cons}(a, \ell), one per a∈Aa \in Aℓ::=[ ]∣a::ℓ\ell ::= [\,] \mid a :: \ell
Full binary treeshoja⁡\operatorname{hoja}nodo⁡(l,r)\operatorname{nodo}(l, r)t::=hoja⁡∣nodo⁡(t,t)t ::= \operatorname{hoja} \mid \operatorname{nodo}(t, t)
Arithmetic expressionsnumbers and xx(e1+e2)(e_1 + e_2), (e1×e2)(e_1 \times e_2)e::=n∣x∣(e+e)∣(e×e)e ::= n \mid x \mid (e + e) \mid (e \times e)
Propositional formulasvariables, ⊤\top, ⊥\bot¬φ\lnot\varphi, (φ∘ψ)(\varphi \circ \psi)lesson 1 grammar

For lists, each a∈Aa \in A gives a unary constructor ℓ↦a::ℓ\ell \mapsto a :: \ell; if AA 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. X0=∅⊆X1X_0 = \varnothing \subseteq X_1, and if Xn−1⊆XnX_{n-1} \subseteq X_n, everything Φ\Phi constructs from elements of Xn−1X_{n-1} it also constructs from elements of XnX_n: Xn⊆Xn+1X_n \subseteq X_{n+1}. This is weak induction on nn.

Each stage lies in II. Induct on nn: X0=∅⊆IX_0 = \varnothing \subseteq I, and if Xn⊆IX_n \subseteq I, then Xn+1=Φ(Xn)⊆IX_{n+1} = \Phi(X_n) \subseteq I because II contains BB and is closed. Thus X∞:=⋃nXn⊆IX_\infty := \bigcup_n X_n \subseteq I.

The union is closed. It contains B=X1B = X_1. If x1,…,xk∈X∞x_1, \dots, x_k \in X_\infty, each xix_i is in some stage XniX_{n_i}; as stages grow, all are in XNX_N with N=max⁡iniN = \max_i n_i, and thus c(x1,…,xk)∈XN+1⊆X∞c(x_1, \dots, x_k) \in X_{N+1} \subseteq X_\infty. Since II is the smallest closed set, I⊆X∞I \subseteq X_\infty.

∎

The last part crucially uses finite constructor arity: finitely many premises always fit in a finite stage. With infinitely many premises (“if 0,1,2,…0, 1, 2, \dots are in XX, then ∞\infty is in XX”) 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 xx is its rank: the number of levels in its best derivation. For full binary trees the rank of tt is its height plus one, and stages contain ∣X1∣=1\abs{X_1} = 1, ∣X2∣=2\abs{X_2} = 2, ∣X3∣=5\abs{X_3} = 5, ∣X4∣=26\abs{X_4} = 26 trees: each stage is the leaf plus all pairs of trees from the previous one, ∣Xn+1∣=1+∣Xn∣2\abs{X_{n+1}} = 1 + \abs{X_n}^2.

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 ¬¬¬⋯\lnot\lnot\lnot\cdots, 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 II the definition suffices. To define functions on II more is needed: each element must be built in one way.

Equivalently every x∈Ix \in I is either a base element or c(x1,…,xk)c(x_1, \dots, x_k) for a unique constructor cc 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 Z\Z from 00 with s(n)=n+1s(n) = n + 1 and p(n)=n−1p(n) = n - 1. This is a valid inductive definition (the smallest subset of Z\Z containing 0 and closed under ss and pp is Z\Z), but not free: 0=p(s(0))0 = p(s(0)), so a base element is also a constructor image. Now try to “define” F(0)=0F(0) = 0, F(s(n))=F(n)+1F(s(n)) = F(n) + 1, F(p(n))=F(n)+1F(p(n)) = F(n) + 1, intending to count steps. These equations force F(1)=1F(1) = 1 and F(0)=F(p(1))=2F(0) = F(p(1)) = 2, contradicting F(0)=0F(0) = 0: 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 hch_c also use the xix_i themselves, not just F(xi)F(x_i), and is proved similarly.

Proof

Existence. Construct the graph of FF as an inductive set. Let G⊆I×AG \subseteq I \times A be the smallest set containing pairs (b,g(b))(b, g(b)) such that, if (xi,ai)∈G(x_i, a_i) \in G for i=1,…,ki = 1, \dots, k, then (c(x1,…,xk), hc(a1,…,ak))∈G\big(c(x_1, \dots, x_k),\, h_c(a_1, \dots, a_k)\big) \in G. We must show GG is a function, meaning the set SS of x∈Ix \in I with exactly one aa such that (x,a)∈G(x, a) \in G is all of II. Since II is the smallest closed set, it suffices to show SS contains BB and is closed.

  • Base. (b,g(b))∈G(b, g(b)) \in G. If also (b,a)∈G(b, a) \in G with a≠g(b)a \ne g(b), G∖{(b,a)}G \setminus \{(b, a)\} would still satisfy the rules: only the base rule produces pairs with first component bb, because bb is not a constructor image. This contradicts minimality of GG.
  • Constructor. Let x=c(x1,…,xk)x = c(x_1, \dots, x_k) with each xi∈Sx_i \in S and unique value aia_i. Then (x,hc(a1,…,ak))∈G(x, h_c(a_1, \dots, a_k)) \in G. If (x,a)∈G(x, a) \in G with another aa, remove it: the only rule that could require it is for a constructor c′c' with c′(y1,…,yk′)=xc'(y_1, \dots, y_{k'}) = x. By free generation, c′=cc' = c and yi=xiy_i = x_i, and since xi∈Sx_i \in S the premises can only be (xi,ai)(x_i, a_i), forcing hc(a1,…,ak)h_c(a_1, \dots, a_k) rather than aa. Again GG would not be smallest.

Thus S=IS = I, and F(x)F(x) := the unique aa with (x,a)∈G(x, a) \in G satisfies the equations by construction.

Uniqueness. If FF and F′F' satisfy the equations, {x∈I:F(x)=F′(x)}\{x \in I : F(x) = F'(x)\} contains BB and is closed: if they agree on the xix_i, they agree on c(x1,…,xk)c(x_1, \dots, x_k) because both equal hch_c of the same arguments. Hence it is all of II.

∎

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 Z\Z example.

By the theorem, each definition below on arithmetic expressions is legitimate; compiler evaluation is the fourth:

n, x(e1+e2), (e1×e2)tam⁡11+tam⁡(e1)+tam⁡(e2)alt⁡01+max⁡(alt⁡(e1),alt⁡(e2))hojas⁡1hojas⁡(e1)+hojas⁡(e2)⟦⋅⟧ρn, ρ(x)⟦e1⟧ρ+⟦e2⟧ρ,  ⟦e1⟧ρ⋅⟦e2⟧ρ\begin{array}{llll} & n,\ x & (e_1 + e_2),\ (e_1 \times e_2) \\[2pt] \operatorname{tam} & 1 & 1 + \operatorname{tam}(e_1) + \operatorname{tam}(e_2) \\ \operatorname{alt} & 0 & 1 + \max\big(\operatorname{alt}(e_1), \operatorname{alt}(e_2)\big) \\ \operatorname{hojas} & 1 & \operatorname{hojas}(e_1) + \operatorname{hojas}(e_2) \\ \llbracket\cdot\rrbracket_\rho & n,\ \rho(x) & \llbracket e_1\rrbracket_\rho + \llbracket e_2\rrbracket_\rho,\ \ \llbracket e_1\rrbracket_\rho \cdot \llbracket e_2\rrbracket_\rho \end{array}

Here ρ\rho is an environment assigning each variable a number, and ⟦e⟧ρ\llbracket e\rrbracket_\rho is the value of ee in it. The number of internal nodes is int⁡(e)=tam⁡(e)−hojas⁡(e)\operatorname{int}(e) = \operatorname{tam}(e) - \operatorname{hojas}(e). For formulas, besides valuation v(φ)v(\varphi) from lesson 1, the most important operation is substitution φ[ψ/p]\varphi[\psi/p], replacing every occurrence of variable pp with formula ψ\psi:

p[ψ/p]=ψ,q[ψ/p]=q (q≠p),(¬φ)[ψ/p]=¬(φ[ψ/p]),(φ1∘φ2)[ψ/p]=(φ1[ψ/p]∘φ2[ψ/p]).p[\psi/p] = \psi, \qquad q[\psi/p] = q \ (q \ne p), \qquad (\lnot\varphi)[\psi/p] = \lnot(\varphi[\psi/p]), \qquad (\varphi_1 \circ \varphi_2)[\psi/p] = (\varphi_1[\psi/p] \circ \varphi_2[\psi/p]).

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 S={x∈I:P(x)}S = \{x \in I : P(x)\}. By 1, B⊆SB \subseteq S. By 2, if x1,…,xk∈Sx_1, \dots, x_k \in S, then c(x1,…,xk)∈Ic(x_1, \dots, x_k) \in I (because II is closed) and satisfies PP: SS is closed. Since II is the smallest closed set, I⊆SI \subseteq S.

∎

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 N\N, base 00 and constructor suc⁡\operatorname{suc}, 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.

InteractiveConstructors, recursion and induction on a tree
(((x + 2) × 3) + (x × x))
x121+3IH31IH×5x1x1×3+9
Selection (product): ((x + 2) × 3)
Recursion: size = 1 + 3 + 1 = 5
Step: IH in the children ✓ ✓ · leaves = 2 + 1 = 3, internal nodes + 1 = (1 + 0 + 1) + 1 = 3 ✓
Proof by structural induction of P(e)P(e): leaves⁡(e)=int⁡(e)+1\operatorname{leaves}(e) = \operatorname{int}(e) + 1: one case per constructor.
✓ nn
1=0+11 = 0 + 1
✓ xx
1=0+11 = 0 + 1
✓ (a+b)(a + b)
(int⁡a+1)+(int⁡b+1)=int⁡(a+b)+1(\operatorname{int} a + 1) + (\operatorname{int} b + 1) = \operatorname{int}(a + b) + 1
✓ (a×b)(a \times b)
as for ++: the constructor has two children and one node
All cases hold, so P(e)P(e) holds for every expression in this grammar, not only for the 9 subexpressions in the tree.
Constructors on the selection
Replace with
Value at each node
size9
height3
leaves, internal nodes5, 4
value with x = 216
Click a node and apply constructors: e↦(e+1)e \mapsto (e + 1) turns the selection into the left child of a sum. Small labels show the chosen function's value on each subtree; the ‘Recursion’ line shows how the selected node is calculated from its children. The case list is the entire proof: one row per constructor. Enable constructor −a-a (unary minus) and compare the three properties: one proves the new case without trouble, two fail, and one application of that constructor produces a counterexample.

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 ×\times, and fails with unary minus: −2-2 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, 1+tam⁡(a)≤2h≤2h+1−11 + \operatorname{tam}(a) \le 2^{h} \le 2^{h+1} - 1, is provable.
  • A case that fails in general constructs a counterexample. If the step for constructor cc does not follow from IH, applying cc to an element satisfying PP 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 φ\varphi, with ψ\psi, pp and vv fixed.

  • φ=p\varphi = p: v(p[ψ/p])=v(ψ)=v′(p)v(p[\psi/p]) = v(\psi) = v'(p).
  • φ=q≠p\varphi = q \ne p (or a constant): q[ψ/p]=qq[\psi/p] = q and v(q)=v′(q)v(q) = v'(q), since v′v' changes only at pp.
  • φ=¬φ1\varphi = \lnot\varphi_1: v((¬φ1)[ψ/p])=v(¬(φ1[ψ/p]))=1−v(φ1[ψ/p])=IH1−v′(φ1)=v′(¬φ1)v((\lnot\varphi_1)[\psi/p]) = v(\lnot(\varphi_1[\psi/p])) = 1 - v(\varphi_1[\psi/p]) \overset{\text{IH}}{=} 1 - v'(\varphi_1) = v'(\lnot\varphi_1).
  • φ=(φ1∘φ2)\varphi = (\varphi_1 \circ \varphi_2): the connective uses the same evaluation table on both sides, and by IH v(φi[ψ/p])=v′(φi)v(\varphi_i[\psi/p]) = v'(\varphi_i).
∎

The key consequence is replacement of equivalents: if ψ≡ψ′\psi \equiv \psi', then φ[ψ/p]≡φ[ψ′/p]\varphi[\psi/p] \equiv \varphi[\psi'/p], because for each vv the modified valuations v[p↦v(ψ)]v[p \mapsto v(\psi)] and v[p↦v(ψ′)]v[p \mapsto v(\psi')] 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 PP for everything smaller when proving P(x)P(x). All that is required is that the relation disallow infinite descent. Recall from the previous lesson that ≺\prec on AA is well-founded if every nonempty subset of AA has a ≺\prec-minimal element, with nothing in the subset below it.

Proof

Suppose not, and let C={x∈A:¬P(x)}≠∅C = \{x \in A : \lnot P(x)\} \ne \varnothing. By well-foundedness CC has a minimal element mm. Every y≺my \prec m lies outside CC (otherwise mm would not be minimal), so satisfies PP. The hypothesis then gives P(m)P(m), contradicting m∈Cm \in C.

∎

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 AA the hypothesis “∀y≺x, P(y)\forall y \prec x,\ P(y)” is empty, and P(x)P(x) must be proved unaided. The converse holds too: if the principle holds for every PP, the relation is well-founded (apply it to “xx is not in CC” for CC without a minimal element). Thus well-founded induction is exactly what well-foundedness permits.

Relation ≺\precInduction obtained
n≺n+1n \prec n + 1 on N\Nweak
m<nm < n on N\Nstrong
xi≺c(x1,…,xk)x_i \prec c(x_1, \dots, x_k) in a freely generated setstructural (immediate argument is well-founded: rank strictly decreases; without free generation cycles may occur, as 0=p(1)0 = p(1) and 1=s(0)1 = s(0) in the Z\Z example)
proper subtermstrong structural: assume PP for all subtrees, not just children
lexicographic order on N×N\N \times \Non pairs: (m′,n′)≺(m,n)(m', n') \prec (m, n) if m′<mm' < m, or m′=mm' = m and n′<nn' < n
μ(y)<μ(x)\mu(y) < \mu(x) for μ:A→N\mu: A \to \Nby measure: most used for termination

Lexicographic order on N×N\N \times \N is well-founded though an element like (1,0)(1, 0) has infinitely many below, (0,0),(0,1),(0,2),…(0, 0), (0, 1), (0, 2), \dots: 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 {a,b}\{a, b\}, dictionary order, is not well-founded: b≻ab≻aab≻aaab≻⋯b \succ ab \succ aab \succ aaab \succ \cdots.

Well-founded recursion and termination measures

Like structural induction, well-founded induction has a function-defining twin: if ≺\prec is well-founded, an equation defining F(x)F(x) using only values F(y)F(y) with y≺xy \prec x determines a unique function FF. 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 y≺μx  ⟺  μ(y)<μ(x)y \prec_\mu x \iff \mu(y) < \mu(x), well-founded because every nonempty set of μ\mu values has a minimum in N\N. Let P(x)P(x) 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.

∎

μ\mu can take values in any well-founded order, not just N\N. Three examples of increasing difficulty:

  • Euclid. gcd⁡(a,b)=gcd⁡(b,a mod b)\gcd(a, b) = \gcd(b, a \bmod b) if b>0b > 0, and gcd⁡(a,0)=a\gcd(a, 0) = a. Measure μ(a,b)=b\mu(a, b) = b decreases because a mod b<ba \bmod b < b. The next lesson’s variant function is this idea applied to a loop.
  • Ackermann. A(0,n)=n+1A(0, n) = n + 1, A(m+1,0)=A(m,1)A(m + 1, 0) = A(m, 1), A(m+1,n+1)=A(m,A(m+1,n))A(m + 1, n + 1) = A(m, A(m + 1, n)). No simple natural measure works: in the last equation the outer call receives a gigantic second argument. But (m,n)(m, n) decreases lexicographically in all three calls: (m,1)≺(m+1,0)(m, 1) \prec (m+1, 0), (m+1,n)≺(m+1,n+1)(m + 1, n) \prec (m + 1, n + 1) and (m,⋅)≺(m+1,n+1)(m, \cdot) \prec (m + 1, n + 1) regardless of second coordinate.
  • Collatz. c(1)=0c(1) = 0, c(n)=1+c(n/2)c(n) = 1 + c(n/2) if nn is even and c(n)=1+c(3n+1)c(n) = 1 + c(3n + 1) if odd. No decreasing measure is known, and whether cc terminates for every n≥1n \ge 1 has been open since 1937. The recursion follows a relation (n→3n+1n \to 3n + 1) 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:

nnf⁡(¬¬φ)=nnf⁡(φ),nnf⁡(¬(φ∧ψ))=nnf⁡(¬φ∨¬ψ),nnf⁡(¬(φ∨ψ))=nnf⁡(¬φ∧¬ψ),nnf⁡(φ∘ψ)=nnf⁡(φ)∘nnf⁡(ψ)(∘∈{∧,∨}),nnf⁡(ℓ)=ℓ  if ℓ is a literal.\begin{aligned} \operatorname{nnf}(\lnot\lnot\varphi) &= \operatorname{nnf}(\varphi), \\ \operatorname{nnf}(\lnot(\varphi \land \psi)) &= \operatorname{nnf}(\lnot\varphi \lor \lnot\psi), \qquad \operatorname{nnf}(\lnot(\varphi \lor \psi)) = \operatorname{nnf}(\lnot\varphi \land \lnot\psi), \\ \operatorname{nnf}(\varphi \circ \psi) &= \operatorname{nnf}(\varphi) \circ \operatorname{nnf}(\psi) \quad (\circ \in \{\land, \lor\}), \qquad \operatorname{nnf}(\ell) = \ell \ \text{ if } \ell \text{ is a literal.} \end{aligned}

This is not structural recursion: ¬φ∨¬ψ\lnot\varphi \lor \lnot\psi is not a subformula of ¬(φ∧ψ)\lnot(\varphi \land \psi), but a new formula. It is larger by one node. Termination needs a measure decreasing in all five equations.

InteractiveFinding a decreasing measure
μ(p)=1,μ(¬φ)= μ(φ)+1,μ(φ∘ψ)=μ(φ)+μ(ψ)+1\mu(p) = 1,\quad \mu(\lnot\varphi) = \,\mu(\varphi) + 1,\quad \mu(\varphi \circ \psi) = \mu(\varphi) + \mu(\psi) + 1
De Morgannnf(¬(p ∧ ¬(q ∨ r)))
μ = 7
∨nnf(¬p ∨ ¬¬(q ∨ r))
7 → 8 ↑
literalnnf(¬p)
8 → 2 ↓
¬¬nnf(¬¬(q ∨ r))
8 → 5 ↓
∨nnf(q ∨ r)
5 → 3 ↓
literalnnf(q)
3 → 1 ↓
literalnnf(r)
3 → 1 ↓
call 7 of 7
Call
Decreases for all φ, ψ if and only if
De Morgan
(k−1) w∘>w¬(k - 1)\,w_\circ > w_\lnot:   0>1\;0 > 1
✗
Double negation
k>1k > 1 or w¬>0w_\lnot > 0
✓
Split ∧, ∨
always: μ(ψ)≥1\mu(\psi) \ge 1
✓
Call 2 does not decrease: μ\mu goes from 7 to 8. With k=1k = 1 no choice of weights fixes De Morgan: the new argument has one more negation.
Factor kk in μ(¬φ)=k μ(φ)+w¬\mu(\lnot\varphi) = k\,\mu(\varphi) + w_\lnot
1
1
calls compared6
μ decreases5
μ unchanged0
μ increases1
Each row is a call to nnf⁡\operatorname{nnf}, indented by recursion depth, with its rule and candidate measure μ\mu compared to the calling measure: green if decreasing, yellow if unchanged, red if increasing. Start with size and find the call that increases it. Then try doubling the measure under each negation. Conditions below are general: they hold for any φ\varphi and ψ\psi, so when all three hold the measure works for every formula, not only the chosen one.

The interactive’s family is μ(p)=1\mu(p) = 1, μ(¬φ)=k μ(φ)+w¬\mu(\lnot\varphi) = k\,\mu(\varphi) + w_\lnot and μ(φ∘ψ)=μ(φ)+μ(ψ)+w∘\mu(\varphi \circ \psi) = \mu(\varphi) + \mu(\psi) + w_\circ. Write a=μ(φ)a = \mu(\varphi) and b=μ(ψ)b = \mu(\psi) and compare De Morgan’s two calls:

μ(¬(φ∧ψ))−μ(¬φ∨¬ψ)=(k(a+b+w∘)+w¬)−(ka+w¬+kb+w¬+w∘)=(k−1) w∘−w¬.\mu\big(\lnot(\varphi \land \psi)\big) - \mu\big(\lnot\varphi \lor \lnot\psi\big) = \big(k(a + b + w_\circ) + w_\lnot\big) - \big(ka + w_\lnot + kb + w_\lnot + w_\circ\big) = (k - 1)\,w_\circ - w_\lnot.

The difference is independent of φ\varphi and ψ\psi, yielding an exact condition: the measure decreases in all De Morgan calls if and only if (k−1) w∘>w¬(k - 1)\,w_\circ > w_\lnot. Three consequences:

  • No additive measure works. With k=1k = 1 (each node adds fixed weight, like size), the condition is 0>w¬0 > w_\lnot, 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 k=2k = 2 and all weights 1, the difference is 00: the measure stays equal in each De Morgan step, and a measure that does not strictly decrease proves nothing.
  • With k=2k = 2, w¬=0w_\lnot = 0 and w∘=1w_\circ = 1 it works. De Morgan drops 1. Double negation drops from 4a4a to aa. Splitting φ∘ψ\varphi \circ \psi drops from a+b+1a + b + 1 to aa or bb. This μ\mu adds 2d2^{d} for each variable and binary connective, where dd counts negations above it; negations add nothing. Pushing a negation below a binary connective drops that connective’s weight from 2d+12^{d+1} to 2d2^{d}, while everything below retains its number of negations above and hence its weight.

If nnf⁡\operatorname{nnf} is written directly, nnf⁡(¬(φ∧ψ))=nnf⁡(¬φ)∨nnf⁡(¬ψ)\operatorname{nnf}(\lnot(\varphi \land \psi)) = \operatorname{nnf}(\lnot\varphi) \lor \operatorname{nnf}(\lnot\psi), the calls are on ¬φ\lnot\varphi and ¬ψ\lnot\psi, with fewer nodes than ¬(φ∧ψ)\lnot(\varphi \land \psi), and size suffices. The same function written differently needs a different termination proof. The lab also shows what happens with →\to, which requires weighting the antecedent more.

Fixed points: the smallest closed set

Return to stages, Xn+1=Φ(Xn)X_{n+1} = \Phi(X_n). “SS is closed” uses the same operator: SS is closed if and only if Φ(S)⊆S\Phi(S) \subseteq S. And Φ\Phi is monotone: if X⊆YX \subseteq Y, everything built from XX can be built from YY, so Φ(X)⊆Φ(Y)\Phi(X) \subseteq \Phi(Y). The inductive set is a fixed point of Φ\Phi, and a special one. For the generality needed in program analysis, work in a complete lattice: a partial order (L,≤)(L, \le) where every subset has supremum ⋁\bigvee and infimum ⋀\bigwedge. In particular it has a minimum ⊥=⋀L\bot = \bigwedge L and maximum ⊤=⋁L\top = \bigvee L. The model example is (P(U),⊆)(\mathcal{P}(U), \subseteq), with union as supremum and intersection as infimum.

The proof of the lfp⁡\operatorname{lfp} formula takes four steps, which you do. The gfp⁡\operatorname{gfp} proof is the same with order reversed.

ProofKnaster–Tarski, guided
Prove: If LL is a complete lattice and f:L→Lf: L \to L is monotone, m=⋀Pm = \bigwedge P with P={x∈L:f(x)≤x}P = \{x \in L : f(x) \le x\} is the least fixed point of ff.
0
Recall: ⋀P\bigwedge P is a lower bound of PP (below all its elements) and is the greatest lower bound.

Step 1 of 4. Why does mm exist?

An inductive set is a least fixed point

Apply the theorem to L=P(U)L = \mathcal{P}(U) and operator Φ(X)=B∪{c(x1,…,xk):xi∈X}\Phi(X) = B \cup \{c(x_1, \dots, x_k) : x_i \in X\}. The pre-fixed points of Φ\Phi are exactly the closed sets, so

I=⋂{S:S closed}=⋀{S:Φ(S)⊆S}=lfp⁡(Φ).I = \bigcap\{S : S \text{ closed}\} = \bigwedge\{S : \Phi(S) \subseteq S\} = \operatorname{lfp}(\Phi).

This equality reorganizes everything above:

  • The inductive definition is a least fixed point: I=Φ(I)I = \Phi(I) says every element of II is a base element or constructor applied to elements of II (nothing else), and II is closed.
  • Structural induction is the exercise’s final sentence, Park’s principle: if Φ(S)⊆S\Phi(S) \subseteq S, then lfp⁡(Φ)⊆S\operatorname{lfp}(\Phi) \subseteq S. Checking induction cases checks that {x:P(x)}\{x : P(x)\} is pre-fixed.
  • Stages are the iteration ∅,Φ(∅),Φ2(∅),…\varnothing, \Phi(\varnothing), \Phi^2(\varnothing), \dots. Their union being the least fixed point is a separate theorem, valid for any lattice with the appropriate assumption.
Proof
  1. ⊥≤f(⊥)\bot \le f(\bot) because ⊥\bot is least; applying monotone ff, fn(⊥)≤fn+1(⊥)f^n(\bot) \le f^{n+1}(\bot) implies fn+1(⊥)≤fn+2(⊥)f^{n+1}(\bot) \le f^{n+2}(\bot). If xx is any fixed point, ⊥≤x\bot \le x, and if fn(⊥)≤xf^n(\bot) \le x, then fn+1(⊥)≤f(x)=xf^{n+1}(\bot) \le f(x) = x. In particular all terms lie below lfp⁡(f)\operatorname{lfp}(f).
  2. Let s=⋁nfn(⊥)s = \bigvee_n f^n(\bot). By continuity, f(s)=⋁nfn+1(⊥)=sf(s) = \bigvee_n f^{n+1}(\bot) = s (removing the first term ⊥\bot does not change the supremum). So ss is fixed and, by 1, lies below all others.
  3. If fn(⊥)<fn+1(⊥)f^{n}(\bot) < f^{n+1}(\bot) for n=0,…,hn = 0, \dots, h, there would be a strictly increasing chain of h+2h + 2 elements. Thus there is a first k≤hk \le h with fk(⊥)=fk+1(⊥)f^k(\bot) = f^{k+1}(\bot), a fixed point and, by 1, the least.
∎

The operator Φ\Phi of a definition with finite-arity constructors is continuous: an element of Φ(⋃nXn)\Phi(\bigcup_n X_n) is built from finitely many arguments, all in some XNX_N in the chain, so belongs to Φ(XN)\Phi(X_N). Thus stages exhaust the inductive set, the theorem at the lesson’s beginning seen from here.

Without continuity iteration may fall short. Take L={0<1<2<⋯<ω<ω+1}L = \{0 < 1 < 2 < \cdots < \omega < \omega + 1\}, a complete lattice, and f(n)=n+1f(n) = n + 1, f(ω)=f(ω+1)=ω+1f(\omega) = f(\omega + 1) = \omega + 1. It is monotone. Iteration from 00 traverses all naturals with supremum ω\omega, but f(ω)=ω+1≠ωf(\omega) = \omega + 1 \ne \omega: the Kleene limit is not even fixed, and lfp⁡(f)=ω+1\operatorname{lfp}(f) = \omega + 1 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 Φ(X)={hoja⁡}∪{nodo⁡(l,r):l,r∈X}\Phi(X) = \{\operatorname{hoja}\} \cup \{\operatorname{nodo}(l, r) : l, r \in X\}. 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 S⊆Φ(S)S \subseteq \Phi(S), then S⊆gfp⁡(Φ)S \subseteq \operatorname{gfp}(\Phi). 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 ii, Xi⊆V={u,t,q,n}X_i \subseteq V = \{u, t, q, n\} is the set of variables that may be tainted on exit from ii. An analysis state is a vector X=(X1,…,X8)X = (X_1, \dots, X_8), ordered by componentwise inclusion. This is the complete lattice P(V)8\mathcal{P}(V)^8, of height 8⋅4=328 \cdot 4 = 32: each strictly increasing step adds at least one variable to some node.

Transfer functions. Each statement transforms the incoming tainted set TT into the outgoing one:

fx=input()(T)=T∪{x},fx=constant(T)=T∖{x},fx=e(T)=(T∖{x})∪{{x}if vars⁡(e)∩T≠∅,∅otherwise,f_{x = \texttt{input()}}(T) = T \cup \{x\}, \qquad f_{x = \text{constant}}(T) = T \setminus \{x\}, \qquad f_{x = e}(T) = (T \setminus \{x\}) \cup \begin{cases} \{x\} & \text{if } \operatorname{vars}(e) \cap T \ne \varnothing, \\ \varnothing & \text{otherwise,} \end{cases}

and a sanitizer x=escape(e)x = \texttt{escape}(e) behaves like a constant. All three are monotone: if T⊆T′T \subseteq T', removing xx preserves inclusion, and if ee touches a variable of TT, it touches one of T′T' 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, X=F(X)X = F(X) with

F(X)i=fi(⋃j→iXj).F(X)_i = f_i\Big(\bigcup_{j \to i} X_j\Big).

FF is monotone because union and each fif_i are. Knaster–Tarski gives a least fixed point, and as the lattice has finite height, Kleene iteration X(0)=⊥X^{(0)} = \bot, X(k+1)=F(X(k))X^{(k+1)} = F(X^{(k)}) reaches it in at most 32 steps.

InteractiveKleene iteration on a flow graph
Control-flow graph: tainted variables at each node’s output
1u = input()utqn2q = "SELECT …"utqn3n = 0utqn4while n < 3:utqn5q = q + tutqn6t = uutqn7n = n + 1utqn8db.execute(q)utqn
Subset lattice of {u, t, q, n}: path of node 4
∅utqnutuquntqtnqnutqutnuqntqnutqn⊥ = ∅ below, ⊤ above; each edge adds one variablepath risesfalls
X14 = F(X13)
Fixed point: F(X13)=X13F(X_{13}) = X_{13} after 13 steps, well below the bound 32 (the lattice height). This is the least fixed point: what can be justified from the source.
Starting point
node 4 after 14 steps{u, t, q}
tainted bits18 of 32
stabilizes in13 steps
q tainted at sinkyes: alarm
Left: the program's flow graph with variables tainted at each node's output in the current step (highlighted nodes just changed). Right: the subset lattice of {u,t,q,n}\{u, t, q, n\} with the selected node's trajectory: it climbs one edge when it gains a variable. Play iteration from ⊥\bot and count steps. Then remove the loop, add the sanitizer or swap lines 5 and 6, and observe whether the fixed point or only step count changes. Start from ⊤\top to reach the greatest fixed point, and enable the nonmonotone transfer to see what happens without monotonicity.

What you should have seen:

  • The trajectory only rises. At loop header (node 4), the tainted set follows ∅⊂{u}⊂{u,t}⊂{u,t,q}\varnothing \subset \{u\} \subset \{u, t\} \subset \{u, t, q\}: input reaches t on the first loop and q on the second. Iteration stabilizes in 13 steps, far below bound 32, and db.execute(q) receives tainted q: the analyzer correctly warns.
  • The loop taints q. Without the back edge, q = q + t runs only with clean t, the fixed point has no q at the sink, and iteration ends in 8 steps. With a sanitizer t is never tainted, nor is q.
  • Statement order changes step count, not the result. Swapping lines 5 and 6 taints q on the first pass: the least fixed point is the same, reached in 9 steps.
  • The greatest fixed point gives false alarms. From ⊤\top, iteration decreases to gfp⁡(F)\operatorname{gfp}(F), which marks n tainted: n = n + 1 justifies taint of n using the existing taint of n, circular reasoning excluded by the least fixed point. With a sanitizer it is worse: the greatest fixed point marks q at db.execute(q), giving a false warning.
  • Without monotonicity there are no guarantees. The faulty transfer “two tainted inputs cancel” (qq tainted if exactly one of qq and tt is) is not monotone: {t}⊆{q,t}\{t\} \subseteq \{q, t\}, but f({t})∋qf(\{t\}) \ni q and f({q,t})∌qf(\{q, t\}) \not\ni q. 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 XiX_i for any XX with F(X)⊆XF(X) \subseteq X; 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 ⊆\subseteq. 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 ⊆\subseteq. 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) X≤lfp⁡(F)X \le \operatorname{lfp}(F): true for ⊥\bot, and if true before updating node ii, monotonicity gives Xi′=fi(⋃j→iXj)≤fi(⋃j→ilfp⁡(F)j)=lfp⁡(F)iX_i' = f_i(\bigcup_{j \to i} X_j) \le f_i(\bigcup_{j \to i} \operatorname{lfp}(F)_j) = \operatorname{lfp}(F)_i. (b) X≤F(X)X \le F(X): true for ⊥\bot; updating ii makes the new value F(X)i≥XiF(X)_i \ge X_i, so XX grows, and monotonicity makes F(X)F(X) 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 ii satisfies Xi=F(X)iX_i = F(X)_i (it was recalculated after its predecessors’ last change, or they never changed). Thus XX 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.

[ ]Expressions, structural recursion and constant foldingBrowser
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.

[ ]Substitution, negation normal form and a decreasing measureBrowser
@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.

[ ]Conjunctive normal form by structural recursionBrowser
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 ⊥\bot until nothing changes; it shows full binary tree stages, constructs a bounded inductive set (balanced-parenthesis strings of length ≤8\le 8), and brute-force checks Knaster–Tarski in a small lattice by enumerating its 256 elements.

[ ]Kleene iteration, stages and pre-fixed pointsBrowser
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 1,3,5,71, 3, 5, 7 form a cycle of justifications (1→3→5→11 \to 3 \to 5 \to 1 and 5→75 \to 7) not fed from 00: 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, 212=40962^{12} = 4096 states), all states are enumerated to find all fixed points and check Kleene’s result lies below every one.

[ ]Taint analysis: Kleene, worklist and all fixed pointsBrowser
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.

[ ]Constant folding on Python ASTsBrowser
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 2n2^n 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.

[ ]Comparison with sympyBrowser
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). and out(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

ProofLeaves and internal nodes in a full tree
Prove: In every full binary tree t::=hoja⁡∣nodo⁡(t,t)t ::= \operatorname{hoja} \mid \operatorname{nodo}(t, t), leaf count H(t)H(t) equals internal-node count I(t)I(t) plus one.
0
By structural recursion: H(hoja⁡)=1H(\operatorname{hoja}) = 1, I(hoja⁡)=0I(\operatorname{hoja}) = 0, H(nodo⁡(l,r))=H(l)+H(r)H(\operatorname{nodo}(l, r)) = H(l) + H(r) and I(nodo⁡(l,r))=I(l)+I(r)+1I(\operatorname{nodo}(l, r)) = I(l) + I(r) + 1.

Step 1 of 4. How do you set up the proof?

ProofBalanced parentheses
Prove: In every fully parenthesized formula φ::=p∣¬φ∣(φ∘φ)\varphi ::= p \mid \lnot\varphi \mid (\varphi \circ \varphi), (a) the number L(φ)L(\varphi) of left parentheses equals the number R(φ)R(\varphi) of right parentheses, and (b) every prefix σ\sigma of φ\varphi satisfies L(σ)≥R(σ)L(\sigma) \ge R(\sigma).
0
A prefix of a string is its first jj symbols for some j≥0j \ge 0: it includes the empty and full string.

Step 1 of 5. What statement do you prove by structural induction?

QuizWhy ‘and nothing else’?
Formulas over {p,q}\{p, q\} are defined as follows: pp and qq are formulas; if φ\varphi and ψ\psi are, then so are ¬φ\lnot\varphi and (φ∧ψ)(\varphi \land \psi). If ‘and nothing else is a formula’ is omitted, which sets also satisfy the definition?

More than one answer may be correct.

NumericStages of full trees
With Φ(X)={hoja⁡}∪{nodo⁡(l,r):l,r∈X}\Phi(X) = \{\operatorname{hoja}\} \cup \{\operatorname{nodo}(l, r) : l, r \in X\}, how many trees are in Φ5(∅)\Phi^5(\varnothing)?
QuizWell-founded?
Which of these relations are well-founded?

More than one answer may be correct.

QuizAckermann's measure
With A(0,n)=n+1A(0, n) = n + 1, A(m+1,0)=A(m,1)A(m+1, 0) = A(m, 1) and A(m+1,n+1)=A(m,A(m+1,n))A(m+1, n+1) = A(m, A(m+1, n)), what measure proves termination?
CodeNegation normal form with a measure
Implement nnf(f) for formulas with Var, Not, And, Or and Imp, and a measure mu(f) returning an integer ≥0\ge 0 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)."""
  pass
Shift+Enter to run
NumericMaximum steps?
A taint analysis uses a flow graph with 50 nodes and a program with 12 variables. Parallel Kleene iteration begins at ⊥\bot. What is the maximum number of strict steps X(k)⊊X(k+1)X^{(k)} \subsetneq X^{(k+1)} before stabilization?
QuizLeast or greatest?
A definitely initialized variables analysis calculates, at each node, variables initialized on all paths reaching it: a node's input is the intersection of predecessor outputs, and assignment adds its variable. Which equation solution do you want?
CodeSanitizers and monotonicity
Complete the taint analyzer. transfer(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 S⊆T⊆S \subseteq T \subseteq universe implies f(S)⊆f(T)f(S) \subseteq f(T). 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 out
Shift+Enter to run

Summary

Key idea
An inductively defined set is the smallest set closed under its rules, hence the least fixed point of a monotone operator. From this come structural recursion, defining functions with one equation per constructor (if generation is free), and structural induction, proving properties with one case per constructor. When recursion is not structural, a measure decreasing in a well-founded order proves termination. On a finite-height lattice, iteration from ⊥\bot reaches the least fixed point: this is how data-flow analysis computes, with monotonicity guaranteeing termination.
  • Inductive definition: base, constructors and ‘nothing else’; the set is the intersection of closed sets and also the union of stages Φn(∅)\Phi^n(\varnothing) 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 N\N 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 ⊥\bot reaches the least. A may analysis’s least fixed point is the most precise sound solution; the greatest permits circular justifications.