2016-09-18 9 views
0

私はハスケルで新しいですし、私は練習のために次のように試みました。エラーはありませんが、プログラムを動作させることはできません。 誰でも私にその理由を教えてもらえますか?あなたが一箇所ですべてのあなたの換算係数を定義した場合私のコードがうまくいかず、エラーメッセージも表示されないのはなぜですか?

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

「クラッシックプログラム」が意味するものの詳細については、こちらをご覧ください。本当に助けになる – mic4ael

答えて

0

これははるかに簡単です:

convert :: Weight -> Weight_unit -> Weight 
convert (Weight v u1) u2 = Weight (v*(cf u1 u2)) u2 
:今

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を呼び出す必要があります

関連する問題