73
votes

What's the difference between fold and reduce in Dart and when would I use one as opposed to the other? They seem to do the same thing according to the docs.

Reduces a collection to a single value by iteratively combining each element of the collection with an existing value using the provided function.

1
Actually the docs are slightly different for both functions. Fold: Reduces a collection to a single value by iteratively combining each element of the collection with an existing value using the provided function. Reduce: Reduces a collection to a single value by iteratively combining elements of the collection using the provided function.Christophe Herreman

1 Answers

117
votes

reduce can only be used on non-empty collections with functions that returns the same type as the types contained in the collection.

fold can be used in all cases.

For instance you cannot compute the sum of the length of all strings in a list with reduce. You have to use fold :

final list = ['a', 'bb', 'ccc'];
// compute the sum of all length
list.fold(0, (t, e) => t + e.length); // result is 6

By the way list.reduce(f) can be seen as a shortcut for list.skip(1).fold(list.first, f).