bigstones
bigstones

Reputation: 15267

An `any` function for Data.Set

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

Answers (2)

Chris Taylor
Chris Taylor

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

w.b
w.b

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

Related Questions