我以以下方式实现了Functor
的StateT
实例
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
但是我对解决方案不满意[[wholly,因为它要求我从swap
导入Data.Tuple
并在元组中两次导入fmap
以便将f
应用于第一个元素。
Functor
实例的方式,我想不起来根本不需要swap