为什么我的代码无法正常工作且没有错误消息?

时间:2016-09-18 13:19:02

标签: haskell

我是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

1 个答案:

答案 0 :(得分: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