use std::collections::HashMap; pub type WordCounts = HashMap; pub fn count(counts: &mut WordCounts, word: String) { add(counts, word, 1); } pub fn add_counts(counts: &mut WordCounts, other: &WordCounts) { for (word, count) in other.iter() { add(counts, word.to_string(), *count); } } pub fn add(counts: &mut WordCounts, word: String, count: u32) { let counter = counts.entry(word).or_insert(0); *counter += count; } pub fn print(counts: &WordCounts, max: usize) { let mut top = Vec::new(); for (word, count) in counts.iter() { top.push((count, word)); if top.len() > max { top.sort(); top.reverse(); top.truncate(max); } } for (count, word) in top.iter() { println!("{} {}", count, word); } }