Reputation: 15267
I need to check if any element of a set satisfies a predicate. So far I've been using lists, so I just used
any myPredicate sx
but using a set in my case is semantically more correct (and probably more efficient). However there's no any
for sets, and I end up with lots of lines like this (Data.Set as S
):
any myPredicate $ S.toList mySet
Is there a way not to litter my code with all those conversions, like with monoids or the like...?
(I mean, there must be a way besides defining anyS p s = any p $ S.toList s
, otherwise why isn't it in Data.Set
...?)
Upvotes: 3
Views: 167
Reputation: 47392
How about
import qualified Data.Set as Set
import Data.Set (Set)
orS :: Set Bool -> Bool
orS = Set.foldr (||) False
anyS :: (a -> Bool) -> Set a -> Bool
anyS p = orS . Set.map p
or, even more simply, since a Set
is Foldable
import qualified Data.Foldable as F
anyS :: (a -> Bool) -> Set a -> Bool
anyS = F.any
Upvotes: 7
Reputation: 11228
import Data.Set (Set)
import qualified Data.Set as Set
anyS :: (a -> Bool) -> Set a -> Bool
anyS predicate s = not $ Set.null $ Set.filter predicate s
Upvotes: 2