[Haskell-cafe] Re: Monad.Reader with updates
Brent Yorgey
byorgey at seas.upenn.edu
Fri Nov 7 08:54:39 EST 2008
On Fri, Nov 07, 2008 at 10:41:01AM +0100, Achim Schneider wrote:
>
> But then, you either want a ReaderT r State s or StateT s Reader r,
> depending on how you want to write your code... the main thing that
> confuses me right now is that nesting order doesn't seem to matter that
> much in this case which makes me wonder if I really understood how
> those two nest.
>From the mtl documentation ([1], [2]):
Reader r a =~ r -> a
State s a =~ s -> (a, s)
StateT s m a =~ s -> m (a, s)
ReaderT r m a =~ r -> m a
where =~ indicates isomorphism of types (up to newtype tags).
So,
ReaderT r (State s) a =~ r -> State s a =~ r -> s -> (a,s)
and
StateT s (Reader r) a =~ s -> Reader r (a,s) =~ s -> r -> (a,s)
which are clearly isomorphic, just a simple function argument
reordering. For some combinations of monad transformers (for
example, StateT and MaybeT), the order of composition really does
matter, but not for Reader and State.
Moreover, if you make your new composed monad using a newtype with
generalized deriving [3], the choice actually doesn't matter since you
can write exactly the same code:
newtype MyMonad a = My { unMy :: ReaderT r (State s) a }
deriving (Functor, Monad, MonadReader r, MonadState s)
You could also write the newtype the other way around, and still use
it with the same code: you can just treat MyMonad as if it is both a
Reader monad (ask, asks, local...) and a State monad (get, gets, put,
modify...) with no icky lifts in sight.
I don't know what this thread was originally about, but just thought
I'd jump in to clarify. =)
-Brent
[1] http://hackage.haskell.org/packages/archive/mtl/1.1.0.1/doc/html/Control-Monad-State-Lazy.html
[2] http://hackage.haskell.org/packages/archive/mtl/1.1.0.1/doc/html/Control-Monad-Reader.html
[3] http://cale.yi.org/index.php/How_To_Use_Monad_Transformers
More information about the Haskell-Cafe
mailing list