@@ -0,0 +1,40 @@
1+{-# LANGUAGE ExplicitForAll #-}
2+{-# LANGUAGE ScopedTypeVariables #-}
4+module Data.TypeRep.Map
11+import Prelude hiding (lookup)
13+import Control.Monad ((<=<))
14+import Data.Dynamic (Dynamic, fromDynamic, toDyn)
15+import Data.Proxy (Proxy (..))
16+import Data.Typeable (TypeRep, Typeable, typeOf, typeRep)
18+import qualified Data.Map.Lazy as LMap
20+-- | Map-like data structure with types served as the keys.
21+newtype TypeRepMap = TypeRepMap
22+ { unMap :: LMap.Map TypeRep Dynamic
27+empty = TypeRepMap mempty
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
33+-- | Looks up the value at the type.
34+-- >>> let x = lookup $ insert (11 :: Int) empty
39+lookup :: forall a . Typeable a => TypeRepMap -> Maybe a
40+lookup = fromDynamic <=< LMap.lookup (typeRep (Proxy :: Proxy a)) . unMap