Reputation: 9264
Here is my function. It checks for positive values, changes them to ones and sums them.
countPositive :: [Integer] -> Integer
countPositive xs = foldr (+) 0 $ map (^0) (filter (>0) xs)
Is there a better strategy to count positive values without using length
but just foldr
, map
and filter
?
Upvotes: 0
Views: 1649
Reputation: 101
Foldr doesn't seem right here. You want foldl' instead. This is my solution:
countPos :: (Num a, Ord a) => [a] -> Int
countPos = length . filter (> 0)
As you don't want to use length
for some reason you would basically just reinvent it:
countPos xs = sum (1 <$ filter (> 0) xs)
or yet another method:
countPos = foldl' (\x _ -> succ x) 0 . filter (> 0)
There are lots and lots of way to do this. If 100 people answer to this post, chances are you get 100 different ways to do it, but the simplest way is to use filter
and length
.
Upvotes: 10
Reputation: 102156
Sure, just directly count them with foldr
:
countPositive = foldr (\n count -> if n > 0 then count + 1 else count) 0
Or reimplement length
with foldr
:
countPositive = foldr (const succ) 0 . filter (>0)
Upvotes: 5