Functional Programming notes: Recursion

  3 mins read

Recursion is a technique that allows us to break down a problem into smaller pieces. This technique allows us to remove some side effects that we perform while writting looping structures and also makes our code more expressive and readable. In this post we will see why is a very present technique in functional programming and how it can help us.

Functional loops

In the function that we wrote in the previous post:

def sumIntsTo(i: Int) = {
  var result = 0
  0 to i foreach((i) => result = result + i)

You could notice that there is a side effect in that imperative-like loop. We are assigning the result of the computation to an accumulator because foreach is a function that returns void, it does not return anything, so we don’t have any other choices. That foreach method therefore is a statement. We say that an statement is a block of code that can be executed but not reducted. In contrast to that, we say that a block of code that can be reducted is an expression.

Head recursion

The first technique that we are going to use is called head recursion. Let’s translate the previous function to a head recursive function:

def sumIntsToRecursive(i: Int) : Int =
  if (i == 0) 0 else i + sumIntsToRecursive(i - 1)

This function does not have any side effects. Internally it calculates a sum until we reach the base case which is 0. Here is the stack trace for sumIntsToRecursive(5):

5 + sumIntsToRecursive(4)
5 + (4 + sumIntsToRecursive(3))
5 + (4 + (3 + sumIntsToRecursive(2)))
5 + (4 + (3 + (2 + sumIntsToRecursive(1))))
5 + (4 + (3 + (2 + (1 + sumIntsToRecursive(0)))))
5 + (4 + (3 + (2 + (1 + 0))))
> 15

We can say that the recursive calls occours before the computation, or at the head. That means that after the recursive call we can have other blocks to evaluate, or like in this case, we evaluate the first sum after all the consequent evaluations are reducted.

You could see as well that we have to keep the state of the current computation until we finish evaluating the stack, so in the last step we will end up holding: 5 + 4 + 3 + 2 + 1 and then we will evaluate the last case to finish up with the computation of all the values that we had in the intermediate steps.

Holding this state can be a problem, specially if we deal with a large amount of numbers. If we try to evaluate the previous function passing Integer.MAX_VALUE as the argument we will see that the function crashes and gives us a StackOverflowException. Even if we achieved our initial purpouse of not having side effects, we do have one if the number is to large to be evaluated. That lead us to the next technique, tail recursion:

Tail recursion

The only difference between head and tail recursion is that the recursive calls occours after the computation, or at the tail. Let’s translate the previous function to a tail recursive function:

def sumIntsToTailRecursive(i: Int) : Int = {
    def go(i: Int, acc: Int): Int = {
      if (i == 0) acc
      else {
        val nextI = i - 1
        val nextAcc = acc + i
        go(nextI, nextAcc)
    go(i, 0)

As you could notice the last call in the method is the tail recursive call, we need to make the computations before invoking it. That lead us to the following stack trace:

go(5, 0)
go(4, 5)
go(3, 9)
go(2, 12)
go(1, 14)
go(0, 15)
> 15

As you could notice we only have to hold the previous intermediate state, but not all the previous to the current one. If we execute this function with the argument Integer.MAX_VALUE we will see that it completes ok.

In modern languages like Java 8, Scala, Kotlin, etc… Tail recursive calls are converted to imperative loops at compile time to optimize the code. In Scala, when we write a tail recursive function we can annotate the recursive method with @tailrec. If we do so, and the function is not tail recursive we will have an error at compile time.

I recommend you to practice recursive functions as in functional programming are a common thing. Fibonacci number, a bowling score calculator or the pascal triangle are good exercises to get used to it.


With this simple post, I conclude on how to write loops in a functional manner. It took me a while to write my first recursive functions because I was not used to it, so if you are in my case, just keep practicing until you get familiar with this technique. Practice makes perfect!



Written by:

Christian Panadero Martinez