๐Ÿฆ€ Functional Rust

100: Step By

Difficulty: Beginner Category: Iterators Concept: Step through ranges: `(0..100).step_by(5)` Key Insight: step_by skips elements at regular intervals โ€” useful for sampling, pagination, and grid traversal
// 100: Step By

fn main() {
    let v: Vec<i32> = (0..10).step_by(2).collect();
    println!("step_by(2): {:?}", v);

    let v: Vec<i32> = (0..100).step_by(25).collect();
    println!("step_by(25): {:?}", v);
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_step_by() {
        let v: Vec<i32> = (0..10).step_by(2).collect();
        assert_eq!(v, vec![0, 2, 4, 6, 8]);
    }

    #[test]
    fn test_step_by_25() {
        let v: Vec<i32> = (0..100).step_by(25).collect();
        assert_eq!(v, vec![0, 25, 50, 75]);
    }

    #[test]
    fn test_step_by_5() {
        let v: Vec<i32> = (0..20).step_by(5).collect();
        assert_eq!(v, vec![0, 5, 10, 15]);
    }

    #[test]
    fn test_step_by_1() {
        let v: Vec<i32> = (0..3).step_by(1).collect();
        assert_eq!(v, vec![0, 1, 2]);
    }
}
(* 100: Step By *)

let step_by start stop step =
  let rec aux acc n =
    if n >= stop then List.rev acc
    else aux (n :: acc) (n + step)
  in
  aux [] start

let range_step start stop step =
  Seq.unfold (fun n -> if n >= stop then None else Some (n, n + step)) start

(* Tests *)
let () =
  assert (step_by 0 10 2 = [0; 2; 4; 6; 8]);
  assert (step_by 0 100 25 = [0; 25; 50; 75]);
  assert (List.of_seq (range_step 0 20 5) = [0; 5; 10; 15]);
  Printf.printf "โœ“ All tests passed\n"

๐Ÿ“Š Detailed Comparison

Core Insight

step_by skips elements at regular intervals โ€” useful for sampling, pagination, and grid traversal

OCaml Approach

  • See example.ml for implementation

Rust Approach

  • See example.rs for implementation

Comparison Table

FeatureOCamlRust
Seeexample.mlexample.rs