Constructors in Haskell #
In haskell, you shall provide a type constructor and one or more data constructors when you define a datatype.
{- File: Shape.hs
`Shape` is a type constructor.
`Circle` and `Rectangle` are data constructors.
-}
data Shape = Circle Float
| Rectangle Float Float
deriving (Show)
Shapeis a type constructor, NOT a type itself. It is afunctionthat takes other types to produce a type at the type level.CircleandRectangleare dataconstructors. They are effectively functions that produce a value of the typeShape.
When defining a datatype in Haskell, the pattern is:
data TypeName = DataConstructor1 Type1 Type2 | DataConstructor2 Type 3 | ... deriving Show
TypeNamedefines the new type nameDataConstructor1,DataConstructor2, etc. are data constructors. They are used to create values of theTypeNametype. These data constructors can take parameters of other types (Type1,Type2,Type3, etc.) to create a value of the new type.- The
|symbol separates different data constructors within the same type definition. - The
derivingShowpart automatically creates an instance of theShowtype class forTypeName, enabling it to be represented as a string for printing.