literator icon indicating copy to clipboard operation
literator copied to clipboard

Consider adding a lazy iterator macro

Open ftxqxd opened this issue 10 years ago • 0 comments

A while ago, I implemented a macro to generate a lazy iterator given a list of parameters (that only get evaluated when the iterator reached them):

macro_rules! iter {
    () => {
        None.into_iter();
    };
    ($e: expr) => {
        Some(move || $e).into_iter().map(|f| f())
    };
    ($e:expr, $($f: expr),*) => {
        Some(move || $e).into_iter().map(|f| f()).chain(iter!($($f),*))
    };
    ($($e: expr),*,) => {
        iter!($($e),*)
    };
}

fn main() {
    for i in iter!(1, { println!("Two"); 2 }, 3) {
        println!("{}", i);
    }
}

// Output:
// 1
// Two
// 2
// 3

I’m not sure about the code bloat/performance implications of the .chain approach (over defining an iterator type as this crate does for the current literator! macro).

ftxqxd avatar Feb 27 '15 04:02 ftxqxd