Grade 12 Computer Science · Recursion

The same idea, another language

What carries over unchanged, and what is added.

The same mistake: it runs there, here it will not compile

A recursive function that forgot a return on one of its paths runs quietly in Python, and blows up much later somewhere else. The very same function in Java does not compile at all. And why, in Java, is the whole array passed again and again, instead of cutting a smaller piece from it?

In grade nine you learned that recursion is a function solving a problem by solving a smaller version of it, and that it requires two parts: a base case and a step that shrinks. All of that is true word for word. What is added this year are two things the new language allows: tracing exactly what happens, and knowing what it costs.

The calls descend to the base, and the answers are built on the way back.
static int total(int[] items, int from) {
    if (from >= items.length) return 0;        // the base returns
    return items[from] + total(items, from + 1);
}

// total(new int[]{4, 7, 2}, 0)  ->  13
// the base is reached when "from" runs past the end

Why there is an extra parameter

In Python it was convenient to cut the list and pass the rest. In this language cutting an array creates a new array at every call, and that is expensive. The accepted form is to pass the array as it is and add a parameter saying where to start — it is the one that grows at every call, and it is the one approaching the base. This is no compromise: this form is both faster and more explanatory, because one sees exactly what changes between call and call.

The partIn the example
A base caseThe position passed the end
A step that shrinksThe position grows by one
The joiningThe current cell plus the total of the rest

Example 1 — why the base must return

  1. The function declares it returns a number.
  2. A path with no return breaks the declaration.
  3. And the code does not compile.

Example 2 — why a parameter and not cutting

  1. Cutting creates a new array at every call.
  2. The parameter costs nothing.
  3. And one sees exactly what changes.
Only from grows between call and call, and it is what approaches the base.