Recursion

INFO I211

Chapter 12

Examples:

12.1 Recursive Thinking

Recursive definitions have:

Lists

Page 584: A list is

But why not: A list is

Factorial Function

Page 585:

But why not

Base Cases

Infinite Recursion

12.2 Recursive Programming

Translating a mathematical recursive definition into a recursive Java method is straightforward.

Do it for factorial:

// assumes n >= 0
public static int factorial (int n) 
{
  if (n == 0)
    return 1;
  else
    return n * factorial(n - 1);
}

How Does Recursion Work?

Recursion and Iteration

Example: Tail-Recursive Factorial

public static int factorial (int n)
{
  return factorial(n, 1);
}

private static int factorial (int n, int result)
{
  if (n == 0)
    return result;
  else
    return factorial(n - 1, n * result);
}

Demonstration

factorial(4) = …

Proper Tail Recursion

We cannot do this in Java, but we can in Haskell:

print_forever :: Int -> IO ()
print_forever n = do
  {
    print n
  ; print_forever (n + 1)
  }

Demonstration

Summary: Comparing Iteration and Recursion

  1. Every iterative method is equivalent to some recursive method and vice-versa—equivalent in the sense of computing the same results.

  2. We have seen how the recursive method may (or may not) be as efficient as the iterative method.

  3. The recursive method may be much more elegant than the iterative method.

  4. In such cases, the equivalent iterative method typically requires an explicit data structure called a stack (covered in chapter 13) to manage the stack of environments.

  5. Some recursive methods are extremely inefficient (but then, so are the equivalent iterative methods).

Direct and Indirect Recursion

See Figure 12.4, p. 590.

Make this more concrete with a pair of methods:

public boolean even (int num)
public boolean odd (int num)

Also note that there is a much simpler, and faster, non-recursive (and non-iterative) solution to the even/odd problems, using % 2.

Part II: Recursion in Graphics

Sec. 12.4: Fractals

Fractals

Part III: Functional Lists

Functional List Class Hierarchy

image
image

Lists

Using Lists

References

Document History