Difference between fold and reduce in Kotlin, When to use which?

KotlinReduceFold

Kotlin Problem Overview


I am pretty confused with both functions fold() and reduce() in Kotlin, can anyone give me a concrete example that distinguishes both of them?

Kotlin Solutions


Solution 1 - Kotlin

fold takes an initial value, and the first invocation of the lambda you pass to it will receive that initial value and the first element of the collection as parameters.

For example, take the following code that calculates the sum of a list of integers:

listOf(1, 2, 3).fold(0) { sum, element -> sum + element }

The first call to the lambda will be with parameters 0 and 1.

Having the ability to pass in an initial value is useful if you have to provide some sort of default value or parameter for your operation. For example, if you were looking for the maximum value inside a list, but for some reason want to return at least 10, you could do the following:

listOf(1, 6, 4).fold(10) { max, element ->
    if (element > max) element else max
}

reduce doesn't take an initial value, but instead starts with the first element of the collection as the accumulator (called sum in the following example).

For example, let's do a sum of integers again:

listOf(1, 2, 3).reduce { sum, element -> sum + element }

The first call to the lambda here will be with parameters 1 and 2.

You can use reduce when your operation does not depend on any values other than those in the collection you're applying it to.

Solution 2 - Kotlin

The major functional difference I would call out (which is mentioned in the comments on the other answer, but may be hard to understand) is that reduce will throw an exception if performed on an empty collection.

listOf<Int>().reduce { x, y -> x + y }
// java.lang.UnsupportedOperationException: Empty collection can't be reduced.

This is because .reduce doesn't know what value to return in the event of "no data".

Contrast this with .fold, which requires you to provide a "starting value", which will be the default value in the event of an empty collection:

val result = listOf<Int>().fold(0) { x, y -> x + y }
assertEquals(0, result)

So, even if you don't want to aggregate your collection down to a single element of a different (non-related) type (which only .fold will let you do), if your starting collection may be empty then you must either check your collection size first and then .reduce, or just use .fold

val collection: List<Int> = // collection of unknown size

val result1 = if (collection.isEmpty()) 0
              else collection.reduce { x, y -> x + y }

val result2 = collection.fold(0) { x, y -> x + y }

assertEquals(result1, result2)

Solution 3 - Kotlin

Another difference that none of the other answers mentioned is the following:

The result of a reduce operation will always be of the same type (or a super type) as the data that is being reduced. We can see that from the definition of the reduce method:

public inline fun <S, T : S> Iterable<T>.reduce(operation: (acc: S, T) -> S): S {
    val iterator = this.iterator()
    if (!iterator.hasNext()) throw UnsupportedOperationException("Empty collection can't be reduced.")
    var accumulator: S = iterator.next()
    while (iterator.hasNext()) {
        accumulator = operation(accumulator, iterator.next())
    }
    return accumulator
}

On the other hand, the result of a fold operation can be anything, because there are no restrictions when it comes to setting up the initial value. So, for example, let us say that we have a string that contains letters and digits. We want to calculate the sum of all the digits. We can easily do that with fold:

val string = "1a2b3"
val result: Int = string.fold(0, { currentSum: Int, char: Char ->
    if (char.isDigit())
        currentSum + Character.getNumericValue(char)
    else currentSum
})

//result is equal to 6

Solution 4 - Kotlin

reduce - The reduce() method transforms a given collection into a single result.

val numbers: List<Int> = listOf(1, 2, 3)
val sum: Int = numbers.reduce { acc, next -> acc + next }
//sum is 6 now.

fold - What would happen in the previous case of an empty list? Actually, there’s no right value to return, so reduce() throws a RuntimeException

In this case, fold is a handy tool. You can put an initial value by it -

val sum: Int = numbers.fold(0, { acc, next -> acc + next })

Here, we’ve provided initial value. In contrast, to reduce(), if the collection is empty, the initial value will be returned which will prevent you from the RuntimeException.

Solution 5 - Kotlin

Simple Answer

Result of both reduce and fold is "a list of items will be transformed into a single item".

In case of fold,we provide 1 extra parameter apart from list but in case of reduce,only items in list will be considered.

Fold

listOf("AC","Fridge").fold("stabilizer") { freeGift, itemBought -> freeGift + itemBought }

//output: stabilizerACFridge

In above case,think as AC,fridge bought from store & they give stabilizer as gift(this will be the parameter passed in the fold).so,you get all 3 items together.Please note that freeGift will be available only once i.e for the first iteration.

Reduce

In case of reduce,we get items in list as parameters and can perform required transformations on it.

listOf("AC","Fridge").reduce { itemBought1, itemBought2 -> itemBought1 + itemBought2 }

//output: ACFridge

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTapanHPView Question on Stackoverflow
Solution 1 - Kotlinzsmb13View Answer on Stackoverflow
Solution 2 - KotlinMatt KleinView Answer on Stackoverflow
Solution 3 - KotlinDimitar SpasovskiView Answer on Stackoverflow
Solution 4 - KotlinGk Mohammad EmonView Answer on Stackoverflow
Solution 5 - KotlinTarun AView Answer on Stackoverflow