0

I have a vector of structs. It is called Updates, I want to reduce this vector to get the maximum wave speed by reducing over the structs. I tried to reduce using the par_iter() from rayon library. Since the input and output types of the identity (id) and operator (op) functions are different my code does not compile. Is there a way for the iterator to only see the max_wavespeed field, or do I have to return an Updates structs and that contains the reduced wave speed?

#[derive(Clone, Copy)]
pub struct Updates {
    pub h_update_left: f32,
    pub h_update_right: f32,
    pub hu_update_left: f32,
    pub hu_update_right: f32,
    pub max_wavespeed: f32,
}

...

let mut updates: Vec<Updates> = vec![Updates::new(); outer * inner];

...

//get max wavespeed
let id = || -> f32 { 0.0f32 };
let op = |upd1: Updates, upd2: Updates| -> f32 {
   f32::max(upd1.max_wavespeed, upd2.max_wavespeed)
};
let max_wavespeed: f32 = updates.par_iter().cloned().reduce(id, op);

The error I have with this code:

error[E0308]: mismatched types
  --> src/block.rs:95:34
   |
95 |         let max_wavespeed: f32 = updates.par_iter().cloned().reduce(id, op);
   |                            ---   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `f32`, found struct `Updates`
   |                            |
   |                            expected due to this

What I want: to know if I can iterate over a member of the Updates struct, or do I have to return an Upates struct.

Cherry Toska
  • 131
  • 8
  • can you explain without math ? – Stargateur Apr 11 '21 at 22:37
  • I want to iterate over my vector of structs, but in this loop, I only need access to one member, the field that is named "max_wavespeed". Is there a way to make an iterator such that it does not see the whole struct "Updates" but only the f32 member "max_wavespeed" (so that I can also return an f32). – Cherry Toska Apr 11 '21 at 22:42
  • 3
    `.map(|updates| updates.max_wavespeed)` add this to where you want to get rid of updates in your iterator – Stargateur Apr 11 '21 at 23:00
  • I will update this as an answer – Cherry Toska Apr 11 '21 at 23:29

1 Answers1

2
 let id = || -> f32 { 0.0f32 };
 let op = |upd1: f32, upd2: f32| -> f32 { f32::max(upd1, upd2) };       

 let max_wavespeed_x: f32 = updates
            .par_iter()
            .cloned()
            .map(|updates| updates.max_wavespeed)
            .reduce(id, op);

This code results with the desired behaviour.

Cherry Toska
  • 131
  • 8