1

I am trying to take the maximum value from an array of f32:

let v: [f32; 5] = [1.0, 2.0, 3.0, 4.0, 5.0];    
let res = v.iter().max().unwrap();

But the trait Ord is not implemented for f32 and I can't implement it because

only traits defined in the current crate can be implemented for arbitrary types [E0117]

I know about PartialOrd, but I cannot figure out how to use it in this situation.

I am sure that my collection is not empty and it does not contain NaN or infinity.

Is there any way to take max value from a f32 collection except by writing own wrappers or an imperative function like this?

fn maxf32(arr: &[f32; 5]) -> f32 {
    let mut res = arr[0];
    for &x in arr {
        if x > res {
            res = x;
        }
    }
    res
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Daiver
  • 1,488
  • 3
  • 18
  • 47
  • 1
    Also of interest is this [Reddit discussion](https://www.reddit.com/r/rust/comments/3fg0xr/how_do_i_find_the_max_value_in_a_vecf64/) – Shepmaster Sep 18 '15 at 13:23
  • @Shepmaster solution from this post works for me but looks a little ugly =( Should i delete my question? – Daiver Sep 18 '15 at 13:36
  • @Shepmaster One additional question - what about performance of our solution? – Daiver Sep 18 '15 at 13:42
  • I wouldn't expect either solution to be drastically different from the other, performance-wise. – Shepmaster Sep 18 '15 at 13:44
  • I just take NonNan struct from http://stackoverflow.com/a/28248065/1349525 add function val to unwrap float value and call it this way: v2.iter().map(|&x| NonNan::new(x).unwrap()).max().unwrap().val() – Daiver Sep 18 '15 at 13:46
  • 1
    itertools' `fold1` can help, but it's a bit method-noisy too: `.iter().cloned().fold1(f32::max).unwrap()` – bluss Sep 19 '15 at 19:04
  • 1
    @bluss looks nice but my compiler (rustc 1.2.0) cannot find fold1 for iterator. But v2.iter().cloned().fold(v2[0], f32::max) works for me. If you want i can try to reopen question. – Daiver Sep 20 '15 at 06:07
  • Right, it's not in std but in itertools, a separate crate. – bluss Sep 20 '15 at 11:11
  • @bluss I miss this. Everything seems to work. Thank you! – Daiver Sep 20 '15 at 13:21

0 Answers0