[英]Instances and class in 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和Eq的实例以定义新的情况(例如Rectangle * * == Rectangle * *),但是出现以下问题:
[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.
为每个类型和作为其实例的每个类型类拆分实例。
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
实例的一部分,它们是Show
和Eq
的类型类实例的一部分,它们恰好是Shape
依赖项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.