我正在尝试在 Haskell 中为我创建的新数据类型添加实例声明,但未成功。到目前为止我已经尝试过:
data Prediction = Prediction Int Int Int
showPrediction :: Prediction -> String
showPrediction (Prediction a b c) = show a ++ "-" ++ show b ++ "-" ++ show c
instance Show (Prediction p) => showPrediction p
似乎最后一行是错误的,但我不确定如何实现我想要的。基本上是能够从解释器调用预测变量并使其可视化,而无需调用 showPrediction。现在这有效:
showPrediction (Prediction 1 2 3)
并显示:
"1-2-3"
正如预期的那样,但我希望它能够工作(从解释器):
Prediction 1 2 3
有什么想法吗?
最佳答案
要派生实例,语法为
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]
也是如此。在这里,所有预测
都可以显示,因此无需担心。当您编写 instance Show (Prediction p) => showPrediction p
时,您犯了一些错误。首先,Prediction p
意味着 Prediction
是一种参数化类型(例如,由 data Prediction a = Prediction a a a
声明),它不是。其次,Show (Prediction p) =>
意味着如果 Prediction P
是可显示的,那么 你想要声明其他一些例子。第三,在 =>
之后,拥有一个函数是没有意义的——Haskell 想要一个类型类名。
此外,为了完整起见,如果您想要显示输出的 Prediction 1 2 3
格式,还有另一种派生 Show
的方法:
data Prediction = Prediction Int Int Int deriving Show
As specified in the Haskell 98 report ,只有少数类型可以通过这种方式派生:Eq
、Ord
、Enum
、Bounded
、显示
和读取
。与the appropriate GHC extensions ,您还可以派生 Data
、Typeable
、Functor
、Foldable
和 Traversable
;您可以派生任何由 newtype
的包装类型为 newtype
派生的类;您可以以独立的方式生成这些自动实例。
关于haskell - Show 的新实例声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4418017/