I'm implemented the Functor
instance for StateT
in the following manner
import Data.Tuple (swap)
newtype StateT s m a =
StateT { runStateT :: s -> m (a, s) }
instance Functor m => Functor (StateT s m) where
fmap f (StateT g) = StateT $ \s -> fmap (fmapSwapTwice f) (g s)
where fmapSwapTwice f tup = swap $ f <$> swap tup
But I'm not wholly satisfied with my solution, because it requires me to import swap
from Data.Tuple
and fmap
it over the tuple twice in order to apply f
to the first element.
To me this seems like a common enough pattern that would have its own abstraction or perhaps there is an alternative way to express the Functor
instance that I can't think of which doesn't require swap
at all
Take advantage of the Bifunctor
instance of tuples. Use Data.Bifunctor.first
instead of fmapSwapTwice
.