haskell - 合并两个 Either Monad 的结果

你如何在 Haskell 中处理这种情况(下面提供了伪代码)?

 x = somethingThatReturnsMaybe(s1)
 y = somethingThatReturnsMaybe(s2)

 if(x == Nothing) return Left "invalid x"
 if(y == Nothing) return Left "invalid y"

 callFn(fromJust(x), fromJust(y));

我可以想到两种方法:-

  1. 从调用处传递Maybes,这样上面的代码就可以包装在一个函数中,我可以在函数绑定(bind)/定义中使用模式匹配。
  2. 我编写了这段代码以使用 Either 组合这些值
mapToRight (\(x, y) -> callFn x y) combined_values
                where { combined_values = (maybeToRight "Invalid x!" x >>= combiner) <*>
                                        maybeToRight "Invalid target position" y;
                mapToRight = second; x = somethingThatReturnsMaybe s1; y = somethingThatReturnsMaybe s2
                }

对于第二个选项,我有以下组合器

combiner :: b -> Either a (b0 -> (b, b0));
combiner x = Right (x,)

maybeToRight :: a -> Maybe b -> Either a b
maybeToRight a Nothing = Left a
maybeToRight a (Just x) = Right x

这两者之间有什么偏好吗(虽然第一个对我来说不太好,因为它可能涉及更多的变化),或者有更好的选择吗?

最佳答案

我会导入 Control.Error ,然后这样写:

do
    x <- note "invalid x" (somethingThatReturnsMaybe s1)
    y <- note "invalid y" (somethingThatReturnsMaybe s2)
    callFn x y

note这是您的 maybeToRightEither(>>=) 实现正在处理展开/组合。

https://stackoverflow.com/questions/66782441/

相关文章:

go - Helm : How to convert a string into lower/upp

c# - 用源发生器代替反射

python-3.x - 根据索引和标签转换数据框

python - Pandas 在特定列的行上创建中位数

user-interface - 在 TreeView Odoo 13 之外添加按钮

python - Pandas:Groupby 并使用剩余的列名和值创建字典

rust - 为什么 Rust 元组不使用方括号访问里面的元素?

javascript - 不要将数字或单词替换为下划线,而是保留破折号并删除其周围的空格

javascript - 如何使用react router dom显示详细信息页面

go - 为什么在地址上取消引用会在 golang 中产生 "invalid indirect"错误