Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart Fold vs Reduce

Tags:

dart

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.

like image 256
basheps Avatar asked Dec 10 '13 10:12

basheps


People also ask

Is reduce the same as fold?

On the one hand, if we operate only on a non-empty collection and combine all elements into a single result of the same type, then reduce() is a good choice. On the other hand, if we want to provide an initial value or change the result type, then fold() gives us the flexibility to do it.

What is reduce in Dart?

method reduceReduces a collection to a single value by iteratively combining elements of the collection using the provided function. The iterable must have at least one element. If it has only one element, that element is returned.

How do you use the reduce method in flutter?

In Dart, the reduce() method (of the Iterable class), as its name describes itself, executes a “reducer” callback function (provided by you) on each element of the collection, in order, passing in the return value from the calculation on the preceding element.

What is use of fold in flutter?

The Fold method Reduces a collection to a single value by iteratively combining each element of the collection with an existing value using the provided function. The fold can be used in all cases. They are used to generate a single value by combining the elements of the list.


2 Answers

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

like image 62
Alexandre Ardhuin Avatar answered Oct 22 '22 17:10

Alexandre Ardhuin


There are a few noticeable differences between them. Other than the ones mentioned above, it is worth highlighting that fold() is able to operate on collections that are empty without producing an error.

reduce() will throw an error saying Bad state: No element whereas fold() will return a non-null value back, using the initial value passed onto it as a fallback return value.

I've discussed about this at length here:

https://medium.com/@darsshanNair/demystifying-fold-in-dart-faacb3bd4efd

like image 3
Darsshan Avatar answered Oct 22 '22 16:10

Darsshan