use*_*227 3 haskell types where-clause
我是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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
我认为问题是我需要以某种方式告诉Haskell总类型,并且可能将它与类型Show相关联,但我不知道如何实现它.谢谢你的帮助.
Sco*_*son 10
问题是你定义total为乘法的结果,它强制它成为a 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
Run Code Online (Sandbox Code Playgroud)
现在,这将运行,但代码看起来有点重复.我会建议这样的事情:
threshold price qty categorySize = "Total: " ++ show total ++ " is " ++ desc
where total = price * qty
desc | total < categorySize = "low"
| total < categorySize*2 = "medium"
| otherwise = "high"
Run Code Online (Sandbox Code Playgroud)