| 1 | # counter |
| 2 | |
| 3 | Counter counts recurrent elements of iterables. It is based on [the Python |
| 4 | implementation](https://docs.python.org/3/library/collections.html#collections.Counter). |
| 5 | |
| 6 | The struct [`Counter`](struct.Counter.html) is the entry-point type for this module. |
| 7 | |
| 8 | ## Math Underpinnings |
| 9 | |
| 10 | Mathematically, a `Counter` implements a hash-based version of a [multiset], |
| 11 | or bag. This is simply an extension of the notion of a set to the idea that |
| 12 | we care not only about whether an entity exists within the set, but the number |
| 13 | of occurrences within the set. Normal set operations such as intersection, |
| 14 | union, etc. are of course still supported. |
| 15 | |
| 16 | [multiset]: https://en.wikipedia.org/wiki/Set_(abstract_data_type)#Multiset |
| 17 | |
| 18 | ## Cargo Features |
| 19 | |
| 20 | - `serde` implements `serde::Serialize` and `serde::Deserialize` for `Counter`. |
| 21 | |
| 22 | ## Examples |
| 23 | |
| 24 | ### Just count an iterable |
| 25 | |
| 26 | ```rust |
| 27 | use counter::Counter; |
| 28 | let char_counts = "barefoot".chars().collect::<Counter<_>>(); |
| 29 | let counts_counts = char_counts.values().collect::<Counter<_>>(); |
| 30 | ``` |
| 31 | |
| 32 | ### Update a count |
| 33 | |
| 34 | ```rust |
| 35 | let mut counts = "aaa".chars().collect::<Counter<_>>(); |
| 36 | counts[&'a'] += 1; |
| 37 | counts[&'b'] += 1; |
| 38 | ``` |
| 39 | |
| 40 | ```rust |
| 41 | let mut counts = "able babble table babble rabble table able fable scrabble" |
| 42 | .split_whitespace().collect::<Counter<_>>(); |
| 43 | // add or subtract an iterable of the same type |
| 44 | counts += "cain and abel fable table cable".split_whitespace(); |
| 45 | // or add or subtract from another Counter of the same type |
| 46 | let other_counts = "scrabble cabbie fable babble" |
| 47 | .split_whitespace().collect::<Counter<_>>(); |
| 48 | let difference = counts - other_counts; |
| 49 | ``` |
| 50 | |
| 51 | Extend a `Counter` with another `Counter`: |
| 52 | ```rust |
| 53 | let mut counter = "abbccc".chars().collect::<Counter<_>>(); |
| 54 | let another = "bccddd".chars().collect::<Counter<_>>(); |
| 55 | counter.extend(&another); |
| 56 | let expect = [('a', 1), ('b', 3), ('c', 5), ('d', 3)].iter() |
| 57 | .cloned().collect::<HashMap<_, _>>(); |
| 58 | assert_eq!(counter.into_map(), expect); |
| 59 | ``` |
| 60 | ### Get items with keys |
| 61 | |
| 62 | ```rust |
| 63 | let counts = "aaa".chars().collect::<Counter<_>>(); |
| 64 | assert_eq!(counts[&'a'], 3); |
| 65 | assert_eq!(counts[&'b'], 0); |
| 66 | ``` |
| 67 | |
| 68 | ### Get the most common items |
| 69 | |
| 70 | [`most_common_ordered()`] uses the natural ordering of keys which are [`Ord`]. |
| 71 | |
| 72 | [`most_common_ordered()`]: Counter::most_common_ordered |
| 73 | [`Ord`]: https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html |
| 74 | |
| 75 | ```rust |
| 76 | let by_common = "eaddbbccc".chars().collect::<Counter<_>>().most_common_ordered(); |
| 77 | let expected = vec![('c', 3), ('b', 2), ('d', 2), ('a', 1), ('e', 1)]; |
| 78 | assert!(by_common == expected); |
| 79 | ``` |
| 80 | |
| 81 | [`k_most_common_ordered()`] takes an argument `k` of type `usize` and returns the top `k` most |
| 82 | common items. This is functionally equivalent to calling `most_common_ordered()` and then |
| 83 | truncating the result to length `k`. However, if `k` is smaller than the length of the counter |
| 84 | then `k_most_common_ordered()` can be more efficient, often much more so. |
| 85 | |
| 86 | ```rust |
| 87 | let by_common = "eaddbbccc".chars().collect::<Counter<_>>().k_most_common_ordered(2); |
| 88 | let expected = vec![('c', 3), ('b', 2)]; |
| 89 | assert!(by_common == expected); |
| 90 | ``` |
| 91 | |
| 92 | [`k_most_common_ordered()`]: Counter::k_most_common_ordered |
| 93 | [`most_common_ordered()`]: Counter::most_common_ordered |
| 94 | |
| 95 | ### Get the most common items using your own ordering |
| 96 | |
| 97 | For example, here we break ties reverse alphabetically. |
| 98 | |
| 99 | ```rust |
| 100 | let counter = "eaddbbccc".chars().collect::<Counter<_>>(); |
| 101 | let by_common = counter.most_common_tiebreaker(|&a, &b| b.cmp(&a)); |
| 102 | let expected = vec![('c', 3), ('d', 2), ('b', 2), ('e', 1), ('a', 1)]; |
| 103 | assert!(by_common == expected); |
| 104 | ``` |
| 105 | |
| 106 | ### Test counters against another |
| 107 | |
| 108 | Counters are multi-sets and so can be sub- or supersets of each other. |
| 109 | |
| 110 | A counter is a _subset_ of another if for all its elements, the other |
| 111 | counter has an equal or higher count. Test for this with [`is_subset()`]: |
| 112 | |
| 113 | ```rust |
| 114 | let counter = "aaabb".chars().collect::<Counter<_>>(); |
| 115 | let superset = "aaabbbc".chars().collect::<Counter<_>>(); |
| 116 | let not_a_superset = "aaae".chars().collect::<Counter<_>>(); |
| 117 | assert!(counter.is_subset(&superset)); |
| 118 | assert!(!counter.is_subset(¬_a_superset)); |
| 119 | ``` |
| 120 | |
| 121 | Testing for a _superset_ is the inverse, [`is_superset()`] is true if the counter can contain another counter in its entirety: |
| 122 | |
| 123 | ```rust |
| 124 | let counter = "aaabbbc".chars().collect::<Counter<_>>(); |
| 125 | let subset = "aabbb".chars().collect::<Counter<_>>(); |
| 126 | let not_a_subset = "aaae".chars().collect::<Counter<_>>(); |
| 127 | assert!(counter.is_superset(&subset)); |
| 128 | assert!(!counter.is_superset(¬_a_subset)); |
| 129 | ``` |
| 130 | |
| 131 | These relationships continue to work when [using a _signed_ integer type for the counter][signed]: all values in the subset must be equal or lower to the values in the superset. Negative |
| 132 | values are interpreted as 'missing' those values, and the subset would need to miss those |
| 133 | same elements, or be short more, to still be a subset: |
| 134 | |
| 135 | ```rust |
| 136 | let mut subset = "aaabb".chars().collect::<Counter<_, i8>>(); |
| 137 | subset.insert('e', -2); // short 2 'e's |
| 138 | subset.insert('f', -1); // and 1 'f' |
| 139 | let mut superset = "aaaabbb".chars().collect::<Counter<_, i8>>(); |
| 140 | superset.insert('e', -1); // short 1 'e' |
| 141 | assert!(subset.is_subset(&superset)); |
| 142 | assert!(superset.is_superset(&subset)); |
| 143 | ``` |
| 144 | |
| 145 | [`is_subset()`]: Counter::is_subset |
| 146 | [`is_superset()`]: Counter::is_superset |
| 147 | [signed]: #use-your-own-type-for-the-count |
| 148 | |
| 149 | ### Counter intersection and union |
| 150 | |
| 151 | You can intersect two counters, giving you the minimal counts of their |
| 152 | combined elements using the [`&` bitwise and operator][BitAnd], and produce |
| 153 | their union with the maximum counts using [`|` bitwise or][BitOr]: |
| 154 | |
| 155 | ```rust |
| 156 | let a = "aaabb".chars().collect::<Counter<_>>(); |
| 157 | let b = "aabbbbe".chars().collect::<Counter<_>>(); |
| 158 | |
| 159 | let intersection = a & b; |
| 160 | let expected_intersection = "aabb".chars().collect::<Counter<_>>(); |
| 161 | assert_eq!(intersection, expected_intersection); |
| 162 | |
| 163 | let c = "aaabb".chars().collect::<Counter<_>>(); |
| 164 | let d = "aabbbbe".chars().collect::<Counter<_>>(); |
| 165 | |
| 166 | let union = c | d; |
| 167 | let expected_union = "aaabbbbe".chars().collect::<Counter<_>>(); |
| 168 | assert_eq!(union, expected_union) |
| 169 | ``` |
| 170 | |
| 171 | The in-place [`&=`] and [`|=`] operations are also supported. |
| 172 | |
| 173 | [BitAnd]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html |
| 174 | [BitOr]: https://doc.rust-lang.org/std/ops/trait.BitOr.html |
| 175 | [`&=`]: https://doc.rust-lang.org/std/ops/trait.BitAndAssign.html |
| 176 | [`|=`]: https://doc.rust-lang.org/std/ops/trait.BitOrAssign.html |
| 177 | |
| 178 | ### Treat it like a `HashMap` |
| 179 | |
| 180 | `Counter<T, N>` implements [`Deref`]`<Target=HashMap<T, N>>` and |
| 181 | [`DerefMut`]`<Target=HashMap<T, N>>`, which means that you can perform any operations |
| 182 | on it which are valid for a [`HashMap`]. |
| 183 | |
| 184 | [`HashMap`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html |
| 185 | [`Deref`]: https://doc.rust-lang.org/stable/std/ops/trait.Deref.html |
| 186 | [`DerefMut`]: https://doc.rust-lang.org/stable/std/ops/trait.DerefMut.html |
| 187 | |
| 188 | ```rust |
| 189 | let mut counter = "aa-bb-cc".chars().collect::<Counter<_>>(); |
| 190 | counter.remove(&'-'); |
| 191 | assert!(counter == "aabbcc".chars().collect::<Counter<_>>()); |
| 192 | ``` |
| 193 | |
| 194 | Note that `Counter<T, N>` itself implements [`Index`]. `Counter::index` returns a reference to |
| 195 | a [`Zero::zero`] value for missing keys. |
| 196 | |
| 197 | [`Index`]: https://doc.rust-lang.org/stable/std/ops/trait.Index.html |
| 198 | [`Zero::zero`]: https://docs.rs/num-traits/latest/num_traits/identities/trait.Zero.html#tymethod.zero |
| 199 | |
| 200 | ```rust |
| 201 | let counter = "aaa".chars().collect::<Counter<_>>(); |
| 202 | assert_eq!(counter[&'b'], 0); |
| 203 | // panics |
| 204 | // assert_eq!((*counter)[&'b'], 0); |
| 205 | ``` |
| 206 | |
| 207 | ## Advanced Usage |
| 208 | |
| 209 | ### Count any iterable which is `Hash + Eq` |
| 210 | |
| 211 | You can't use the `most_common*` functions unless `T` is also [`Clone`], but simple counting |
| 212 | works fine on a minimal data type. |
| 213 | |
| 214 | [`Clone`]: https://doc.rust-lang.org/stable/std/clone/trait.Clone.html |
| 215 | |
| 216 | ```rust |
| 217 | #[derive(Debug, Hash, PartialEq, Eq)] |
| 218 | struct Inty { |
| 219 | i: usize, |
| 220 | } |
| 221 | |
| 222 | impl Inty { |
| 223 | pub fn new(i: usize) -> Inty { |
| 224 | Inty { i: i } |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | // <https://en.wikipedia.org/wiki/867-5309/Jenny> |
| 229 | let intys = vec![ |
| 230 | Inty::new(8), |
| 231 | Inty::new(0), |
| 232 | Inty::new(0), |
| 233 | Inty::new(8), |
| 234 | Inty::new(6), |
| 235 | Inty::new(7), |
| 236 | Inty::new(5), |
| 237 | Inty::new(3), |
| 238 | Inty::new(0), |
| 239 | Inty::new(9), |
| 240 | ]; |
| 241 | |
| 242 | let inty_counts = intys.iter().collect::<Counter<_>>(); |
| 243 | println!("{:?}", inty_counts); |
| 244 | // {Inty { i: 8 }: 2, Inty { i: 0 }: 3, Inty { i: 9 }: 1, Inty { i: 3 }: 1, |
| 245 | // Inty { i: 7 }: 1, Inty { i: 6 }: 1, Inty { i: 5 }: 1} |
| 246 | assert!(inty_counts.get(&Inty { i: 8 }) == Some(&2)); |
| 247 | assert!(inty_counts.get(&Inty { i: 0 }) == Some(&3)); |
| 248 | assert!(inty_counts.get(&Inty { i: 6 }) == Some(&1)); |
| 249 | ``` |
| 250 | |
| 251 | ### Use your own type for the count |
| 252 | |
| 253 | Sometimes [`usize`] just isn't enough. If you find yourself overflowing your |
| 254 | machine's native size, you can use your own type. Here, we use an [`i8`], but |
| 255 | you can use most numeric types, including bignums, as necessary. |
| 256 | |
| 257 | [`usize`]: https://doc.rust-lang.org/stable/std/primitive.usize.html |
| 258 | [`i8`]: https://doc.rust-lang.org/stable/std/primitive.i8.html |
| 259 | |
| 260 | ```rust |
| 261 | let counter: Counter<_, i8> = "abbccc".chars().collect(); |
| 262 | let expected: HashMap<char, i8> = [('a', 1), ('b', 2), ('c', 3)].iter().cloned().collect(); |
| 263 | assert!(counter.into_map() == expected); |
| 264 | ``` |
| 265 | |
| 266 | License: MIT |