[Haskell-beginners] Maybe, Either

Michael Snoyman michael at snoyman.com
Sat Sep 12 14:13:58 EDT 2009


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

Hope that helps.

On Sat, Sep 12, 2009 at 6:51 PM, Yusaku Hashimoto <nonowarn at gmail.com>wrote:

> I think there is no such function in standard library.
>
> But you can also do the same by `maybe (Left err) Right (lookup key
> assoc)` without defining eitherLookup.
>
> HTH
> -nwn
>
> On Sun, Sep 13, 2009 at 12:14 AM, Michael Mossey <mpm at alumni.caltech.edu>
> wrote:
> > I want to use 'lookup' inside an Either String monad. So I want to write
> > something like
> >
> > eitherLookup :: Eq a => String -> a -> [(a,b)] -> Either String b
> > eitherLookup s x ps = case lookup x ps of
> >                         Just y -> Right y
> >                         Nothing -> Left s
> >
> > Is there such a function existing?
> >
> > Thanks,
> > Mike
> > _______________________________________________
> > Beginners mailing list
> > Beginners at haskell.org
> > http://www.haskell.org/mailman/listinfo/beginners
> >
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20090912/0080fad9/attachment.html


More information about the Beginners mailing list