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?
Does Haskell standard library have a function that given a list and a predicate,
Share
The
length . filter pimplementation 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
vectorpackage,length . filter pwill actually be optimized so as to avoid creating an intermediate vector. Lists, however, use what’s calledfoldr/buildfusion at the moment, which is not quite smart enough to optimizelength . filter pwithout 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/buildoptimizations can never (AFAIK) make performance actively worse.