为 StateT 实施 Applicative (<*>)

Implementing Applicative (<*>) for StateT

有人问过这个问题 before,但没有真正的答案。事实上,接受的答案表明这是不可能的,尽管

我读到过的 MaybeT 实现之一

liftA2 (<*>) :: (Applicative f, Applicative f1) => f (f1 (a -> b)) -> f (f1 a) -> f (f1 b)

实现 Applicative,但我无法在此处实现。我正在进行的工作围绕以下方面尝试了很多选项:

-- (<*>) :: StateT s f (a -> b) -> State s f a -> State s f b
instance (Applicative f) => Applicative (StateT s f) where
    pure a =  StateT $ \s -> pure (a, s)
    (StateT f) <*> (StateT g) = StateT $ \s ->          -- f :: s -> m (a -> b, s),  g :: s -> m (a, s)
                                    let
                                        mabs = f s          -- mabs :: m (a -> b, s)
                                        mab = fmap fst mabs
                                        ms' = fmap snd mabs

                                    in undefined

我想知道我错过了什么,希望我能在这个过程中学到一些关于 Applicative 的东西。

一个实现(取自Tony Morris' functional programming course)可以是

(<*>) :: (Functor f, Monad f) =>
  StateT s f (a -> b)
  -> StateT s f a
  -> StateT s f b
StateT f <*> StateT a =
  StateT (\s -> (\(g, t) -> (\(z, u) -> (g z, u)) <$> a t) =<< f s)

Tony 使用了一些替代符号,而 Simon 的回答非常简洁,所以我最终得到的是:

-- (<*>) :: StateT s f (a -> b) -> State s f a -> State s f b
instance (Monad f, Applicative f) => Applicative (StateT s f) where
    pure a =  StateT $ \s -> pure (a, s)
    StateT f <*> StateT a =
        StateT $ \s -> 
                f s >>= \(g, t) ->                   -- (f s) :: m (a->b, s)
                    let mapper = \(z, u) -> (g z, u) -- :: (a, s) -> (b, s)
                    in fmap mapper (a t)             -- (a t) :: m (a, s)

我不得不将 f 也声明为 Monad,但这没关系,因为据我所知,它是 Monad 转换器定义的一部分。