2011-04-30 61 views
5

我對Haskell比較新。我寫了一個卡片遊戲uno的克隆,我想要一張卡片的漂亮輸出。我做Haskell爲導入的數據類型派生額外的實例

import System.Console.ANSI 

提供

data Color = Black 
      | Red 
      | Green 
      | Yellow 
      | Blue 
      | Magenta 
      | Cyan 
      | White 
      deriving (Bounded, Enum, Show) 

現在我想補充推導(奧德式),以及,我可以在導入包的源文件中寫入這一點,但應該有一個更簡單的方法來做到這一點 我沒有線索什麼關鍵字谷歌或尋找一本書。

回答

4

無需編輯庫。在源文件中,狀態:

instance Eq Color where 
    x == y = fromEnum x == fromEnum y 

instance Ord Color where 
    compare x y = compare (fromEnum x) (fromEnum y) 

說明:fromEnum是返回intBlack -> 0Red -> 1等)上Enum功能。整數顯然是平等可比的,並且是有序的。

編輯:@風鈴草的版本,在評論,顯然是漂亮:

instance Eq Color where 
    (==) = (==) `on` fromEnum 

instance Ord Color where 
    compare = compare `on` fromEnum 
+0

對於讀類型類添加以下行 '比如讀出的彩色where¬ readsPrec _海峽= [ (顏色(c),t)|← (c,t)←讀取str]← 其中顏色x =「黑色」的情況x→黑色 「紅色」→紅色 「綠色」→綠色 「黃色」→黃色, 「Blue」→藍色 ...' – epsilonhalbe 2011-04-30 11:51:24

+1

使用'import Data.Function(on)':'instance Eq Color其中(==)=(==)\'from \'fromEnum','Ord Color比較= from \ from \ from \ from \「。 – rampion 2011-04-30 13:53:42

+6

他不能使用獨立派生自動派生Ord和Eq嗎? http://www.haskell.org/haskellwiki/GHC/Stand-alone_deriving_declarations – 2011-04-30 15:37:07