8

请考虑以下代码:

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"

你可以看到我必须重复两次:with theRight和 with the errorcase。

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

4

2 回答 2

10

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

case action1 of
  Right a -> a
  Left f
    | Failure1 a <- f       -> a
    | Failure2 a <- f
    , Right b <- action2 a  -> b
  _ -> error "Unexpected failure"
于 2013-06-21T07:30:10.767 回答
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
于 2013-06-21T15:15:13.447 回答