Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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.

like image 473
kabuche Avatar asked Sep 19 '14 00:09

kabuche


1 Answers

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.

like image 78
David Miani Avatar answered Sep 18 '22 17:09

David Miani