In writing my own generic sigma summation function to get practice with Rust, I've hit an issue with providing a seed value of zero as the accumulator.
fn sigma<I, T, F>(iter: I, func: F) -> T
where I: Iterator<Item=T>,
T: Add<Output=T>,
F: Fn(T) -> T
{
iter.fold(0, |acc, x| acc + func(x))
}
I understand that it's wrong, as 0 is a concrete type, and thus not T
. Other answers (like this and this one) rely on constructs like Int::zero
, which are deprecated as of 1.11.
There are other ways of doing this, but I am particularly interested in how it should be done, as testing for one, zero, or negativity is a common operation in numeric procedures that I'll hit again soon enough. Plus, now I'm curious.
My Rust version is 1.16.