3

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

Haskell 回应:

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

我认为问题在于我需要以某种方式告诉 Haskell 总计的类型,并可能将其与类型类 Show 相关联,但我不知道如何实现。谢谢你的帮助。

4

2 回答 2

10

问题是您将其定义total为乘法的结果,这迫使它成为 a Num a => a,然后您将其用作++字符串的参数,迫使它成为[Char]

您需要转换totalString

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"
于 2013-03-29T17:39:13.567 回答
3

问题似乎是您需要在字符串和数字之间显式转换。Haskell 不会自动将字符串强制转换为数字,反之亦然。

要将数字转换为字符串显示,请使用show.

要将字符串解析为数字,请使用read. 由于read实际上适用于许多类型,您可能需要指定结果的类型,如:

price :: Integer
price = read price_input_string
于 2013-03-29T17:43:06.533 回答