NotJustMaybe

A very common technique is to use Maybe to represent a possibly failing function as in:

 > lookup :: Eq a => a -> [(a,b)] -> Maybe b
 > lookup k ((k',v):_) | k == k' = Just v
 > lookup k (_:xs) = lookup k xs
 > lookup k [] = Nothing

rather than force the use of maybe, let your function work with any monad whatsoever.

 > lookup :: (Monad m, Eq a) => a -> [(a,b)] -> m b
 > lookup k ((k',v):_) | k == k' = return v
 > lookup k (_:xs) = lookup k xs
 > lookup k [] = fail "key not found"

now, since Maybe is an instance of Monad, your new function can be used anywhere your old one could have been without change, plus you can use it in any state/io/parser/list/whatever monad seamlessly. this also works the other way, if you have to use code which returns maybe, you can use it as a monad, see ExceptionMonad

- JohnMeacham

You could also use ContinuationPassingStyle, but UsingMonads is probably better.

Is there an argument for abstracting the failure behaviour out of Monad?

 > class Failable m where
 >   fail   :: String -> m a
 >
 > class Monad m where
 >   (>>=)  :: m a -> (a -> m b) -> m b
 >   return :: a -> m a
(Error fixed; thanks, Stefan.)

- AndrewBromage?

I've always felt a little disgusted by fail in the Monad class. (Also, firstly I confused it with mzero).

- StefanLjungstrand


EditText of this page (last edited 2002/05/08)
FindPage by browsing or searching
SubscribeForChangeNotification via email for this page (or unsubscribe)