Skip to content

std::averageable

Import with import std::averageable.

Interfaces

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.

TypeRRounding
IntFloatthe exact sum over the count, rounded once to the nearest Float
FloatFloatcompensated (Neumaier) sum, then one division
DecimalDecimalthe exact sum divided by the count with Decimal’s /
DurationDurationthe 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)
fn mean(values: Iter<self>) -> Maybe<R>

interface Averageable