rubypoe
rubypoe

Reputation: 103

How do I get the length of my list in Haskell after creating it?

So using the filter function I created something that returns a list based on user-specified criteria. For example, ispos x = x > 0 and you call that on the list using my function and it will return a list, but I want it to return the length of that list. How do I do that?

count'filter :: (a -> Bool) -> [a] -> [a]
count'filter p xs = [ x | x <- xs, p x]

Upvotes: 1

Views: 641

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

With length :: Foldable f => f a -> Int:

countfilter :: (a -> Bool) -> [a] -> Int
countfilter p xs = length [ x | x <- xs, p x]

instead of the list comprehension, you can use filter :: (a -> Bool) -> [a] -> [a]:

countfilter :: (a -> Bool) -> [a] -> Int
countfilter p = length . filter p

Upvotes: 2

Related Questions