省道折叠 vs 减少

在 Dart 中 弃牌减少的区别是什么? 我什么时候使用其中一个而不是另一个?根据记录,他们也是这么做的。

通过迭代组合每个 元素,该元素具有使用提供的 功能。

39445 次浏览

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

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