Dart折叠vs减少 [英] Dart Fold vs Reduce
问题描述
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.
推荐答案
fold 可用于所有情况。
例如,您无法计算列表中所有字符串的长度之和与 reduce
。您必须使用 fold
:
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
顺便说一下 list.reduce(f) / code>可以看作是
list.skip(1).fold(list.first,f)
的快捷方式。
By the way list.reduce(f)
can be seen as a shortcut for list.skip(1).fold(list.first, f)
.
这篇关于Dart折叠vs减少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!