[Haskell-beginners] Randomly selecting a data constructor

Yitzchak Gale gale at sefer.org
Sun Mar 14 07:39:19 EDT 2010


Thomas Davie wrote:
> data FigType = TR1 | TR2 | TR3 | TR4 | SQ | L1 | L2 | Z1 | Z2 | Z3 | Z4 |
> NoFigure
>                deriving (Enum)
> randomFigure :: IO FigType
> randomFigure = toEnum <$> randomRIO (1,11)

You actually want randomRIO (0,10).

If you don't want to have to remember that, or to remember
to change "10" whenever the number of constructors changes,
you can use:

> data FigType = TR1 | TR2 | TR3 | TR4 | SQ | L1 | L2 | Z1 | Z2 | Z3 | Z4 |
> NoFigure
>                deriving (Enum, Bounded)
> randomFigure :: IO FigType
> randomFigure = toEnum <$>
>  randomRIO (fromEnum (minBound :: FigType), fromEnum maxBound)

Regards,
Yitz


More information about the Beginners mailing list