2

I am trying to map items of an iterator, N at a time. Something like this:

let a = vec![1, 2, 3, 4];
let b = a.iter().map2(|i, j| i + j);

b.collect() would then yield b = [3, 7]

Is there a simple way to achieve this?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
franc0is
  • 733
  • 9
  • 14

1 Answers1

4

Not as-stated. You need to break it down into "split vec into iterator of disjoint subsets" and "sum each subset":

let a = vec![1, 2, 3, 4];
let b = a.chunks(2).map(|chunk| chunk.iter().sum::<i32>());
println!("b = {:?}", b.collect::<Vec<_>>());

Note that this doesn't work when a is a general iterator (it relies on it being a slice), though you can get it to work using the itertools crate:

use itertools::Itertools;

let a = vec![1, 2, 3, 4];
let a = a.iter().cloned(); // we can't rely on a being a Vec any more.
let b = (&a.chunks(2)).into_iter()
    .map(|chunk| chunk.sum::<i32>())
    .collect::<Vec<_>>();
println!("b = {:?}", b);
DK.
  • 55,277
  • 5
  • 189
  • 162