//! 265. Conditional skipping with skip_while()
//!
//! `skip_while(pred)` discards elements until predicate first returns false, then yields all remaining.
fn main() {
let nums = [1i32, 2, 3, 4, 5, 4, 3, 2, 1];
let from_4: Vec<i32> = nums.iter().copied().skip_while(|&x| x < 4).collect();
println!("Skip <4: {:?}", from_4);
// Note: [4,5,4,3,2,1] โ trailing 3,2,1 are included
let input = " hello world";
let stripped: String = input.chars().skip_while(|c| c.is_whitespace()).collect();
println!("Stripped: '{}'", stripped);
let with_zeros = [0i32, 0, 0, 1, 2, 3, 0, 4];
let no_leading: Vec<i32> = with_zeros.iter().copied()
.skip_while(|&x| x == 0).collect();
println!("No leading zeros: {:?}", no_leading);
// The 0 at position 6 is kept
// Combine skip_while + take_while for range extraction
let range: Vec<i32> = nums.iter().copied()
.skip_while(|&x| x < 3)
.take_while(|&x| x < 6)
.collect();
println!("Elements in [3,6): {:?}", range);
}
#[cfg(test)]
mod tests {
#[test]
fn test_skip_while_basic() {
let result: Vec<i32> = [1, 2, 3, 4, 5].iter().copied()
.skip_while(|&x| x < 3).collect();
assert_eq!(result, vec![3, 4, 5]);
}
#[test]
fn test_skip_while_includes_later_matches() {
let result: Vec<i32> = [0i32, 0, 1, 0].iter().copied()
.skip_while(|&x| x == 0).collect();
assert_eq!(result, vec![1, 0]);
}
#[test]
fn test_skip_while_all() {
let result: Vec<i32> = [1, 2, 3].iter().copied()
.skip_while(|&x| x < 10).collect();
assert!(result.is_empty());
}
#[test]
fn test_skip_while_none() {
let result: Vec<i32> = [1, 2, 3].iter().copied()
.skip_while(|&x| x > 10).collect();
assert_eq!(result, vec![1, 2, 3]);
}
}
(* 265. Conditional skipping with skip_while() - OCaml *)
let rec skip_while pred = function
| [] -> []
| x :: xs as lst ->
if pred x then skip_while pred xs else lst
let () =
let nums = [1; 2; 3; 4; 5; 4; 3; 2; 1] in
let from_4 = skip_while (fun x -> x < 4) nums in
Printf.printf "Skip <4: %s\n"
(String.concat ", " (List.map string_of_int from_4));
let tokens = [' '; ' '; 'h'; 'e'; 'l'; 'l'; 'o'] in
let stripped = skip_while (fun c -> c = ' ') tokens in
Printf.printf "Stripped: '%s'\n"
(String.concat "" (List.map (String.make 1) stripped));
let with_zeros = [0; 0; 0; 1; 2; 3; 0; 4] in
let no_leading = skip_while (fun x -> x = 0) with_zeros in
Printf.printf "No leading zeros: %s\n"
(String.concat ", " (List.map string_of_int no_leading))