[Haskell-cafe] [C][enums][newbie] What is natural Haskell representation of such enum?

Malcolm Wallace malcolm.wallace at me.com
Mon Jan 23 11:15:42 CET 2012


> 2012/1/22 Данило Глинський <abcz2.uprola at gmail.com>
> What is natural Haskell representation of such enum?
> 
> enum TypeMask
> {
>    UNIT,
>    GAMEOBJECT,
> 
>    CREATURE_OR_GAMEOBJECT = UNIT | GAMEOBJECT
> };

I don't think that definition makes any sense in C, because UNIT is 0, so UNIT | GAMEOBJECT == GAMEOBJECT == 1

Nevertheless, in Haskell something vaguely similar might be:

data TypeMask = UNIT | GAMEOBJECT | CREATURE_OR_GAMEOBJECT

> // 1-byte flaged enum
> enum TypeMask
> {
>    // ...
>    UNIT        = 0x0004,
>    GAMEOBJECT  = 0x0008,
>    // ...
> 
>    CREATURE_OR_GAMEOBJECT = UNIT | GAMEOBJECT
>    WORLDOBJECT = UNIT | PLAYER | GAMEOBJECT | DYNAMICOBJECT | CORPSE 
>    // ... even more enum combos ...
> };

import Data.Bits
data TypeMask = UNIT | GAMEOBJECT | CREATURE_OR_GAMEOBJECT | WORLDOBJECT
instance Enum TypeMask where
    fromEnum UNIT = 0x4
    fromEnum GAMEOBJECT = 0x8
    fromEnum CREATURE_OR_GAMEOBJECT = fromEnum UNIT .|. fromEnum GAMEOBJECT
    fromEnum WORLDOBJECT = fromEnum UNIT .|. fromEnum PLAYER .|. fromEnum GAMEOBJECT
                           .|. fromEnum DYNAMICOBJECT .|. fromEnum CORPSE

    toEnum 0x4 = UNIT
    toEnum 0x8 = GAMEOBJECT
    toEnum _   = error "unspecified enumeration value of type TypeMask"

isCreatureOrGameObject :: Int -> Bool
isCreatureOrGameObject x = (x .|. fromEnum CREATURE_OR_GAMEOBJECT) /= 0

isWorldObject :: Int -> Bool
isWorldObject x = (x .|. fromEnum WORLDOBJECT) /= 0

-- But fundamentally, this is not an idiomatic Haskell way of doing things.
-- The other posts in this thread have shown more Haskell-ish translations.





More information about the Haskell-Cafe mailing list