Recursive Data Types and Structural Induction
Lists, trees, arithmetic expressions and JSON documents are recursive data types: each is defined by a few base cases and constructor rules that build bigger values from smaller ones. Functions on them are naturally recursive, and the matching proof method is structural induction: prove a property for the base cases and show each constructor preserves it.
Recursive definitions
A recursive definition of a set has two parts:
- Base cases: some elements are in the set outright.
- Constructor cases: if certain elements are in the set, so are elements built from them.
Nothing else is in the set. Examples:
| Data type | Base case | Constructor |
|---|---|---|
| strings over | the empty string | if is a string and , then is a string |
| binary trees | the empty tree (a leaf) | if are trees, then is a tree |
| balanced brackets | if then | |
| arithmetic expressions | numbers and the variable | if are expressions, so are and |
Structural induction
To prove for every element of a recursively defined set:
- Prove for every base case .
- For every constructor, assuming holds for the parts, prove for the result.
Theorem. Every string in the balanced-brackets set has equal numbers of [ and ].
Proof. Base: has 0 of each. Constructor: if and each have equal counts, then adds one [ and one ], so its counts are equal too.
Trees: leaves and internal nodes
Define full binary trees: a single leaf is a tree; if and are trees, is a tree with a new root. Let be the number of leaves and the number of internal nodes.
Theorem. for every full binary tree.
Proof. Base: a leaf has , . Constructor: for , .
This is why a knockout tournament with 64 teams has exactly 63 matches.
import random
# a full binary tree is either "leaf" or a pair (left, right)
def random_tree(n_leaves, rng):
if n_leaves == 1:
return "leaf"
k = rng.randint(1, n_leaves - 1)
return (random_tree(k, rng), random_tree(n_leaves - k, rng))
def leaves(t):
return 1 if t == "leaf" else leaves(t[0]) + leaves(t[1])
def internal(t):
return 0 if t == "leaf" else 1 + internal(t[0]) + internal(t[1])
def height(t):
return 0 if t == "leaf" else 1 + max(height(t[0]), height(t[1]))
rng = random.Random(5)
for n in [1, 2, 7, 64]:
t = random_tree(n, rng)
print(f"leaves={leaves(t):3d} internal={internal(t):3d} height={height(t):3d} "
f"leaves <= 2^height: {leaves(t) <= 2 ** height(t)}")leaves= 1 internal= 0 height= 0 leaves <= 2^height: True
leaves= 2 internal= 1 height= 1 leaves <= 2^height: True
leaves= 7 internal= 6 height= 4 leaves <= 2^height: True
leaves= 64 internal= 63 height= 11 leaves <= 2^height: True
The last column checks a second theorem with the same proof method: a tree of height has at most leaves.
Recursive functions on recursive data
Functions are defined by the same cases. Evaluating an arithmetic expression:
Such a definition is well defined when every value can be built in only one way (the definition is unambiguous). The bracket rule is unambiguous; a rule like " is balanced if and are" would be ambiguous, since [][][] splits in two ways.
# expressions as nested tuples: ("+", e, f), ("*", e, f), "x", or a number
def ev(e, x):
if e == "x":
return x
if isinstance(e, int):
return e
op, a, b = e
return ev(a, x) + ev(b, x) if op == "+" else ev(a, x) * ev(b, x)
def show(e):
if e == "x" or isinstance(e, int):
return str(e)
op, a, b = e
return f"({show(a)} {op} {show(b)})"
expr = ("+", ("*", 3, ("*", "x", "x")), ("+", ("*", -2, "x"), 5)) # 3x^2 - 2x + 5
print(show(expr))
print([ev(expr, x) for x in range(5)])((3 * (x * x)) + ((-2 * x) + 5))
[5, 6, 13, 26, 45]
In software
Compilers, interpreters, JSON parsers and HTML renderers all walk recursive data types (abstract syntax trees, DOM trees). Functional languages make the pattern explicit with algebraic data types and pattern matching, and their type checkers verify that every constructor case is handled.
Exercises
Exercise 1: Length of concatenation
Strings are built from by . Define , , and , . Prove .
Answer
Structural induction on .
Solution
Base : . Constructor :
using the hypothesis for .
Exercise 2: Tournament
A knockout tournament starts with 100 players and has no draws. How many games are played?
Answer
Solution
The bracket is a full binary tree with 100 leaves (players) and one internal node per game, so there are games. Equivalently, each game eliminates exactly one player, and 99 must be eliminated.
Exercise 3: Count balanced strings (code)
Generate all balanced bracket strings of length for with the rule and count them.
Answer
1, 2, 5, 14, 42, 132 (the Catalan numbers).
Solution
A string of pairs is with having pairs and having ; because the rule is unambiguous, each string appears once.
from functools import lru_cache
@lru_cache(None)
def balanced(n):
if n == 0:
return ("",)
return tuple("[" + s + "]" + t for k in range(n) for s in balanced(k) for t in balanced(n - 1 - k))
print([len(balanced(n)) for n in range(1, 7)])
print(balanced(3))[1, 2, 5, 14, 42, 132]
('[][][]', '[][[]]', '[[]][]', '[[][]]', '[[[]]]')
Test yourself
What does structural induction prove for each constructor?
- That the base case holds
- That the property holds for the built value, assuming it for the parts
- That the set is finite
- That the definition is ambiguous
A full binary tree has 20 internal nodes. How many leaves does it have?
- 19
- 20
- 21
- 40
Why must a recursive data type definition be unambiguous for recursive functions on it?
- To save memory
- So each value is built in only one way, giving each function value one definition
- To make it finite
- It need not be