Dart折叠与减少

siotufzp  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(139)

Dart中的foldreduce之间有什么区别?我何时使用其中一个而不是另一个?根据文档,它们似乎做同样的事情。
使用提供的函式,反覆地将集合的每个元素与现有值结合,将集合缩减为单一值。

pobjuy32

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

xnifntxz

xnifntxz2#

它们之间有一些明显的区别,除了上面提到的,值得强调的是fold()能够在空集合上操作而不会产生错误。
reduce()将抛出错误Bad state: No element,而fold()将返回一个非空值,使用传递给它的初始值作为回退返回值。
我已经在这里详细讨论过了:
https://medium.com/@darsshanNair/demystifying-fold-in-dart-faacb3bd4efd

相关问题