允许数据构造函数的多个声明 [英] Allowing multiple declarations of data constructors
问题描述
我目前正在试验数据类型,但遇到了涉及数据构造函数的多个声明的问题.
I am currently experimenting with data types and I've ran into an issue involving multiple declarations of data constructors.
data DBPosition = Unknown
| Omega Integer
| Delta Integer
deriving (Show, Eq, Ord)
data DBGeometry = Unknown | Cis | Trans
deriving (Show, Eq, Ord)
data DoubleBond = DoubleBond DBPosition DBGeometry
deriving (Show, Eq, Ord)
如果我要输入-let bond = DoubleBond Unknown Unknown
之类的值,则可以推断出第一个Unknown
具有DBPosition
类型,而第二个Unknown
具有DBPosition
类型.不幸的是,情况并非如此:
If I was to make a value such as - let bond = DoubleBond Unknown Unknown
, then it could be inferred that the first Unknown
has a type of DBPosition
while the second Unknown
has a type of DBPosition
. Unfortunately this is not the case:
test.hs:6:27:
Multiple declarations of `Unknown'
Declared at: test.hs:1:27
test.hs:6:27
Failed, modules loaded: none.
有没有可用于解决此问题的语言扩展?
Are there any language extensions that can be used to get around this?
推荐答案
正如Carsten所指出的,您的定义不起作用,因为您有两个名称相同的构造函数.您需要使用例如UnknownDBPosition
和UnknownDBGeometry
.但是,我认为更好的解决方案是通过识别:
As Carsten pointed out above, your definition does not work because you have two constructors with the same name. You'd need to use e.g. UnknownDBPosition
and UnknownDBGeometry
. However, I'd argue a better solution arises from recognising:
- 无论您谈论的是双键位置,几何形状还是其他任何事物,未知值的概念都以完全相同的方式起作用;和
-
Unknown
实际上不是各种双键几何形状或位置.
- That the concept of an unknown value works in precisely the same way no matter if you are talking about double bond positions, geometries, or whatever else; and
- That
Unknown
is not actually a variety of double bond geometry or position.
既然如此,我建议您同时删除Unknown
和使用Maybe
来指定知识不足.
That being so, I recommend that you remove both Unknown
and use Maybe
to specify lack of knowledge.
data DBPosition = Omega Integer
| Delta Integer
deriving (Show, Eq, Ord)
data DBGeometry = Cis | Trans
deriving (Show, Eq, Ord)
data DoubleBond = DoubleBond (Maybe DBPosition) (Maybe DBGeometry)
deriving (Show, Eq, Ord)
这篇关于允许数据构造函数的多个声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!