I have implemented the following function that calculates the mean of a sequence:
fn mean<T, R>(seq: &[T]) -> R
where R: Div<R, Output=R> + From<T> + From<usize> + Sum<R>
{
let total: R = seq.iter().map(|&x| R::from(x)).sum()
let size = R::from(seq.len())
total / size
}
However, I'm having trouble when converting the usize that is returned from seq.len()
let numbers = vec![10, 20, 30, 40, 50, 60];
let result: f32 = mean(&numbers);
println!("{:?}", result);
5 | fn mean<T, R>(seq: &[T]) -> R
| ----
6 | where R: Div<R, Output=R> + From<T> + From<usize> + Sum<R>
| ----------- required by this bound in `mean`
...
15 | let result: f32 = mean(&numbers);
| ^^^^ the trait `std::convert::From<usize>` is not implemented for `f32`
I'm quite blocked by this since I'm still a beginner with traits. How can I solve this specific problem? (if it can be done)