Skip to content

Instantly share code, notes, and snippets.

@mattyhall
Created July 13, 2018 16:32
Show Gist options
  • Save mattyhall/9de1919dbdbd96dba0c76f5829357329 to your computer and use it in GitHub Desktop.
Save mattyhall/9de1919dbdbd96dba0c76f5829357329 to your computer and use it in GitHub Desktop.
A Rust version of Python's counter
use std::cmp::Eq;
use std::collections::HashMap;
use std::hash::Hash;
#[derive(Debug)]
struct Counter<V>
where
V: Eq + Hash,
{
map: HashMap<V, i32>,
}
impl<V> Counter<V>
where
V: Eq + Hash,
{
fn new<T: Iterator<Item = V>>(iter: T) -> Counter<V> {
let mut hm = HashMap::new();
for v in iter {
let counter = hm.entry(v).or_insert(0);
*counter += 1;
}
Counter { map: hm }
}
}
impl<T: Hash + Eq> std::ops::Deref for Counter<T> {
type Target = HashMap<T, i32>;
fn deref(&self) -> &Self::Target {
&self.map
}
}
impl<T: Hash + Eq> std::iter::FromIterator<T> for Counter<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
Counter::new(iter.into_iter())
}
}
fn main() {
let c: Counter<_> = "hello world".chars().collect();
println!("{:?}", Counter::new("hello world".chars()));
println!(
"{:?}",
Counter::new(vec![1, 2, 3, 2, 2, 2, 5, 6, 7, 7, 8, 9, 10].iter())
);
for v in c.keys() {
println!("{}", v);
}
println!("There are {} ls", c[&'l']);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment