๐Ÿฆ€ Functional Rust
๐ŸŽฌ How Rust Iterators Work Lazy evaluation, chaining, collect(), and zero-cost abstractions.
๐Ÿ“ Text version (for readers / accessibility)

โ€ข Iterators are lazy โ€” .map(), .filter(), .take() build a chain but do no work until consumed

โ€ข .collect() triggers evaluation, transforming the chain into a Vec, HashMap, or other collection

โ€ข Zero-cost abstraction: iterator chains compile to the same machine code as hand-written loops

โ€ข .iter() borrows, .into_iter() consumes, .iter_mut() borrows mutably

โ€ข Chaining replaces nested loops with a readable, composable pipeline

092: Scan Accumulate

Difficulty: Intermediate Category: Iterators Concept: Scan with accumulator for running totals Key Insight: Scan is fold that emits every intermediate state โ€” useful for running sums, products, or state machines
// 092: Scan with Accumulator

fn running_sum(v: &[i32]) -> Vec<i32> {
    let mut result = vec![0];
    result.extend(v.iter().scan(0, |acc, &x| { *acc += x; Some(*acc) }));
    result
}

fn running_max(v: &[i32]) -> Vec<i32> {
    if v.is_empty() { return vec![]; }
    let mut max_val = v[0];
    let mut result = vec![max_val];
    for &x in &v[1..] {
        max_val = max_val.max(x);
        result.push(max_val);
    }
    result
}

fn main() {
    println!("running_sum: {:?}", running_sum(&[1, 2, 3, 4]));
    println!("running_max: {:?}", running_max(&[3, 1, 4, 1, 5]));
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_running_sum() {
        assert_eq!(running_sum(&[1, 2, 3, 4]), vec![0, 1, 3, 6, 10]);
    }

    #[test]
    fn test_running_max() {
        assert_eq!(running_max(&[3, 1, 4, 1, 5]), vec![3, 3, 4, 4, 5]);
    }
}
(* 092: Scan with Accumulator *)

let scan_left f init lst =
  let _, result =
    List.fold_left (fun (acc, res) x ->
      let next = f acc x in (next, next :: res)
    ) (init, [init]) lst
  in
  List.rev result

let running_sum lst = scan_left ( + ) 0 lst
let running_max lst =
  match lst with
  | [] -> []
  | x :: xs -> scan_left max x xs

(* Tests *)
let () =
  assert (running_sum [1; 2; 3; 4] = [0; 1; 3; 6; 10]);
  assert (running_max [3; 1; 4; 1; 5] = [3; 3; 4; 4; 5]);
  Printf.printf "โœ“ All tests passed\n"

๐Ÿ“Š Detailed Comparison

Core Insight

Scan is fold that emits every intermediate state โ€” useful for running sums, products, or state machines

OCaml Approach

  • See example.ml for implementation

Rust Approach

  • See example.rs for implementation

Comparison Table

FeatureOCamlRust
Seeexample.mlexample.rs