Skip to content

How to Recursion

Recursion is a concept that is more scary than it has to be. The difficulty of recursion is not in the concept itself, but in its vast applications.

Mechanical Steps

If you have no idea how to start thinking of a recursive function, you can start by religiously following these steps:

  1. Define what you want the function \(f\) to do

    • Specify the inputs and outputs of the function
    • "Given \(n \ge 0\), \(f\) will return the sum of numbers from \(0\) to \(n\)"
    • The general structure I follow is like: "Given <input>, \(f\) will <do what>"

    Info

    When specifying the inputs and outputs, do not only specify the types, but also mention the property.

    • Negative example: "Given a list, \(f\) will return a number"
    • Better example: "Given a non-empty list of numbers, \(f\) will return its maximum"
  2. Recursive Case

    • Identify smaller sub-problems
    • Combine solutions of smaller sub-problems
  3. Base Case

    • Smallest possible sub-problem

Info

  • If you prefer, you can come up with the base case before the recursive case.

  • Some people also call the recursive step the "leap of faith". I must admit that some faith is needed in this stage

Recursion as a Tree Traversal

Info

This might not make sense to you on first read, since we haven't learned DFS at this point. But trust me, this framing is superior. Once you learn DFS, a lot of people will say: "Oh why didn't you just say that recursion is just DFS".

At its core, you're traversing through a tree.

void func() {
    // A

    for (int i = 0; i < 2; i++) {
        // B1 (i = 0), B2 (i = 1)
        func();
        // C1 (i = 0), C2 (i = 1)
    }

    // D
}

Try to correlate the code to the tree.

Exponentiation (Shrink by One)

Problem: Given an integer \(a\) and \(n \ge 0\), we want to compute \(a^n\).

  1. Define what the function \(\operatorname{pow}\) does: "Given \(n \ge 0\), \(\operatorname{pow}(a, n)\) will return \(a^n\)."
  2. Recursive Case
    • Decompose: Compute \(\operatorname{pow}(a, n - 1)\)
    • Combine: Return \(a \cdot \operatorname{pow}(a, n - 1)\)
  3. Base Case
    • When \(n = 0\), return \(1\).

For completeness, the recursive formula looks like

\[ \operatorname{pow}(a, n) = \begin{cases} 1 & \text{if } n = 0 \\ a \cdot \operatorname{pow}(a, n - 1) & \text{if } n > 0 \end{cases} \]
Draw out the recursion tree of pow(2, 8)

The recursion tree is a chain of depth \(n\).

Exponentiation (Split by Half)

Here's another way to compute \(a^n\). The main difference here is that the decomposition of the problem is different.

  1. Define what the function \(\operatorname{pow}\) does: "Given \(n \ge 0\), \(\operatorname{pow}(a, n)\) will return \(a^n\)."
  2. Recursive Case
    • Decompose: Compute \(h = \operatorname{pow}(a, \lfloor n/2 \rfloor)\)
    • Combine: Return \(h^2\) if \(n\) is even, and \(a \cdot h^2\) if \(n\) is odd
  3. Base Case
    • When \(n = 0\), return \(1\).
Write out the recursive formula for pow(a, n)
\[ \operatorname{pow}(a, n) = \begin{cases} 1 & \text{if } n = 0 \\ \operatorname{pow}(a, n / 2)^2 & \text{if } n \text{ is even} \\ a \cdot \operatorname{pow}(a, \lfloor n / 2 \rfloor)^2 & \text{if } n \text{ is odd} \end{cases} \]
Draw out the recursion tree of pow(2, 8)

The recursion tree is a chain of depth \(\log n\).

Write out the implementation in your favourite language

If you wrote it out in C it may look like this:

int power(int a, int n) {
  if (n == 0) return 1;
  if (n % 2 == 0) return power(a, n / 2) * power(a, n / 2);
  return a * power(a, n / 2) * power(a, n / 2);
}

Hint: The solution isn't the most efficient, can you see why?

int power(int a, int n) {
  if (n == 0) return 1;
  int h = power(a, n / 2);
  if (n % 2 == 0) return h * h;
  return a * h * h;
}
What's the diff?

The first version calls power(a, n / 2) twice, so each call branches into two identical sub-problems. Here's the recursion tree of \(\operatorname{pow}(2, 4)\).

The second version calls it once and reuses h, so the tree collapses back into the chain above.

A Different Way of Writing Recursive Functions (Passing an Accumulator)

Info

I tried introducing this concept to a Programming Methodology class, but it wasn't the best idea. They just looked lost. However, I still believe that it's an important concept, and I hope that they will be able to understand this someday.

In this style of writing recursive functions, we pass an additional variable called \(\text{acc}\). It will store the computation that we have done so far.

\[ \operatorname{pow}(a, n, \text{acc}) = \begin{cases} \text{acc} & \text{if } n = 0 \\ \operatorname{pow}(a, n - 1, \text{acc} \cdot a) & \text{if } n > 0 \end{cases} \]

Notice that this kinda changes the definition of the function. "Given \(n \ge 0\), \(\operatorname{pow}(a, n, \text{acc})\) will return \(a^n \cdot \text{acc}\)." So to get \(a^n\), we call \(\operatorname{pow}(a, n, 1)\), passing in the initial value of \(1\) for the accumulator.

Now let us trace one execution of \(\operatorname{pow}(2, 3, 1)\).

\[ \begin{aligned} \operatorname{pow}(2, 3, 1) &= \operatorname{pow}(2, 2, 2) \\ &= \operatorname{pow}(2, 1, 4) \\ &= \operatorname{pow}(2, 0, 8) \\ &= 8 \end{aligned} \]
What does the recursion tree look like?

So, what do we gain from passing an accumulator? If you look at the recursion tree, you should see that on the way back up, we are just passing the exact same value back up the tree.

Tail call elimination

Since the recursive call is the last thing the function does (a tail call), some languages can reuse the stack frame instead of pushing a new one. See tail call elimination.