Is there a way to filter a list of union types in Elm without explict case/pattern matching?

Viewed 41

I've got a list of things and I want to filter based on a Union type. simplified, it might be something like this:

type Groceries =
  Apples
  | Cheese
  | Widgets

shoppingList = [Apples, Cheese, Cheese, Widgets, Apples]

is there a nice syntax for filtering all the elements that match a particular subtype?

# idk, eg
fruit = shoppingList |> List.filter =Apple? 

I know i can use a lambda with a case statement but it seems so verbose!

1 Answers

You can do:

fruit = shoppingList |> List.filter ((==) Apples)

(==) takes the infix equals operator and treats it as an ordinary function. Then, applying Apples to it will return a partially applied function that compares whatever is applied to it to Apples.

However, this will only work on simple variants that can be directly compared.

Related