git.iko.soy/monoidal-containers
on master help sign in
Merge pull request #19 from k-bx/master

Add insert and insertOrreplace operations

commitb0d505be3d14329b923809785af77d32a933be07 authorBen Gamari <ben@smart-cactus.org> dateWed 9 May 2018, 12:42 (8 years ago) parent2e1884a1802c74
1 file changed+24
src/Data/HashMap/Monoidal.hs+24
src/Data/HashMap/Monoidal.hs+24
@@ -30,6 +30,8 @@ module Data.HashMap.Monoidal
3030 , keys
3131 , delete
3232 , mapKeys
33+ , insert
34+ , insertOrReplace
3335 , modify
3436 , modifyDef
3537 , map
@@ -181,6 +183,28 @@ toList :: MonoidalHashMap k a -> [(k,a)]
181183toList = M.toList . unpack
182184{-# INLINE toList #-}
183185
186+-- | /O(log n)/. Insert a value on some key, if it exists -- mappend
187+-- to the existing one.
188+insert :: (Semigroup a, Hashable k, Eq k)
189+ => a
190+ -> k
191+ -> MonoidalHashMap k a
192+ -> MonoidalHashMap k a
193+insert x k = pack
194+ . M.insertWith (<>) k x
195+ . unpack
196+
197+-- | /O(log n)/. Insert a value on some key with a function, if value
198+-- under key exists -- replace it.
199+insertOrReplace :: (Semigroup a, Hashable k, Eq k)
200+ => a
201+ -> k
202+ -> MonoidalHashMap k a
203+ -> MonoidalHashMap k a
204+insertOrReplace x k = pack
205+ . M.insert k x
206+ . unpack
207+
184208-- | /O(log n)/. Modify a value on some key with a function, if value
185209-- under key doesn't exist -- use mempty.
186210modify :: (Monoid a, Hashable k, Eq k)