module Control.Monad.Trans.Reader (
Reader,
reader,
runReader,
mapReader,
withReader,
ReaderT(..),
mapReaderT,
withReaderT,
ask,
local,
asks,
liftCallCC,
liftCatch,
) where
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Data.Functor.Identity
import Control.Applicative
import Control.Monad
import Control.Monad.Fix
#if !(MIN_VERSION_base(4,6,0))
import Control.Monad.Instances ()
#endif
type Reader r = ReaderT r Identity
reader :: (r -> a) -> Reader r a
reader f = ReaderT (Identity . f)
runReader :: Reader r a
-> r
-> a
runReader m = runIdentity . runReaderT m
mapReader :: (a -> b) -> Reader r a -> Reader r b
mapReader f = mapReaderT (Identity . f . runIdentity)
withReader
:: (r' -> r)
-> Reader r a
-> Reader r' a
withReader = withReaderT
newtype ReaderT r m a = ReaderT {
runReaderT :: r -> m a
}
mapReaderT :: (m a -> n b) -> ReaderT r m a -> ReaderT r n b
mapReaderT f m = ReaderT $ f . runReaderT m
withReaderT
:: (r' -> r)
-> ReaderT r m a
-> ReaderT r' m a
withReaderT f m = ReaderT $ runReaderT m . f
instance (Functor m) => Functor (ReaderT r m) where
fmap f = mapReaderT (fmap f)
instance (Applicative m) => Applicative (ReaderT r m) where
pure = liftReaderT . pure
f <*> v = ReaderT $ \ r -> runReaderT f r <*> runReaderT v r
instance (Alternative m) => Alternative (ReaderT r m) where
empty = liftReaderT empty
m <|> n = ReaderT $ \ r -> runReaderT m r <|> runReaderT n r
instance (Monad m) => Monad (ReaderT r m) where
return = lift . return
m >>= k = ReaderT $ \ r -> do
a <- runReaderT m r
runReaderT (k a) r
fail msg = lift (fail msg)
instance (MonadPlus m) => MonadPlus (ReaderT r m) where
mzero = lift mzero
m `mplus` n = ReaderT $ \ r -> runReaderT m r `mplus` runReaderT n r
instance (MonadFix m) => MonadFix (ReaderT r m) where
mfix f = ReaderT $ \ r -> mfix $ \ a -> runReaderT (f a) r
instance MonadTrans (ReaderT r) where
lift = liftReaderT
instance (MonadIO m) => MonadIO (ReaderT r m) where
liftIO = lift . liftIO
liftReaderT :: m a -> ReaderT r m a
liftReaderT m = ReaderT (const m)
ask :: (Monad m) => ReaderT r m r
ask = ReaderT return
local :: (Monad m)
=> (r -> r)
-> ReaderT r m a
-> ReaderT r m a
local = withReaderT
asks :: (Monad m)
=> (r -> a)
-> ReaderT r m a
asks f = liftM f ask
liftCallCC ::
(((a -> m b) -> m a) -> m a)
-> ((a -> ReaderT r m b) -> ReaderT r m a) -> ReaderT r m a
liftCallCC callCC f = ReaderT $ \ r ->
callCC $ \ c ->
runReaderT (f (ReaderT . const . c)) r
liftCatch ::
(m a -> (e -> m a) -> m a)
-> ReaderT r m a
-> (e -> ReaderT r m a)
-> ReaderT r m a
liftCatch f m h =
ReaderT $ \ r -> f (runReaderT m r) (\ e -> runReaderT (h e) r)