Reputation:
I am trying to define a data type using other data types like this:
data A = Something String | SomethingElse Int
data B = Another B | YetAnother A
data C = A | B
x :: [ C ]
x = [ YetAnother (SomethingElse 0), Something "Hello World" ]
But this is giving me an error saying that I cannot have a type A when expecting a type B. Why is this?
Upvotes: 1
Views: 483
Reputation: 53705
Haskell does not have true "union" types, unions in Haskell must be tagged with constructors. (see Wikipedia > Tagged union).
Either is the general-purpose tagged union type in Haskell, where data is tagged as Left
or Right
.
data Either a b = Left a | Right b
Upvotes: 0
Reputation: 61439
The A
and B
in data C = A | B
are declarations of new data constructors, not references to your existing types A
and B
. (Constructors are not optional in data
declarations.)
Upvotes: 4
Reputation: 137987
You're missing the data constructors for C
.
data A = Something String
| SomethingElse Int
data B = Another B
| YetAnother A
data C = C0 A
| C1 B
x :: [ C ]
x = [ C1 (YetAnother (SomethingElse 0))
, C0 (Something "Hello World")
]
Upvotes: 7