**************************************************************
So far, we've talked about several closely related ideas:
1: General recursion
2: Tail recursion
3: Iteration
A recursive problem is one that is defined in terms of itself.
There
are two important featuresthat there be one or more trivial base
cases, and that there be a way to solve "big" instances by first
solving "smaller" instances, then performing a simple computation.
Recursive problems usually follow the structure of an inductive proof.
Once a problem has been stated in recursive terms, it is fairly simple
to write a recursive program to solve it.
Unfortunately, such
programs often require one stack frame for every recursive call; this
can be substantial.
To solve this, we considered tail recursive programs.
The essential
nature of a tail recursive solution is that it requires only "constant
space"it doesn't matter how "large" the problem to be solved is, we
only need a fixed number of stack frames to solve it, as long as our
compiler is sufficiently clever.
For example, in our tailrecursive
factorial solution, we only need the first fact_helper stack frame, no
matter how large N happens to be.
That turns out to also be true for iterative solutions of the same
problems.
In fact, the two versions of factorial() we've seen are
very very similar.
It turns out that that similarity is no accident!
Outline for today
1) Get a little practice in "proof by construction"
2) Prove that tailrecursion is a subset of iteration.
We'll show that for *any* tailrecursive function, you can write an
iterative equivalent.
In other words, tailrecursion is *just*
iteration.
The equivalence we will show is *not* true for general
recursive programsin particular, there are some recursive programs
that cannot be solved in constant space, including the tree traversal
problem from project 2.
++++++++++++++++++++++++++++++++++++++++++
The general idea behind what we are trying to do today is simple.
We
want to show that tailrecursion is "no more powerful" than
iterationthat for any computation we could express
tailrecursively, we could also express it iteratively.
We do this by
giving a method for converting an arbitrary tailrecursive function to
an iterative one.
This technique is called "proof by construction."
To see how it works, let's start with an easy one.
C++ has three
different kinds of loops: while, do, and for:
while (<booleancondition>)
<bodystatement>
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
On entry, the condition is evaluated.
If the condition is false,
the loop terminates.
Otherwise, the body statement is evaluated,
and the loop is reentered.
This is the end of the preview.
Sign up
to
access the rest of the document.
 Winter '08
 NOBLE
 Recursion, Tail recursion, Control flow, int num, that

Click to edit the document details