use std::collections::HashMap; use std::ops::Index; use std::hash::Hash; #[derive(Debug)] pub struct Counter { values: HashMap } impl Counter { pub fn new() -> Self { Self { values: HashMap::new() } } pub fn of>(collection: C) -> Counter { let mut counter = Counter::new(); counter.add(collection); counter } pub fn add>(&mut self, collection: C) { for x in collection { self.values.insert(x.clone(), self.values.get(&x).unwrap_or(&0) + 1); } } } impl Index for Counter { type Output = usize; fn index(&self, idx: T) -> &usize { self.values.get(&idx).unwrap_or(&0) } }