我的目标是创建一个在 ReaderT WriterT 堆栈或 RWS 堆栈中使用列表 monad 的函数。更一般地说,如何在 mtl 类型类(例如 MonadReader、MonadWriter)中使用列表 monad?
我为什么要尝试这样做?这个问题是一个练习哈斯克尔入门 http://www.apress.com/9781430262503。它要求我“使用 MonadReader 和 MonadWriter 的功能来包装基本列表 monad。要检查该功能是否通用,请使用两个不同的 monad 来[测试]所请求的功能:ReaderT r (WriterT w []) a
and RWST r w s m a
“所以这本书暗示这是可能的。
我不知道如何“告诉”编译器使用列表单子。如果我使用ask >>= lift
or ask >>= lift . lift
我可以获得 2 级堆栈(RWST []
) 或 3 级堆栈 (ReaderT WriterT []
)工作,但不能两者兼而有之。
我的问题重点:
pathImplicitStack' start end | start == end = tell [end]
pathImplicitStack' start end =
do (s0, e0) <- ask >>= lift
guard $ s0 == start
tell [start]
pathImplicitStack' e0 end
另外,我想知道如何输入该函数。到目前为止我最好的尝试看起来像pathImplicitStack' :: (MonadReader [(Int, Int)] m, MonadWriter [Int] m, MonadPlus m) => Int -> Int -> m ()
我知道这是不对的,列表单子可能丢失了。另外,我认为 MonadPlus 在类型签名中可能有用,但我不太确定。
这行:do (s0, e0) <- ask >>= lift
是那个给我带来麻烦的人。我尝试了 0、1、2 次电梯,但都没有成功。我想ask
for a [(Int, Int)]
然后使用列表 monad 来处理(Int, Int)
(并让列表单子为我尝试所有可能性)。
作为练习的一部分,我需要能够调用pathImplicitStack'
具有这两个功能(或非常相似的功能):
pathImplicitRW :: [(Int, Int)] -> Int -> Int -> [[Int]]
pathImplicitRW edges start end = execWriterT rdr
where rdr = runReaderT (pathImplicitStack' start end) edges :: WriterT [Int] [] ()
pathImplicitRWS :: [(Int, Int)] -> Int -> Int -> [[Int]]
pathImplicitRWS edges start end = map snd exec
where exec = execRWST (pathImplicitStack' start end) edges ()
这与我之前的问题有关:如何在 ReaderT 中使用列表 monad? https://stackoverflow.com/questions/24178800/how-do-i-use-list-monad-inside-of-readert
整个文件方便测试:
{-# LANGUAGE FlexibleContexts #-}
module Foo where
import Control.Monad.Reader
import Control.Monad.Writer
import Control.Monad.RWS
graph1 :: [(Int, Int)]
graph1 = [(2013,501),(2013,1004),(501,2558),(1004,2558)]
pathImplicitRW :: [(Int, Int)] -> Int -> Int -> [[Int]]
pathImplicitRW edges start end = execWriterT rdr
where rdr = runReaderT (pathImplicitStack' start end) edges :: WriterT [Int] [] ()
pathImplicitRWS :: [(Int, Int)] -> Int -> Int -> [[Int]]
pathImplicitRWS edges start end = map snd exec
where exec = execRWST (pathImplicitStack' start end) edges ()
pathImplicitStack' :: (MonadReader [(Int, Int)] m, MonadWriter [Int] m, MonadPlus m) => Int -> Int -> [m ()]
pathImplicitStack' start end | start == end = tell [end]
pathImplicitStack' start end =
do (s0, e0) <- ask >>= lift
guard $ s0 == start
tell [start]
pathImplicitStack' e0 end
edit
根据约翰·L的反馈我尝试过
pathImplicitStack' :: (MonadReader [(Int, Int)] (t []), MonadWriter [Int] (t []), MonadPlus (t []), MonadTrans t) => Int -> Int -> t [] ()
pathImplicitStack' start end | start == end = tell [end]
pathImplicitStack' start end =
do (s0, e0) <- ask >>= lift
guard $ s0 == start
tell [start]
pathImplicitStack' e0 end
但正如他指出的,它只能与一个 monad 转换器一起使用来包装列表 monad,即 RSWT,并且不能与 ReaderT WriterT 一起使用。所以这不是我正在寻找的解决方案。