A Scala "fold left" function written using recursion
Briefly

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.
Read at Alvinalexander
[
add
]
[
|
|
]