Folding and reducing data sets
While the map()
operator takes a list of a given size and returns another list of the same size and of the modified type, the fold()
and reduce()
operations applied to the data set return a single element, composed of the consecutive elements of the data set. This may sound like a simple scenario for using a plain, imperative-style loop and local accumulator variable that holds a current state and is updated at each iteration. We can consider the simple task of summing up integer values. Let's consider that we want to compute a sum of consecutive integers from 0
to 10
. We could achieve it using a simple for
loop:
var sum = 0 (1..10).forEach { sum += it }
However, there is an alternative, functional way of performing such computations, using the fold()
function:
val sum = (1..3).toList().fold(0) { acc, i -> acc + i }
The second approach is desirable whenever we implement a chain of functional data-processing operations. Compared to the for loop, the fold...