[Haskell-beginners] Using Either and Maybe

Alan Buxton alanbuxton at gmail.com
Sun May 4 15:28:32 UTC 2014


So I had a function that would leave me with a Nothing or a Just, and I
wanted to use the result of this function to lookup in a Map. So something
like this was very easy to do.

 

h> let list = Data.Map.fromList [(1,2),(3,4),(5,6)]

 

h> Just 4 >>= flip Data.Map.lookup list

Nothing

 

h> Just 3 >>= flip Data.Map.lookup list

Just 4

 

Now, however, my source function gives me an Either. I ended up writing this
function to let me chain Either with Data.Map.lookups:

 

(>>?=) :: (Either a b, a) -> (b -> Maybe c) -> (Either a c,a)

(>>?=) (Left x,e) _ = (Left x,e)

(>>?=) (Right y,e) f = case f y of 

                        Nothing -> (Left e,e)

                        Just z -> (Right z,e)

 

But I can't help thinking I'm reinventing the wheel here somehow. There must
be a better way, right?

 

Thanks in advance for any pointers.


Alan

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20140504/1446097e/attachment.html>


More information about the Beginners mailing list