2011-10-07 96 views
2

如果有两个不同的数据类型,但他们得到了类似的功能:哈斯克尔 - 实施和实例

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) 

我的问题是实现一个类型类“交通”,让汽车和自行车成为交通的情况下, 。所有的实例都会实现一个名为“comparePrice”的函数。

我已经试过:

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) 

它似乎无法与我已经声明comparePrice多次错误味精工作。如何使代码作为问题描述工作?任何帮助,thx!

回答

7

您需要缩进类和实例定义的正文。否则,它认为body是空的,comparePrice的定义意味着独立于Traffic类。