Skip to content

Commit 18e8e8b

Browse files
committed
Add MapExtras function to return the interned key and value in a map
1 parent c20fece commit 18e8e8b

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

libs/cardano-data/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
## 1.3.0.0
44

5+
* Add `lookupInternMap`
56
* Replace `okeyL` with `toOKey`
67

78
## 1.2.4.1

libs/cardano-data/src/Data/MapExtras.hs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ module Data.MapExtras (
2828
extractKeysSmallSet,
2929
fromKeys,
3030
fromElems,
31+
lookupInternMap,
3132
) where
3233

3334
import Data.Foldable (toList)
@@ -270,3 +271,16 @@ fromElems f vs =
270271
-- a nice optimization for already sorted keys and with list fusion there should be no overhead
271272
Map.fromList [(f v, v) | v <- toList vs]
272273
{-# INLINE fromElems #-}
274+
275+
-- | Look up a key in a map and return the interned key together with its value, if present.
276+
-- The returned key is exactly the one stored in the map.
277+
-- Useful for maximizing sharing by avoiding duplicate-but-equal keys.
278+
lookupInternMap :: Ord k => k -> Map k v -> Maybe (k, v)
279+
lookupInternMap k = go
280+
where
281+
go Tip = Nothing
282+
go (Bin _ kx v l r) =
283+
case compare k kx of
284+
LT -> go l
285+
GT -> go r
286+
EQ -> Just (kx, v)

0 commit comments

Comments
 (0)