Volume P1 · Proof, induction and invariants
Recursion and structural induction
Draft. This chapter is written and checked by the tools of the project, and a person has not reviewed it yet. Read it with care.
Read first
Recursive definitions
Statement
Definition P1.6.1 (recursion on the natural numbers). A function on is defined by recursion if its value at is given and its value at is given by a rule from and :
The first line is the base and the second is the recursive step.
Lean: Nat.rec is the recursor; a definition by pattern matching on 0 and n + 1 is compiled to it.
Example P1.6.2. The factorial: and . The power: and . The sum: and . The values of the factorial are .
Lean: Nat.factorial with Nat.factorial_succ : (n + 1)! = (n + 1) * n ! (Mathlib).
Theorem P1.6.3 (a recursive definition defines one function). For every and there is exactly one function on with and for all .
Proof. Uniqueness. Let and both satisfy the rules. Prove by induction. Base: . Step: if , then .
Existence. Call a list of values good if and for . By induction on there is exactly one good list of each length: the list for is the list for with added at the end, and the uniqueness is as above. Define to be the last value of the good list of length . Then , and since the good list of length extends the good list of length .
Definition P1.6.4 (recursion with several previous values). The recursive step may use and , as in the Fibonacci numbers , , , or all of . The theorem holds in the same form, with a proof by strong induction. The definition of a function on the integers by and is of this kind: it uses a value at a number smaller than , not at .
Example P1.6.5. The number of digits of in base : and . The values at are .
Example P1.6.6 (the sum of the digits). Let for and for . Then .
A proof about a recursively defined function follows the shape of the definition. A base case for the base, and a step for the step.
Example P1.6.7. Claim: for . Base: . Step: . This is Exercise 4.1-5 in the form of a recursive definition.
Example P1.6.8 (the number of calls). Define a recursive procedure fib(n): if return ; otherwise return fib(n-1) + fib(n-2). The number of calls (counting the first) satisfies and . Claim: . Base: , . Step: . The values for are , so the procedure makes calls to compute . The number of calls grows as fast as the number computed, which is why this procedure is slow.
Proof
A recursive definition can fail in three ways.
No base case. The rule with no value given at does not define a function by this theorem: the constants for any all satisfy the rule, so the function is not unique.
A step that does not reach the base. The rule refers to a larger number, and it defines nothing. The rule for even and for odd , with , is an example with a hidden difficulty: whether it defines a function on all positive integers is the open problem of Collatz. For the chain reaches after steps, and for after steps. A definition must be accompanied by a proof that the chain reaches the base case, and for this rule there is none.
Two rules for one input. The rules and with agree at , where both give , and differ at , where they give and . A definition that offers both rules for each does not define a function. A recursive definition must give one rule for each .
The theorem above is the proof that the usual definitions (factorial, power, Fibonacci) are all right. A definition is correct if each falls under one case, the value is computed from smaller arguments, and the chain of arguments reaches the base in finitely many steps. For a rule that uses the last point is true by the well-ordering principle: a decreasing sequence of natural numbers is finite.
Examples
Example P1.6.9 (the Ackermann function). Define , and . The recursion is not of the form of the theorem, since the second rule refers to for a large second argument. It defines a function on pairs because the pair decreases in the lexicographic order: either decreases, or stays and decreases. This order is a well order on pairs of natural numbers (Chapter 7), so each chain reaches a base. The values are , and . The function grows faster than every primitive recursive function.
Example P1.6.10 (the greatest common divisor). The recursion and for is a recursive definition that is not on but on a smaller remainder. Section 5.3 shows that the chain ends and that the value is the greatest common divisor.
Example P1.6.11 (a base that is not ). The Fibonacci recurrence has two base cases. The rule needs three. A definition with fewer base cases than the rule refers back to gives a function that is not defined at some values.
Exercises
- [10] Compute for and by the recursive definition of the power for .
- [12] Define by recursion the sum and prove .
- [14] Define by recursion the function that gives the number of digits of in base , and compute and .
- [14] Let be the sum of the digits in base , defined by recursion. Prove that and compute .
- [15] Let and . Find and prove the formula.
- [M18] The procedure
fib(n)of the text makes calls. Prove that , and find the number of calls for . - [M20] Show that the two rules , for and , define different functions, and find the least where they differ.
- [M22] Prove the uniqueness part of the theorem for the Fibonacci recursion: two functions with , and the rule for are equal.
- [M25] Prove that as defined by the recursion of the text has the property that each step reduces the second argument, so the recursion ends for . Compute by the recursion.
- [M25] Compute the Ackermann function for , in general: prove that and .
Lean
A recursive definition in Lean is written by pattern matching, as def f : ℕ → ℕ | 0 => c | n + 1 => g n (f n). Lean accepts it only if the recursion ends, and it checks this with a structural or a well-founded argument. A definition of the Ackermann function is accepted because the pair decreases in the lexicographic order. The definition def collatz : ℕ → ℕ with the rule of the text is not accepted without a proof that it ends, since no such proof is known.
Notes and history
The recursion theorem for the natural numbers is due to Dedekind (1888), who proved it from the axioms and saw its role. The function of Ackermann is from 1928 (in the form with three arguments), and the two-argument form is due to Peter. The problem of Collatz is from 1937 and is open. TAOCP defines the factorial and the Fibonacci numbers by recursive rules in Sections 1.2.5 and 1.2.8.
Lists and trees
Statement
Definition P1.6.12 (a recursively defined set). A set is defined recursively by constructors: a list of rules of the form "this is an element" (base rules) and "if are elements, so is " (step rules), together with the clause that nothing else is an element. The elements are exactly the objects that are built by finitely many uses of the rules.
Definition P1.6.13 (lists). Let be a set (of letters). The set of lists over is defined by two rules: the empty list is a list, and if and is a list then is a list. Write for .
Lean: the type List α with the constructors List.nil and List.cons (Lean core).
Definition P1.6.14 (functions on lists). A function on lists is defined by one case for each constructor.
- Length: and .
- Append: and .
- Reverse: and .
Lean: List.length, List.append (written ++) and List.reverse, with List.length_append, List.reverse_append, List.reverse_reverse and List.append_assoc for the laws below.
Example P1.6.15. and .
Theorem P1.6.16 (the principle of structural induction for lists). Let be a statement about lists. If holds, and for all and lists the statement holds, then holds for every list .
Lean: the tactic induction xs with | nil => ... | cons a xs ih => ... (Lean core).
Proof. Every list has a length (the number of uses of ). Prove by induction on that holds for each list of length . For the list is . A list of length is with of length , for which holds by the hypothesis of the induction, and the step gives .
Theorem P1.6.17 (laws of lists). For all lists :
- ;
- ;
- ;
- ;
- .
Proof. Each by structural induction on , using the definitions.
- For : . For : by the hypothesis.
- For both sides equal . For both sides are and , which are equal by the hypothesis.
- For : . For : .
- For : by law 1. For : , which by law 2 is .
- For it is immediate. For : , by law 4 and the hypothesis.
The order of the laws is the order of their proofs: law 4 uses laws 1 and 2, and law 5 uses law 4.
Definition P1.6.18 (full binary trees). The set of binary trees is defined by two rules: a leaf is a tree, and if and are trees, then the node is a tree. A node is an internal node, and and are its left and right subtrees.
Lean: inductive BTree | leaf : BTree | node : BTree → BTree → BTree, with induction t with as the principle.
Definition P1.6.19 (functions on trees).
- Leaves: and .
- Internal nodes: and .
- Height: and .
Theorem P1.6.20 (structural induction for trees). If holds, and for all trees and , then holds for every tree .
Proof. By strong induction on the number of nodes (internal and leaves) of : the subtrees and of have fewer nodes than the tree, so the strong hypothesis applies to both.
Theorem P1.6.21 (counting in trees). For every tree : and .
Proof. By structural induction. For the leaf: and . For with the hypothesis for and :
- ;
- .
Example P1.6.22. The tree has leaves, internal nodes and height , and and . The number of trees with internal nodes is for (the Catalan numbers, computed by a program that counts the choices of the sizes of the subtrees).
Proof
A proof by structural induction has the plan: name the principle and the statement; one case for each constructor; in the case of a constructor with subobjects, assume the statement for each subobject. The base cases are the constructors without subobjects (nil, leaf). The proof is correct because every object is built in finitely many steps, and so the principle follows from the induction on the number of steps, as shown for lists.
The choice of the object of the induction matters. The laws above are proved by induction on , the first argument of , and not on , because the definition of recurses on the first argument. An induction on would not unfold the definition. A rule: induct on the argument that the function recurses on.
An auxiliary lemma is often needed, as law 1 for law 4. If a proof by induction gets stuck on an expression that the definitions do not simplify, find the lemma that simplifies it and prove the lemma first.
Examples
Example P1.6.23 (the number of nodes). A tree has nodes in all. So a tree with leaves has internal nodes and nodes in all. Since , a tree with leaves has height at least . For the height is at least .
Example P1.6.24 (the reverse takes quadratic time). The definition of calls on a list of the length of , so the number of cons steps that performs to reverse a list of elements is , by the formula of Chapter 4. For it is . A better definition uses an accumulator: and , with . Its correctness is the statement for all and , a stronger claim in the sense of Chapter 4, Section 2: the plain claim cannot be proved by induction on since the second argument changes.
Example P1.6.25 (arithmetic expressions). The expressions built from numbers and the operations and are a recursively defined set: a number is an expression, and if and are expressions so are and . Claim: each expression has an equal number of left and right brackets, and the number of operators is one less than the number of numbers. Both are proved by structural induction, as for trees: the second is the law where the numbers are the leaves.
Exercises
- [10] Compute , and from the definitions.
- [12] Prove law 1: .
- [14] Prove law 2, the associativity of the append.
- [14] Prove law 3, the length of an append, and find the length of in terms of the length of .
- [15] Prove that a tree with internal nodes has nodes in all, and find the number of nodes of a tree with leaves.
- [M18] Prove law 4 and law 5 for the reverse.
- [M20] Prove that a tree of height has at most leaves and at most nodes in all.
- [M22] Define by the accumulator rule and prove that for all lists. Deduce that .
- [M25] List the five trees with internal nodes and compute the height and the number of leaves of each.
- [M25] Let the set of strings of brackets be defined by: the empty string is in ; if and are in , so is . Prove that each string in has equally many left and right brackets, and that in each initial segment the number of left brackets is at least that of the right ones.
Lean
For lists, induction xs with | nil => simp | cons a xs ih => simp [ih] proves many of the laws above, and simp knows List.length_append, List.reverse_append and List.reverse_reverse. For a new type of trees the statement inductive BTree with the two constructors produces the induction principle, and the proof of is induction t with | leaf => ... | node l r ihl ihr => ...with the functions leaves and internal defined by the equations of the text. The exact script depends on the definitions, so write the two functions first and test the script in the version that you use.
Notes and history
The definition of a set by constructors and the principle of structural induction were made precise in the work of Burstall (1969), who used it for proofs of programs. The type of lists with nil and cons is the base of the language Lisp (McCarthy, 1958). TAOCP treats lists and trees in Chapter 2 of Volume 1, and the identity is the fact that an extended binary tree with internal nodes has external nodes (Section 2.3).
Recursive algorithms
Statement
A recursive procedure is a procedure that calls itself on a smaller argument. It is a recursive definition of a function, with the calls as the steps, and it is proved correct by the induction that fits its recursion: weak induction for a call on , strong induction for a call on or on a remainder, and structural induction for a call on a part of a list or a tree.
Definition P1.6.26 (a proof of a recursive procedure). To prove that a procedure returns a value with the property for every legal input , prove two things. Termination: each chain of calls ends, which follows if the argument decreases in a well-ordered measure (a natural number) at each call. Correctness: by induction on the measure, assume that every call on a smaller argument returns a value with the property, and show that the value returned for has it.
Example P1.6.27 (the power by squaring). The procedure for is: if return ; if is even let and return ; if is odd return . Claim: . The measure is . Termination: the calls are on and (for ). Correctness by strong induction on : for the value is . For even the hypothesis gives and . For odd the hypothesis gives , and .
Theorem P1.6.28 (the cost of the power). For the procedure makes multiplications, where is the number of s in the binary form of .
Proof. Let be the number of multiplications. Then , for even and for odd . Strong induction. For : . For even : and , so . For odd : and , so .
For the count is , against for the product of factors. For it is .
Example P1.6.29 (the towers of Hanoi). There are three pegs and disks of different sizes on the first peg, the smaller above the larger. A move takes the top disk of one peg to another peg and never puts a disk on a smaller one. The task is to move all disks to the second peg. The procedure for moves disks from peg to peg using peg : if do nothing; otherwise do , move one disk from to , do .
Theorem P1.6.30 (Hanoi). moves the top disks of to by legal moves, and no solution has fewer moves.
Proof. The number of moves is and , so by induction (). Correctness by induction on : for the top disks, the first call moves the smaller ones to (legal, since they are above the largest, which lies still on and which does not obstruct); the move of the largest disk is legal because has no smaller disk on top; the second call moves the disks from onto the largest on , and no disk is bigger than a disk that it is put on. For minimality, let be the least number of moves of any solution. The largest disk must move at least once. Just before its first move, the other disks are all on the third peg, so at least moves have been made before it (the smaller disks move as in a game with disks). After its last move they are all on the third peg again, and at least more moves are needed to put them on it. So , and by induction.
Example P1.6.31. For the moves, written as (from, to), are , and . For the number is , and for it is .
Example P1.6.32 (binary search). A sorted array of keys is searched for a key . The procedure compares with the middle key, and continues in the left half or the right half. Let be the greatest number of comparisons for an array of keys. Then and for since each half has at most keys. By strong induction : if , then , so (for , by the hypothesis) and . A program that tests every key in arrays of keys finds the worst cases , which are equal to the bound.
Proof
A recursive procedure is replaced by a loop when the recursive call is the last thing that the procedure does (tail recursion), or when the procedure can be arranged to be so by a new argument, an accumulator. The loop is correct by a statement that holds before each pass, an invariant (Chapter 8).
Example P1.6.33 (the power as a loop). Let , , . While : if is odd, ; then and . The invariant is . At the start it is . In a pass with even, . In a pass with odd, and . When the invariant is . For and the values of are , and becomes and then .
Example P1.6.34 (Euclid's algorithm). The procedure : if return , else return is tail recursive, and the loop is Algorithm 1.1E of TAOCP, with the invariant .
The converse is not always so simple. A recursion such as Hanoi, with two calls, does not become a loop without a stack. The depth of the recursion, the length of the longest chain of calls, is the amount of memory used by the stack: it is for Hanoi and about for binary search.
Examples
Example P1.6.35 (a procedure that is not correct). Let be: if return , else return . For the chain goes and never reaches . The termination proof fails: the measure does not decrease to a well-ordered base, since may be negative. For even the procedure is right and returns .
Example P1.6.36 (a count by recursion). The number of ways to climb steps by steps of or satisfies , and , so . For there are ways.
Example P1.6.37 (merge of two lists). The recursive merge of two sorted lists: , , and for , it returns if and otherwise. The measure is , which decreases by at each call. By induction on the measure the result is sorted and has the elements of both lists.
Exercises
- [10] Trace by hand and count the multiplications.
- [12] Write the moves of that move three disks from to .
- [14] Prove that makes moves, and find the time for at one move per second, in years (a computer is enough).
- [14] Prove that the number of ways to climb steps with steps of or is .
- [15] Prove that the loop for the power has the invariant , and trace it for and .
- [M18] Prove that makes multiplications and find for which it is greatest.
- [M20] Prove that binary search on sorted keys needs at most comparisons.
- [M22] Prove that the recursive merge of two sorted lists returns a sorted list with all elements of both.
- [M24] Prove that the procedure of the text returns for , and that it makes at most calls for . Count the calls for .
- [M25] Prove that Hanoi has a unique shortest solution, by showing that in each shortest solution the largest disk moves exactly once.
Lean
A recursive function with a call on a smaller argument is accepted when Lean can prove that the argument decreases, by termination_by and decreasing_by for a measure that is not the structural one. The function Nat.gcd is defined by well-founded recursion in this way. The correctness of pw as pw x n = x ^ n is proved by Nat.strong_induction_on with a case split on the parity, as in the proof of this section.
Notes and history
The towers of Hanoi are a puzzle of Lucas of 1883, and the story of the monks and the sixty-four disks goes with it. The method of binary search was described by Mauchly in 1946 and the first fully correct programs came later, a point that Knuth makes in Volume 3. The power by squaring is old, and TAOCP discusses it with its history in Section 4.6.3. The loop and the invariant are the subject of Chapter 8.
A recursive definition describes an object by a rule that uses smaller objects of the same kind. The factorial, the Fibonacci numbers, a list and a tree are all defined in this way. A proof about such an object follows its definition, and the proof method that results is structural induction, a form of the induction of Chapters 4 and 5.
Section 1 treats the recursive definition of a function on the natural numbers, proves that such a definition defines exactly one function, and shows what goes wrong when the recursion does not reach a base case. Section 2 defines lists and binary trees as recursively defined sets, defines the length, the append, the reverse, the number of leaves and the height, and proves their laws by structural induction. Section 3 turns to programs: recursive procedures, their proofs by induction, the towers of Hanoi, binary search, and the loop that replaces a recursion.
The chapter assumes Chapters 1 to 5. The spine texts are Velleman, How to Prove It, Section 6.3, and Lehman, Leighton and Meyer, Mathematics for Computer Science, Chapters 6 and 7. TAOCP uses the structures of Section 2 in Chapter 2 of Volume 1, on information structures, and the recursion of Section 3 in many of its algorithms.
The source of this page. Something is wrong? Report it.