gpt4 book ai didi

haskell - 偏向 Monad 变压器

转载 作者:行者123 更新时间:2023-12-02 09:54:04 25 4
gpt4 key购买 nike

我正在尝试从 attoparsec 解构 IResult monad分成几 block 。这是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 转换器吗?

最佳答案

肯定有!您的 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 中的操作。我们免费获得 PartialityTMonadMonadTrans 实例,因为免费的 monad 转换器自动成为任何给定仿函数的 monad 和 monad 转换器。

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

>>> runPartialityT [1..] printer
1
2
3
...

我建议您阅读this post I wrote about free monad transformers 。然而,免费 monad 转换器的新官方主页是 free 包。

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

关于haskell - 偏向 Monad 变压器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15192897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com