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?
(>)
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.