我正在尝试在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
Run Code Online (Sandbox Code Playgroud)
似乎最后一行是错误的,但我不确定如何实现我想要的.基本上是能够从解释器调用一个Prediction变量并使其可视化而无需调用showPrediction.现在这个工作:
showPrediction (Prediction 1 2 3)
Run Code Online (Sandbox Code Playgroud)
并显示:
"1-2-3"
Run Code Online (Sandbox Code Playgroud)
正如所料,但我希望这可以工作(来自翻译):
Prediction 1 2 3
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
Ant*_*sky 58
要派生实例,语法是
instance «preconditions» => Class «type» where
«method» = «definition»
Run Code Online (Sandbox Code Playgroud)
所以在这里,例如,你有
instance Show Prediction where
show (Prediction a b c) = show a ++ "-" ++ show b ++ "-" ++ show c
Run Code Online (Sandbox Code Playgroud)
没有先决条件; 你会将它用于类似的东西instance Show a => Show [a] where ...,它表示如果 a可以展示,那么就是这样[a].在这里,所有Predictions都是可以展示的,所以没有什么可担心的.当你写作时instance Show (Prediction p) => showPrediction p,你犯了一些错误.首先,Prediction p暗示这Prediction是一个参数化类型(例如,由一个声明的类型data Prediction a = Prediction a a a),它不是.其次,Show (Prediction p) =>暗示如果 Prediction P是可显示的,那么你想要声明一些其他实例.第三,在=>具有一个功能是无意义的之后--Haskell想要一个类型类名.
此外,为了完整起见,Show如果您想要Prediction 1 2 3显示输出的格式,还有另一种方法可以派生:
data Prediction = Prediction Int Int Int deriving Show
Run Code Online (Sandbox Code Playgroud)
正如哈斯克尔98报告指定的,目前只有可得出这样的类型屈指可数:Eq,Ord,Enum,Bounded,Show,和Read.有了适当的GHC的扩展,你也可以得到Data,Typeable,Functor,Foldable,和Traversable; 你可以派生出任何一个newtype派生类型的类newtype; 并且您可以以独立方式生成这些自动实例.
sep*_*p2k 14
你有实例的语法错误.要创建Show写入实例:
instance Show Foo where
show = ...
-- or
show x = ...
Run Code Online (Sandbox Code Playgroud)
其中...包含您的show函数定义Foo.
所以在这种情况下你想要:
instance Show Prediction where
show = showPrediction
Run Code Online (Sandbox Code Playgroud)
或者,因为根本没有重要的理由showPrediction:
instance Show Prediction where
show (Prediction a b c) = show a ++ "-" ++ show b ++ "-" ++ show c
Run Code Online (Sandbox Code Playgroud)
小智 6
将最后一行替换为:
instance Show Prediction where
show = showPrediction
Run Code Online (Sandbox Code Playgroud)