Heterogeneous map

你。 提交于 2019-12-12 10:38:43

问题


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


回答1:


Try using a proper existential type.

{-# LANGUAGE ExistentialQuantification #-}

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

type HMap = Map Int Elem


来源:https://stackoverflow.com/questions/10740549/heterogeneous-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!