Open
Description
We can’t have a Traversable
instance for Set
, but there’s no reason we can’t have a constrained traverse
just like we have Set.map
even tho we can’t have Functor
either. My initial attempt uses toList
/fromList
:
traverse :: (Ord b, Applicative f) => (a -> f b) -> Set a -> f (Set b)
traverse f = fmap fromList . Prelude.traverse f . toList
When I asked around on Twitter, @chris-martin came up with this variant:
traverse f = foldMap (fmap singleton . f)
which requires an extra Monoid (f a)
constraint, but the latter was resolved by Liam Goodacre:
traverse f = getAp . foldMap (Ap . singleton . f)
I haven’t thought too hard about the asymptotics or other performance characteristics here, and there may well be better implementations possible, but it was certainly a fun thought experiment! What do folks think about adding a traverse
for Set
?