[Haskell-beginners] Type unions

Hector Guilarte hectorg87 at gmail.com
Tue Dec 14 21:56:49 CET 2010


Hello,

Nobody has explained you why that doesn't compile...

Here's the deal

Suppose you have a data A which has a constructor named B and a Int

> data A = B Int

now suppose you have a data C which has a constructor named A and a Int

> data C = A Int

that compiles because the name of your data type is different from
the constructor,

that is, the names of the data types and the constructors they have are in
different
scopes, so for doing what you want, you would need to do:

> data A = Aconstructor Int
> data B = Bconstructor Int
> data AorB = A A  | B B

Where the first A is a constructor named A and the second references a data
type A,
idem for B

Hope that helps you,

Héctor Guilarte

On Tue, Dec 14, 2010 at 3:39 PM, Russ Abbott <russ.abbott at gmail.com> wrote:

> Is there a way to get this to work?
>
>  data A = Aconstructor Int
> data B = Bconstructor Int
> data AorB = A | B
>
> f :: Int -> AorB
> f x
>   | even x     = Aconstructor x
>   | otherwise = Bconstructor x
>
>  I get this diagnostic.
>
> Couldn't match expected type `AorB' against inferred type `A'
>
>
> Since AorB is A or B, why is this not permitted?
>
> If instead I write
>
> data AorB = Aconstructor Int | Bconstructor Int
>
>
> everything works out ok. But what if I want separate types for A and B?
>
> Thanks,
> *
> -- Russ *
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20101214/1ae1d262/attachment-0001.htm>


More information about the Beginners mailing list