Skip to content

Instantly share code, notes, and snippets.

@wackywendell
Created August 18, 2014 17:57
Show Gist options
  • Save wackywendell/8c6442e9e46783d1d736 to your computer and use it in GitHub Desktop.
Save wackywendell/8c6442e9e46783d1d736 to your computer and use it in GitHub Desktop.
A counter for Rust
/// A simple counter.
#[warn(non_camel_case_types)]
#[warn(unnecessary_qualification)]
#[warn(non_uppercase_statics)]
#[warn(missing_doc)]
extern crate collections;
use collections::TreeMap;
/// Count the number of occurrences of each value in an iterator
pub fn get_counts<K : Ord, I : Iterator<K>>(mut list : I) -> TreeMap<K, uint> {
let mut counter : TreeMap<K, uint> = TreeMap::new();
for key in list {
// TODO: if key is not in the tree, this looks for its position twice
// there used to be an 'insert_or_update_with' method
// Note: can't use following, because of the borrow checker.
//~ match counter.find(&key) {
//~ None => {counter.insert(key, 1);},
//~ Some(mut value) => {(*value) += 1;}
//~ }
if counter.contains_key(&key) {
match counter.find_mut(&key) {
Some(value) => {(*value) += 1;}
None => {fail!("Impossible!");}
}
} else {
counter.insert(key, 1);
}
}
counter
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment