执行ghc-modi`type`命令时出错:

时间:2017-08-13 05:03:06

标签: haskell

我尝试使用data.maybe类型但失败了。当我试图在ghci中运行它时,它告诉我"构造函数'Ramen'应该没有参数,但是已经给了1。"。我该如何解决?

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 个答案:

答案 0 :(得分: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移至功能定义中,或将数据构造函数更改为{{1}并将data Product = Ramen Integer | Chips Integer移出Integer。可能第一种选择更合适。

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

totalPrice :: 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.0case失败,但在x >= 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 中使用error,仅仅Haskell归还0是否为负?

count