3

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...?)

4

2 回答 2

7

怎么样

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

或者,更简单地说,因为 aSetFoldable

import qualified Data.Foldable as F

anyS :: (a -> Bool) -> Set a -> Bool
anyS = F.any
于 2013-10-07T10:34:26.703 回答
2
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
于 2013-10-07T10:42:03.823 回答