[Haskell-beginners] Type unions

Russ Abbott russ.abbott at gmail.com
Tue Dec 14 21:44:32 CET 2010


I guess the point is that you can't put type names into the declaration of
some other type.

data A = ...
data B = ...

-- No good
data AorB = A | B
f :: Int -> AorB
f x
  | even x    = Aconstructor x
  | otherwise = Bconstructor x

-- OK
data AorB = AType A | BType B
f :: Int -> AorB
f x
  | even x    = AType $ Aconstructor x
  | otherwise = BType $ Bconstructor x


What's confusing is that


data AorB = A | B

compiles with error.

That raises the question of what it really means!

*-- Russ*
***
*
**


On Tue, Dec 14, 2010 at 12:35 PM, Tobias Brandt
<tob.brandt at googlemail.com>wrote:

> On 14 December 2010 21:26, Russ Abbott <russ.abbott at gmail.com> wrote:
> > Isn't "Either" the same thing as AorB in
> >
> > data AorB = Aconstructor Int | Bconstructor Int
> >
> > I want two separate types A and B along with a third type which is their
> > Union. Is that not possible?
>
> That's exactly what either is:
>
> data A = ...
> data B = ...
>
> f :: Int -> Either A B
>
> > In my actual case, I have more than two types.  So I would like a way to
> > take the union of an arbitrarily number of types.
> >
> > data Union = A1 | A2 | ...
> >
> > where each of A1, A2, ... has its own data declaration.
>
> You can create a new data type:
>
> data MyUnion = First A1 | Second A2 | Third A3
>
> and use it like this:
>
> f :: Int -> MyUnion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20101214/524f6d2f/attachment.htm>


More information about the Beginners mailing list