I'm pulling together code from a number of different places, and I'm trying to deal with the following:
Problem
I have a transformer stack with the following simplified type:
action :: m (ReaderT r IO) a
and I'm trying to use the action in the context of a different stack, which has a different reader environment:
desired :: m (ReaderT r' IO) a
I can of course provide
f :: r' -> r
Example
things :: m (ReaderT r' IO) ()
things = do
-- ... some stuff
-- <want to use action here>
action :: m (ReaderT r IO) a -- broken
-- ... more stuff
pure ()
What I've considered
withReaderT :: (r' -> r) -> ReaderT r m a -> ReaderT r' m a
This has the problem that ReaderT is the outer monad, whilst I want to use it on an inner one.
I've also considered that this might be related to MonadBase or MonadTransControl, but I'm not familiar with their workings.
I don't think it's possible to write a function with signature:
the issue being that the only operation possible, in general, on the second argument is lifting it to
t (m (ReaderT r IO)) afor some monad transformert, which doesn't buy you anything.That is, the
MonadTrans mconstraint alone doesn't provide enough structure to do what you want. You either needmto be an instance of a typeclass likeMFunctorin themmorphpackage that allows you to modify an inner layer of the monad stack in a general way by providing a function like:(which is what @Juan Pablo Santos was saying), or else you need an ability to dig into the structure of your
mmonad transformer to partially run and rebuild it (which will be transformer-specific).The first approach (using
hoistfrom themmorphpackage) will be most convenient if yourmis already made up of transformers supported by themmorphpackage. For example, the following typechecks, and you don't have to write any instances:You'll need a
hoistfor each layer inM.The second approach avoids
hoistand requisiteMFunctorinstances but requires tailoring to your specificM. For the above type , it looks something like:You basically need to run the monad down to the
ReaderTlayer and then rebuild it back up, treating layers likeStateTwith care. This is exactly what theMFunctorinstances inmmorphare doing automatically.