Created
August 31, 2021 12:07
-
-
Save blankhart/83c65e6db1422e747479b0c6cca3be4d to your computer and use it in GitHub Desktop.
Abstracting over iterators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(box_syntax)] | |
fn go(outer: impl Iterator<Item = impl Iterator<Item = usize>>) { | |
print!("[ "); | |
for inner in outer { | |
print!("["); | |
for x in inner { | |
print!(" {} ", x) | |
} | |
print!("]"); | |
} | |
print!(" ]\n"); | |
} | |
fn main() { | |
let grid = vec![vec![1, 2, 3], vec![4, 5]]; | |
// Unrolling works | |
go(grid.iter().map(|v| v.iter().cloned())); | |
go(grid.iter().map(|v| v.iter().cloned().rev())); | |
go(grid.iter().rev().map(|v| v.iter().cloned())); | |
go(grid.iter().rev().map(|v| v.iter().cloned().rev())); | |
// Abstracting works like this | |
type It<'a, T> = Box<dyn Iterator<Item = Box<dyn Iterator<Item = T> + 'a>> + 'a>; | |
let its: [It<usize>; 4] = [ | |
box grid.iter().map(|v| box v.iter().cloned() as Box<dyn Iterator<Item = usize> + '_>), | |
box grid.iter().map(|v| box v.iter().cloned().rev() as Box<dyn Iterator<Item = usize> + '_>), | |
box grid.iter().rev().map(|v| box v.iter().cloned() as Box<dyn Iterator<Item = usize> + '_>), | |
box grid.iter().rev().map(|v| box v.iter().cloned().rev() as Box<dyn Iterator<Item = usize> + '_>), | |
]; | |
for it in its { | |
go(it); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment