haskell

How to factor out duplication code Haskell ( Maybe & If-Else)


Here is the dummy code,

   case fruit of 
       Just apple ->
           if testSweet apple then 
               <ProcessA>
           else
               <ProcessB>
       Nothing ->
               <ProcessB>

But it looks duplication here , any way to fix this ? I think the optimal way there should be only one <ProcessB> in the code.


Solution

  • You can use a guard and a catch-all fallback:

    case fruit of 
       Just apple | testSweet apple ->
          <ProcessA>
       _ ->
          <ProcessB>
    

    The last case _ will match both Nothing and Just non_sweet cases.