[Haskell-beginners] Maybe, Either

Michael Snoyman michael at snoyman.com
Mon Sep 14 14:42:22 EDT 2009


On Sun, Sep 13, 2009 at 3:40 PM, Brent Yorgey <byorgey at seas.upenn.edu>wrote:

> On Sat, Sep 12, 2009 at 09:13:58PM +0300, Michael Snoyman wrote:
> > I often times have to write a lookup function that returns its value into
> > any monad instead of just Maybe. For example:
> >
> > mLookup :: (Eq k, Monad m) => k -> [(k, v)] -> m v
> > mLookup k pairs = case lookup k pairs of
> >                                 Nothing -> fail "mLookup: nothing found"
> >                                 Just v -> return v
> >
>
> This is actually the type that the lookup function USED to have, but
> it was changed since monads actually have nothing to do with failing
> (the fail method is just a hack used to handle pattern-match failures
> in do-notation).  Probably a better implementation of this would be
>
>  mLookup :: (Eq k, MonadPlus m) => k -> [(k,v)] -> m v
>  mLookup k pairs = maybe mzero return (lookup k pairs)
>
>
I understand that fail being in Monad is controversial, but my version of
the function works in *all* monads. This is very useful for:

1) Quickly writing up code in the IO monad (ie, for a shell script)
2) Check out the data-objects library; having an mLookup function makes
dealing with mappings very convenient.

Michael
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20090914/437f6726/attachment.html


More information about the Beginners mailing list