The error message in the title is a common beginner mistake. Let's see how it arises and how to fix it.
Suppose we need to compute the average value of a list of numbers; the following declaration would seem to do it, but it wouldn't compile:
averageOfList ll = sum ll / length ll
The problem is with the division (/)
function: its signature is (/) :: Fractional a => a -> a -> a
, but in the case above the denominator (given by length :: Foldable t => t a -> Int
) is of type Int
(and Int
does not belong to the Fractional
class) hence the error message.
We can fix the error message with fromIntegral :: (Num b, Integral a) => a -> b
. One can see that this function accepts values of any Integral
type and returns corresponding ones in the Num
class:
averageOfList' :: (Foldable t, Fractional a) => t a -> a
averageOfList' ll = sum ll / fromIntegral (length ll)