Last active
December 17, 2015 00:39
-
-
Save stesh/5522364 to your computer and use it in GitHub Desktop.
An Error transformer monad
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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