Haskell Show的新实例声明
我正在尝试在Haskell中为我创建的新数据类型添加实例声明,但未成功。以下是我迄今为止所做的尝试:Haskell Show的新实例声明,haskell,Haskell,我正在尝试在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) => show
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"
正如预期的那样,但我希望这能起作用(来自口译员):
有什么想法吗?实例的语法有误。要创建
Show
write的实例,请执行以下操作:
instance Show Foo where
show = ...
-- or
show x = ...
其中,…
包含您对Foo
的show
函数的定义
因此,在这种情况下,您需要:
instance Show Prediction where
show = showPrediction
或者,因为根本没有重要的理由进行showPrediction
:
instance Show Prediction where
show (Prediction a b c) = show a ++ "-" ++ show b ++ "-" ++ show c
要派生实例,语法为
instance «preconditions» => Class «type» where
«method» = «definition»
例如,在这里,你会
instance Show Prediction where
show (Prediction a b c) = show a ++ "-" ++ show b ++ "-" ++ show c
没有先决条件;您可以将其用于实例Show a=>Show[a]where…
,这表示如果a
是可显示的,那么[a]
也是可显示的。在这里,所有的预测
都是可以显示的,所以没有什么好担心的。编写实例显示(预测p)=>showPrediction p
时,您犯了一些错误。首先,Prediction p
意味着Prediction
是一种参数化类型(例如,data Prediction a=Prediction a
声明的类型),而它不是。其次,Show(Prediction p)=>
意味着如果Prediction p
是可显示的,那么您需要声明一些其他实例。第三,在=>
之后,拥有一个函数是毫无意义的,Haskell想要一个类型类名
此外,为了完整性起见,如果您想要显示输出的Prediction 1 2 3
格式,还有另一种推导Show
的方法:
data Prediction = Prediction Int Int Int deriving Show
,只有少数类型可以通过这种方式派生:
Eq
、Ord
、Enum
、Bounded
、Show
和Read
。使用,您还可以派生数据
,可键入
,函子
,可折叠
,以及可遍历
;您可以派生newtype
的包装类型为newtype
派生的任何类;您可以以独立方式生成这些自动实例。将最后一行替换为:
instance Show Prediction where
show = showPrediction
是的,就是这样。非常感谢您的回复!:)++高质量、深入、全面的回答。谢谢您的回复!“衍生秀”也非常成功。很高兴知道;)
instance Show Prediction where
show = showPrediction