How to optimize the coincidence of a nested template with multiple repeating cases?

Please review 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 twice: with Right and with error cases.

How can I optimize this? Is it possible at all?

+8
pattern-matching haskell
source share
2 answers

I would put the error handling part outside the case part:

 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 
+4
source share

This is a good application for templates>:

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

All Articles