异构地图 [英] Heterogeneous map

查看:125
本文介绍了异构地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个可以包含任意值的映射,只要它们的类型是相同的类型类型。我的第一个幼稚的方法是这样的:

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

我以为我需要特殊的异构集合,但奇怪的是我找不到除了这个以外的任何Google,但是这个库似乎有点sc and和旧。
这样做的方式是什么(希望没有其他库,只使用GHC扩展)?

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

这篇关于异构地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆