//! 278. Getting the last element
//!
//! `last()` consumes the iterator to return `Option<T>` with the final element.
fn main() {
let nums = [1i32, 2, 3, 4, 5];
// Iterator's last() โ consumes entire iterator
println!("Last: {:?}", nums.iter().last());
// Slice's last() โ O(1), returns reference
println!("Slice last: {:?}", nums.last());
// Empty
let empty: Vec<i32> = vec![];
println!("Last of empty: {:?}", empty.iter().last());
// Last element after filtering
let last_even = (1..=10).filter(|x| x % 2 == 0).last();
println!("Last even in 1..10: {:?}", last_even);
// Last word in a sentence
let sentence = "the quick brown fox";
let last_word = sentence.split_whitespace().last();
println!("Last word: {:?}", last_word);
// Practical: last line of a multiline string
let text = "line1
line2
line3
line4";
let last_line = text.lines().last();
println!("Last line: {:?}", last_line);
}
#[cfg(test)]
mod tests {
#[test]
fn test_last_basic() {
let v = [1i32, 2, 3, 4, 5];
assert_eq!(v.iter().last(), Some(&5));
}
#[test]
fn test_last_empty() {
let empty: Vec<i32> = vec![];
assert_eq!(empty.iter().last(), None);
}
#[test]
fn test_last_after_filter() {
let last_even = (1i32..=10).filter(|x| x % 2 == 0).last();
assert_eq!(last_even, Some(10));
}
#[test]
fn test_last_single() {
assert_eq!([42i32].iter().last(), Some(&42));
}
}
(* 278. Getting the last element - OCaml *)
let last = function
| [] -> None
| lst -> Some (List.nth lst (List.length lst - 1))
let () =
let nums = [1; 2; 3; 4; 5] in
Printf.printf "Last: %s\n" (match last nums with Some n -> string_of_int n | None -> "None");
Printf.printf "Last of []: %s\n" (match last [] with Some _ -> "Some" | None -> "None");
let words = ["apple"; "banana"; "cherry"] in
Printf.printf "Last word: %s\n"
(match last words with Some w -> w | None -> "None");
(* Last filtered element *)
let last_even = last (List.filter (fun x -> x mod 2 = 0) nums) in
Printf.printf "Last even: %s\n"
(match last_even with Some n -> string_of_int n | None -> "None")