The fold function

This function performs arithmetic operations on all the elements of a list and returns a result. To understand the concept of the fold function, we'll use addition as the operation. Let's add all the elements of the list and return a result. The fold function takes an integer parameter and a lambda expression. The first parameter indicates the initial value, and the second parameter takes a lambda expression for adding two values:

var numbers = listOf<Int>(1,2,3,4,5)

var result = numbers.fold(0){i,j -> i + j}
println("From beginning : add all elements of the list, Initial value is 0: " + result)

The fold function takes 0 as an initializer, adds all elements, and returns a result. To understand how things works under the hood, create a function that matches the signature of the lambda expression that takes two parameters of the integer type and returns a result:

fun foldHelper(i : Int, j : Int) : Int{
println("$i , $j")
return i + j
}

We can print the the value of i and j, and return the value by adding them together. Pass foldHelper to the fold function, as shown here, and execute the program:

var numbers = listOf<Int>(1,2,3,4,5)
var result = numbers.fold(0, ::foldHelper)
println("Answer = " + result)

The output of this function will be as follows:

0 , 1
1 , 2
3 , 3
6 , 4
10 , 5
Answer = 15

On each iteration, the fold function takes an element from the list, assigns it to i, and stores it in j after the arithmetic operation. There are two variants of the fold function. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.107.193