haskell求和型多重声明错误 [英] haskell sum type multiple declaration error
问题描述
数据A = A
数据B = B
数据AB = A | B
从A和B得到AB类型的和。
但最后一行会导致编译错误multiple declarations的B
我也试过这样的:
data A = Int | Bool
编译。但为什么ghc不允许我为用户定义的类型创建和类型?
你被骗了。你认为当你写数据A = Int | Bool
时,你认为类型 A
的值可以是一个类型 Int
的值或类型 Bool
的值;但实际上你所说的是有两个新的值级构造函数,分别是 Int
和 Bool
,每个都不包含任何信息,类型 A
。同样,您认为 data AB = A | B
表示您可以是 A
类型或 B
,但实际上你说你可以拥有值 A
或值 B
。
要记住的关键是有两个命名空间,type-level和术语级别,并且它们是截然不同的。
以下是一个简单的示例:
data A = A
data B = B
data AB = LA | RB
最后一行声明两个新的术语级构造函数, L
和 R
。 L
构造函数的值为 type A
,而 R
构造函数的值为 type B
。
<您可能还喜欢
或者
类型,定义如下: 数据ab =左a |右b
你可以用它来实现你的 AB
如果你想要的话:
type AB = AB
类似地,您可以使用 Either Bool
作为 Int
和 Bool
。
data A=A
data B=B
data AB=A|B
Which makes a sum type AB from A and B.
but the last line induces a compile error "multiple declarations of B"
I also tried sth like this:
data A=Int|Bool
It compiles. but why ghc disallows me from making sum types for user-defined types?
You're getting fooled. You think when you write data A=Int|Bool
that you are saying that a value of type A
can be a value of type Int
or a value of type Bool
; but what you are actually saying is that there are two new value-level constructors named Int
and Bool
, each containing no information at all, of type A
. Similarly, you think that data AB=A|B
says you can either be of type A
or type B
, but in fact you are saying you can either have value A
or value B
.
The key thing to keep in mind is that there are two namespaces, type-level and term-level, and that they are distinct.
Here is a simple example of how to do it right:
data A=A
data B=B
data AB=L A|R B
The last line declares two new term-level constructors, L
and R
. The L
constructor carries a value of type A
, while the R
constructor carries a value of type B
.
You might also like the Either
type, defined as follows:
data Either a b = Left a | Right b
You could use this to implement your AB
if you wanted:
type AB = Either A B
Similarly, you could use Either Int Bool
for your tagged union of Int
and Bool
.
这篇关于haskell求和型多重声明错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!