Does Haskell standard library have a function that given a list and a predicate, returns the number of elements satisfying that predicate? Something like with type (a -> Bool) -> [a] -> Int
. My hoogle search didn't return anything interesting. Currently I am using length . filter pred
, which I don't find to be a particularly elegant solution. My use case seems to be common enough to have a better library solution that that. Is that the case or is my premonition wrong?
The most straightforward way to get the number of elements in a list is to use the Python built-in function len() . As the name function suggests, len() returns the length of the list, regardless of the types of elements in it.
To count the number of elements of a string, the len() method can be used.
We can simply use an if-then-else statement that either increments N is N1+1 , or sets N = N1 , like: count([],0). count([H|Tail], N) :- count(Tail, N1), ( number(H) -> N is N1 + 1 ; N = N1 ).
The count() is a built-in function in Python. It will return you the count of a given element in a list or a string. In the case of a list, the element to be counted needs to be given to the count() function, and it will return the count of the element. The count() method returns an integer value.
The length . filter p
implementation isn't nearly as bad as you suggest. In particular, it has only constant overhead in memory and speed, so yeah.
For things that use stream fusion, like the vector
package, length . filter p
will actually be optimized so as to avoid creating an intermediate vector. Lists, however, use what's called foldr/build
fusion at the moment, which is not quite smart enough to optimize length . filter p
without creating linearly large thunks that risk stack overflows.
For details on stream fusion, see this paper. As I understand it, the reason that stream fusion is not currently used in the main Haskell libraries is that (as described in the paper) about 5% of programs perform dramatically worse when implemented on top of stream-based libraries, while foldr/build
optimizations can never (AFAIK) make performance actively worse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With