2013-06-21 25 views
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" 

你可以看到,我不得不重複自己兩次:與Right並與error箱子。

我該如何優化?它有可能嗎?

+2

你的陰影變量'了'不是很好,是它?我首先無害地複製了它,但它破壞了我的解決方案。 – leftaroundabout

回答

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 
+1

我不得不說,從慣用的角度來看,這是一個非常好的解決方案。謝謝! –

10

這對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" 
+1

謝謝!一個很好的建議。 –