The haskell code below compiles, Ok.
data Point = Point Float Float
data Radius = Radius Float
data Shape = Circle Point Radius
Is it possible to write something in line with the code below (Code fails compiling):
data LengthQty = Radius Float | Length Float | Width Float
data Shape = Circle Point Radius
Idea behind this attempt is that Radius, Length and Width are representing Physical Quantity Length.
Please note that in the second part second line if written like
data Shape = Circle Point LengthQty
Then, it compiles, but in that case the “LengthQty” can be anything like Length, Width or Radius, where only Radius is required.
(1) What is wrong in second part?
(2) How it can be corrected to implement the idea of Physical Quantity Length (LengthQty)?
The reason that your code doesn’t compile is that the right-hand side of a data declaration must be a constructor followed by a list of types, i.e. of the form
In your example, when you define
you have made
LengthQtya type whereasRadius,LengthandWidthare constructors. Therefore when you writethe compiler sees something of the form
i.e. it sees a constructor where it is expecting a type, so it throws an error. In the original code, the symbol
Radiuswas used for both a constructor and a type. When the compiler seesit knows that
Radiusin this context has to be a type, so there is no possibility of confusion with the constructor radius.With this in mind, you can make your code compile correctly if you just write
and you can get a particular instance of a circle with