У меня есть следующий код в Haskell:Инстансы и класс в 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
, и я хочу, чтобы добавить экземпляры Show и уравнения для того, чтобы определить новые случаи (например, прямоугольник * * == Прямоугольник * *), но у меня возникает следующая проблема:
[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.
Что это значит? И как я могу заставить его работать?
EDIT: Теперь код: (строка 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'), вы столкнетесь с меньшим количеством gotchas вообще (но не сможете принимать квадратные корни и т. Д.). – dfeuer
Если вы хотите определить «стандартные» экземпляры, не забудьте попробовать «geting (Show, Eq)». Для пользовательских, вам нужно написать свой собственный код. – chi