on main help sign in
Implement simple TypeRepMap
commit0f3b672efc6c1fb5262d0d5c02670d105a62a73c authorvrom911 <vrom911@gmail.com> dateSat 16 Dec 2017, 03:37 (9 years ago) parent4b3fd4e
2 files changed+42−1
src/Data/TypeRep/Map.hs+40 typerep-map.cabal+2−1
src/Data/TypeRep/Map.hsnew file+40
@@ -0,0 +1,40 @@
1+{-# LANGUAGE ExplicitForAll #-}
2+{-# LANGUAGE ScopedTypeVariables #-}
3+
4+module Data.TypeRep.Map
5+ ( TypeRepMap (..)
6+ , empty
7+ , insert
8+ , lookup
9+ ) where
10+
11+import Prelude hiding (lookup)
12+
13+import Control.Monad ((<=<))
14+import Data.Dynamic (Dynamic, fromDynamic, toDyn)
15+import Data.Proxy (Proxy (..))
16+import Data.Typeable (TypeRep, Typeable, typeOf, typeRep)
17+
18+import qualified Data.Map.Lazy as LMap
19+
20+-- | Map-like data structure with types served as the keys.
21+newtype TypeRepMap = TypeRepMap
22+ { unMap :: LMap.Map TypeRep Dynamic
23+ } deriving (Show)
24+
25+-- | Empty structure.
26+empty :: TypeRepMap
27+empty = TypeRepMap mempty
28+
29+-- | Inserts the value with its type as a key.
30+insert :: Typeable a => a -> TypeRepMap -> TypeRepMap
31+insert val = TypeRepMap . LMap.insert (typeOf val) (toDyn val) . unMap
32+
33+-- | Looks up the value at the type.
34+-- >>> let x = lookup $ insert (11 :: Int) empty
35+-- >>> x :: Maybe Int
36+-- Just 11
37+-- >>> x :: Maybe ()
38+-- Nothing
39+lookup :: forall a . Typeable a => TypeRepMap -> Maybe a
40+lookup = fromDynamic <=< LMap.lookup (typeRep (Proxy :: Proxy a)) . unMap
typerep-map.cabal+2−1
@@ -16,9 +16,10 @@ tested-with: GHC == 8.0.1
1616
1717library
1818 hs-source-dirs: src
19− exposed-modules: Lib
19+ exposed-modules: Data.TypeRep.Map
2020 ghc-options: -Wall
2121 build-depends: base
22+ , containers
2223 default-language: Haskell2010
2324
2425test-suite typerep-map-test