我在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.
'Float'並不是'Eq'的真正*合法實例。這不涉及你目前的問題,但它可能會導致你的麻煩。如果切換到像Rational這樣的更好類型的類型(來自'Data.Ratio'),那麼通常會遇到更少的陷阱(但不能採用平方根等)。 – dfeuer
如果你想定義「標準」實例,不要忘記嘗試'導出(Show,Eq)'。對於自定義的,你必須編寫你自己的代碼。 – chi