Count How Often Each Item Appears
Fold a slice into a HashMap that maps each value to how many times it occurs, incrementing the entry on each pass.
use std::collections::HashMap;
use std::hash::Hash;
fn frequency_count<T: Copy + Eq + Hash>(items: &[T]) -> HashMap<T, usize> {
items.iter().fold(HashMap::new(), |mut acc, &item| {
*acc.entry(item).or_insert(0) += 1;
acc
})
}
Caveats
Needs T: Copy + Eq + Hash. Use Clone instead of Copy if the items are not Copy.