Search code examples
haskellfilterlist-comprehension

List comprehenension in the case of countpositives


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?


Solution

  • 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