kabuche
kabuche

Reputation: 117

Haskell, obtain a list of all enum values without naming them

I have this (and cannot be changed):

data Example = Value1 | Value2 | Value3
    deriving (Eq, Ord, Enum, Show)

And I need this function which returns the list of all values in the data definition:

examples :: [Example]

But I can't use the names of the values like this:

examples :: [Example]
examples = [Value1 ..]

I tried things like these, but they don't work:

examples :: [Example]
examples = [x | x <- Example]

Thanks for your help.

Upvotes: 11

Views: 5597

Answers (2)

David Miani
David Miani

Reputation: 14678

Using toEnum 0 to generate the first value, and enumFrom to then generate the list of values is the only way here without the Bounded class.

Eg:

generateEnumValues :: (Enum a) => [a]
generateEnumValues = enumFrom (toEnum 0)

examples :: [Example]
examples = generateEnumValues

The main issue with this approach is it isn't guaranteed that the toEnum 0 will always give the first enum value (I don't see any such guarantee on the Enum docs page). However it will be true for any enum instance created with deriving Enum.

So if at all possible, add the Bounded class to the type, and just use [minBound..] instead.

Upvotes: 25

luqui
luqui

Reputation: 60483

Derive Bounded and use [minBound..maxBound].

Upvotes: 22

Related Questions