问题
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?
回答1:
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")
]
回答2:
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.)
回答3:
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
来源:https://stackoverflow.com/questions/10553803/encapsulating-data-definitions-in-haskell