Consider the State
type - or at least a simplified version:
newtype State s a = State { runState :: s -> (a, s) }
Now, let's say we want to derive the StateT
monad transformer. transformers
defines it as follows:
newtype StateT s m a = StateT { runStateT :: s -> m (a, s) }
Here, the m
has been placed on the right of the function arrow, but outside the tuple. However, if we didn't know the correct answer, we might instead put m
somewhere else:
newtype StateT s m a = StateT { runStateT :: m (s -> ( a, s)) }
newtype StateT s m a = StateT { runStateT :: s -> (m a, s) }
Obviously the version in transformers
is correct, but why? More generally, how does one know where to put the type variable for the 'inner' monad when defining a monad transformer? Generalising even more, is there a similar rule for comonad transformers?