Partiality Monad变压器

J. *_*son 11 monads haskell

我试图将attadarsec中IResultmonad 解构为几块.这里的IResult

data IResult t r = Fail t [String] String
                 | Partial (t -> IResult t r)
                 | Done t r
Run Code Online (Sandbox Code Playgroud)

这感觉它应该是效果,"偏袒"和失败的组合.如果失败被表示为只是一个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
Run Code Online (Sandbox Code Playgroud)

(当你使用时,它会从Danielsson的论文中获得同名Partiality ())

我可以Partiality用作基础monad,但是有PartialityTmonad变换器吗?

Gab*_*lez 12

肯定有!你的Partialitymonad是一个免费的monad:

import Control.Monad.Free  -- from the `free` package

type Partiality t = Free ((->) t)
Run Code Online (Sandbox Code Playgroud)

...而相应的PartialityT是一个免费的monad变换器:

import Control.Monad.Trans.Free  -- also from the `free` package

type PartialityT t = FreeT ((->) t)
Run Code Online (Sandbox Code Playgroud)

这是一个示例程序,展示了如何使用它:

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)
Run Code Online (Sandbox Code Playgroud)

我们使用await命令构建free monad转换器来请求新值并lift调用基monad中的动作.我们免费获得MonadMonadTrans实例PartialityT,因为免费的monad变换器自动为任何给定的仿函数的monad和monad变换器.

我们像这样运行上面的程序:

>>> runPartialityT [1..] printer
1
2
3
...
Run Code Online (Sandbox Code Playgroud)

我建议你阅读我写的关于免费monad变形金刚的这篇文章.然而,免费monad变压器的新官方主页是free包.

此外,如果您正在寻找一个有效的增量解析器,我将pipes-parse在几天内将其作为包发布.您可以在此处查看当前草稿.

  • 哦,当然是!我的缺点是我无法弄清楚内部monadic层应该在哪里并定义`data PartialityT tma = PT {runPT :: m(Partiality ta)}`...它只给我一个内在的monadic层!感谢你向正确的方向推进(以及明显的推广!) (2认同)