[Haskell-beginners] Randomly selecting a data constructor

Thomas Davie tom.davie at gmail.com
Sun Mar 14 07:08:59 EDT 2010


data FigType = TR1 | TR2 | TR3 | TR4 | SQ | L1 | L2 | Z1 | Z2 | Z3 | Z4 | NoFigure
               deriving (Enum)

randomFigure :: IO FigType
randomFigure = toEnum <$> randomRIO (1,11)

Bob

On 14 Mar 2010, at 10:57, Evgenij Merenkov wrote:

> Hello.
> 
> I have the following data and it's constructors:
> 
> FigType = TR1 | TR2 | TR3 | TR4 | SQ | L1 | L2 | Z1 | Z2 | Z3 | Z4 | NoFigure
> 
> I need to randomly return one of them in a function. The obvious solution to me, is simply using a random number generator and case statement, where each value generated is associated with each data constructor. Like this:
> 
> import System.Random
> 
> randomFigType :: IO FigType
> randomFigure = do
>   x <- randomRIO (1::Int,11::Int)
>   return $ case x of
>              1 -> TR1
>              2 -> TR2
>              3 -> TR3
> e t.c.
> 
> But is there a more direct way to do this?
> 
> Hotmail: Trusted email with Microsoft’s powerful SPAM protection. Sign up now. _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100314/16b65e08/attachment.html


More information about the Beginners mailing list