typestar

Laziness, peekable and scan in Rust

Adapters do nothing until something pulls — which is what makes peeking and scanning cheap.

fn main() {
    let mut it = [1, 2, 3].iter().peekable();
    while let Some(n) = it.next() {
        if let Some(next) = it.peek() {
            println!("{n} then {next}");
        } else {
            println!("{n} is last");
        }
    }

    let running: Vec<i32> = [5, 10, 20]
        .iter()
        .scan(0, |total, n| {
            *total += n;
            Some(*total)
        })
        .collect();
    println!("{:?}", running);
}

How it works

  1. Nothing runs until a terminal method asks for values.
  2. peekable looks at the next item without consuming it.
  3. scan carries state along, emitting one value per step.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
321
Tokens
128
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 77 seconds.

Type this snippet

Step 3 of 3 in Closures & folding, step 8 of 14 in Iterators & closures.

← Previous Next →