我是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 total的类型,并可能将其与类型类Show关联,但我不知道如何完成。谢谢你的帮助。
问题是您将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"
问题似乎是需要显式地在字符串和数字之间进行转换。Haskell不会自动将字符串强制转换为数字,反之亦然。
将数字转换为字符串,使用show
。
使用read
将字符串解析为数字。由于read
实际上适用于许多类型,因此您可能需要指定结果的类型,如:
price :: Integer
price = read price_input_string