//! 256. Chaining iterators with chain()
//!
//! `chain()` concatenates two iterators lazily โ no allocation, just composition.
fn main() {
let first = [1, 2, 3];
let second = [4, 5, 6];
let chained: Vec<i32> = first.iter().chain(second.iter()).copied().collect();
println!("Chained: {:?}", chained);
let greetings = vec!["hello", "hi", "hey"];
let farewells = vec!["bye", "goodbye", "ciao"];
let all: Vec<_> = greetings.iter().chain(farewells.iter()).collect();
println!("All words: {:?}", all);
let evens = (0..10i32).filter(|x| x % 2 == 0);
let odds = (0..10i32).filter(|x| x % 2 != 0);
let combined: Vec<i32> = evens.chain(odds).collect();
println!("Evens then odds: {:?}", combined);
// Chain three iterators
let a = vec![1i32];
let b = vec![2i32];
let c = vec![3i32];
let abc: Vec<i32> = a.into_iter().chain(b).chain(c).collect();
println!("Three-way chain: {:?}", abc);
}
#[cfg(test)]
mod tests {
#[test]
fn test_chain_basic() {
let a = [1i32, 2, 3];
let b = [4i32, 5, 6];
let result: Vec<i32> = a.iter().chain(b.iter()).copied().collect();
assert_eq!(result, vec![1, 2, 3, 4, 5, 6]);
}
#[test]
fn test_chain_empty() {
let a: Vec<i32> = vec![];
let b = vec![1, 2];
let result: Vec<i32> = a.iter().chain(b.iter()).copied().collect();
assert_eq!(result, vec![1, 2]);
}
#[test]
fn test_chain_count() {
let a = [1i32, 2, 3];
let b = [4i32, 5];
assert_eq!(a.iter().chain(b.iter()).count(), 5);
}
}
(* 256. Chaining iterators with chain() - OCaml *)
(* OCaml uses @ or List.append to concatenate lists eagerly *)
let () =
let first = [1; 2; 3] in
let second = [4; 5; 6] in
(* @ operator is syntactic sugar for List.append -- allocates a new list *)
let chained = first @ second in
List.iter (fun x -> Printf.printf "%d " x) chained;
print_newline ();
let words_a = ["hello"; "world"] in
let words_b = ["foo"; "bar"] in
let all_words = List.append words_a words_b in
List.iter (fun w -> Printf.printf "%s " w) all_words;
print_newline ();
(* Simulating lazy chaining with Seq module *)
let seq1 = List.to_seq [10; 20; 30] in
let seq2 = List.to_seq [40; 50; 60] in
let chained_seq = Seq.append seq1 seq2 in
Seq.iter (fun x -> Printf.printf "%d " x) chained_seq;
print_newline ()