我正在尝试将attoparsec中的IResult monad解构为几个片段。这是IResult
data IResult t r = Fail t [String] String
| Partial (t -> IResult t r)
| Done t r这感觉应该是影响、“偏爱”和失败的组合。如果故障仅表示为Either ([String], String),则偏好可能是
data Partiality t a = Now a | Later (t -> Partiality t a)
instance Monad (Partiality t) where
return = pure
(Now a) >>= f = f a
(Later go) >>= f = Later $ \t -> go t >>= f
class MonadPartial t m where
feed :: t -> m a -> m a
final :: m a -> Bool
instance MonadPartial t (Partiality t) where
feed _ (Now a) = Now a
feed t (Later go) = go t
final (Now _) = True
final (Later _) = False(当您使用Partiality ()时,它从a paper by Danielsson获得其同名)
我可以使用Partiality作为基础monad,但是有PartialityT monad转换器吗?
发布于 2013-03-04 12:18:13
当然有!你的Partiality monad是一个免费的monad:
import Control.Monad.Free -- from the `free` package
type Partiality t = Free ((->) t)..。相应的PartialityT是一个自由的monad转换器:
import Control.Monad.Trans.Free -- also from the `free` package
type PartialityT t = FreeT ((->) t)下面是一个示例程序,展示了如何使用它:
import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.Free
type PartialityT t = FreeT ((->) t)
await :: (Monad m) => PartialityT t m t
await = liftF id
printer :: (Show a) => PartialityT a IO r
printer = forever $ do
a <- await
lift $ print a
runPartialityT :: (Monad m) => [a] -> PartialityT a m r -> m ()
runPartialityT as p = case as of
[] -> return ()
a:as -> do
x <- runFreeT p
case x of
Pure _ -> return ()
Free k -> runPartialityT as (k a)我们使用await命令来请求新值,使用lift来调用基础monad中的操作,从而构建自由的monad转换器。我们免费获得PartialityT的Monad和MonadTrans实例,因为免费的monad转换器对于任何给定的functor都会自动成为monad和monad转换器。
我们像这样运行上面的程序:
>>> runPartialityT [1..] printer
1
2
3
...我建议你阅读this post I wrote about free monad transformers。然而,免费的monad转换器的新官方主页是free包。
此外,如果您正在寻找一个有效的增量式解析器,我将在几天内将其作为pipes-parse包发布。您可以查看current draft here。
https://stackoverflow.com/questions/15192897
复制相似问题