你如何在 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));
Run Code Online (Sandbox Code Playgroud)
我可以想到两种方法:-
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
}
Run Code Online (Sandbox Code Playgroud)
对于第二个选项,我有以下组合器
combiner :: b -> Either a (b0 -> (b, b0));
combiner x = Right (x,) …Run Code Online (Sandbox Code Playgroud)