existKotlin
middle,reduce()
andfold()
It is a high-order function commonly used in functional programming. They are all functions that aggregate elements in a collection, reducing elements in a collection to a separate value. They are used very similarly, but the return values are slightly different. Here are their differences:
-
reduce()
A function aggregates all elements in a collection and returns the last merge processed value. -
fold()
In addition to merging all elements, a function can also accept an initial value and return it with the aggregate result. Note: If the set is empty, only the initial value will be returned.
Reduce example
1. Usereduce()
Functions calculate the sum of all numbers in the list:
fun reduceAdd() { val list = listOf(1, 2, 3, 4, 5) val sum = { acc, i -> println("acc:$acc, i:$i") acc + i } println("sum is $sum") // 15 }
Execution results:
acc:1, i:2
acc:3, i:3
acc:6, i:4
acc:10, i:5
sum is 15
2. Usereduce()
Functions calculate the splicing result of all strings in the string list:
val strings = listOf("apple", "banana", "orange", "pear") val result = { acc, s -> "$acc, $s" } println(result) // apple, banana, orange, pear
Execution results:
apple, banana, orange, pear
folder example
1. Usefold()
The function calculates the sum of all numbers in the list and adds an initial value to it:
val numbers = listOf(1, 2, 3, 4, 5) val sum = (10) { acc, i -> acc + i } println(sum) // 25
The execution result is:
acc:10, i:1
acc:11, i:2
acc:13, i:3
acc:16, i:4
acc:20, i:5
sum is 25
2. Use the fold() function to concatenate all strings in the list and add an initial value to it:
val strings = listOf("apple", "banana", "orange", "pear") val result = ("Fruits:") { acc, s -> "$acc $s" } println(result) // Fruits: apple banana orange pear
Execution results:
Fruits: apple banana orange pear
Source code analysis
reduce()
existKotlin
The implementation of the standard library is as follows:
public inline fun <S, T : S> Iterable<T>.reduce(operation: (acc: S, T) -> S): S { val iterator = () if (!()) throw UnsupportedOperationException("Empty collection can't be reduced.") var accumulator: S = () while (()) { accumulator = operation(accumulator, ()) } return accumulator }
As can be seen from the code,reduce
The function receives aoperation
Parameter, it is alambda
Expression, used for aggregation calculations.reduce
The function first obtains the iterator of the collection and determines whether the collection is empty. If it is empty, an exception will be thrown. Then, through an iterator, iterates through each element in the set, performs aggregation calculation on the elements, and passes the calculation result to the next element as an accumulator until all elements are aggregated. Finally, the result of the aggregation calculation is returned.
fold()
existKotlin
The implementation of the standard library is as follows:
public inline fun <T, R> Iterable<T>.fold( initial: R, operation: (acc: R, T) -> R ): R { var accumulator: R = initial for (element in this) { accumulator = operation(accumulator, element) } return accumulator }
As can be seen from the code,fold
The function receives two parameters, the initial parameter is the initial value of the accumulator.operation
The parameter is alambda
Expression, used for aggregation calculations.
fold
The function first assigns the initial value to the accumulator, then traverses each element in the set, performs aggregation calculation on the elements, and passes the calculation result as an accumulator to the next element until all elements are aggregated. Finally, the result of the aggregation calculation is returned.
Summarize
-
reduce()
Suitable for aggregation operations that do not require initial values.fold()
Suitable for aggregation operations that require initial values. -
reduce()
The operation can directly return the aggregated result, andfold()
Operation needs to be passedlambda
The return value of the expression to update the accumulator value.
When using it, you need to choose which function to use according to the specific scenario.
This is the article about Kotlin's advanced function reduce and fold usage examples. For more related Kotlin reduce and fold content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!