2011-05-28 92 views
1

是否可以使用像下面这样的变量?显示变量的实例

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

这没有编译,有没有我加错了字符串,或者这通常不可能?

我试图写一个显示功能,具有以下效果;

示例:show(内容2 4 5)导致字符串“Contents 2 boxes,4 parcels and 5 letters”。

回答

4

我想你有这样的事情:

data Box = Contents Integer Integer Integer

由于IntegerShow -instance,只是尝试以下方法:(和BTW,使用(.)这里,比使用++更有效)

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

这是可能的,你的实现是正确的,但要确保xyzString第一。 (如果没有,show他们)

+0

XYZ将是数字,是一个问题 – Lunar 2011-05-28 18:39:58

+0

@Lunar:是的,它是。 – kennytm 2011-05-28 18:40:41

+0

@Lunar'“Contents”++(show x)++ ...' – 2011-05-28 18:48:49