//! 257. Pairing elements with zip()
//!
//! `zip()` pairs elements from two iterators, stopping at the shorter one.
fn main() {
let names = ["Alice", "Bob", "Carol"];
let scores = [95u32, 87, 92];
for (name, score) in names.iter().zip(scores.iter()) {
println!("{}: {}", name, score);
}
let keys = vec!["a".to_string(), "b".to_string(), "c".to_string()];
let values = vec![1i32, 2, 3];
let map: std::collections::HashMap<String, i32> =
keys.into_iter().zip(values).collect();
println!("Map: {:?}", map);
// zip truncates at shorter
let long = [1i32, 2, 3, 4, 5];
let short = ["x", "y"];
let truncated: Vec<_> = long.iter().zip(short.iter()).collect();
println!("Truncated zip length: {}", truncated.len());
let xs = 0i32..4;
let ys = (0i32..4).map(|y| y * y);
let coords: Vec<(i32, i32)> = xs.zip(ys).collect();
println!("Coordinates: {:?}", coords);
let (left, right): (Vec<i32>, Vec<i32>) = vec![(1,10),(2,20),(3,30)]
.into_iter().unzip();
println!("Left: {:?}, Right: {:?}", left, right);
}
#[cfg(test)]
mod tests {
#[test]
fn test_zip_basic() {
let a = [1i32, 2, 3];
let b = ["x", "y", "z"];
let result: Vec<_> = a.iter().zip(b.iter()).collect();
assert_eq!(result.len(), 3);
assert_eq!(result[0], (&1, &"x"));
}
#[test]
fn test_zip_truncates() {
let a = [1i32, 2, 3, 4, 5];
let b = [10i32, 20];
let result: Vec<_> = a.iter().zip(b.iter()).collect();
assert_eq!(result.len(), 2);
}
#[test]
fn test_zip_into_hashmap() {
let keys = vec!["a", "b"];
let vals = vec![1i32, 2];
let map: std::collections::HashMap<_, _> = keys.into_iter().zip(vals).collect();
assert_eq!(map["a"], 1);
assert_eq!(map["b"], 2);
}
}
(* 257. Pairing elements with zip() - OCaml *)
let () =
let names = ["Alice"; "Bob"; "Carol"] in
let scores = [95; 87; 92] in
let paired = List.combine names scores in
List.iter (fun (name, score) ->
Printf.printf "%s: %d\n" name score
) paired;
let (ns, ss) = List.split paired in
Printf.printf "Names: %s\n" (String.concat ", " ns);
Printf.printf "Scores: %s\n" (String.concat ", " (List.map string_of_int ss));
let indexed = List.mapi (fun i x -> (i, x)) ["a"; "b"; "c"] in
List.iter (fun (i, x) -> Printf.printf "%d: %s\n" i x) indexed