03-tailrecursion.student

03-tailrecursion.student - Last Time: * The stack: calling...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Last Time: * The stack: calling multiple funcitons * Recursion: base case, inductive step * Recursive functions: factorial, numOnes Today: * The recursion "space problem": * what it is, and how to fix it * Tail-recursion: a "small" recursive twist * Testing programs ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ So far, we've introduced the notion of recursive problems and, correspondingly, recursive functions. Something is recursive if it refers to itself. A problem is recursive if it has: * One or more trivial base cases * Other cases defined in terms of smaller problem instances. (these are "inductive steps") A function is recursive if it calls itself. We then gave a few examples of how to map from recursive definitions to recursive functions: identify the base case, and write that down. Then, write the inductive step as a recursive call. Happily, there is a way to re-write the recursive version to use (approximately) the same amount of space as is required by the iterative version. Consider the following implementation: int fact_helper(int n, int result) // REQUIRES: n >= 0 // EFFECTS: returns result * n! { if (n == 0) { return result; } else { return fact_helper(n-1, result * n); } } int factorial(int num) // REQUIRES: n >= 0 // EFFECTS: returns num! { return fact_helper(num, 1); } There is an important thing to notice about fact_helper. For *every* call to fact_helper: n! * result == num!
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is called the "recursive invariant" of fact_helper; an invariant is something that is always true. Being able to write down invariants makes it much easier to write these sorts of functions. So what's the big deal? This just looks like a more complicated way to write the solution. Let's trace out a call to the "new" factorial(2), and compare it to the "old" factorial(2): "new" "old" factorial(2) factorial(2) -->fact_helper(2, 1) -->2 * factorial(1) -->fact_helper(1, 2) -->1 * factorial(0) -->fact_helper(0, 2) <--1 <--2 <--1*1 (==1) <--2 <--2*1 (==2) <--2 As the two recursions progress, they look the same.
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/28/2010 for the course EECS 280 taught by Professor Noble during the Winter '08 term at University of Michigan.

Page1 / 6

03-tailrecursion.student - Last Time: * The stack: calling...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online