2010-12-11 62 views
20

我想在Haskell中爲我創建的新數據類型添加實例聲明失敗。在這裏,我已經嘗試到目前爲止: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 

似乎最後一行是錯誤的,但我不知道如何實現我想要的。基本上就是能夠從解釋器調用Prediction變量並使其可視化而不必調用showPrediction。現在這個工程:

showPrediction (Prediction 1 2 3) 

,並顯示:

"1-2-3" 

如預期,但我想這(從解釋)工作:

Prediction 1 2 3 

任何想法?

回答

44

爲了得到一個實例,語法是

instance «preconditions» => Class «type» where 
    «method» = «definition» 

因此,在這裏,例如,你會有

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

沒有先決條件;你會用它來做類似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 

As specified in the Haskell 98 report,只有一個類型的極少數可以得出這樣:EqOrdEnum,Bounded,ShowRead。使用the appropriate GHC extensions,您也可以派生出Data,Typeable,Functor,FoldableTraversable;你可以派生出newtype的包裝類型爲newtype;並且可以以獨立方式生成這些自動實例。

+0

++高質量,深入,全面的答案。 – delnan 2010-12-11 17:56:54

+0

感謝您的好回覆! 「派對秀」也很完美。很高興知道 ;)) – 2010-12-11 17:58:18

10

你有錯誤的實例的語法。要創建Show寫的一個實例:

instance Show Foo where 
    show = ... 
    -- or 
    show x = ... 

其中...包含您的show功能Foo的定義。

因此,在這種情況下,你想:

instance Show Prediction where 
    show = showPrediction 

,或者因爲沒有有showPrediction在所有的重要原因:

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

是啊,這是它。非常感謝答覆! :)) – 2010-12-11 17:53:28

4

替換爲你的最後一行:

instance Show Prediction where 
    show = showPrediction