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

Add unionDedupe, intersectDedupe, isSubsetBy #32

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 48 additions & 2 deletions src/Dict/Extra.elm
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module Dict.Extra exposing
( groupBy, filterGroupBy, fromListBy, fromListDedupe, fromListDedupeBy, frequencies
, removeWhen, removeMany, keepOnly, insertDedupe, mapKeys, filterMap, invert
, removeWhen, removeMany, keepOnly, insertDedupe, mapKeys, filterMap, invert, unionDedupe, intersectDedupe, isSubsetBy
, any, find
)

Expand All @@ -14,7 +14,7 @@ module Dict.Extra exposing

# Manipulation

@docs removeWhen, removeMany, keepOnly, insertDedupe, mapKeys, filterMap, invert
@docs removeWhen, removeMany, keepOnly, insertDedupe, mapKeys, filterMap, invert, unionDedupe, intersectDedupe, isSubsetBy


# Utilities
Expand Down Expand Up @@ -323,6 +323,52 @@ invert dict =
dict


{-| Combine two dictionaries. If there is a collision, both values are combined using the function.
-}
unionDedupe : (a -> a -> a) -> Dict comparable a -> Dict comparable a -> Dict comparable a
unionDedupe combine a b =
Dict.merge
Dict.insert
(\k va vb -> Dict.insert k (combine va vb))
Dict.insert
a
b
Dict.empty


{-| Keep only keys that appear in both dictionaries, combining their values with the function. If the function returns Nothing then the key is deleted.
-}
intersectDedupe : (a -> a -> Maybe a) -> Dict comparable a -> Dict comparable a -> Dict comparable a
intersectDedupe combine a b =
Dict.merge
(\_ _ res -> res)
(\k va vb ->
case combine va vb of
Nothing ->
identity

Just v ->
Dict.insert k v
)
(\_ _ res -> res)
a
b
Dict.empty


{-| Returns true if every key of the second dictionary appears in the first, and the function returns true for every pair of values at the same key.
-}
isSubsetBy : (a -> a -> Bool) -> Dict comparable a -> Dict comparable a -> Bool
isSubsetBy compare larger smaller =
Dict.merge
(\_ _ -> (&&) True)
(\_ l s -> (&&) (compare l s))
(\_ _ -> (&&) False)
larger
smaller
True


{-| Determine if any key/value pair satisfies some test.

import Dict
Expand Down