当前位置:  开发笔记 > 编程语言 > 正文

Haskell中的实例和类

如何解决《Haskell中的实例和类》经验,为你挑选了1个好方法。

我在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.

Louis Wasser.. 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.



1> Louis Wasser..:

拆分每种类型的实例和每个类型类的实例.

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.

推荐阅读
刘美娥94662
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有