Partiality Monad变压器

时间:2013-03-04 00:55:43

标签: haskell monads

我正试图将IResult monad从attoparsec解构为几件。这是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变换器吗?

1 个答案:

答案 0 :(得分:12)

确实有!你的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命令构建免费的monad转换器以请求新值,并lift调用基本monad中的操作。我们免费获得Monad的{​​{1}}和MonadTrans个实例,因为免费的monad变换器会自动成为任何给定仿函数的monad和monad变换器。

我们像这样运行上述程序:

PartialityT

我建议你阅读this post I wrote about free monad transformers。然而,免费monad变换器的新官方主页是>>> runPartialityT [1..] printer 1 2 3 ... 包。

此外,如果您正在寻找有效的增量解析器,我将在几天内将其作为free包发布。您可以查看current draft here