[Haskell-cafe] Is there a generic way to detect "mzero"?

Ting Lei tinlyx at hotmail.com
Mon Mar 26 20:33:16 CEST 2012


I was writing a code trying to use MonadPlus to detect some error cases (representing missing values etc. in pure code). With the Maybe monad, I can do this:

can0 :: (a -> Maybe b) -> a -> Bool
can0 f x = case f x of
                  Nothing -> False
                  Just  x -> True

And I got the expected result:

*Main> can0 (\x -> Just x) 1

But, when I try to generalize this using MonadPlus, as follows:

can :: (MonadPlus m) => (a -> m b) -> a -> Bool
can f x = case f x of 
            mzero -> False
            _ -> True

I got a warning:

    Warning: Pattern match(es) are overlapped
             In a case alternative: _ -> ...
Ok, modules loaded: Main.

And the result is also not as intended (see also can0):

*Main> can (\x -> Just x) 1

Can anyone help to explain why this wouldn't work or if there is a workaround to use Monadplus and mzero (or Monad and fail) to achieve this?

Thanks in advance for your help


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20120326/69b30e30/attachment.htm>

More information about the Haskell-Cafe mailing list