I´m a second-year under-graduate student and have just started learning Haskell. My problem is regarding type-handling versus pattern-matching. I have defined a type Car which contains different parameters and the specification if the car´s gearbox is a stick or automatic, like so:
data Car = Stick [Char] Integer | Automatic [Char] Integer
This solution has worked brilliantly for pattern-matching cars so far, but now I need a function which takes a car as input and returns the Stick/Automatic information, and don´t want to have to change the Stick/Automatic handling to string-handling. I don´t know what return-type to specify for that function. What would that return-type be?
You could introduce a new type for the type of tranmission:
data TransmissionType = Stick | Automatic
and change your definition of car to:
data Car = Car TransmissionType [Char] Integer
You can then add a function to get the type
transmissionType :: Car -> TransmissionType
transmissionType (Car t _ _) = t
Since you only have one constructor you could use records instead:
data Car = Car {
transmissionType :: TransmissionType,
field1 :: [Char],
field2 :: Integer
}
If you don't want to change your definition you could add a function
isManual :: Car -> Bool
isManual (Stick _ _) = True
isManual (Automatic _ _) = False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With