Dart Fold vs Reduce

Dart

Dart Problem Overview


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.

Dart Solutions


Solution 1 - Dart

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).

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
QuestionbashepsView Question on Stackoverflow
Solution 1 - DartAlexandre ArdhuinView Answer on Stackoverflow