17 haskell state-monad monad-transformers
我正在努力,Data.Fresh并且Control.Monad.Trans.Fresh,正在进行中.定义用于生成新变量的接口,以及实现此接口的monad变换器.
我最初认为可以Applicative为我实现实例,FreshT v m只有Applicative m存在的唯一要求.但是,我卡住了,似乎我需要Monad m.不相信我的Haskell的福,我再转向变压器包,并且很惊讶我发现Control.Monad.Trans.State.Lazy和.Strict:
instance (Functor m, Monad m) => Applicative (StateT s m) where
    pure = return
    (<*>) = ap
所以这是我的问题:是否可以使用以下实例头创建具有等效语义的实例?
instance (Applicative m) => Applicative (StateT s m) where
Mac*_*tka 14
考虑一下你有两个功能:
 f :: s -> m (s, a -> b)
 g :: s -> m (s, a)
而你想要创建一个功能 h = StateT f <*> StateF g
 h :: s -> m (s, b)
从上面你有一个s你可以通过,f所以你有:
 f' :: m (s, a -> b)
 g :: s -> m (s, a)
然而让s出f'你需要的单子(无论你与应用性将仍然是在做形式m s,所以你将无法应用价值g).
您可以使用定义并使用免费的monad,但是对于您需要的状态崩溃join.
Applicative变压器型号虽然无法为其定义适用变压器StateT,但可以定义一个有效的较弱变量.我们可以使用或等效地s -> m (a, s),而不是在国家决定下一个效果(因此m必须是单子格)的地方.m (s -> (a, s))m (State s a)
import Control.Applicative
import Control.Monad
import Control.Monad.State
import Control.Monad.Trans
newtype StateTA s m a = StateTA (m (State s a))
这严重弱于StateT.每一个StateTA都可以制成StateT(但反之亦然):
toStateTA :: Applicative m => StateTA s m a -> StateT s m a
toStateTA (StateTA k) = StateT $ \s -> flip runState s <$> k
定义Functor并且Applicative只是将操作提升State到底层的问题m:
instance (Functor m) => Functor (StateTA s m) where
    fmap f (StateTA k) = StateTA $ liftM f <$> k
instance (Applicative m) => Applicative (StateTA s m) where
    pure = StateTA . pure . return
    (StateTA f) <*> (StateTA k) = StateTA $ ap <$> f <*> k    
我们可以定义一个适用的变体lift:
lift :: (Applicative m) => m a -> StateTA s m a
lift = StateTA . fmap return
更新:实际上上面没有必要,因为两个applicative functor的组合总是一个applicative functor(不像monads).我们StateTA是同构的Compose m (State s),它是自动的Applicative:
instance (Applicative f, Applicative g) => Applicative (Compose f g) where
    pure x = Compose (pure (pure x))
    Compose f <*> Compose x = Compose ((<*>) <$> f <*> x)
因此我们可以写
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
import Control.Applicative
import Control.Monad.State
import Data.Functor.Compose
newtype StateTA s m a = StateTA (Compose m (State s) a)
    deriving (Functor, Applicative)
虽然,如前面的答案所述,这个实例一般不能定义,但值得注意的是,当fis Applicative和sa时Monoid,StateT s f也是Applicative,因为它可以被视为应用函子的组合:
StateT s f = Reader s `Compose` f `Compose` Writer s
| 归档时间: | 
 | 
| 查看次数: | 878 次 | 
| 最近记录: |