2016-01-06 78 views
2

我在Haskell下面的代碼:實例和類哈斯克爾

module Shape where 
type Height = Float 
type Width = Float 
type Radius = Float 
data Rectangle = Rectangle Height Width 
data Circle = Circle Radius 

class (Eq a, Show a) => Shape a where 
    area :: a -> Float 
    perimeter :: a -> Float 

instance Shape Rectangle where 
    area (Rectangle h w) = h * w 
    perimeter (Rectangle h w) = h*2 + w*2 
    show (Rectangle h w) = "rectangle " ++ (show h) ++ " " ++ (show w) 
    (==) (Rectangle h w) (Rectangle c d) = (h == c) && (w == d) 


instance Shape Circle where 
    area (Circle r) = pi * r**2 
    perimeter (Circle r) = 2 * pi * r 
    show (Circle r) = "circle " ++ (show r) 
    (==) (Circle r) (Circle x) = r == x 

,我想補充展和公式的情況下,以確定新的情況下(如矩形* ==矩形* *)但我得到以下問題:

[1 of 1] Compiling Shape   (Shape.hs, interpreted) 
Shape.hs:24:17: `show' is not a (visible) method of class `Shape' 
Shape.hs:25:17: `==' is not a (visible) method of class `Shape' 
Shape.hs:31:12: `show' is not a (visible) method of class `Shape' 
Shape.hs:32:12: `==' is not a (visible) method of class `Shape' 
Failed, modules loaded: none. 

這是什麼意思?我怎樣才能使它工作?


編輯: 現在的代碼: (線13至31)

instance Eq Rectangle where 
    (Rectangle h w) == (Rectangle c d) = (h == c) && (w == d) 

instance Show Rectangle where 
    show (Rectangle h w) = "rectangle " ++ (show h) ++ " " ++ (show w) 

instance Shape Rectangle where 
    area (Rectangle h w) = h * w 
    perimeter (Rectangle h w) = h*2 + w*2 

instance Eq Circle where 
    (Circle r) == (Circle x) = r == x 

instance Show Circle where 
    show (Circle r) = "circle " ++ (show r) 

instance Shape Circle where 
    area (Circle r) = pi * r**2 
    perimeter (Circle r) = 2 * pi * r 

錯誤:

[1 of 1] Compiling Shape   (Shape.hs, interpreted) 
Shape.hs:19:5: parse error on input `instance' 
Failed, modules loaded: none. 
+1

'Float'並不是'Eq'的真正*合法實例。這不涉及你目前的問題,但它可能會導致你的麻煩。如果切換到像Rational這樣的更好類型的類型(來自'Data.Ratio'),那麼通常會遇到更少的陷阱(但不能採用平方根等)。 – dfeuer

+0

如果你想定義「標準」實例,不要忘記嘗試'導出(Show,Eq)'。對於自定義的,你必須編寫你自己的代碼。 – chi

回答

6

拆分出每種類型的實例,並且每個類型類它是一個實例。

instance Eq Rectangle where 
    (==) (Rectangle h w) (Rectangle c d) = (h == c) && (w == d) 
instance Show Rectangle where 
    show (Rectangle h w) = "rectangle " ++ (show h) ++ " " ++ (show w) 
instance Shape Rectangle where 
    area (Rectangle h w) = h * w 
    perimeter (Rectangle h w) = h*2 + w*2 

這只是每種類型的show==定義不是Shape實例的一部分,他們爲ShowEq這恰好是Shape依賴類型類實例的一部分。

+0

我改變它完全像你說的,我得到這個錯誤:'[1的1]編譯形狀(Shape.hs,解釋) Shape.hs:19:5:解析錯誤輸入'實例' 失敗,模塊加載:無。' – xBlackout

+0

哪一行是第19行?它之前有什麼?這表明缺少括號或其他語法錯誤。 –

+0

顯示帖子。我編輯它 – xBlackout