Dart Fold vs Reduce

前端 未结 1 1155
小鲜肉
小鲜肉 2020-12-29 18:12

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 acc

1条回答
  •  一生所求
    2020-12-29 18:43

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

    0 讨论(0)
提交回复
热议问题