Skip to content

Commit 4ff0e9f

Browse files
committed
Extras for working with maps
Two extra helper functions that simplifies working with maps. boundedEnumMap builds a functional index map for a bounded values. lookupMapFail provides conventient search with error reporting.
1 parent 532def7 commit 4ff0e9f

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ module Data.MapExtras (
2424
intersectDomPLeft,
2525
intersectMapSetFold,
2626
disjointMapSetFold,
27+
boundedEnumMap,
28+
lookupMapFail,
2729
extractKeys,
2830
extractKeysSmallSet,
2931
fromKeys,
@@ -284,3 +286,13 @@ lookupInternMap k = go
284286
LT -> go l
285287
GT -> go r
286288
EQ -> Just (kx, v)
289+
290+
boundedEnumMap :: (Ord k, Bounded a, Enum a) => (a -> k) -> Map k a
291+
boundedEnumMap toTxt = Map.fromList [(toTxt t, t) | t <- [minBound .. maxBound]]
292+
293+
lookupMapFail ::
294+
(Ord k, Show k, MonadFail m) => String -> Map k v -> k -> m v
295+
lookupMapFail name m key =
296+
case Map.lookup key m of
297+
Just t -> pure t
298+
Nothing -> fail $ "Unrecognized " <> name <> ": " ++ show key

libs/cardano-data/test/Test/Cardano/Data/MapExtrasSpec.hs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import Control.Monad
66
import Data.Map (Map)
77
import qualified Data.Map.Strict as Map
88
import Data.MapExtras
9+
import Data.Word (Word8)
910
import Test.Cardano.Data
1011
import Test.Hspec
1112
import Test.Hspec.QuickCheck
@@ -39,3 +40,9 @@ mapExtrasSpec =
3940
ma = intersectDomPLeft f m1 m2
4041
expectValidMap ma
4142
ma `shouldBe` Map.mapMaybeWithKey (\k v -> v <$ (guard . f k =<< Map.lookup k m2)) m1
43+
prop "boundedEnumMap" $ do
44+
let convert = fromIntegral :: Word8 -> Int
45+
m = boundedEnumMap convert :: Map Int Word8
46+
expectValidMap m
47+
forM_ [minBound .. maxBound] $ \t -> do
48+
Map.lookup (convert t) m `shouldBe` Just t

0 commit comments

Comments
 (0)