Scala fold, foldLeft and foldRight

foldLeft

foldLeft takes 2 parameters. First one is a starting value, an empty string in our case. Second one is a function { (m: String, n: String) => m + n } , which in turn takes 2 parameters.

The first parameter (m) is an accumulator with an initial value of ” “. The second parameter (n) is the value from the list starting with “a”.

The following are the values for parameters m, n and the result at the end of each iteration.

Note:
The start value is passed as the first parameter to the function and list is evaluated from left to right.

foldRight

foldRight takes 2 parameters. First one is a starting value, an empty string. Second one is a function { (m: String, n: String) => m + n }‘ , which in turn takes 2 parameters.

The First parameter (m) is the value from the list starting with “c“. The second parameter (n) is an accumulator starting with the start value ” “. This is different from foldLeft.

The following are the values for parameters m, n and result at the end of each iteration.

Note:
The start value is passed as the second parameter to the function and list is evaluated from right to left. This is different from foldLeft.

fold

fold works same as above, except the order in which operations are performed is unspecified, because of this, there are 2 additional conditions on fold.

  1. Starting value must be neutral. e.g., Nil for list concatenation, 0 for addition, or 1 for multiplication. This is necessary as fold operation can work in parallel.
  2. Fold is done on supertype of values in a given collection.