Skip to content
This repository was archived by the owner on Oct 4, 2020. It is now read-only.

Add unionsWith #147

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
4 changes: 4 additions & 0 deletions src/Data/Map.purs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ module Data.Map
, union
, unionWith
, unions
, unionsWith
, isSubmap
, size
, mapWithKey
Expand Down Expand Up @@ -608,6 +609,9 @@ union = unionWith const
unions :: forall k v f. Ord k => Foldable f => f (Map k v) -> Map k v
unions = foldl union empty

unionsWith :: forall k v f. Ord k => Foldable f => (v -> v -> v) -> f (Map k v) -> Map k v
unionsWith f = foldl (unionWith f) empty

-- | Test whether one map contains all of the keys and values contained in another map
isSubmap :: forall k v. Ord k => Eq v => Map k v -> Map k v -> Boolean
isSubmap m1 m2 = LL.all f $ (toUnfoldable m1 :: LL.List (Tuple k v))
Expand Down
23 changes: 23 additions & 0 deletions test/Test/Data/Map.purs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ import Test.QuickCheck.Gen (elements, oneOf)

newtype TestMap k v = TestMap (M.Map k v)

unwrap :: forall k v. TestMap k v -> M.Map k v
unwrap (TestMap m) = m

instance arbTestMap :: (Eq k, Ord k, Arbitrary k, Arbitrary v) => Arbitrary (TestMap k v) where
arbitrary = TestMap <$> genMap arbitrary arbitrary

Expand Down Expand Up @@ -214,6 +217,26 @@ mapTests = do
Just v -> Just v == v2
Nothing -> not (in1 || in2)

log "unionsWith"
for_ [Tuple (+) 0, Tuple (*) 1] $ \(Tuple op ident) ->
quickCheck $ \(testMaps :: Array (TestMap SmallKey Int)) k ->
let testMaps' = unwrap <$> testMaps
u = M.unionsWith op testMaps'
in case M.lookup k u of
Nothing -> A.all (not <<< M.member k) testMaps'
Just v -> (v == _) <<< A.foldl op ident <<< map (fromMaybe ident <<< M.lookup k) $ testMaps'

log "unionsWith argument order"
quickCheck $ \(testMaps :: Array (TestMap SmallKey Int)) k ->
let testMaps' = unwrap <$> testMaps
u = M.unionsWith (-) testMaps'
in case M.lookup k u of
Just v ->
case A.uncons <<< A.mapMaybe (M.lookup k) $ testMaps' of
Nothing -> false
Just { head, tail } -> v == foldl (-) head tail
Nothing -> A.all (not <<< M.member k) testMaps'

log "size"
quickCheck $ \xs ->
let xs' = nubBy ((==) `on` fst) xs
Expand Down