Home > Software engineering >  List comprehenension in the case of countpositives
List comprehenension in the case of countpositives

Time:12-11

I think about the function to count all positives numbers in a list. My idee was

countPositives :: [Int] -> Int 
countPositives xs = length [ x | x <- xs, x > 0]

That code work, but I thinking it is possible to write with the filter function or with guards. Is it possilbe and if yes, how can I write it?

CodePudding user response:

As yet another alternative, use a fold:

ghci> lst = [1, 2, 4, 7, -2, -3, 0, 8]
ghci> foldr (\x i -> if x > 0 then i   1 else i) 0 lst
5

CodePudding user response:

Both approaches would be pretty straightforward.

  1. Filter the collection and count it's length:

    countPositives' :: [Int] -> Int 
    countPositives' = length.filter (>0)  
    
  2. With guards:

    countPositives'' :: [Int] -> Int 
    countPositives'' [] = 0 
    countPositives'' (x:xs) | x > 0     = 1   countPositives'' xs
                            | otherwise = countPositives'' xs
    
  • Related