I want to define a function to calculate the median of a vector that contains either f32 or u32 values, or possibly all numeric types. f32 and u32 are my current use cases.
I don't think I understand generics or traits sufficiently. The best I could do is below, where I specify that the generic type parameter T needs to implement some traits to allow mathematical operations. If possible I would also like to cast the return type to be f32 rather than T.
fn median<T: Add<Output = T> + From<f32> + Div<Output = T>>(array: &Vec<T>) -> T {
if (array.len() % 2) == 0 {
let ind_left = array.len() / 2 - 1;
let ind_right = array.len() / 2;
(array[ind_left] + array[ind_right]) / 2.0
} else {
array[(array.len() / 2)]
}
}
But this has a problem on line 5:
mismatched types
expected type parameter `T`
found type `{float}`rustcE0308
I could use map to convert the vector of one type to the other, but that feels like unnecessary work.