2013-03-29 235 views
3

我是Haskell的新手,遇到類型系統問題。我有以下功能:Haskell類型聲明

threshold price qty categorySize 
    | total < categorySize = "Total: " ++ total ++ " is low" 
    | total < categorySize*2 = "Total: " ++ total ++ " is medium" 
    | otherwise = "Total: " ++ total ++ " is high" 
    where total = price * qty 

哈斯克爾與迴應:

No instance for (Num [Char]) 
     arising from a use of `*' 
    Possible fix: add an instance declaration for (Num [Char]) 
    In the expression: price * qty 
    In an equation for `total': total = price * qty 
    In an equation for `threshold': 
    ... repeats function definition 

我認爲這個問題是我需要以某種方式告訴哈斯克爾總的類型,也許這與類型類展會關聯,但我不知道該如何實現。謝謝你的幫助。

回答

10

問題是你定義total爲乘法,這迫使它是一個Num a => a然後使用它作爲參數傳遞給++用繩子,迫使它是[Char]的結果。

您需要total轉換爲String:現在

threshold price qty categorySize 
    | total < categorySize = "Total: " ++ totalStr ++ " is low" 
    | total < categorySize*2 = "Total: " ++ totalStr ++ " is medium" 
    | otherwise    = "Total: " ++ totalStr ++ " is high" 
    where total = price * qty 
      totalStr = show total 

,將運行,但代碼看起來有點重複。我會建議這樣的事情:

threshold price qty categorySize = "Total: " ++ show total ++ " is " ++ desc 
    where total = price * qty 
      desc | total < categorySize = "low" 
       | total < categorySize*2 = "medium" 
       | otherwise    = "high" 
3

問題似乎是,你需要顯式轉換字符串和數字。 Haskell不會自動將字符串強制轉換爲數字,反之亦然。

要將顯示的數字轉換爲字符串,請使用show

要將字符串解析爲數字,請使用read。由於read實際上適用於多種類型,因此您可能需要指定結果的類型,如下所示:

price :: Integer 
price = read price_input_string