简体   繁体   English

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

[英]How to optimise a nested pattern match with multiple repeated cases?

Please consider this code: 请考虑以下代码:

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"

You can see that I have to repeat myself twice: with the Right and with the error cases. 您可以看到我必须重复两次:使用Righterror情况。

How can I optimise this? 我该如何优化呢? Is it possible at all? 有可能吗?

That's a good application for pattern guards : 这是模式保护的一个很好的应用:

case action1 of
  Right a -> a
  Left f
    | Failure1 a <- f       -> a
    | Failure2 a <- f
    , Right b <- action2 a  -> b
  _ -> error "Unexpected failure"

I'd put the error handling part outside the case part: 我将错误处理部分放在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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM