Counter
Simple counter library for Rust iterables. Inspired by, and largely mimicing the API of, Python's Counter.
Examples
Just count an iterable
let char_counts = init;
let counts_counts = init;
Updates are simple
let mut counts = init;
// add or subtract an iterable of the same type
counts += "cain and abel fable table cable".split_whitespace;
// or add or subtract from another Counter of the same type
let other_counts = init;
let difference = counts - other_counts;
Get the most common items
most_common_ordered()
uses the natural ordering of keys which are Ord
.
let by_common = init
.most_common_ordered;
let expected = vec!;
assert!;
Get the most common items using your own ordering
For example, here we break ties reverse alphabetically.
let counter = init;
let by_common = counter.most_common_tiebreaker;
let expected = vec!;
assert!;
Treat it like a Map
Counter<T>
implements Deref<Target=HashMap<T, usize>>
and
DerefMut<Target=HashMap<T, usize>>
, which means that you can perform any operations
on it which are valid for a HashMap
.
let mut counter = init;
counter.remove;
assert!;
Count any iterable which is Hash + Eq
You can't use the most_common*
functions unless T is also Clone
, but simple counting works fine on a minimal data type.
// <https://en.wikipedia.org/wiki/867-5309/Jenny>
let intys = vec!;
let inty_counts = init;
println!;
// {Inty { i: 8 }: 2, Inty { i: 0 }: 3, Inty { i: 9 }: 1, Inty { i: 3 }: 1,
// Inty { i: 7 }: 1, Inty { i: 6 }: 1, Inty { i: 5 }: 1}
assert!;
assert!;
assert!;