Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: type versus pattern matching

Tags:

haskell

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?

like image 213
URL_Flip Avatar asked Nov 22 '25 11:11

URL_Flip


1 Answers

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
like image 62
Lee Avatar answered Nov 24 '25 06:11

Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!