Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Random Tuples Haskell

I was wondering if it's possible to generate random tuples with a code like:

take 4 $ randomRs ((0,0),(70,100)) $ mkStdGen x  :: [(Double,Double)]

when I try this one I get the error:

No instance for (Random (Float, Float)) arising from a use of 'randoms'

Is there a way to get random tuples without using zip?

like image 633
user1544128 Avatar asked Dec 27 '22 13:12

user1544128


1 Answers

Basically the error message is saying that there isn't a defined way of making random tuples. But you can of course add one yourself.

Off the top of my head (i.e., I haven't actually tested this), you can do something like

instance (Random x, Random y) => Random (x, y) where
  randomR ((x1, y1), (x2, y2)) gen1 =
    let (x, gen2) = randomR (x1, x2) gen1
        (y, gen3) = randomR (y1, y2) gen2
    in ((x, y), gen3)

Now you can use randomR on tuples (provided that the types in the tuple support random generation).

like image 192
MathematicalOrchid Avatar answered Dec 30 '22 15:12

MathematicalOrchid