Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

haskell sum type multiple declaration error

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...