Heterogeneous map

I need a map that can contain arbitrary values ​​if their types have the same class. My first naive approach was something like this:

type HMap = forall a . MyClass a => M.Map Int a 

but it does not work: the following code gives a compilation error:

 testFunction :: (forall a . MyClass a => M.Map Int a) -> Int -> IO () testFunction mi = do case M.lookup im of Nothing -> return () Just v -> someActionFromMyClass v >> putStrLn "OK" Ambiguous type variable `a0' in the constraint: (MyClass a0) arising from a use of `m' Probable fix: add a type signature that fixes these type variable(s) In the second argument of `M.lookup', namely `m' In the expression: (M.lookup im) In a stmt of a 'do' block: case (M.lookup im) of { Nothing -> return () Just v -> someActionFromMyClass v >> putStrLn "OK" } 

I thought I needed a special heterogeneous collection, but, oddly enough, I could not find anything on Google except this , but this library seems a bit shabby and old. What is the way to do it right (hopefully without other libraries using only GHC extensions)?

+7
source share
1 answer

Try using the correct existential type.

 {-# LANGUAGE ExistentialQuantification #-} data Elem = forall e. C e => Elem e type HMap = Map Int Elem 
+9
source

All Articles