[−][src]Macro iter_python::iter
Write the most pervasive iterator adapters (filtering and mapping) as Python generator expressions.
Examples
Squaring even numbers
ⓘThis code runs with edition 2018
let mut all_evens_squared = iter!( x * x for x in (0 ..) if x % 2 == 0 ); assert_eq!(all_evens_squared.next(), Some(0)); assert_eq!(all_evens_squared.next(), Some(4)); assert_eq!(all_evens_squared.next(), Some(16));
filter
ing is optional, such as in Python:
ⓘThis code runs with edition 2018
let mut numbers_binary = iter!(format!("{:02b}", x) for x in 1 ..= 3); assert_eq!(numbers_binary.next(), Some("01".into())); assert_eq!(numbers_binary.next(), Some("10".into())); assert_eq!(numbers_binary.next(), Some("11".into())); assert_eq!(numbers_binary.next(), None);
You may also filter
with if let
:
ⓘThis code runs with edition 2018
let strings = ["42", "0", "zero", "27"]; let parsed_as_i32s = iter!(s.parse::<i32>() for &s in &strings); let total: i32 = Iterator::sum(iter!( x for res in parsed_as_i32s if let Ok(x) = res )); assert_eq!(total, 42 + 0 + 27);
ⓘThis code runs with edition 2018
enum Fruit { Banana, Peach, RottenApple } use Fruit::*; impl Fruit { fn is_fresh (&self) -> bool { if let RottenApple = self { false } else { true } } } static BASKET: &[Fruit] = &[Banana, RottenApple, Peach, Banana]; let no_rotten_apple = iter!( fruit for fruit in BASKET if let Banana | Peach = fruit ); assert!({no_rotten_apple}.all(Fruit::is_fresh));