Vla*_*eev 8 polymorphism haskell existential-type higher-rank-types
我需要一个可以包含任意值的映射,只要它们的类型具有相同的类型类.我的第一个天真的方法是这样的:
type HMap = forall a . MyClass a => M.Map Int a
Run Code Online (Sandbox Code Playgroud)
但它似乎不起作用:以下代码给出了编译错误:
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" }
Run Code Online (Sandbox Code Playgroud)
我认为我需要特殊的异构集合,但奇怪的是我除了这个之外在谷歌找不到任何东西,但是这个库似乎有点邋and和陈旧.正确执行此操作的方式是什么(希望没有其他库,仅使用GHC扩展)?
尝试使用适当的存在类型.
{-# LANGUAGE ExistentialQuantification #-}
data Elem = forall e. C e => Elem e
type HMap = Map Int Elem
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
538 次 |
| 最近记录: |