你如何在 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));
我可以想到两种方法:-
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
这是您的 maybeToRight
。 Either
的 (>>=)
实现正在处理展开/组合。
https://stackoverflow.com/questions/66782441/