要派生实例,语法为
instance «preconditions» => Class «type» where
«method» = «definition»
所以在这里,例如,你会有
instance Show Prediction where
show (Prediction a b c) = show a ++ "-" ++ show b ++ "-" ++ show c
没有先决条件;你会用它来做类似的事情instance Show a => Show [a] where ...
,这说明了if a
是可显示的,那么也是[a]
。在这里,所有Predictions
是可以展示的,所以没有什么可担心的。当你写下instance Show (Prediction p) => showPrediction p
,你犯了一些错误。第一的,Prediction p
暗示Prediction
是一种参数化类型(例如,通过以下方式声明的类型)data Prediction a = Prediction a a a
),但事实并非如此。第二,Show (Prediction p) =>
暗示if Prediction P
是可显示的,then你想声明一些其他实例。第三,之后=>
,拥有一个函数是没有意义的——Haskell 想要一个类型类名。
另外,为了完整起见,还有另一种方法可以导出Show
如果你想要Prediction 1 2 3
显示输出的格式:
data Prediction = Prediction Int Int Int deriving Show
正如 Haskell 98 报告中所指定的 http://www.haskell.org/onlinereport/decls.html#derived-decls,只有少数类型可以通过这种方式派生:Eq
, Ord
, Enum
, Bounded
, Show
, and Read
. With 适当的 GHC 扩展 http://www.haskell.org/ghc/docs/latest/html/users_guide/deriving.html,你还可以推导出Data
, Typeable
, Functor
, Foldable
, and Traversable
;你可以派生任何类newtype
的包装类型派生为newtype
;您可以以独立的方式生成这些自动实例。