Skip to content

Commit 98875e0

Browse files
authored
Merge pull request #970 from haskell/issue-952-keymap-insertWith
Issue #952: KeyMap.insertWith
2 parents 92a7e1d + af8a9b3 commit 98875e0

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

changelog.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ For the latest version of this document, please see [https://github.com/haskell/
33
### 2.1.1.0
44

55
- Add `Data.Aeson.KeyMap.!?` (flipped) alias to `Data.Aeson.KeyMap.lookup`.
6+
- Add `Data.Aeson.KeyMap.insertWith` function.
67
- Use `unsafeDupablePerformIO` instead of incorrect `accursedUnutterablePerformIO` in creation of keys in TH serialisation.
78
This fixes a bug in TH deriving, e.g. when `Strict` pragma was enabled.
89

src/Data/Aeson/KeyMap.hs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ module Data.Aeson.KeyMap (
2626

2727
-- ** Insertion
2828
insert,
29+
insertWith,
2930

3031
-- * Deletion
3132
delete,
@@ -191,6 +192,12 @@ lookup t tm = M.lookup t (unKeyMap tm)
191192
insert :: Key -> v -> KeyMap v -> KeyMap v
192193
insert k v tm = KeyMap (M.insert k v (unKeyMap tm))
193194

195+
-- | Insert with a function combining new and old values, taken in that order.
196+
--
197+
-- @since 2.1.1.0
198+
insertWith :: (a -> a -> a) -> Key -> a -> KeyMap a -> KeyMap a
199+
insertWith f k v m = KeyMap (M.insertWith f k v (unKeyMap m))
200+
194201
-- | Map a function over all values in the map.
195202
map :: (a -> b) -> KeyMap a -> KeyMap b
196203
map = fmap
@@ -394,6 +401,12 @@ lookup t tm = H.lookup t (unKeyMap tm)
394401
insert :: Key -> v -> KeyMap v -> KeyMap v
395402
insert k v tm = KeyMap (H.insert k v (unKeyMap tm))
396403

404+
-- | Insert with a function combining new and old values, taken in that order.
405+
--
406+
-- @since 2.1.1.0
407+
insertWith :: (a -> a -> a) -> Key -> a -> KeyMap a -> KeyMap a
408+
insertWith f k v m = KeyMap (H.insertWith f k v (unKeyMap m))
409+
397410
-- | Map a function over all values in the map.
398411
map :: (a -> b) -> KeyMap a -> KeyMap b
399412
map = fmap

tests/UnitTests.hs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -826,4 +826,9 @@ tests = testGroup "unit" [
826826
]
827827
, monadFixTests
828828
, issue967
829+
, testCase "KeyMap.insertWith" $ do
830+
KM.insertWith (-) "a" 2 (KM.fromList [("a", 1)]) @?= KM.fromList [("a",1 :: Int)]
831+
KM.insertWith (flip (-)) "a" 2 (KM.fromList [("a", 1)]) @?= KM.fromList [("a",-1 :: Int)]
832+
KM.insertWith (-) "b" 2 (KM.fromList [("a", 1)]) @?= KM.fromList [("a",1),("b",2 :: Int)]
833+
KM.insertWith (-) "b" 2 KM.empty @?= KM.fromList [("b",2 :: Int)]
829834
]

0 commit comments

Comments
 (0)