Recursion: The Base Case

    Recursion: The Base Case

      What's your game plan for the zombie apocalypse?

      Our looks something like this:

      Step One: Look around to see if there are zombies.
      Step Two: If there are zombies, kill them or run away, then go back to Step One.
      Step Three: If there are no zombies, stop killing them and/or running away.

      Seems like a pretty solid plan if you ask us, and it all works because of recursion. Recursion works by starting at some case and breaking a problem or situation down, further and further, until reaching a base case—in this case, Step Three. To get to that coveted base case, the breaking down happens when the recursive function calls itself over and over again.

      There's just one problem: Before it can keep calling itself, though, the function needs a base case as its stopping point. There has to be a way for the recursive algorithm/ function to end itself.

      Otherwise…it'll loop forever. That's not good.

      In our survival plan, the zombie-infested earth is the current problem. We look around to see if there are any undead nearby. If there are, we handle it with the classic fight-or-flight maneuver (but probably the flight part of it more) then repeat the process by looking again—that's the recursive bit. To keep us from infinitely running away from nothing, there's a base case that says when we can't find any more zombies, go ahead and stop (and try to put the shambles of your life back together, probably).

      If this plan were put into pseudocode (so that maybe our robot friends could escape with us), it would look more like this:

      FUNCTION escapeZombies(numberOfZombies)
      	IF zombies > 0:
      		runaway()
      		numberOfZombies = lookForZombies()
      		CALL escapeZombies(numberOfZombies)
      	ELSE:
      		Stop running
      	END IF
      END FUNCTION

      To make this escapeZombies() function work, though, we'd need a function that looks around for zombies and tells how many there are for us to run away from. That's totally fine; nothing says that a recursive algorithm has to be completely self-contained in a function. You just have to be careful to make sure you can reach the base case. Having other functions in there might distract from seeing a spot for infinite recursion. It could be a dangerous situation.

      More dangerous than zombies, some would argue, since infinite recursion actually exists.

      No, really. Recursive functions, unlike even the best-designed perpetual motion machines, are perfectly self-sustaining because they just keep calling themselves. The only way to keep a recursive function from looping infinitely is by using a base case to keep it in check.

      Whenever you build a recursive function, start with the base case so that you absolutely, positively know the recursion's going to end instead of running infinitely and killing your computer.

      Then you can go back to killing zombies.