モチベーション。私はモナド変換子を作成しようとしています。これは、「、f <||> g
を含むこのブロック全体をf <||> g
、1回f
は、、次はを含む」という意味の特別な命令を使用して作成していg
ます。他のアプリケーションを想像することはできますが、これはDSL変換を目的としています。
使用例。モナドは、computation
さまざまな可能な選択肢(この場合は印刷するもの)を表します。この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 et al。の「モナド変換子のバックトラッキング、インターリーブ、および終了」の論文を見ましたが、それらの実装を完全に把握することはできません(msplit
継続して実装に到達すると)。
現在の実装。私の現在の実装は、行われる分岐決定のリストを渡すことです。モナドは実際に選択したブランチのリストを返し、次に可能な最後のブランチを切り替えます。コードは次のとおりです(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)