我有这样的代码:转换型家庭实例来诠释
type family Id obj :: *
type instance Id Box = Int
我想让它,所以我总是可以从ID类型的家庭得到诠释。我承认需要进行转换。
我想也许创建一个类将工作:
class IdToInt a where
idToInt :: Id a -> Int
instance IdToInt Box where
idToInt s = s
这实际上编译。但是,当我尝试使用它:
testFunc :: Id a -> Int
testFunc x = idToInt x
我得到错误:
src/Snowfall/Spatial.hs:29:22:
Couldn't match type `Id a0' with `Id a'
NB: `Id' is a type function, and may not be injective
In the first argument of `idToInt', namely `x'
In the expression: idToInt x
In an equation for `testFunc': testFunc x = idToInt x
所以,我怎样才能创建一个类型系列ID来获得一个int转换?
基于由ehird答案,我尝试以下,但它不工作之一:
class IdStuff a where
type Id a :: *
idToInt :: Id a -> Int
instance IdStuff Box where
type Id Box = Int
idToInt s = s
testFunc :: (IdStuff a) => Id a -> Int
testFunc x = idToInt x
它提供了错误:
src/Snowfall/Spatial.hs:45:22:
Could not deduce (Id a0 ~ Id a)
from the context (IdStuff a)
bound by the type signature for
testFunc :: IdStuff a => Id a -> Int
at src/Snowfall/Spatial.hs:45:1-22
NB: `Id' is a type function, and may not be injective
In the first argument of `idToInt', namely `x'
In the expression: idToInt x
In an equation for `testFunc': testFunc x = idToInt x
谢谢。我仍然没有得到它。我根据你在问题中的回答发布了我的结果,以便它能够正确格式化。 – mentics 2012-03-14 16:55:37
@taotree:哦,那是因为你正在使用类型同义词族,而不是数据类型族。这个具体的问题实际上可能是一个bug,但总的来说,类型同义词族很没用;因为两个实例完全可能具有相同的关联类型,所以GHC几乎放弃了推演任何事情,并最终导致混乱。使用数据类型系列将解决所有这些问题。 – ehird 2012-03-14 16:59:44