Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An `any` function for Data.Set

Tags:

haskell

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

like image 955
bigstones Avatar asked Jul 14 '26 21:07

bigstones


2 Answers

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
like image 86
Chris Taylor Avatar answered Jul 17 '26 20:07

Chris Taylor


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
like image 36
w.b Avatar answered Jul 17 '26 19:07

w.b



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!