2011-10-07 89 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類。