Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

haskell - New instance declaration for Show

I'm trying to add an instance declaration in Haskell for a new data type I've created unsuccessfully. Here what I've tried so far:

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

Seems the last line is wrong but I'm not sure how to achieve what I want. Basically is to be able to call from the interpreter a Prediction variable and get it visualized without having to call the showPrediction. Right now this works:

showPrediction (Prediction 1 2 3)

and shows:

"1-2-3"

as expected, but I would like this to work (from the interpreter):

Prediction 1 2 3

Any ideas?

question from:https://stackoverflow.com/questions/4418017/new-instance-declaration-for-show

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To derive an instance, the syntax is

instance ?preconditions? => Class ?type? where
  ?method? = ?definition?

So here, for instance, you'd have

instance Show Prediction where
  show (Prediction a b c) = show a ++ "-" ++ show b ++ "-" ++ show c

There's no precondition; you'd use that for something like instance Show a => Show [a] where ..., which says that if a is showable, then so is [a]. Here, all Predictions are showable, so there's nothing to worry about. When you wrote instance Show (Prediction p) => showPrediction p, you made a few mistakes. First, Prediction p implies that Prediction is a parametrized type (one declared by, for instance, data Prediction a = Prediction a a a), which it isn't. Second, Show (Prediction p) => implies that if Prediction P is showable, then you want to declare some other instance. And third, after the =>, having a function is nonsensical—Haskell wanted a type class name.

Also, for completeness's sake, there's another way to derive Show if you want the Prediction 1 2 3 format for displayed output:

data Prediction = Prediction Int Int Int deriving Show

As specified in the Haskell 98 report, there are only a handful of types which can be derived this way: Eq, Ord, Enum, Bounded, Show, and Read. With the appropriate GHC extensions, you can also derive Data, Typeable, Functor, Foldable, and Traversable; you can derive any class which a newtype's wrapped type derived for a newtype; and you can generate these automatic instances in a standalone way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...