Better Way to Define an Enum in Haskell
enums, haskell
Solution
instance Enum MyDataType where
fromEnum = fromJust . flip lookup table
toEnum = fromJust . flip lookup (map swap table)
table = [(Foo, 0), (Bar, 1), (Baz, 2)]
Problem
I want a datatype to represent a finite set of integers that can be addressed by specific names. I figure the best way to do that is to use an Enum. However, there is one small problem. The only way I know for defining an Enum is something like this: ``` data MyDataType = Foo | Bar | Baz instance Enum MyDataType toEnum 0 = Foo toEnum 1 = Bar toEnum 2 = Baz fromEnum Foo = 0 fromEnum Bar = 1 fromEnum Baz = 2 ``` Note that I have to repeat the same pair two times - one time when defining an integer-to-enum mapping and the other time when defining an enum-to-integer mapping. Is there a way to avoid this repetition?