Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heterogeneous map

I need a map which can contain arbitrary values as long as their types are of the same typeclass. My first naive approach was something like this:

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

but it does not seem to work: the following code gives a compile error:

testFunction :: (forall a . MyClass a => M.Map Int a) -> Int -> IO ()
testFunction m i = do
    case M.lookup i m 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 i m)
In a stmt of a 'do' block:
  case (M.lookup i m) of {
    Nothing -> return ()
    Just v -> someActionFromMyClass v >> putStrLn "OK" }

I thought that I need special heterogeneous collection, but strangely I couldn't find anything in Google except this, but this library seems kind of scruffy and old. What is the way of doing this correctly (hopefully without other libraries, using GHC extensions only)?

like image 362
Vladimir Matveev Avatar asked May 24 '12 15:05

Vladimir Matveev


1 Answers

Try using a proper existential type.

{-# LANGUAGE ExistentialQuantification #-}

data Elem = forall e. C e => Elem e

type HMap = Map Int Elem
like image 155
Don Stewart Avatar answered Oct 03 '22 00:10

Don Stewart