Reputation: 163
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?
Upvotes: 3
Views: 204
Reputation: 144126
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
Upvotes: 14
Reputation: 833
In Haskell, the return-type you write in the code (in the declaration) is not for the compiler. It is for you. The compiler figures out what type your function is, then checks whether you got it right.
What I suggest you do, is to make the function you need. ( I haven't really figured out what that should be.) After you have done that, open ghci (the compiler, interactive), load your code. then use :t to have the compiler figure out what type it is. Then you can write it in the declaration if you want to. It is not necessary.
$ ghci
prelude> :load yourfile
prelude> :t yourfunction
Upvotes: -6