2011-05-28 95 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