Is there some trade-off between these two examples of the same thing?
My bias is to always use a functional style, but if I'm running billions of these foldLeft
s, is creating a new FunctionalA
for every step in every list less efficient than just updating a var
instead?
A generic collection of values:
case class B(b: Int)
val bb = (1 to 20).toList.map(B(_))
folded imperatively:
class ImperativeA {
var a = 0
def ingest(x: B): Unit = a += x.b
}
val imperative_fold =
bb.foldLeft(new ImperativeA)((a,b) => {a ingest b; a} )
imperative_fold.a // 210
folded functionally:
class FunctionalA(val a: Int = 0) {
def ingest(x: B) = new FunctionalA(a + x.b)
}
val functional_fold =
bb.foldLeft(new FunctionalA())(_ ingest _)
functional_fold.a // 210