I want to include String as part of my constructor:
> data Car = Wheel | Trunk | String deriving (Show)
> test::Car->Car->Car
> test Wheel Wheel = "Wheel"
> test _ _ = ""
it says: Couldn’t match Car with [Char]
if I change the constructor to
> data Car = Wheel | Trunk | [Char] deriving (Show)
it says: error in constructor in data/newtype declaration: [Char]
So how do I create a data type where one of the constructors is also a string?
Haskell does not provide unnamed unions as you have used in your
Cardata type. Each element in the definition of a data type must have a constructor. For example, you could define the following data type.In this definition
Constrdenotes a constructor andStringis the type of its argument. For example, you can construct a value of typeCarby usingConstr "Wheel". If you omit theStringin the example above, it is a constructor calledConstrwithout an argument. Similarly, in your example,Stringis a constructor, even if there exists a type with the same name.With the definition of
Carabove, you can definetestas follows.By adding the constructor
Stringon the right hand side of the definitions, the string is lifted into theCardata type. However, as mentioned in the comments, a definition like this seems a little odd astestalways yields a value of typeString. Therefore, another possible definition would be the following.