Beginner question - "or" in pattern matches?

Hi, I think some other languages support a pattern match that uses an or operator like “|”. Does that exist in Elm? If not, how to people deal with duplication if they use two case clauses?

For example:

case x of
  1 | 2 -> ...

I’m new to Elm but this issue came up in my first app - which deals with our nine solar-system planets.

I had started with an elm type with 9 values. Only one of these “Earth” required different handling so I wanted to know how to match against “any of” Mercury, Venus, Mars, Jupiter … Pluto.

The solution was to change my type to only have two types: Earth | Alien.

Doing this simplified my case statements.

You don’t, I think, provide a real-world example, but could you also review how you’ve defined x?

1 Like

It’s not possible to do exactly what you’re asking for in elm. The solution I usually use is to factor out the body of the case statement to a function to avoid duplication. Your example would become:

factoredOut = ...

case x of
    1 ->
    2 ->

If you think it’s valuable to be able to handle all the other planets differently, you can also always use _.

case x of 
    Earth -> 
        -- do whatever
    _ ->
        -- handle all other planets

I believe using this should be your last resort though. Imagine you add more variants to your type, you lose out on the compiler being able to show you all the places where you haven’t added a case for it.

1 Like

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