讓我們有以下的數據類型:如何爲幻像類型創建返回幻像類型的實例?
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