如何针对多个重复案例优化嵌套模式匹配?

Nik*_*kov 8 haskell pattern-matching

请考虑以下代码:

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"
Run Code Online (Sandbox Code Playgroud)

你可以看到,我不得不重复自己两次与Right和与error案件.

我该如何优化呢?有可能吗?

lef*_*out 10

这是模式保护的一个很好的应用:

case action1 of
  Right a -> a
  Left f
    | Failure1 a <- f       -> a
    | Failure2 a <- f
    , Right b <- action2 a  -> b
  _ -> error "Unexpected failure"
Run Code Online (Sandbox Code Playgroud)


Pet*_*lák 4

我将错误处理部分放在该case部分之外:

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
Run Code Online (Sandbox Code Playgroud)