//! 270. Finding index with position()
//!
//! `position(pred)` returns `Option<usize>` โ index of first element where predicate holds.
fn main() {
let nums = [10i32, 20, 30, 40, 50];
let idx = nums.iter().position(|&x| x > 25);
println!("First >25 at index: {:?}", idx);
let words = ["apple", "banana", "cherry", "date"];
match words.iter().position(|&w| w == "cherry") {
Some(i) => println!("'cherry' at index {}", i),
None => println!("Not found"),
}
if let Some(split) = nums.iter().position(|&x| x == 30) {
println!("Before 30: {:?}", &nums[..split]);
println!("After 30: {:?}", &nums[split+1..]);
}
let data = [1i32, 2, 3, 2, 1];
let first = data.iter().position(|&x| x == 2);
let last = data.iter().rposition(|&x| x == 2);
println!("First 2: {:?}, Last 2: {:?}", first, last);
let message = nums.iter()
.position(|&x| x >= 35)
.map(|i| format!("Found {} at index {}", nums[i], i))
.unwrap_or_else(|| "Nothing >= 35".to_string());
println!("{}", message);
}
#[cfg(test)]
mod tests {
#[test]
fn test_position_found() {
let v = [10i32, 20, 30, 40];
assert_eq!(v.iter().position(|&x| x == 30), Some(2));
}
#[test]
fn test_position_not_found() {
let v = [1i32, 2, 3];
assert_eq!(v.iter().position(|&x| x == 99), None);
}
#[test]
fn test_rposition() {
let v = [1i32, 2, 3, 2, 1];
assert_eq!(v.iter().rposition(|&x| x == 2), Some(3));
}
#[test]
fn test_position_first_occurrence() {
let v = [5i32, 5, 5];
assert_eq!(v.iter().position(|&x| x == 5), Some(0));
}
}
(* 270. Finding index with position() - OCaml *)
let position pred lst =
let rec aux i = function
| [] -> None
| x :: xs -> if pred x then Some i else aux (i + 1) xs
in
aux 0 lst
let () =
let nums = [10; 20; 30; 40; 50] in
(match position (fun x -> x > 25) nums with
| Some i -> Printf.printf "First >25 at index %d\n" i
| None -> print_endline "Not found");
let words = ["apple"; "banana"; "cherry"] in
(match position (fun w -> w = "banana") words with
| Some i -> Printf.printf "banana at index %d\n" i
| None -> print_endline "Not found");
(match position (fun x -> x = 30) nums with
| Some i ->
let before = List.filteri (fun j _ -> j < i) nums in
Printf.printf "Before 30: %s\n"
(String.concat ", " (List.map string_of_int before))
| None -> print_endline "30 not found")