class - Haskell 中的实例和类

标签 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 -> 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 行)

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 实例的一部分,而是ShowEq 的类型类实例恰好是 Shape 的依赖项。

关于class - Haskell 中的实例和类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34641364/

相关文章:

c++ - 需要快速帮助 基类未定义

c# - 重载 Console.ReadLine 可能吗? (或任何静态类方法)

macos - 如何在 OSX El Capitan 上运行 Haskell

java - 无法创建构造函数

python - 创建具有相同属性的方法

haskell - 无法推断 (m ~ m1)

haskell - 如何为三级类型构造函数 (ext3) 的类型扩展定义 SYB 函数?

java - 创建新实例 SQLITE 时出现错误

java - 如果使用相同的值构造,则使用现有实例

c# List<t> 在一个类中