gpt4 book ai didi

Haskell where 类型声明

转载 作者:行者123 更新时间:2023-12-02 10:46:11 24 4
gpt4 key购买 nike

我是 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 相关联,但我不知道如何实现这一点。感谢您的帮助。

最佳答案

问题是您将 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 where 类型声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15708408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com