Haskell 如何在多个重复情况下优化嵌套模式匹配? 请考虑此代码: case action1 of Right a -> a Left (Failure1 a) -> a Left (Failure2 a) -> case action2 a of Right a -> a _ -> error "Unexpected failure" _ -> error "Unexpected failure"

Haskell 如何在多个重复情况下优化嵌套模式匹配? 请考虑此代码: case action1 of Right a -> a Left (Failure1 a) -> a Left (Failure2 a) -> case action2 a of Right a -> a _ -> error "Unexpected failure" _ -> error "Unexpected failure",haskell,pattern-matching,Haskell,Pattern Matching,您可以看到,我必须重复两次:使用右侧和错误案例 我如何优化这一点?有可能吗?这是一个很好的应用程序: 案例行动1 右a->a 左f |失败 |故障2错误“意外故障” 我将错误处理部分放在案例之外部分: fromMaybe (error "Unexpected failure") $ let eitherToMaybe = either (const Nothing) Just in case action1 of Right a ->

您可以看到,我必须重复两次:使用
右侧
错误
案例


我如何优化这一点?有可能吗?

这是一个很好的应用程序:

案例行动1
右a->a
左f
|失败
|故障2错误“意外故障”

我将错误处理部分放在
案例之外
部分:

fromMaybe (error "Unexpected failure") $
    let eitherToMaybe = either (const Nothing) Just
    in case action1 of
          Right a           -> Just a
          Left (Failure1 a) -> Just a
          Left (Failure2 a) -> eitherToMaybe (action2 a)
          _                 -> Nothing

你的阴影变量
a
不是很好,是吗?我一开始是无害地复制它,但它破坏了我的解决方案。我不得不说,从惯用的角度来看,这是一个非常好的解决方案。谢谢谢谢一个很好的建议。
fromMaybe (error "Unexpected failure") $
    let eitherToMaybe = either (const Nothing) Just
    in case action1 of
          Right a           -> Just a
          Left (Failure1 a) -> Just a
          Left (Failure2 a) -> eitherToMaybe (action2 a)
          _                 -> Nothing