6

我想制作所有类型的实例EnumBounded也是Random. 以下代码执行此操作并且应该可以工作(启用了适当的扩展):

import System.Random

instance (Enum r, Bounded r) => Random r where
   randomR (hi, lo) = inFst toEnum . randomR (fromEnum hi, fromEnum lo)
      where inFst f (x,y) = (f x, y)
   random = randomR (maxBound, minBound)

但我知道这是不好的风格,因为instance (Enum r, Bounded r) => Random r为 all 创建了一个实例r,只是对 and 进行类型检查EnumBounded而不是仅仅将实例放在 and 的类型EnumBounded。这实际上意味着我正在为所有类型定义一个实例:(

另一种方法是我必须编写独立的函数来提供我想要的行为,并为我想要成为实例的每种类型编写一些样板Random

randomBoundedEnum :: (Enum r, Bounded r, RandomGen g) => g -> (r, g)
randomBoundedEnum = randomRBoundedEnum (minBound, maxBound)

randomBoundedEnumR :: (Enum r, Bounded r, RandomGen g) => (r, r) -> g -> (r, g)
randomBoundedEnumR (hi, lo) = inFst toEnum . randomR (fromEnum hi, fromEnum lo)
   where inFst f (x,y) = (f x, y)

data Side = Top | Right | Bottom | Left 
   deriving (Enum, Bounded)

-- Boilerplatey :( 
instance Random Side where
   randomR = randomBoundedEnumR
   random = randomBoundedEnum

data Hygiene = Spotless | Normal | Scruffy | Grubby | Flithy
   deriving (Enum, Bounded)

-- Boilerplatey, duplication :(
instance Random Hyigene where
   randomR = randomBoundedEnumR
   random = randomBoundedEnum

有没有更好的选择?我应该如何处理这个问题?我什至不应该尝试这个吗?我是否过度担心样板文件?

4

1 回答 1

8

是的,正如我刚刚回答了一个稍微相关的问题,您可以使用 newtype 包装器 - 这是制作此类实例而不会惹恼整个社区的常见且安全的方法。

newtype RandomForBoundedEnum a = RfBE { unRfBE :: a}
instance (Enum a, Bounded a) => Random (RandomForBoundedEnum a) where
    ....

以这种方式,想要使用此实例的用户只需要包装(或解包)调用:

first unRfBE . random $ g :: (Side, StdGen)
于 2010-10-15T18:50:41.150 回答