3 | module Control.Monad.Error.Either
5 | import Control.Monad.Trans
19 | data EitherT : (e : Type) -> (m : Type -> Type) -> (a : Type) -> Type where
20 | MkEitherT : m (Either e a) -> EitherT e m a
25 | runEitherT : EitherT e m a -> m (Either e a)
26 | runEitherT (MkEitherT x) = x
33 | eitherT : Monad m => (a -> m c) -> (b -> m c) -> EitherT a m b -> m c
34 | eitherT f g x = runEitherT x >>= either f g
39 | mapEitherT : (m (Either e a) -> n (Either e' a')) -> EitherT e m a -> EitherT e' n a'
40 | mapEitherT f = MkEitherT . f . runEitherT
44 | bimapEitherT : Functor m => (a -> c) -> (b -> d)
45 | -> EitherT a m b -> EitherT c m d
46 | bimapEitherT f g x = mapEitherT (map (either (Left . f) (Right . g))) x
53 | left : Applicative m => e -> EitherT e m a
54 | left = MkEitherT . pure . Left
61 | right : Applicative m => a -> EitherT e m a
62 | right = MkEitherT . pure . Right
66 | swapEitherT : Functor m => EitherT e m a -> EitherT a m e
67 | swapEitherT = mapEitherT (map (either Right Left))
76 | throwE : Applicative m => e -> EitherT e m a
77 | throwE = MkEitherT . pure . Left
84 | catchE : Monad m => EitherT e m a -> (e -> EitherT e' m a) -> EitherT e' m a
86 | = MkEitherT $
runEitherT et >>= either (runEitherT . f) (pure . Right)
94 | Eq (m (Either e a)) => Eq (EitherT e m a) where
95 | (==) = (==) `on` runEitherT
98 | Ord (m (Either e a)) => Ord (EitherT e m a) where
99 | compare = compare `on` runEitherT
102 | Show (m (Either e a)) => Show (EitherT e m a) where
103 | showPrec d (MkEitherT x) = showCon d "MkEitherT" $
showArg x
109 | Monad m => Semigroup (EitherT e m a) where
110 | MkEitherT x <+> MkEitherT y = MkEitherT $
do
116 | Functor m => Functor (EitherT e m) where
117 | map f e = MkEitherT $
map f <$> runEitherT e
120 | Foldable m => Foldable (EitherT e m) where
121 | foldr f acc (MkEitherT e)
122 | = foldr (\x,xs => either (const xs) (`f` xs) x) acc e
124 | null (MkEitherT e) = null e
127 | Traversable m => Traversable (EitherT e m) where
128 | traverse f (MkEitherT x)
129 | = MkEitherT <$> traverse (either (pure . Left) (map Right . f)) x
132 | Applicative m => Applicative (EitherT e m) where
133 | pure = MkEitherT . pure . Right
134 | f <*> x = MkEitherT [| runEitherT f <*> runEitherT x |]
137 | Monad m => Monad (EitherT e m) where
138 | x >>= k = MkEitherT $
runEitherT x >>= either (pure . Left) (runEitherT . k)
143 | (Monad m, Monoid e) => Alternative (EitherT e m) where
144 | empty = left neutral
145 | MkEitherT x <|> my = MkEitherT $
do
147 | | Right r => pure (Right r)
148 | Left l' <- runEitherT my
149 | | Right r => pure (Right r)
150 | pure (Left (l <+> l'))
153 | MonadTrans (EitherT e) where
154 | lift = MkEitherT . map Right
157 | HasIO m => HasIO (EitherT e m) where
158 | liftIO act = MkEitherT $
liftIO (io_bind act (pure . Right))