A Scala ‘foldLeft’ function written using recursion

As a short note, here’s some Scala source code that shows how to write a foldLeft function using recursion:

package folding

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, 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

Note that it’s easy to convert this function into a generic function:

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)
    }
}

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.