具有起始值的枚举

时间:2014-05-13 10:39:50

标签: haskell enums

我需要从c ++代码中导出一些枚举。 https://github.com/horde3d/Horde3D/blob/master/Horde3D/Bindings/C%2B%2B/Horde3D.h

struct H3DGeoRes
{
   enum List
   {
      GeometryElem = 200,
      //...
   };
};

struct H3DAnimRes
{
   enum List
   {
      EntityElem = 300,
      //...
   };
};

我怎么能在Haskell中写这个?我可以覆盖fromEnum类型吗?

data H3DGeoRes = GeometryElem | ... deriving (Show, Eq, Ord, Bounded, Enum)
data H3DAnimRes = EntityElem | ... deriving (Show, Eq, Ord, Bounded, Enum)

-- not work

instance Enum H3DGeoRes where
  fromEnum x = (fromEnum x) + 200

instance Enum H3DAnimRes where
  fromEnum x = (fromEnum x) + 300

1 个答案:

答案 0 :(得分:1)

在没有太多输入的情况下解决问题的一种方法是创建一个类似于Enum的新类型类。我们称之为Enumerable

class Enumerable a where fromEnumerable :: a -> Int

然后,您可以使用Enumerable编写Enum的实例:

instance Enumerable H3DGeoRes where fromEnumerable x = fromEnum x + 200

每当使用类型H3DGeoResH3DAnimRes的枚举时,您必须使用Enumerable类而不是Enum类中的函数。这有点令人讨厌,因为它会阻止您使用Enum的方便列表语法。