๐Ÿฆ€ 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

096: Exact Size

Difficulty: Intermediate Category: Iterators Concept: `ExactSizeIterator` with `len()` Key Insight: ExactSizeIterator knows its length upfront โ€” enables optimized allocation and bounds checking
// 096: Exact Size Iterator

fn main() {
    let v = vec![1, 2, 3, 4, 5];

    // ExactSizeIterator provides len()
    let iter = v.iter();
    println!("len: {}", iter.len());

    // Vec, Range, and slice iterators are ExactSize
    let range = 0..10;
    println!("range len: {}", range.len());

    // chunks_exact: only full chunks
    let chunks: Vec<&[i32]> = v.chunks_exact(2).collect();
    println!("chunks_exact(2): {:?}", chunks);
    println!("remainder: {:?}", v.chunks_exact(2).remainder());
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_exact_size() {
        let v = vec![1, 2, 3, 4, 5];
        assert_eq!(v.iter().len(), 5);
        assert_eq!((0..10).len(), 10);
    }

    #[test]
    fn test_enumerate_len() {
        let v = vec!["a", "b", "c"];
        let e: Vec<_> = v.iter().enumerate().collect();
        assert_eq!(e, vec![(0, &"a"), (1, &"b"), (2, &"c")]);
    }

    #[test]
    fn test_chunks_exact() {
        let v = vec![1, 2, 3, 4, 5];
        let c: Vec<&[i32]> = v.chunks_exact(2).collect();
        assert_eq!(c, vec![&[1,2][..], &[3,4][..]]);
        assert_eq!(v.chunks_exact(2).remainder(), &[5]);
    }
}
(* 096: Exact Size *)
(* OCaml: List.length is O(n), Array.length is O(1) *)

let array_len arr = Array.length arr  (* O(1) *)
let list_len lst = List.length lst    (* O(n) *)

(* Sized iteration *)
let enumerate lst =
  List.mapi (fun i x -> (i, x)) lst

let chunks_exact n lst =
  let len = List.length lst in
  let full = len / n in
  let rec aux acc i = function
    | _ when i >= full -> List.rev acc
    | lst ->
      let chunk = List.filteri (fun j _ -> j < n) lst in
      let rest = List.filteri (fun j _ -> j >= n) lst in
      aux (chunk :: acc) (i + 1) rest
  in
  aux [] 0 lst

(* Tests *)
let () =
  assert (array_len [|1;2;3|] = 3);
  assert (enumerate ["a";"b";"c"] = [(0,"a"); (1,"b"); (2,"c")]);
  assert (chunks_exact 2 [1;2;3;4;5] = [[1;2]; [3;4]]);
  Printf.printf "โœ“ All tests passed\n"

๐Ÿ“Š Detailed Comparison

Core Insight

ExactSizeIterator knows its length upfront โ€” enables optimized allocation and bounds checking

OCaml Approach

  • See example.ml for implementation

Rust Approach

  • See example.rs for implementation

Comparison Table

FeatureOCamlRust
Seeexample.mlexample.rs