【发布时间】:2014-12-23 11:42:50
【问题描述】:
让我们有以下数据类型:
data Foo1 a = Foo1
data Foo2 a = Foo2 (Foo3 a)
data Foo3 a = C1 (Foo1 a) | C2 Int
现在我们希望能够从 Foo1 或 Int 中获取 Foo3。 一个解决方案可能是使用类型类:
class ToFoo3 a where
toFoo3 :: a -> Foo3 b -- Here start the problems with this phantom type b...
instance ToFoo3 (Foo1 b) where
toFoo3 foo1 = C1 foo1
instance ToFoo3 Int where
toFoo3 int = C2 int
这里编译器抱怨(正确!)它无法将 b 与 b1 匹配,因为类定义中 Foo3 的“b”与实例中 Foo1 的“b”不同。
有没有办法解决这个问题?
【问题讨论】:
-
我尝试使用多参数类型类和函数依赖来解决它。但是,我被 Int 实例卡住了,因为它没有幻像类型,因此类型类的第二个参数是未定义的。
标签: haskell typeclass phantom-types