haskell-unordered-containers / unordered-containers

Efficient hashing-based container types
BSD 3-Clause "New" or "Revised" License
221 stars 97 forks source link

`Hash{Map,Set}.compareSize` and associated rules #397

Open sjakobi opened 2 years ago

sjakobi commented 2 years ago

HashMap.size and HashSet.size have complexity O(n). Nevertheless there is a lot of code like

HashMap.size m > CONSTANT

…which could be O(min(n,CONSTANT)) if the HashMap traversal would stop once at most CONSTANT elements have been counted.

For this purpose it would be nice to have a function

compareSize :: HashMap -> Int -> Ordering

and rules that rewrite size comparisons against constants to applications of compareSize.

Similar functionality already exists in bytestring: https://github.com/haskell/bytestring/blob/707e50bac1f1ef7c1729a9246e05f95a4909fd27/Data/ByteString/Lazy.hs#L552-L592

(Analogous feature request for IntMap: https://github.com/haskell/containers/issues/826)