i am new to Haskell and probably missing something really basic here, but i am not able to re-use same value constructor among different data types.
data Colour = Red | Pink | Orange | Yellow
data Fruit = Apple | Orange | Banana
This produces error saying
Multiple declarations of ‘Orange’
Not sure why this isn't allowed, i have been using OCaml before learning Haskell and was able to define types like this
As a quick exercise try just defining one of your data types and then opening up GHCi to inspect it.
If you use
:t
in GHCi, it will tell you the type of anything.So this tells you that your data constructor
Orange
is really just a function that takes no arguments and produces a value of typeColour
.So what happens if you add a duplicate declaration?
Now you have defined a function
Orange
that takes no arguments and produces a value of typeColour
or a value of typeFruit
. This won't work at all! It would be the same as defining your own custom functionfoo
and giving it multiple type signatures:Which obviously doesn't work either.
To get around this, you can define each data type in its own module, and use a qualified import to scope them correctly:
Now, you might be thinking "The compiler is smart, it should know what
Orange
I'm talking about when I'm using it." and you'd be partially right. There is an ongoing effort to bring Overloaded or Duplicate record fields into Haskell. There are various other questions of that ilk already defined here, but I'll list a few references for further reading.