gpt4 book ai didi

haskell - 对类型类约束感到困惑

转载 作者:行者123 更新时间:2023-12-02 09:22:58 25 4
gpt4 key购买 nike

我是 Haskell 的初学者,目前很困惑,我确信这与我使用的约束有关,我不断收到错误

代码

averageThreeNumbers:: Floating a=> (a, a, a) -> a
averageThreeNumbers (x,y,z) = ((x+y+z)/3)

howManyBelowAverage:: Floating a=> (a, a, a) -> [a]
howManyBelowAverage (b,c,d) = [x|x <- [b,c,d], x > averageThreeNumbers(b,c,d)]

错误

Could not deduce (Ord a) arising from a use of `>'
from the context: Floating a
bound by the type signature for:
howManyBelowAverage :: Floating a=> (a, a, a) -> [a]
Possible fix: add (Ord a) to the context of the type signature

尽管当我使用相同的列表但在控制台中使用原始 float 时,它工作得很好。我在这里错过了一些大事吗?如有任何帮助,我们将不胜感激。

编译良好:

[x|x <- [1.2, 3.2, 4.6], x > averageThreeNumbers (1.2, 3.2, 4.6)]

最佳答案

由于您将 value 输出值与 averageThreeNumbers 的结果进行比较,因此您需要在 howManyBelowAverage 函数中包含 Ord 约束。我还认为您的意思是检查 x 是否小于函数返回值(在上面的代码片段中,您执行相反的操作)。

修改约束和比较检查,我们最终得到以下结果:

howManyBelowAverage :: (Ord a, Floating a) => (a,a,a) -> [a]
howManyBelowAverage (b,c,d) = [ x | x <- [b,c,d], x < averageThreeNumbers(b,c,d)]

关于haskell - 对类型类约束感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40499316/

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