2
我定義了一個簡單的列表類型:「實例」的具體類型而不是typeclass?
data MyList a = End
|Entry a (MyList a)
而不是deriving (Show)
我實現明確自己所有MyList a
其中a
是Show
一個實例。
instance Show a => Show (MyList a)
where show End = ""
show (Entry a l) = (show a) ++","++(show l)
這工作得很好。現在我想改變這種只有MyList String
是Show
一個實例,並且這樣做,我寫
instance Show (MyList String)
where show End = ""
show (Entry a l) = a ++","++(show l)
,但是這導致的錯誤,我不明白:
Illegal instance declaration for `Show (MyList String)'
(All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.
Use FlexibleInstances if you want to disable this.)
In the instance declaration for `Show (MyList String)'
能
人解釋爲什麼這不起作用,這個錯誤告訴我什麼?
因此,如果不啓用'FlexibleInstances',我只能爲整個類型類指示'show',但不能指定特定類型? – flawr
對於一個類型構造函數(例如你的'MyList :: * - > *'),你只能對類MyList a''的整個「類型族」一次性實現類(例如'Show')特定的個人喜歡'MyList String'或'MyList Bool'。 – kirelagin
順便說一下,這就是爲什麼'Show'具有hacky ['showList']的原因(https://hackage.haskell.org/package/base-4.9.1.0/docs/Prelude.html#v:showList ) 方法。你想顯示不同於所有其他類型列表的'Char'列表,但是你不能在標準Haskell中單獨實現一個單獨的'Show [Char]'實例。 – kirelagin