Similar to this question: How do I interleave two Rust vectors by chunks of threes into a new vector?
Instead, I'd like to perform the opposite behavior. Separate an iterator into two different iterators without having to collect their contents (a.k.a. I do not want to use unzip).
Furthermore, I want to separate an iterator without collecting the entire contents of the original iterator.
Here is an semi-example:
#[derive(Debug)]
struct Foo(i32);
fn main() {
// note array elements of Foo cannot be copied or cloned
// v1: [0, 1, 2, 3]
// v2: [4, 5, 6, 7]
let v1 = (0..4).map(|num| Foo(num)).collect::<Vec<_>>();
let v2 = (4..8).map(|num| Foo(num)).collect::<Vec<_>>();
// generate interleaved iterator
// interleaved: [0, 1, 4, 5, 2, 3, 6, 7]
let interleaved = v1.chunks(2)
.zip(v2.chunks(2))
.flat_map(|(c1, c2)| c1.iter().chain(c2));
println!("interleaved: {:?}", interleaved.collect::<Vec<_>>());
// regenerate interleaved iterator
let interleaved = v1.chunks(2)
.zip(v2.chunks(2))
.flat_map(|(c1, c2)| c1.iter().chain(c2));
let mut v3: Vec<&Foo> = vec![];
let mut v4: Vec<&Foo> = vec![];
for (idx, item) in interleaved.enumerate() {
if idx % 4 < 2 {
v3.push(item);
} else {
v4.push(item);
}
}
println!("v3: {:?}, v4: {:?}", v3, v4);
}
I'd like to find an idiomatic solution to un-interleave the iterator, without having to collect their references into a container.
More generally, I'd like to figure out how to reduce an iterator of n
elements down to m
elements where n >= m
. In this case, I would want to reduce my interleaved iterator of length 8 down to an iterator with chunks of 2 of length 4. Then the chunked iterator would be separated into two other iterators.
In that sense, I want to "parse" my iterator into chunks of 2.