Why does the `iterator::Sum` exist (Compare to just call `Add::add` repetitively)?

I just discovered that the trait iterator::Sum exists. Why does the iterator::sum() function requires that trait? I would personally just used Add<Iterator::Item> over the elements. I think I'm missing something.

If you're trying to sum up an iterator of hundreds of u8, you may not want to store its summation within u8 type.

I guess it has to do with Add not defining the neutral element for the addition, so Sum captures that information too.

It is true that if we had:

trait Monoid : Add<Self, Output = Self> {
    const ZERO: Self;
}

then we could write:

impl<T : Monoid> Sum for T {
    fn sum<I : Iterator<Item = Self>> (iter: I)
      -> Self
    {
        iter.fold(Self::ZERO, Self::add)
    }
}
2 Likes

True, Sum allows a different output type; so the actual trait constrait would be something like:

trait MonoidProject<T = Self>
where
    T : Add<Self, Output = T>,
{
    const ZERO: T;
}
1 Like

I really feels that a few numerical trait are missing in std. It's not the first time that I would have like a Monoid trait, as well as VecN (to be able to express a 1D, 2D, 3D, … point) from one library to another.

That's right. We would need specialization to have the Sum type automatically created for T from Add<T> and Monoid<T>, while still allowing a specialization that uses another output type.

In fact, the stdlib had descent amount of math traits in it before v1.0 freeze. But we though the interface needs more polishing and breaking changes, which is not possible after the 1.0 api freeze. So we split it into its own crate called num-traits.

1 Like

Then why is half of the world re-creating them? There is a huge ecosystem split (for example many crates are generics over f32/f64, but don't use num_traits::float::Float).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.