1
votes

I'm new to Haskell and I have no idea what I'm doing wrong here. The following code generates an error.

numOfPos :: Num a => [a] -> Int
numOfPos xs = length [x | x <- xs, x > 0]

The code just returns the number of positive elements in the list. The list can contain any type of number.

The error says "Could not deduce (Ord a) arising from a use of '<' from the context (Num a)..."

What is the type declaration supposed to be to allow for this function?

1
(Num a, Ord a) => [a] -> Int - Louis Wasserman

1 Answers

4
votes

(>) is defined on the Ord typeclass, not the Num typeclass, so you need to put both the Num and Ord constraints on a for this to work:

numOfPos :: (Num a, Ord a) => [a] -> Int
numOfPos xs = length [x | x <- xs, x > 0]

For more information about why elements of Num ("numbers") aren't elements of Ord ("objects that have an ordering"), see this question.