//! 259. Flattening with flat_map()
//!
//! `flat_map(f)` = `map(f).flatten()` โ the iterator monad's bind operation.
fn main() {
let words = ["hello", "world"];
let bytes: Vec<u8> = words.iter().flat_map(|w| w.bytes()).collect();
println!("Bytes count: {}", bytes.len());
let nums = [1i32, 2, 3, 4];
let expanded: Vec<i32> = nums.iter().flat_map(|&n| 0..n).collect();
println!("Expanded: {:?}", expanded);
// Filter and transform simultaneously
let strings = ["1", "two", "3", "four", "5"];
let valid: Vec<i32> = strings.iter()
.flat_map(|s| s.parse::<i32>())
.collect();
println!("Valid numbers: {:?}", valid);
// Flatten nested structure
let sentences = ["the quick brown", "fox jumps over"];
let all_words: Vec<&str> = sentences.iter()
.flat_map(|s| s.split_whitespace())
.collect();
println!("All words: {:?}", all_words);
// CSV parsing
let csv = "1,2,3
4,5,6";
let values: Vec<&str> = csv.lines().flat_map(|line| line.split(',')).collect();
println!("CSV values: {:?}", values);
}
#[cfg(test)]
mod tests {
#[test]
fn test_flat_map_expand() {
let result: Vec<i32> = [1i32, 2, 3].iter().flat_map(|&n| 0..n).collect();
assert_eq!(result, vec![0, 0, 1, 0, 1, 2]);
}
#[test]
fn test_flat_map_filter_parse() {
let strings = ["1", "x", "2", "y", "3"];
let result: Vec<i32> = strings.iter()
.flat_map(|s| s.parse::<i32>())
.collect();
assert_eq!(result, vec![1, 2, 3]);
}
#[test]
fn test_flat_map_words() {
let sentences = ["hello world", "foo bar"];
let words: Vec<&str> = sentences.iter()
.flat_map(|s| s.split_whitespace())
.collect();
assert_eq!(words.len(), 4);
}
}
(* 259. Flattening with flat_map() - OCaml *)
let () =
let words = ["hello"; "world"] in
let chars = List.concat_map (fun w ->
List.init (String.length w) (fun i -> w.[i])
) words in
List.iter (fun c -> Printf.printf "%c " c) chars;
print_newline ();
let nums = [1; 2; 3] in
let expanded = List.concat_map (fun n -> List.init n Fun.id) nums in
Printf.printf "%s\n" (String.concat ", " (List.map string_of_int expanded));
let strs = ["1"; "two"; "3"; "four"; "5"] in
let parsed = List.concat_map (fun s ->
match int_of_string_opt s with
| Some n -> [n * 2]
| None -> []
) strs in
Printf.printf "%s\n" (String.concat ", " (List.map string_of_int parsed))