Haskell, get a list of all enum values ​​without naming them

I have (and cannot be changed):

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

      

And I need this function that returns a list of all values ​​in the data definition:

examples :: [Example]

      

But I cannot use value names like this:

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

      

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

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

      

Thank you for your help.

+3


source to share


2 answers


Using toEnum 0

to generate the first value, and enumFrom

then to generate the list of values, is the only way here without a class Bounded

.

For example:

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

examples :: [Example]
examples = generateEnumValues

      



The main problem with this approach is that it is not guaranteed to toEnum 0

always give the first enum value (I see no such guarantee in the Enum docs page ). However, this will be true for any enum instance created with deriving Enum

.

So, if at all possible, add the class Bounded

to the type and just use [minBound..]

.

+12


source


Withdraw Bounded

and use [minBound..maxBound]

.



+8


source







All Articles