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"

2 回繰り返す必要があることがわかります。ケースRighterrorケースです。

これを最適化するにはどうすればよいですか?それはまったく可能ですか?

4

2 に答える 2

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 に答える