diff --git a/README.md b/README.md index 31702d7..2b2b516 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,9 @@ -# Counter +# counter Counter counts recurrent elements of iterables. It is based on [the Python implementation](https://docs.python.org/3.5/library/collections.html#collections.Counter). +The struct [`Counter`](struct.Counter.html) is the entry-point type for this module. + ## Examples ### Just count an iterable @@ -14,6 +16,12 @@ let counts_counts = char_counts.values().collect::>(); ### Update a count +```rust +let mut counts = "aaa".chars().collect::>(); +counts[&'a'] += 1; +counts[&'b'] += 1; +``` + ```rust let mut counts = "able babble table babble rabble table able fable scrabble" .split_whitespace().collect::>(); @@ -25,6 +33,14 @@ let other_counts = "scrabble cabbie fable babble" let difference = counts - other_counts; ``` +### Get items with keys + +```rust +let counts = "aaa".chars().collect::>(); +assert_eq!(counts[&'a'], 3); +assert_eq!(counts[&'b'], 0); +``` + ### Get the most common items `most_common_ordered()` uses the natural ordering of keys which are `Ord`. @@ -58,6 +74,15 @@ counter.remove(&'-'); assert!(counter == "aabbcc".chars().collect::>()); ``` +Note that `Counter` itself implements `Index`. `Counter::index` returns a reference to a `zero` value for missing keys. + +```rust +let counter = "aaa".chars().collect::>(); +assert_eq!(counter[&'b'], 0); +// panics +// assert_eq!((*counter)[&'b'], 0); +``` + ## Advanced Usage ### Count any iterable which is `Hash + Eq` @@ -110,3 +135,5 @@ let counter: Counter<_, i8> = "abbccc".chars().collect(); let expected: HashMap = [('a', 1), ('b', 2), ('c', 3)].iter().cloned().collect(); assert!(counter.into_map() == expected); ``` + +License: MIT