Skip to content

Commit 679179c

Browse files
Add strict version of differenceWith.
1 parent f28153d commit 679179c

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

Data/HashMap/Strict.hs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,9 +99,9 @@ import Prelude hiding (map)
9999
import qualified Data.HashMap.Array as A
100100
import qualified Data.HashMap.Base as HM
101101
import Data.HashMap.Base hiding (
102-
alter, adjust, fromList, fromListWith, insert, insertWith, intersectionWith,
103-
intersectionWithKey, map, mapWithKey, mapMaybe, mapMaybeWithKey, singleton,
104-
update, unionWith, unionWithKey)
102+
alter, adjust, fromList, fromListWith, insert, insertWith, differenceWith,
103+
intersectionWith, intersectionWithKey, map, mapWithKey, mapMaybe,
104+
mapMaybeWithKey, singleton, update, unionWith, unionWithKey)
105105
import Data.HashMap.Unsafe (runST)
106106

107107
-- $strictness
@@ -395,6 +395,18 @@ mapMaybe f = mapMaybeWithKey (const f)
395395
------------------------------------------------------------------------
396396
-- * Difference and intersection
397397

398+
-- | /O(n*log m)/ Difference with a combining function. When two equal keys are
399+
-- encountered, the combining function is applied to the values of these keys.
400+
-- If it returns 'Nothing', the element is discarded (proper set difference). If
401+
-- it returns (@'Just' y@), the element is updated with a new value @y@.
402+
differenceWith :: (Eq k, Hashable k) => (v -> w -> Maybe v) -> HashMap k v -> HashMap k w -> HashMap k v
403+
differenceWith f a b = foldlWithKey' go empty a
404+
where
405+
go m k v = case HM.lookup k b of
406+
Nothing -> insert k v m
407+
Just w -> maybe m (\y -> insert k y m) (f v w)
408+
{-# INLINABLE differenceWith #-}
409+
398410
-- | /O(n+m)/ Intersection of two maps. If a key occurs in both maps
399411
-- the provided function is used to combine the values from the two
400412
-- maps.

0 commit comments

Comments
 (0)