对类型类约束感到困惑

时间:2016-11-09 02:04:08

标签: haskell typeclass

我是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

虽然当我使用相同的列表但在控制台中使用原始浮动时它可以正常工作。我在这里错过了一些大事吗?任何帮助表示赞赏。

编译好:

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

1 个答案:

答案 0 :(得分:5)

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

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

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