2016-09-18 55 views
0

我是Haskell的新手,我嘗試了下面的練習。它沒有錯誤,但它不能工作和粉碎程序。 誰能告訴我爲什麼?爲什麼我的代碼無法工作,也沒有錯誤信息?

type Weight_value = Float 
data Weight_unit = G | KG | T 
    deriving (Show, Eq) 
data Weight = Weight {value :: Weight_value, unit :: Weight_unit} 
    deriving (Show) 
instance Eq Weight where 
    weight_left == weight_right = 
     convert weight_left KG == convert weight_right KG 

to_g :: Weight -> Weight 
to_g weight = case weight of 
    Weight gram G -> Weight gram G 
    Weight kilo KG -> Weight (kilo*1000) G 
    Weight tone T -> Weight (tone*1000000)G 

to_kg :: Weight -> Weight 
to_kg weight = case weight of 
    Weight gram G -> Weight (gram/1000) KG 
    Weight kilo KG -> Weight kilo KG 
    Weight tone T -> Weight (tone*1000) KG 

to_t :: Weight ->Weight 
to_t weight = case weight of 
    Weight gram G -> Weight (gram/1000000) T 
    Weight kilo KG -> Weight (kilo/1000) T 
    Weight tone T -> Weight tone T 

convert :: Weight -> Weight_unit -> Weight 
convert weight unit = case unit of 
    G  -> to_g   weight 
    KG  -> to_kg  weight 
    T  -> to_t   weight 
+0

您可能想要閱讀https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ –

+1

更多有關「crush program」意味着什麼的詳細信息真的很有幫助 – mic4ael

回答

0

,如果你在一個地方定義所有的轉換系數這是簡單得多:

cf :: Weight_unit -> Weight_unit -> Float 
cf G KG = 1/1000 
cf G T = 1/1000000 
cf KG T = 1/1000 
cf KG G = 1000 
cf T KG = 1000 
cf T G = 1000000 
cf _ _ = 1 

現在,您convert功能只需要使用當前和目標單位打電話cf

convert :: Weight -> Weight_unit -> Weight 
convert (Weight v u1) u2 = Weight (v*(cf u1 u2)) u2 
相關問題