1 | module Control.Monad.Error.Interface
3 | import Control.Monad.Error.Either
4 | import Control.Monad.Maybe
5 | import Control.Monad.RWS.CPS
6 | import Control.Monad.Reader.Reader
7 | import Control.Monad.State.State
8 | import Control.Monad.Trans
9 | import Control.Monad.Writer.CPS
23 | interface Monad m => MonadError e m | m where
25 | throwError : e -> m a
33 | catchError : m a -> (e -> m a) -> m a
37 | liftEither : MonadError e m => Either e a -> m a
38 | liftEither = either throwError pure
43 | tryError : MonadError e m => m a -> m (Either e a)
44 | tryError action = (map Right action) `catchError` (pure . Left)
50 | withError : MonadError e m => (e -> e) -> m a -> m a
51 | withError f action = tryError action >>= either (throwError . f) pure
55 | handleError : MonadError e m => (e -> m a) -> m a -> m a
56 | handleError = flip catchError
62 | mapError : (MonadError e m, MonadError e' n)
63 | => (m (Either e a) -> n (Either e' b)) -> m a -> n b
64 | mapError f action = f (tryError action) >>= liftEither
71 | MonadError () Maybe where
72 | throwError () = Nothing
73 | catchError Nothing f = f ()
77 | Monad m => MonadError () (MaybeT m) where
78 | throwError () = MkMaybeT $
pure Nothing
79 | catchError (MkMaybeT m) f = MkMaybeT $
m >>= maybe (runMaybeT $
f ()) (pure @{Compose})
82 | MonadError e (Either e) where
84 | Left l `catchError` h = h l
85 | Right r `catchError` _ = Right r
88 | Monad m => MonadError e (EitherT e m) where
93 | MonadError e m => MonadError e (MaybeT m) where
94 | throwError = lift . throwError
95 | catchError (MkMaybeT m) f = MkMaybeT (catchError m (runMaybeT . f))
98 | MonadError e m => MonadError e (ReaderT r m) where
99 | throwError = lift . throwError
100 | catchError (MkReaderT m) f =
101 | MkReaderT $
\e => catchError (m e) (runReaderT e . f)
104 | MonadError e m => MonadError e (StateT r m) where
105 | throwError = lift . throwError
106 | catchError (ST m) f =
107 | ST $
\s => catchError (m s) (runStateT s . f)
110 | MonadError e m => MonadError e (RWST r w s m) where
111 | throwError = lift . throwError
112 | catchError (MkRWST m) f =
113 | MkRWST $
\r,w,s => catchError (m r w s) (\e => unRWST (f e) r w s)
116 | MonadError e m => MonadError e (WriterT w m) where
117 | throwError = lift . throwError
118 | catchError (MkWriterT m) f =
119 | MkWriterT $
\w => catchError (m w) (\e => unWriterT (f e) w)