Getting a list of all possible data type values in Haskell

Not sure if it is an anti-pattern (nor can I think of a good use right now), but it’s possible. Use the Enum (allows to generate a list like [someCtor .. someOtherCtor]) and Bounded (for minBound and maxBound) type classes. Luckily, you can derive both:

data Color = Red
           | Yellow
           | Green
           deriving (Enum, Bounded)

allColors = [(minBound :: Color) ..]

If you ever add another color, allColors get updated automatically. One restriction though: Enum requires all contructors to be nullary, i.e. adding Foo Int breaks the whole thing. Luckily, because a list of all possible values for this would be way too large.

Edit: The other answer works as well, maybe better since it doesn’t require deriving Bounded and is therefore a bit shorter. I’ll still leave mine because I love over-engineered but extremely generic code 😉

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)