haskell - 创建相同类型但不同类型的值列表
问题描述
我是 Haskell 的新手,正在尝试做一些我确信很容易的事情,但我没有看到正确的方法。
我想要的是一个特定类型类的值列表,但该类型类的不同类型。例如:
class Shape a where
area :: a -> Double
numVertices :: a -> Integer
data Triangle = Triangle {...}
data Square = Square {...}
instance Shape Triangle where ...
instance Shape Square where ...
x = [Triangle (...), Square (...)]
我收到编译器错误,因为列表具有不同的类型。做我在这里想做的事情的正确方法是什么?我唯一能想到的就是做这样的事情:
data WrappedShape = WrappedShape {
getArea :: () -> Double
, getNumVertices :: () -> Integer
}
wrap s = WrappedShape {
getArea = \ () -> area s
, getNumVertices = \ () -> vertices s
}
x = [wrap (Triangle (...)), wrap (Square (...))]
这可行,但它在样板中很重,因为我必须有效地定义 Shape 两次并且使用不同命名的成员。做这种事情的标准方法是什么?
解决方案
如果你只需要几个不同的形状,你可以枚举每个形状作为构造函数,这里是一个例子:
data SomeShapes = Triangle {...}
| Square {...}
instance Shape SomeShapes where
area (Triangle x) = ...
area (Square x) = ....
现在你可以把它们放在一个列表中,因为它们是相同类型的 SomeShapes
[Triangle {...}, Square {...}]
推荐阅读
- regex - 正则表达式 - 使用可选字符解析日期
- image - 如何在 Matlab 中保存图像以获得指定的输出尺寸?
- facebook-graph-api - Facebook Graph Api v3.0 如何获取用户权限?
- react-native - 如何使用 cocoapods 安装 react-native-onesignal ???
- typescript - 成功将图像保存到firebase云存储后,firebase函数获取下载url
- sql-server - OrderBy 在 LINQ 中没有任何影响
- java - Spring读取类路径外的属性文件
- excel - 如何在excel的“文本到列”中使用两个斜杠?
- actions-on-google - 是否可以使用琐事(模板之一)从 google 项目的操作中发送 HTTP 请求?
- android - 将数据保存在共享首选项中而不覆盖旧数据