Aez
Aez

Reputation: 43

Confused about type class constraints

I am a beginner in Haskell and I am currently confused I am sure it's something to do with the constraints I used I keep getting errors

The code

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)]

The error

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

Although when I use the same list but with raw floats in the console it works just fine. Am I missing something big here? Any help is appreciated.

This compiles fine:

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

Upvotes: 2

Views: 186

Answers (1)

mnoronha
mnoronha

Reputation: 2625

Because you compare the value output value with the result of averageThreeNumbers, you need to include the Ord constraint on your howManyBelowAverage function. I also think you meant to check if x is less than the function return value (in the code snippets above, you do the opposite).

Amending the constraint and the comparison check, we end up with this:

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

Upvotes: 5

Related Questions