foldRight<S> method Null safety

S foldRight<S>(
  1. S initial,
  2. ReversedAccumulate<S, E> f
)

Accumulates a collection to a single value of type S, which starts from an initial value, by combining each element with the current accumulator value, with the combinator f in a reversed order.

Please notice that the arguments' order of the combinator f is (element, acc), which is reversed to the one for fold. For example:

[1, 2, 3, 4].foldRight(0, (x, acc) => x - acc) // => (1 - (2 - (3 - (4 - 0)))) => -2

Caution: to reverse an Iterable may cause performance issue, see sdk#26928

See also: List.reversed

Implementation

S foldRight<S>(S initial, ReversedAccumulate<S, E> f) {
  var acc = initial;
  asList().reversed.forEach((e) => acc = f(e, acc));
  return acc;
}