我最近写
do
e <- (Left <$> m) <|> (Right <$> n)
more actions
case e of
Left x -> ...
Right y -> ...
这似乎很尴尬。我知道protolude
(和其他一些包)定义-- Called eitherP in parser combinator libraries
eitherA :: Alternative f => f a -> f b -> f (Either a b)
但即便如此,这一切都感觉有点手动。有没有一些我没见过的很好的模式来收紧它?
最佳答案
我刚刚注意到 OP 表达了同样的想法 in a comment .无论如何我都会发表我的想法。
Coyoneda 是一个巧妙的技巧,但对于这个特殊问题来说有点过分了。我认为您所需要的只是常规的旧延续。
让我们将它们命名为 ...
年代:
do
e <- (Left <$> m) <|> (Right <$> n)
more actions
case e of
Left x -> fx x
Right y -> fy y
然后,我们可以把它写成:do
e <- (fx <$> m) <|> (fy <$> n)
more actions
e
这有点微妙——使用 <$>
很重要。尽管看起来您可能想使用 =<<
因此第一行的结果实际上是稍后执行的一元操作,而不是立即执行的操作。
关于haskell - 如何在 MonadPlus/Alternative 中组合然后分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70840743/