Home > Net >  Haskell - Why do multiple declarations not work?
Haskell - Why do multiple declarations not work?

Time:12-05

I was trying to do a task, but when I tried to do this:

data Fruit  = Pear | Orange | Apple | Banana
data Colour = Red | Orange | Yellow | Green

I got an error. What is the problem? Why can I not use Orange twice?

CodePudding user response:

In the code you provided, you are defining two different data types, Fruit and Colour, each with their own set of possible values. However, you are using the same value, Orange, for two different cases in these data types. This is not allowed in many programming languages, including Haskell, because it can lead to ambiguity and confusion.

For example, if you have a variable of type Fruit that is assigned the value Orange, how does the compiler know if you are referring to the Orange case of the Fruit data type or the Orange case of the Colour data type? In order to avoid this ambiguity, most programming languages do not allow you to use the same value for multiple cases in different data types.

One way to solve this problem is to use different names for the cases that have the same value, such as FruitOrange and ColourOrange. This makes it clear which case you are referring to, and eliminates the ambiguity. For example:

data Fruit  = Pear | FruitOrange | Apple | Banana
data Colour = Red | ColourOrange | Yellow | Green

Alternatively, you could use a type alias to give the same type a different name, which would also avoid the conflict. For example:

type Fruit  = Orange | Apple | Banana
type Colour = Orange | Yellow | Green

In this case, the Fruit and Colour types are both aliased to the Orange type, so you can use the same value for multiple cases without causing a conflict.

  • Related