Skip to content

Instantly share code, notes, and snippets.

@stesh
Last active December 17, 2015 00:39
Show Gist options
  • Select an option

  • Save stesh/5522364 to your computer and use it in GitHub Desktop.

Select an option

Save stesh/5522364 to your computer and use it in GitHub Desktop.
An Error transformer monad
class Monad m => MonadError e m | m -> e where
catchError :: e -> m a
throwError :: m a -> (e -> m a) -> m a
data ErrorT e m a = ErrorT {
runErrorT :: m (Either e a)
}
instance MonadTrans (ErrorT e m) where
lift m = ErrorT $ do
a <- m
return $ Right a
instance Monad (ErrorT e m) where
return a = ErrorT $ return (Right a)
m >>= k = ErrorT $ do
a <- runErrorT m
case a of
(Left v) -> return $ Left v
(Right v) -> runErrorT (k v)
instance MonadError (ErrorT e m) where
throwError e = ErrorT $ return (Left e)
catchError m handler = ErrorT $ do
a <- runErrorT m
case a of
(Left v) -> runErrorT (handler v)
(Right v) -> return a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment