While going through Functional Programming in Scala, I came across this question:
Can you right foldLeft in terms of foldRight? How about the other way
That code is chaining several function objects together, one function for each element in the list. Here is an example that shows that more clearly.
val f = (a: Int, b: Int) => a+b
val list = List(2,3,4)
println(list.foldLeft(1)(f))
val f1 = (b: Int) => f(b, 2)
val f2 = (b: Int) => f(b, 3)
val f3 = (b: Int) => f(b, 4)
val f4 = (b: Int) => b
val ftotal = f1 andThen f2 andThen f3 andThen f4
println(ftotal(1))
You can imagine that as a linked list of function objects. When you pass in a value it "flows" through all the functions. It's a little like dataflow programming.