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?
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?
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);