本页尚未翻译,因此以英文显示。 参与翻译

fxProduct · fxProductBy

The multiplying sibling of sum — and an empty input is 1, not 0.

num fxProduct(Iterable<num> iterable) num fxProductBy<A>(num Function(A a) f, Iterable<A> iterable) Future<num> fxProductAsync(FxAsyncIterable<num> iterable) Future<num> fxProductByAsync<A>(FutureOr<num> Function(A a) f, FxAsyncIterable<A> iterable) num Fx<num>.product() // chain (sync) num Fx<T>.productBy(num Function(T a) f) // chain (sync) Future<num> FxAsync<num>.product() // chain (async) Future<num> FxAsync<T>.productBy(FutureOr<num> Function(T a) f) // chain (async)

Lecture

fxProduct(xs) multiplies every number in the iterable; fxProductBy(f, xs) multiplies a numeric key of every element — map + product in one pass, the counterpart of sumBy. Both are terminal: they pull the whole input and return one num.

Empty input returns 1, the multiplicative identity, for the same reason sum of nothing is 0: it is the only value that keeps product(xs + ys) == product(xs) * product(ys) true when one side is empty. If 0 came back, splitting a batch into chunks would zero out every total that had an empty chunk.

The accumulation follows sum: while every value is an int the result is an int; the first double switches it to double seeded with the running total — exactly what a boxed num acc *= v would hold. On the chain they are fx(numbers).product() and fx(items).productBy(f), and the async twins (fxProductAsync, fxProductByAsync, and the same names on FxAsync) accept a key function that returns a Future. fxdart extension (FxTS has sum but no product).

Demo 1 · Basics, empty input & int vs double

Demo 2 · productBy and async

Try it yourself

Exercise: replace the multiplying loop with one call.

Related: sum · sumBy — the additive pair, empty is 0 · fold — any other accumulation, with your own seed · average — the next numeric aggregate