Re: deleteM :: (Ord a) => a -> Maybe (Set a) -> Maybe (Set a)
Martin Hofmann wrote:
> I often come across the problem to insert into a collection which might
> not exist yet, or delete from it and want the collection to be deleted
> if it is empty afterwards.
> I always end up with these two functions:
> deleteM :: (Ord a) => a -> Maybe (Set a) -> Maybe (Set a)
> deleteM e s =
> liftM (S.delete e) s >>= \s' ->
> if S.null s' then return s' else Nothing
> insertM :: (Ord a) => a -> Maybe (Set a) -> Maybe (Set a)
> insertM e s =
> case s of
> (Just s') -> return $ S.insert e s'
> Nothing -> return $ S.insert S.empty
> Is there a way to express each in a (polymorphic) point-free one-liner?
> If not, why isn't there such a function for the standard collection,
> because IMHO this is what you need when using 'alter'.
Yes, there is a way. :)
deleteM e = (\s -> if S.null s then Just s else Nothing) . S.delete e
insertM e = Just . S.insert e . maybe S.empty id
The maybe function is from Data.Maybe .
I did wonder why you want to delete the empty set, but now I see that
you need it for alter .