If there are two different datatypes but they got a similar function:
type model = String
type priceOfC = Int
data Car = Cars model priceOfC
ComparePricesCar :: Car -> Car -> Int
.... (some codes here to compare prices between two cars)
type color = String
type priceOfB = Int
data Bike = Bikes color priceOfB
ComparePricesBike :: Bike -> Bike -> Int
.... (some codes here to compare prices between two bikes)
The problem I got is to implement a type class “Traffic” and let Car and Bike become instances of Traffic. And all the instances will implement a function called “comparePrice”.
I’ve tried:
class Traffic a where
comparePrice :: a -> a -> Int
instance Traffic Car where
comparePrice (Cars a b)(Cars c d) = ComparePricesCar (Cars a b)(Cars c d)
instance Traffic Bike where
comparePrice (Bikes a b)(Bikes c d) = ComparePricesBike (Bikes a b)(Bikes c d)
It seems not working with error msg that I’ve declared comparePrice multiple times. How to makes codes working as the problem description? Any help, thx!
You need to indent the body of the class and instance definitions. Otherwise it thinks that the body is empty and the definition of comparePrice is meant to be independent of the Traffic class.