我有這樣的代碼:轉換型家庭實例來詮釋
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