Skip to content

Commit b0ea719

Browse files
philderbeastphadej
authored andcommitted
Add an insertWith functiion.
1 parent 92a7e1d commit b0ea719

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

src/Data/Aeson/KeyMap.hs

Lines changed: 11 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,11 @@ 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+
insertWith :: (a -> a -> a) -> Key -> a -> KeyMap a -> KeyMap a
198+
insertWith f k v m = KeyMap (M.insertWith f k v (unKeyMap m))
199+
194200
-- | Map a function over all values in the map.
195201
map :: (a -> b) -> KeyMap a -> KeyMap b
196202
map = fmap
@@ -394,6 +400,11 @@ lookup t tm = H.lookup t (unKeyMap tm)
394400
insert :: Key -> v -> KeyMap v -> KeyMap v
395401
insert k v tm = KeyMap (H.insert k v (unKeyMap tm))
396402

403+
-- | Insert with a function combining new and old values, taken in that order.
404+
--
405+
insertWith :: (a -> a -> a) -> Key -> a -> KeyMap a -> KeyMap a
406+
insertWith f k v m = KeyMap (H.insertWith f k v (unKeyMap m))
407+
397408
-- | Map a function over all values in the map.
398409
map :: (a -> b) -> KeyMap a -> KeyMap b
399410
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)