我是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相关联,但我不知道如何实现它。谢谢你的帮助。
答案 0 :(得分: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"
答案 1 :(得分:3)
问题似乎是您需要在字符串和数字之间进行显式转换。 Haskell不会自动将字符串强制转换为数字,反之亦然。
要将数字转换为字符串显示,请使用show
。
要将字符串解析为数字,请使用read
。由于read
实际上适用于多种类型,因此您可能需要指定结果的类型,如:
price :: Integer
price = read price_input_string