Ordered and Unordered Collection Equality
A list, set, and frequency map answer different equality questions about order and multiplicity.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Compare three inputs
Lists [2, 3] and [3, 2] differ by order. Both give the same set containing 2 and 3. The list [2, 2, 3] gives that set too but has different frequencies.
Match the assertion to the promise
A returned sorted list should be checked as a sequence. A collection of distinct affected identifiers may be checked as a set when order is unspecified. Consult the postcondition before turning a result into a set just to make testing easier.[1]
Compare three representations on one example
The sequences [red, blue, red] and [blue, red, red] differ by order. Their bags agree because they have equal counts for each color. Their sets also agree, and the set would still agree if one of the red entries disappeared. Use sequence comparison for a route, multiplicity comparison for counted items, and set comparison for active tags. Test a pure reordering and a pure multiplicity change. See membership and duplicates.
Choose equality before constructing a hash or fingerprint
Sorting can make an unordered comparison reproducible when values have a meaningful total order. Converting to a set removes duplicates, so it is unsuitable when counts matter. An order-independent encoding should serialize equivalent collections consistently, with unambiguous boundaries between component values. Use the same equality basis for the representation and tests. See subtracting inventories with counts.