A Scala “fold left” function written using recursion

As a brief note, here’s some Scala source code that shows how to write a fold left (foldLeft) function using recursion:

// scala 2

object FoldLeft extends App {

    val a = List(1,2,3,4)

    def add(a: Int, b: Int) = a + b

    println(foldLeft(0)(a)(add))

    def foldLeft(lastResult: Int)(list: List[Int])(f: (Int, Int) => Int): Int = list match {
        case Nil => lastResult
        case x :: xs => {
            val result = f(lastResult, x)
            println(s"last: $lastResult, x: $x, result = $result")
            foldLeft(result)(xs)(f)
        }
    }

}

The output of this example code looks like this:

last: 0, x: 1, result = 1
last: 1, x: 2, result = 3
last: 3, x: 3, result = 6
last: 6, x: 4, result = 10
10

I’ll explain this code in my new book on functional programming, but for the moment I’m just sharing the code here in case anyone wants/needs to see how to do this.

A generic version of ‘foldLeft’

You can also convert that to a generic function, like this:

def foldLeftGen[A](lastResult: A)(list: List[A])(f: (A, A) => A): A = list match {
    case Nil =>
        lastResult
    case x :: xs => {
        val result = f(lastResult, x)
        foldLeftGen(result)(xs)(f)
    }
}

This is a relatively simple conversion to a generic algorithm, as I mostly just replace each Int with the generic parameter A. Notice that because the Int isn’t referenced inside the function — in the function’s algorithm — making this change is about as easy as things get.

A Scala 3 generic version

Lastly, here’s a Scala 3 version of that generic function (with the tailrec annotation added):

import scala.annotation.tailrec

@tailrec
def foldLeft[A](lastResult: A)(list: List[A])(f: (A, A) => A): A = list match
    case Nil =>
        lastResult
    case x :: xs =>
        val result = f(lastResult, x)
        foldLeft(result)(xs)(f)

If you ever wanted to see how to write a “fold” algorithm in Scala, I hope this has been helpful.