Skip to content

Commit 28d25e4

Browse files
committed
Add size-aware alterInternal and updateInternal functions
1 parent 999c489 commit 28d25e4

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Data/HashMap/Base.hs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -982,6 +982,20 @@ update :: (Eq k, Hashable k) => (a -> Maybe a) -> k -> HashMap k a -> HashMap k
982982
update f = alter (>>= f)
983983
{-# INLINABLE update #-}
984984

985+
-- | /O(log n)/ The expression (@'updateInternal' f k map@) updates the
986+
-- value @x@ at @k@, (if it is in the map). If (f k x) is @'Nothing',
987+
-- the element is deleted.
988+
-- If it is (@'Just' y), the key k is bound to the new value y.
989+
-- Returns a tuple where the first component is the hashmap's change in size,
990+
-- and the second is hashmap after the operation.
991+
updateInternal
992+
:: (Eq k, Hashable k)
993+
=> (a -> Maybe a)
994+
-> k
995+
-> HashMap k a
996+
-> (Int, HashMap k a)
997+
updateInternal f = alterInternal (>>= f)
998+
{-# INLINABLE updateInternal #-}
985999

9861000
-- | /O(log n)/ The expression (@'alter' f k map@) alters the value @x@ at @k@, or
9871001
-- absence thereof. @alter@ can be used to insert, delete, or update a value in a
@@ -993,6 +1007,23 @@ alter f k m =
9931007
Just v -> insert k v m
9941008
{-# INLINABLE alter #-}
9951009

1010+
-- | /O(log n)/ The expression (@'alterInternal' f k map@) alters the
1011+
-- value @x@ at @k@, or absence thereof. @alterInternal@ can be used to
1012+
-- insert, delete, or update a value in a map.
1013+
-- Returns a tuple where the first component is the hashmap's change in
1014+
-- size, and the second the hashmap after the operation.
1015+
alterInternal
1016+
:: (Eq k, Hashable k)
1017+
=> (Maybe v -> Maybe v)
1018+
-> k
1019+
-> HashMap k v
1020+
-> (Int, HashMap k v)
1021+
alterInternal f k m =
1022+
case f (lookup k m) of
1023+
Nothing -> deleteInternal k m
1024+
Just v -> insertInternal k v m
1025+
{-# INLINABLE alterInternal #-}
1026+
9961027
------------------------------------------------------------------------
9971028
-- * Combine
9981029

0 commit comments

Comments
 (0)