Avoid Nested Pattern Matching

What’s the recommendations to fix nested pattern matching that has more than 2 variations (e.g. something like RemoteData, not Result or Maybe)?

Been stuck in TypeScript, and using their Unions, you have to use switch statements, and they can get nested quickly. In my head, I see the red squiggles from that elm-review rule saying “You can’t nest pattern matching beyond 1 level, we suggest Maybe.andThen”. Figured if I knew how to solve this in Elm, I could carry over the same idea to TypeScript.

Some quick googling: The Scala kids say if not a dual Monad, “Eitherise” your type so you can do a sort of “andThen”. This may not work if you don’t have sum type that has a zero or error equivalent; mine don’t.

The Rust/F# cats say use their yield, but… again, this only works for Either’s.

The Elixir examples, and even a SonarQube rule equivalent, just say to make functions that abstract away the choice, and you can then have 3 functions together to remove the nesting entirely. I may just do this, but curious if there are other ways.

Im not sure if i understood your question correctly,
but i try giving an example: RemoteData (Maybe Error) (List String).

I would do exhaustive pattern matching like this

case remoteData of
  NotAsked -> "Not loaded"
  Loading -> "Loading"
  Failure Nothing -> "something is wrong"
  Failure (Just head) -> "an error occured:" ++ Error.toString head
  Success [] -> "Nothing Found"
  Success list -> "Found " +  (String.join ", " list)

Personally however, i like using nested pattern matching if its talking about different domains. Like in this example, Error.toString will again be using pattern matching, I don’t see this as a code smell.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.