Lists

Using List class foldLeft method

An example of using List class foldLeft method:

val l1: Int = List(1,2,3).foldLeft(20)((a, b) => a + b) = ((20 + 1) + 2) + 3 = 26

foldLeft calculation starts from the initial value 20, consecutively iterates over all list elements, from the leftmost to the rightmost, adding the preceding iteration result to the list current element value.

Step 0. Calculation starts from the initial value 20

Step 1. a is equal to 20 (the initial value), b is equal to 1 (the list first element value), so (a + b) = (20 + 1) produces 21

Step 2. a is equal to 21 (the first step result), b is equal to 2 (the list second element value), so (a + b) = (21 + 2) produces 23

Step 3. a is equal to 23 (the second step result), b is equal to 3 (the list third element value), so (a + b) = (23 + 3) produces 26

Wildcard operators can be used in foldLeft. The expression above can also be written as follows:

val l1: Int = List(1,2,3).foldLeft(20)(_ + _)

Documentation: https://www.scala-lang.org/api/current/scala/collection/immutable/List.html

Using List class foldRight method

An example of using List class foldRight method:

val l2: Int = List(1,2,3).foldRight(20)((a, b) => a - b) = 1 - (2 - (3 - 20) = -18

foldRight calculation starts from the initial value 20, consecutively iterates over all list elements, from the rightmost to the leftmost, subtracting the preceding iteration result from the list current element value.

Step 0. Calculation starts from the initial value 20

Step 1. a is equal to 3 (the list last element value), b is equal to 20 (the initial value), so (a – b) = (3 – 20) produces -17

Step 2. a is equal to 2 (the list second element value), b is equal to -17 (the first step result), so (a – b) = (2 – (-17)) produces 19

Step 3. a is equal to 1 (the list first value), b is equal to 19 (the second step result), so (a – b) = (1 – 19) produces -18

As with foldLeft, wildcard operators can be used in foldRight. So, the expression above can also be written as follows:

val l2: Int = List(1,2,3).foldRight(20)(_ - _)

Documentation: https://www.scala-lang.org/api/current/scala/collection/immutable/List.html