2012-05-24 22 views
7

我需要一个地图,可以包含任意值,只要它们的类型相同类型类。我的第一个幼稚的做法是这样的:异构地图

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

,但它似乎并没有工作:下面的代码给出了一个编译错误:

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" } 

我想,我需要特别均质集合体,但奇怪的是我找不到在谷歌任何东西,除了this,但这个库似乎有点邋遢老。 什么是正确的这样做的(希望没有其他图书馆只使用GHC扩展)的方式吗?

回答

9

尝试使用适当的生存型。

{-# LANGUAGE ExistentialQuantification #-} 

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

type HMap = Map Int Elem 
+0

非常感谢您!这是我自己没有得到的耻辱。我想我现在必须睡得比现在更多) –