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) .
2条答案
按热度按时间pobjuy321#
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 usefold
:By the way
list.reduce(f)
can be seen as a shortcut forlist.skip(1).fold(list.first, f)
.xnifntxz2#
它们之间有一些明显的区别,除了上面提到的,值得强调的是
fold()
能够在空集合上操作而不会产生错误。reduce()
将抛出错误Bad state: No element
,而fold()
将返回一个非空值,使用传递给它的初始值作为回退返回值。我已经在这里详细讨论过了:
https://medium.com/@darsshanNair/demystifying-fold-in-dart-faacb3bd4efd