开发者

instance of show variables

Is it possible to use a variable like below?

instance Show Box where
        show (Contents x y z) = "Contents " ++ x ++ " items, " ++ y ++ " items and " ++ z ++ " items"

This doesnt compile, have i added the string together wrong, or this generally not possible?

Im trying to write a show function that has the following effect;

EXAMPLE: show (Con开发者_C百科tents 2 4 5) results in the string "Contents 2 boxes, 4 parcels and 5 letters".


I guess you have something like this:

data Box = Contents Integer Integer Integer

Since Integer has a Show-instance, just try the following: (And BTW, using (.) here, is more efficient than using ++)

instance Show Box where 
  showsPrec _ (Contents x y z) = showString "Contents " . shows x . 
                                 showString " items, " . shows y . 
                                 showString "items and " . shows z . 
                                 showString "items"


It is possible, and your implementation is correct, but make sure that x, y and z are Strings first. (If not, show them.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜