TExcelTAD
Home › Discrete Mathematics › Recursive Data Types and Structural Induction

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 Σ\Sigma the empty string λ\lambda if ss is a string and a∈Σa \in \Sigma, then asas is a string
binary trees the empty tree (a leaf) if L,RL, R are trees, then node(L,R)\text{node}(L, R) is a tree
balanced brackets BB λ∈B\lambda \in B if s,t∈Bs, t \in B then [s]t∈B[s]t \in B
arithmetic expressions numbers and the variable xx if e,fe, f are expressions, so are (e+f)(e + f) and (e⋅f)(e \cdot f)

Structural induction

To prove P(x)P(x) for every element xx of a recursively defined set:

  1. Prove P(b)P(b) for every base case bb.
  2. For every constructor, assuming PP holds for the parts, prove PP for the result.

Theorem. Every string in the balanced-brackets set BB has equal numbers of [ and ].

Proof. Base: λ\lambda has 0 of each. Constructor: if ss and tt each have equal counts, then [s]t[s]t adds one [ and one ], so its counts are equal too. ■\blacksquare

Trees: leaves and internal nodes

Define full binary trees: a single leaf is a tree; if LL and RR are trees, node(L,R)\text{node}(L, R) is a tree with a new root. Let ℓ(T)\ell(T) be the number of leaves and i(T)i(T) the number of internal nodes.

Theorem. ℓ(T)=i(T)+1\ell(T) = i(T) + 1 for every full binary tree.

Proof. Base: a leaf has ℓ=1\ell = 1, i=0i = 0. Constructor: for T=node(L,R)T = \text{node}(L, R), ℓ(T)=ℓ(L)+ℓ(R)=(i(L)+1)+(i(R)+1)=(i(L)+i(R)+1)+1=i(T)+1\ell(T) = \ell(L) + \ell(R) = (i(L) + 1) + (i(R) + 1) = (i(L) + i(R) + 1) + 1 = i(T) + 1. ■\blacksquare

This is why a knockout tournament with 64 teams has exactly 63 matches.

python · try it yourself
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 hh has at most 2h2^h leaves.

Recursive functions on recursive data

Functions are defined by the same cases. Evaluating an arithmetic expression:

eval(n,v)=nfor a number n,eval(x,v)=veval((e+f),v)=eval(e,v)+eval(f,v)eval((e⋅f),v)=eval(e,v)⋅eval(f,v)\begin{aligned} \text{eval}(n, v) &= n \quad \text{for a number } n, \qquad \text{eval}(x, v) = v \\ \text{eval}((e + f), v) &= \text{eval}(e, v) + \text{eval}(f, v) \\ \text{eval}((e \cdot f), v) &= \text{eval}(e, v) \cdot \text{eval}(f, v) \end{aligned}

Such a definition is well defined when every value can be built in only one way (the definition is unambiguous). The bracket rule [s]t[s]t is unambiguous; a rule like "stst is balanced if ss and tt are" would be ambiguous, since [][][] splits in two ways.

python · try it yourself
# 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 λ\lambda by asas. Define ∣λ∣=0\lvert \lambda \rvert = 0, ∣as∣=1+∣s∣\lvert as \rvert = 1 + \lvert s \rvert, and λ⋅t=t\lambda \cdot t = t, (as)⋅t=a(s⋅t)(as) \cdot t = a(s \cdot t). Prove ∣s⋅t∣=∣s∣+∣t∣\lvert s \cdot t \rvert = \lvert s \rvert + \lvert t \rvert.

Answer

Structural induction on ss.

Solution

Base s=λs = \lambda: ∣λ⋅t∣=∣t∣=0+∣t∣\lvert \lambda \cdot t \rvert = \lvert t \rvert = 0 + \lvert t \rvert. Constructor s=as′s = as':

∣(as′)⋅t∣=∣a(s′⋅t)∣=1+∣s′⋅t∣=1+∣s′∣+∣t∣=∣as′∣+∣t∣\lvert (as') \cdot t \rvert = \lvert a(s' \cdot t) \rvert = 1 + \lvert s' \cdot t \rvert = 1 + \lvert s' \rvert + \lvert t \rvert = \lvert as' \rvert + \lvert t \rvert

using the hypothesis for s′s'. ■\blacksquare

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 100−1=99100 - 1 = 99 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 2n2n for n=1,…,6n = 1, \ldots, 6 with the rule [s]t[s]t and count them.

Answer

1, 2, 5, 14, 42, 132 (the Catalan numbers).

Solution

A string of nn pairs is [s]t[s]t with ss having kk pairs and tt having n−1−kn - 1 - k; because the rule is unambiguous, each string appears once.

python · try it yourself
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?

  1. That the base case holds
  2. That the property holds for the built value, assuming it for the parts
  3. That the set is finite
  4. That the definition is ambiguous

A full binary tree has 20 internal nodes. How many leaves does it have?

  1. 19
  2. 20
  3. 21
  4. 40

Why must a recursive data type definition be unambiguous for recursive functions on it?

  1. To save memory
  2. So each value is built in only one way, giving each function value one definition
  3. To make it finite
  4. It need not be