[Haskell-cafe] Generalizing catMaybes

Roman Cheplyaka roma at ro-che.info
Sat Jan 8 11:03:35 CET 2011


* Tony Morris <tonymorris at gmail.com> [2011-01-08 12:56:28+1000]
> 
>  I am wondering if it possible to generalise catMaybes:
> 
> (Something f, SomethingElse t) => t (f a) -> t a
> 
> I have being doing some gymnastics with Traversable and Foldable and a
> couple of other things from category-extras to no avail. Perhaps
> someone else's brain is molded into an appropriate shape to reveal an
> answer!

For example,

    import Control.Applicative
    import Data.Foldable as F
    import Control.Monad.Writer

    cat' :: (Applicative list, Foldable list, Monoid (list a), Foldable maybe)
         => list (maybe a) -> list a
    cat' = fold . fmap (execWriter . F.mapM_ (\x -> tell (pure x)))

However, this looks rather useless -- there are probably not many
containers which can be substituted instead of 'list'.

I think catMaybes deserves its own typeclass, which would represent
"truncatable" structures:

    class Truncatable struct where
        catMaybes :: struct (Maybe a) -> Maybe a
  
This would make perfect sense for Set, Map etc.

-- 
Roman I. Cheplyaka :: http://ro-che.info/
Don't worry what people think, they don't do it very often.



More information about the Haskell-Cafe mailing list