1
\$\begingroup\$

I'm trying to write a generic mean function for all values within an Vector of generic numerical primitive type.

Could the following implementation be possible more efficient, yet still generic enough for all the possible numerical primitives?

Is the num crate really needed?

extern crate num;
use std::iter::Sum;
use std::ops::Div;

fn mean<'a, T, U>(values: &'a [T]) -> U::Output
    where T: Sum<&'a T> + num::ToPrimitive,
          U: num::NumCast + Div
{
    U::from(values.iter().sum::<T>()).unwrap() / U::from(values.len()).unwrap()
}

fn main() {
    let arr_i32: Vec<i32> = vec![1, 2, 5];
    let arr_f32: Vec<f32> = vec![1.1, 2.2, 5.5];
    println!("Mean of ({:?}) is: {}", arr_i32, mean::<_, f32>(&arr_i32));
    println!("Mean of ({:?}) is: {}", arr_f32, mean::<_, f32>(&arr_f32));
}
\$\endgroup\$
  • \$\begingroup\$ Why do you think this is not efficient ? \$\endgroup\$ – Stargateur Apr 14 at 21:35
  • \$\begingroup\$ I didn't say I think that, I was just asking, if this code could be written more efficiently. For example, I think that the wrapping U into Option<U> and then calling theunwrap() method is unnecessary, because iter::sum has always a value and &[].len() has it too. \$\endgroup\$ – jirislav Apr 15 at 10:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.