Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More Data.Map compatibility: Add insertLookupWithKey #467

Open
axman6 opened this issue May 16, 2022 · 2 comments
Open

More Data.Map compatibility: Add insertLookupWithKey #467

axman6 opened this issue May 16, 2022 · 2 comments

Comments

@axman6
Copy link

axman6 commented May 16, 2022

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.

@sjakobi
Copy link
Member

sjakobi commented May 16, 2022

#245 is a feature request for a very similar function.

An implementation in terms of alterF should look similar to the one in #245 (comment).

Note that the current alterF implementation still takes two map traversals. A PR that optimizes the implementation would be very welcome though.

Since the implementation in terms of alterF is so simple, I'd currently prefer not to add a dedicated insertLookupWithKey function to the API.

@axman6
Copy link
Author

axman6 commented May 16, 2022

Interesting, I'll have to see if I can make it work with alterF

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants