Sat*_*mar 2 haskell functional-programming
你如何在 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,)
maybeToRight :: a -> Maybe b -> Either a b
maybeToRight a Nothing = Left a
maybeToRight a (Just x) = Right x
Run Code Online (Sandbox Code Playgroud)
这两者之间是否有任何偏好(虽然第一个对我来说不太可取,因为它可能涉及更多的变化),或者有没有更好的选择?
我会导入Control.Error,然后写这个:
do
x <- note "invalid x" (somethingThatReturnsMaybe s1)
y <- note "invalid y" (somethingThatReturnsMaybe s2)
callFn x y
Run Code Online (Sandbox Code Playgroud)
这note是您的maybeToRight. 的Either的的实现(>>=)是处理解缠/组合。