Rust learning: lessons, notes, and exercise crates
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
use std::{collections::HashMap, hash::Hash};
|
||||
|
||||
pub fn tally<T, K, F>(items: &[T], key: F) -> HashMap<K, usize>
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user