Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to refactor such a dummy code with help of Haskell's standard libraries?

I am currently working with quite dirty project written in Haskell. It contains lots of code like:

try_parse_parameters (p:ps) kvps options = 
        let maybeKvp = try_parse_kvp p 
        in
          if isJust maybeKvp 
            then try_parse_parameters ps ((fromJust maybeKvp) : kvps) options
            else 
              let maybeOption = try_parse_option p
              in 
                if isJust maybeOption
                  then try_parse_parameters ps kvps ((fromJust maybeOption) : options)
                  else try_parse_parameters ps kvps options

Thus, my questions is: is there some standard method(s) to deal with such a situation?

like image 988
Zazeil Avatar asked Dec 05 '25 04:12

Zazeil


1 Answers

You can also handle more than one case with pattern matching, avoiding the pyramid of doom.

try_parse_parameters (p:ps) kvps options = 
    case (try_parse_kvp p, try_parse_option p) of
      (Just k, _)       -> try_parse_parameters ps (k : kvps) options
      (Nothing, Just o) -> try_parse_parameters ps kvps (o : options)
      (Nothing, Nothing)-> try_parse_parameters ps kvps options
like image 88
Euge Avatar answered Dec 07 '25 19:12

Euge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!