sum
Adds up every number a lazy pipeline produces.
Lecture
sum is a terminal operator, and one of the simplest
special-cased folds in the library: it's literally
fold(0, (a, b) => a + b, iterable) underneath. Like every
terminal, calling it pulls the entire lazy pipeline upstream of it — so
you can build an elaborate chain of map/filter
steps and only pay for the values sum actually needs, which
is all of them.
Because the seed is 0, summing an empty iterable gives
0 — no error, no NaN. That's different from its
neighbors min,
max, and
average, which each have their
own (surprising!) empty-input behavior worth knowing about.
The chain form is available as an extension method,
Fx<num>.sum() / FxAsync<num>.sum() —
it only shows up once your chain's element type is known to be
num (or int/double, thanks to
generic covariance).
Demo 1 · Basics
Demo 2 · Async
Try it yourself
Exercise: sum only the even numbers in the list.