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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With