表示StateT Functor实例定义的替代方法

问题描述 投票:1回答:1

我以以下方式实现了FunctorStateT实例

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
haskell functor state-monad
1个回答
0
投票
利用元组的Bifunctor实例。使用Data.Bifunctor.first代替Data.Bifunctor.first
© www.soinside.com 2019 - 2024. All rights reserved.