[Haskell-beginners] deleteM :: (Ord a) => a -> Maybe (Set a) -> Maybe (Set a)

Martin Hofmann martin.hofmann at uni-bamberg.de
Mon Jan 26 04:33:36 EST 2009

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'.



More information about the Beginners mailing list