[][src]Macro iter_python::iter

macro_rules! iter {
    (
        $mapped_expr:expr ,
        for $var:pat in $iterable:expr ,
        if $cond:expr $(,)?
    ) => { ... };
    (
        $mapped_expr:expr ,
        for $var:pat in $iterable:expr ,
        if let $( $pat:pat )|+ = $value:expr $(,)?
    ) => { ... };
    (
        $mapped_expr:expr ,
        for $var:pat in $iterable:expr $(,)?
    ) => { ... };
    (@parsing_mapped_expr
        $mapped_expression:tt
        for
        $($rest:tt)*
    ) => { ... };
    (@parsing_mapped_expr
        [ $($mapped_expression_tts:tt)* ]
        $current_tt:tt
        $($rest:tt)*
    ) => { ... };
    (@parsing_for
        [ $($mapped_expression_tts:tt)* ]
        [ $($for_body_tts:tt)* ]
    ) => { ... };
    (@parsing_for
        [ $($mapped_expression_tts:tt)* ]
        [ $($for_body_tts:tt)* ]
        if
        $($rest:tt)*
    ) => { ... };
    (@parsing_for
        $mapped_expression:tt
        [ $($for_body_tts:tt)* ]
        $current_tt:tt
        $($rest:tt)*
    ) => { ... };
    (
        $($tt:tt)*
    ) => { ... };
}

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

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