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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…