我需要一个可以包含任意值的映射,只要它们的类型属于相同的类型类。我的第一个天真的方法是这样的:
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 http://hackage.haskell.org/package/hetero-map,但是这个图书馆看起来有点破旧和陈旧。
正确执行此操作的方法是什么(希望没有其他库,仅使用 GHC 扩展)?
尝试使用正确的存在类型。
{-# LANGUAGE ExistentialQuantification #-}
data Elem = forall e. C e => Elem e
type HMap = Map Int Elem
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)