سؤال

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)?

هل كانت مفيدة؟

المحلول

Try using a proper existential type.

{-# LANGUAGE ExistentialQuantification #-}

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

type HMap = Map Int Elem
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top