[Haskell-cafe] (newbie) instance Enum MyType where, smarter way?

Jules Bean jules at jellybean.co.uk
Tue Mar 27 12:20:50 EDT 2007


Adrian Neumann wrote:
> I defined an enumeration datatype like this
>
> data MyType = One | Two | Four | Eight
>
> and want to make it an instance of the class Enum. deriving Enum won't
> do what I want, as it labels the items 0,1,2,3. Is there a better way to
> do this than

Define them as deriving Enum. Now on top of this define

bitValue :: MyType -> Int
bitValue m = 2^(fromEnum m)

and, if you need it, the converse. Or even something neater which splits 
a number into an array of constructors corresponding to bitnums

manyValues :: [MyType] -> Int
manyValues = foldr (.|.) . map bitValue
-- you need Data.Bits for the bitwise or, .|.

fromInt :: Int -> [MyType]
fromInt i = filter (\n -> i .&. (bitValue n) > 0) [One..Eight]

Of course, I'm taking the liberty of guessing here that you're modelling 
binary-flags-as-bitfields

Jules


More information about the Haskell-Cafe mailing list