让我们有以下的数据类型:如何为幻像类型创建返回幻像类型的实例?
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中的一个。
有没有办法解决这个问题?
我试图用多参数型类和函数依赖来解决它。但是,我遇到了Int实例,因为它没有幻像类型,因此未定义类型的第二个参数。 – leo 2014-10-28 06:25:54