首页 > 解决方案 > Haskell 中的类型重用

问题描述

我试图让类型Shape重新使用类型CircleRectangle

data Point = Point {
    x :: Float,
    y :: Float
} deriving (Show)

data Circle = Circle {
    c :: Point,
    r :: Float
} deriving (Show)

data Rectangle = Rectangle {
    p1 :: Point,
    p2 :: Point
} deriving (Show)

-- the following obviously doesn't compile
data Shape = Circle Circle | Rectangle Rectangle deriving (Show)

以上导致编译错误

Multiple declarations of ‘Circle’
18 | data Shape = Circle Circle | Rectangle Rectangle deriving (Show)
   |              ^^^^^^^^^^^^^
...
Multiple declarations of ‘Rectangle’
18 | data Shape = Circle Circle | Rectangle Rectangle deriving (Show)
   |                              ^^^^^^^^^^^^^^^^^^^

如何声明一个类型Shape,它将是所有可能的不同形状(如CircleRectangle)的联合,以便我能够在后续函数中使用它们,如下所示?

area :: Shape -> Float
area (Circle _ r) = pi * r * 2
area (Rectangle p1 p2) = abs (x p2 - x p1) * abs (y p2 - y p1)

标签: haskelltypes

解决方案


data Circle = Circle ... -- one
data Shape  = Circle ... -- two

您正在尝试定义两个名为Circle的单独数据构造函数:一个用于数据类型Circle,另一个用于数据类型Shape。你不能在同一个模块中做到这一点(至少没有一些高级语言扩展)。重命名Circle右侧的 s 之一=。左边的数据类型=还是可以Circle的,没有冲突。


推荐阅读