2017-08-13 112 views
-2

我尝试使用data.maybe类型,但失败。当我尝试在ghci中运行它时,它告诉我:“构造函数'Ramen'应该没有参数,但已经给出了1。”。我该如何解决它?执行ghc-modi`type`命令时出错:

data Product = Ramen | Chips 

totalPrice :: Product -> Integer -> Float 

totalPrice product = case product of 
       Ramen x 
        | x >= 200 -> 1.35*x 
        | x <= 200 -> 1.4*x 
        | x <= 100 -> 1.5*x 
        | x <= 30 -> 1.8*x 
        | x <= 10 -> 2.0*x 
        | otherwise -> error "Something's wrong." 
       Chips x 
        | x >= 21 -> 2.35*x 
        | x <= 20 -> 2.5*x 
        | x <= 10 -> 2.7*x 
        | x <= 5 -> 2.95*x 
        | x >= 1 && x <= 2 -> 3.0*x 
        |otherwise -> error "Something's wrong." 

回答

1

的问题是在什么编译器说:

The constructor ‘Ramen’ should have no arguments, but has been given 1. 

RamenChips有定义data Product = Ramen | Chips,但在case表达(Ramen xChips x)收到的参数。为了解决编译错误,你将需要:

要么改变Ramen xChips x只是RamenChips和移动x到函数定义或改变你的数据构造函数data Product = Ramen Integer | Chips Integer和移动IntegertotalPrice :: Product -> Integer -> Float。或许,第一种选择更适合。

但解决这个问题后,你会得到另一个问题:

Couldn't match expected type ‘Float’ with actual type ‘Integer’ 

它可以通过使用fromIntegral :: (Num b, Integral a) => a -> b固定。

这应该可以解决编译错误,但在调用totalPrice Ramen 10之后,您将得到14.0,但我认为您期望得到20.0。这是因为casex >= 200 -> 1.35*x上失败,但在x <= 200 -> 1.4*x上成功。

下面的例子将编译并返回:

200 * 1.35 on totalPrice Ramen 200 
150 * 1.4 on totalPrice Ramen 150 
and 
10 * 2.0 on totalPrice Ramen 10 

但是,我认为这是不鼓励使用Haskellerror,那只是返回0count是负的?

totalPrice :: Product -> Integer -> Float  
totalPrice product count = case product of 
       Ramen 
        | x >= 200 -> 1.35*x 
        | x > 100 -> 1.4*x 
        | x > 30 -> 1.5*x 
        | x > 10 -> 1.8*x 
        | x >= 0 -> 2.0*x 
        | otherwise -> 0 
       Chips 
        | x >= 21 -> 2.35*x 
        | x > 10 -> 2.5*x 
        | x > 5 -> 2.7*x 
        | x > 2 -> 2.95*x 
        | x >= 0 -> 3.0*x 
        | otherwise -> 0 
    where x = fromIntegral count 
+0

很好的回答!为我工作。感谢您的建议。 –