-
Notifications
You must be signed in to change notification settings - Fork 102
Open
Labels
Description
Following on from #172, adding insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k -> (Maybe a, Map k a)
would be quite useful for avoiding multiple traversals of a map in various algorithms. An example I was working on recently was implementing the Misra-Gries summary for finding the most frequent elements in a streaming dataset:
misraGries :: Ord k => Int -> Fold k (M.Map k Int)
misraGries n = Fold step (M.empty :: M.Map k Int) id where
step !old k = case M.insertLookupWithKey (\_k n _ -> n+1) k 1 old of
(Just _prev, new) -> new
(Nothing, new)
| M.size new < n -> new
| otherwise -> M.mapMaybe (\case 1 -> Nothing; n -> Just (n-1)) old
I'd also like to have a HashMap based implementation but doing so involves several more traversals of the HashMap.