antisplice-0.7.0.0: src/Game/Antisplice/Utils/Fail.hs
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
{-
This module is part of Antisplice.
Copyleft (c) 2014 Marvin Cohrs
All wrongs reversed. Sharing is an act of love, not crime.
Please share Antisplice with everyone you like.
Antisplice is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Antisplice is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Antisplice. If not, see <http://www.gnu.org/licenses/>.
-}
-- | Provides a monad for error handling. Okay, I confess it's equal to ErrorT...
module Game.Antisplice.Utils.Fail where
import Control.Monad
import Control.Monad.Error.Class
import Control.Monad.Trans.Class
-- | The error handling monad.
newtype FailT e m a = Fail { runFailT :: m (Either e a) }
instance Monad m => Functor (FailT e m) where
fmap f a = Fail $ do
v <- runFailT a
case v of
Left e -> return $ Left e
Right x -> return $ Right (f x)
instance Monad m => Monad (FailT e m) where
return a = Fail $ return $ Right a
m >>= f = Fail $ do
v <- runFailT m
case v of
Left e -> return $ Left e
Right x -> runFailT $ f x
instance MonadTrans (FailT e) where
lift m = Fail $ do
a <- m
return $ Right a
instance Monad m => MonadError e (FailT e m) where
throwError e = Fail $ return $ Left e
catchError m h = Fail $ do
v <- runFailT m
case v of
Left e -> runFailT $ h e
Right x -> return v