2017-08-13 117 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

很好的回答!爲我工作。感謝您的建議。 –