use std::{collections::HashMap, hash::Hash}; pub fn tally(items: &[T], key: F) -> HashMap where K: Eq + Hash, F: Fn(&T) -> K, { let mut counts = HashMap::new(); for item in items { *counts.entry(key(item)).or_insert(0) += 1; } counts } #[cfg(test)] mod test { use super::*; #[test] fn owned_key() { let words = ["apple", "avocado", "banana"]; let counts = tally(&words, |w| w.chars().next().unwrap().to_string()); assert_eq!(counts.get("a"), Some(&2), "keys: {:?}", counts); assert_eq!(counts.len(), 2, "keys: {:?}", counts); } }