动机。我正在尝试创建一个 monad 转换器,其特殊指令f <||> g
表示“重复整个块,其中包含f <||> g
一次f
,下一次使用g
”。这旨在用于 DSL 转换,尽管您可以想象其他应用程序。
示例用法。computation
monad 表达了不同的可能选择(在这种情况下,是要打印的东西)。该printme
函数说明如何处理每个不同的结果。在这种情况下,我们在运行之前打印“开始计算”,之后打印“---”。
computation = do
lift (print "start -- always")
(lift (print "first choice") <||> lift (print "second choice"))
lift (print "intermediate -- always")
(lift (print "third choice") <||> lift (print "fourth choice"))
lift (print "end -- always")
printme x = do
putStrLn "=== start computation"
xv <- x
putStrLn "---\n"
return xv
test = runIndep printme computation
输出如下,
=== start computation
"start -- always"
"first choice"
"intermediate -- always"
"third choice"
"end -- always"
---
=== start computation
"start -- always"
"first choice"
"intermediate -- always"
"fourth choice"
"end -- always"
---
=== start computation
"start -- always"
"second choice"
"intermediate -- always"
"third choice"
"end -- always"
---
=== start computation
"start -- always"
"second choice"
"intermediate -- always"
"fourth choice"
"end -- always"
---
问题。有没有一种干净的方法可以使用某种延续传递风格的单子变压器来实现上述行为?我查看了 Oleg 等人的“Backtracking, Interleaving, and Terminating Monad Transformers”论文,但似乎无法完全掌握它们的实现(一旦他们msplit
使用延续实现)。
当前实施。我当前的实现是传入要做出的分支决策列表。monad 将返回它实际选择的分支列表,然后下次我们将切换最后一个可能的分支。代码如下(应该在7.0.3运行),
import Control.Monad.Trans.Class
data IndepModelT α = IndepModelT {
unIndepModelT :: [Bool] -> (α, [Bool]) }
instance Monad => Monad (IndepModelT ) where
return x = IndepModelT $ \choices -> return (x, [])
(IndepModelT x) >>= f = IndepModelT $ \choices -> do
(xv, branches) <- x choices
let choices' = drop (length branches) choices
(fxv, branches') <- unIndepModelT (f xv) choices'
return (fxv, branches ++ branches')
instance MonadTrans IndepModelT where
lift x = IndepModelT $ \c -> liftWithChoice [] x
liftWithChoice cs mx = mx >>= \xv -> return (xv, cs)
(<||>)
:: Monad => IndepModelT α -> IndepModelT α -> IndepModelT α
(IndepModelT f) <||> (IndepModelT g) = IndepModelT go where
go (False:cs) = do
(fv, branches) <- f cs
return (fv, False : branches)
go (True:cs) = do
(fv, branches) <- g cs
return (fv, True : branches)
run_inner next_choices k comp@(IndepModelT comp_inner) = do
(xv, branches) <- k $ comp_inner next_choices
case (get_next_choices branches) of
Nothing -> return ()
Just choices -> run_inner (choices ++ repeat False) k comp
where
get_next_choices [] = Nothing
get_next_choices [True] = Nothing
get_next_choices [False] = Just [True]
get_next_choices (c:cs)
| Just cs' <- get_next_choices cs = Just $ c:cs'
| c Prelude.== False = Just [True]
| otherwise = Nothing
runIndep :: Monad =>
( (α, [Bool]) -> (β, [Bool]))
-> IndepModelT α
-> ()
runIndep = run_inner (repeat False)
runIndepFirst (IndepModelT comp) = comp (repeat False)