haskell - Haskell 中的类型重用
问题描述
我试图让类型Shape
重新使用类型Circle
和Rectangle
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
,它将是所有可能的不同形状(如Circle
或Rectangle
)的联合,以便我能够在后续函数中使用它们,如下所示?
area :: Shape -> Float
area (Circle _ r) = pi * r * 2
area (Rectangle p1 p2) = abs (x p2 - x p1) * abs (y p2 - y p1)
解决方案
data Circle = Circle ... -- one
data Shape = Circle ... -- two
您正在尝试定义两个名为Circle
的单独数据构造函数:一个用于数据类型Circle
,另一个用于数据类型Shape
。你不能在同一个模块中做到这一点(至少没有一些高级语言扩展)。重命名Circle
右侧的 s 之一=
。左边的数据类型=
还是可以Circle
的,没有冲突。
推荐阅读
- git - 如何将 core.sshCommand 选项传播到子模块更新?
- c# - 在应用服务层访问 HttpContext
- visual-studio-code - vscode 查找选项卡始终转到要包含的文件
- docker - Docker克隆mysql镜像进行备份
- sql - 如何在我的 T-SQL 查询的过滤条件中实现“小于”和“IN”的逻辑?
- shell - 使用 sed 替换文件中的版本
- string - Shell 脚本 - 如何从 sting "T=50" 中获得 50?
- google-maps - 如何使用 Google Maps For Flutter 将初始相机位置设置为当前设备的经纬度
- javascript - Puppeteer 无限滚动
- angular - 使用 httpClient 和 Angular 下载 .tar 文件