代表无限动作链的 Monad 转换器?

问题描述

我尝试实现一个表示无限动作链的单子转换器,如下所示:

import Control.Arrow
import Control.Monad
import Data.Functor.Classes
import Data.Functor.Identity
import Data.Monoid
import Data.Semigroup
import Text.Read

import qualified Control.Monad.Trans.Class as T

newtype WhileT m a = WhileT {uncons :: m (a,WhileT m a)}

instance T.MonadTrans WhileT where
    lift m = WhileT $ do
        x <- m
        pure (x,T.lift m)

headW :: Functor m => WhileT m a -> m a
headW (WhileT m) = fmap fst m

tailW :: Functor m => WhileT m a -> m (WhileT m a)
tailW (WhileT m) = fmap snd m

drop1 :: Monad m => WhileT m a -> WhileT m a
drop1 m = WhileT (tailW m >>= uncons)

dropN :: Monad m => Int -> WhileT m a -> WhileT m a
dropN n = appEndo (stimes n (Endo drop1))

instance Functor m => Functor (WhileT m) where
    fmap f (WhileT m) = WhileT (fmap (f *** fmap f) m)

instance Monad m => applicative (WhileT m) where
    pure x = WhileT (pure (x,pure x))
    (<*>) = ap

instance Monad m => Monad (WhileT m) where
    WhileT m >>= f = WhileT $ do
        (x,xs) <- m
        y <- headW (f x)
        let ys = xs >>= drop1 . f
        pure (y,ys)

名称 WhileT 在 C 的 while 之后。很容易看出 WhileT Identity一个 monad。

但是 m 的其他选择呢?特别是,从一些实验来看,WhileT Maybe似乎等价于ZipList。但是已经知道没有instance Monad ZipList。这是否意味着 WhileT 不是真正的 monad 转换器?

解决方法

this link 的反例也适用于您的 WhileT Maybe

-- to make these things a bit more convenient to type/read
fromListW :: [a] -> WhileT Maybe a
fromListW [] = WhileT Nothing
fromListW (x:xs) = WhileT (Just (x,fromListW xs))

xs = fromListW [1,2]

f 1 = fromListW [11]
f 2 = fromListW [21,22]

g 11 = fromListW [111]
g 21 = fromListW []
g 22 = fromListW [221,222]

然后,在 ghci 中:

> (xs >>= f) >>= g
WhileT {uncons = Just (111,WhileT {uncons = Just (222,WhileT {uncons = Nothing})})}
> xs >>= (\x -> f x >>= g)
WhileT {uncons = Just (111,WhileT {uncons = Nothing})}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...