Previously, Nicolas Rinaudo answered my question on Scala\'s List foldRight Always Using foldLeft?
Studying Haskell currently, my understanding is that foldRig
@Rein Henrichs' answer is indeed irrelevant to Scala, because Scala's implementation of foldLeft
and foldRight
is completely different (for starters, Scala has eager evaluation).
foldLeft
and foldRight
themselves have actually very little to do wrt the performance of your program. Both are (liberally speaking) O(n*c_f) where c_f is the complexity of one call to the function f
that is given. foldRight
is slower by a constant factor because of the additional reverse
, though.
So the real factor that differentiates one from the other is the complexity of the anonymous function that you give. Sometimes, it is easier to write an efficient function designed to work with foldLeft
, and sometimes to foldRight
. In your example, the foldRight
version is best, because the anonymous function that you give to foldRight
is O(1). In contrast, the anonymous function that you give to foldLeft
is O(n) itself (amortized, which is what matters here), because acc
keeps growing from 0 to n-1, and appending to a list of n elements is O(n).
So it actually matters whether you choose foldLeft
or foldRight
, but not because of these functions themselves, but because of the anonymous functions given to them. If both are equivalent, choose foldLeft
by default.