std::averageable
Import with import std::averageable.
Exports
Section titled “Exports”Interfaces
interface Averageable
Section titled “interface Averageable”interface Averageable<R> fn mean(values: Iter<self>) -> Maybe<R> end
A type whose values have a mean of type R: mean(values) is the
arithmetic mean of values, or None when there are none.
Iter.mean and Iter.mean_by call it.
The impl owns the arithmetic, since a good mean depends on the type:
Int’s mean is a Float rounded once from the exact sum, Float’s sums with
compensation, and Decimal’s divides its exact sum as Decimal’s / does.
An impl reads values once, with one fold that keeps the running sum and
the count together, since an Iter may be lazy or yield its elements
only once; it never counts first and sums after.
| Type | R | Rounding |
|---|---|---|
| Int | Float | the exact sum over the count, rounded once to the nearest Float |
| Float | Float | compensated (Neumaier) sum, then one division |
| Decimal | Decimal | the exact sum divided by the count with Decimal’s / |
| Duration | Duration | the exact sum over the count, to the nearest nanosecond, ties to even |
A refinement has its base’s impl, so the mean of NonNegativeInts is
Int’s, a Float.
type Celsius Float impl Averageable<Celsius> for Celsius fn mean(values: Iter<Celsius>) -> Maybe<Celsius> values |> Iter.map(fn Celsius(c) -> c) |> Iter.mean() |> Maybe.map(Celsius) end end
assert Int.mean([1, 2]) == Some(1.5)
assert Iter.mean([1.5, 2.5]) == Some(2.0)
Averageable.mean
Section titled “Averageable.mean”fn mean(values: Iter<self>) -> Maybe<R>
interface Averageable