[英]In composite StateT / Maybe monad, how to take either possibility that succeeds?
在 Haskell 中,这是一个结合了 State 和 Maybe monad 的 monad:
type StatefulMaybe a = StateT Int Maybe a
这是一个可以成功(返回值)或失败的计算。 如果成功,它会携带一个 state 以及返回值。
我想写一个 function
choice :: StatefulMaybe a -> StatefulMaybe a -> StatefulMaybe a
它需要两次这样的计算并返回成功的第一个(如果有的话)。 只有通过成功计算的 state 更改被结转。
事实上,经过一些实验,我想出了如何写这个。 这里是:
orMaybe :: Maybe a -> Maybe a -> Maybe a
orMaybe (Just x) _ = Just x
orMaybe Nothing x = x
choice :: StatefulMaybe a -> StatefulMaybe a -> StatefulMaybe a
choice mx my = StateT (\s ->
(runStateT mx s) `orMaybe` (runStateT my s)
)
有用:
foo :: StatefulMaybe String
foo = do
modify (+ 20)
fail "didn't succeed"
baz :: StatefulMaybe String
baz = do
modify (+ 30)
return "two"
bar :: StatefulMaybe String
bar = do
s <- choice foo baz
return (s ++ " done")
> runStateT bar 0
Just ("two done",30)
我的问题是:有没有比我上面的实现更简单或更自然的方法来编写这个选择 function? 特别是,有什么方法可以将orMaybe
function 提升到我的单子中?
如果我正确理解了这个问题,我认为这个 function 已经存在: <|> :
bar :: StatefulMaybe String
bar = do
s <- foo <|> baz
return (s ++ " done")
<|>
function 是Applicative
类型 class 的一部分,其中StateT
是当内部 monad 既是Functor
又是MonadPlus
实例时的一个实例,这对于Maybe
来说是正确的。
*Q66992923> runStateT bar 0
Just ("two done",30)
正如 luqui 在评论中所建议的那样,我认为mplus
应该可以工作,因为mplus
的默认实现是<|>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.