1

I am trying to learn how to use fold left and fold right. This is my first time learning functional programming. I am having trouble understanding when to use fold left and when to use fold right. It seems to me that a lot of the time the two functions are interchangeable. For example (in Scala)the two functions:

val nums = List(1, 2, 3, 4, 5)

val sum1 = nums.foldLeft(0) { (total, n) =>
  total + n
}
val sum2 = nums.foldRight(0) {(total, n) =>
  total + n
}

both yield the same result. Why and when would I choose one or the other?

krishna Prasad
  • 3,541
  • 1
  • 34
  • 44
jcm
  • 5,499
  • 11
  • 49
  • 78

2 Answers2

0

foldleft and foldright differ in the way the function is nested.

foldleft: (((...) + a) + a) + a
foldright: a + (a + (a + (...)))

Since the function you are using is addition, both of them give the same result. Try using subtraction.

Moreover, the motivation to use fold(left/right) is not the result - in most of the cases, both yield the same result. It depends on which you you want your function to be aggregated.

Wraith
  • 63
  • 5
0

Since the operator you are using is associated & commutative operator means a + b = b + a that's why leftFold and rightFold worked equivalent but it's not the equivalent in general as you can visualised by below examples where operator(+) is not associative & commutative operation i.e in case of string concatenation '+' operator is not associative & commutative means 'a' + 'b' != 'b' + 'a'

val listString = List("a", "b", "c") // : List[String] = List(a,b,c)
val leftFoldValue = listString.foldLeft("z")((el, acc) => el + acc) // : String = zabc
val rightFoldValue = listString.foldRight("z")((el, acc) => el + acc) // : abcz 

OR in shorthand ways

val leftFoldValue = listString.foldLeft("z")(_ + _) // : String = zabc
val rightFoldValue = listString.foldRight("z")(_ + _) // : String = abcz

Explanation:

leftFold is worked as ( ( ('z' + 'a') + 'b') + 'c') = ( ('za' + 'b') + 'c') = ('zab' + 'c') = 'zabc'

and rightFold as ('a' + ('b' + ('c' + 'z'))) = ('a' + ('b' + 'cz')) = ('a' + 'bcz') = 'abcz'

So in short for operators that are associative and commutative, foldLeft and foldRight are equivalent (even though there may be a difference in efficiency). But sometimes, only one of the two operators is appropriate.

krishna Prasad
  • 3,541
  • 1
  • 34
  • 44