我有一小段代码,其中声明了两个数据类型。我已经自动将它们都归为typeclass enum的成员,但是,我不喜欢它们不是“圆形”的。通过这个,我的意思是,调用succ Sun应该会给我Monsucc Dec应该产生Jan。因此,我没有写我自己的枚举,而是这样做的:

data WeekDay = Mon | Tue | Wed | Thu | Fri | Sat | Sun
             deriving (Enum, Show, Eq, Bounded)

data Month = Jan | Feb | Mar | Apr | May | Jun | July | Aug | Sep | Oct | Nov
             | Dec
           deriving (Enum, Show, Eq, Bounded)

class Circ a where
  next :: Enum a => a -> a

instance Circ WeekDay where
  next a = if a == maxBound then minBound else succ a

instance Circ Month where      -- this is nearly identical to the one above
  next a = if a == maxBound then minBound else succ a

我的问题是:是否有一种更整洁,更少冗余的方式编写此代码?换句话说,我编写了两个几乎相同的实例,其中数据类型名称(WeekDay vs. Month)是唯一更改的变量。

最佳答案

class (Enum a, Bounded a, Eq a) => Circ a where
     next :: a -> a
     next a = if a == maxBound then minBound else succ a

instance Circ WeekDay
instance Circ Month

关于haskell - 创建 "circular"枚举类型类的实例的较少冗余方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20294273/

10-09 02:56