System.Random: enumRandomR, boundedEnumRandom

Henning Thielemann lemming at henning-thielemann.de
Wed Dec 5 09:40:45 EST 2007


Did you also already need Random instances of enumerations? Wouldn't it be
nice to have some helper functions in System.Random:


enumRandomR :: (Enum a, RandomGen g) => (a,a) -> g -> (a,g)
enumRandomR (l,r) =
   mapFst toEnum . randomR (fromEnum l, fromEnum r)

boundedEnumRandom :: (Enum a, Bounded a, RandomGen g) => g -> (a,g)
boundedEnumRandom  =  enumRandomR (minBound, maxBound)

mapFst :: (a -> c) -> (a,b) -> (c,b)
mapFst f ~(x,y) = (f x, y)



Example application:

instance Random Day where
   random  = boundedEnumRandom
   randomR = enumRandomR


More information about the Libraries mailing list