0
votes

Hi I'm new to haskell and I created a function to compute the absolute value of a number.

absVal :: (Num a) => a -> a
absVal x
    | x < 0     = x - x - x
    | otherwise = x

this code gives me an error (what kind of error is this called?) "Could not deduce (Ord a) arising from a use of ‘<’ "

But when I rewrite the function as

absVal :: (Ord a) => a -> a
absVal x
    | x < 0     = x - x - x
    | otherwise = x

I get the error "Could not deduce (Num a) arising from the literal ‘0’ "

When I write the type signature as Float -> Float the function works as intended

Why is this?

1
Normally one would expect Num to be a subclass of Ord but not all Num class member types are orderable i.e. complex numbers. So you have to mention both constraints in the signature.Redu

1 Answers

4
votes

Operator - (subtraction) requires the Num class, and so does the literal 0 (zero). Operator < (less) requires the Ord class. Since you're using all three of them in your function, both classes are required.

You can specify several classes by tupling them like this:

absVal :: (Num a, Ord a) => a -> a

Changing the type to Float works, because Float does have instances of both Num and Ord