Class Haskell中的实例和类

Class Haskell中的实例和类,class,haskell,instance,Class,Haskell,Instance,我在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

我在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的实例,以便定义新的案例(例如矩形**==矩形**),但我遇到了以下问题:

[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行)

错误:

[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
的typeclass实例的一部分,恰好是
Shape
的依赖项,我完全按照你说的那样更改了它,我得到了这个错误:“[1/1]编译Shape(Shape.hs,已解释)Shape.hs:19:5:输入'instance'的解析错误失败,加载的模块:无。'哪一行是第19行?什么在它之前?这表明缺少括号或其他语法错误。@xBlackout我对该代码没有任何问题,我不确定发生了什么事?这个问题与制表有关,而不是与代码错误有关。谢谢大家!
Float
实际上不是
Eq
的合法实例。这与你目前的问题无关,但很可能会给你带来麻烦。如果您切换到行为更好的类型,如
Rational
(从
Data.Ratio
),通常会遇到更少的gotcha(但不能求平方根等)。如果您想定义“标准”实例,不要忘了尝试
派生(Show,Eq)
。对于定制的,您必须编写自己的代码。
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