Why this obsession with IO? There should be no IO involved in this, except for getting the initial generator.<br>Using IO just confuses what is going on.<br><br> -- Lennart<br><br><div><span class="gmail_quote">On 7/30/07,
<b class="gmail_sendername">Cale Gibbard</b> <<a href="mailto:email@example.com">firstname.lastname@example.org</a>> wrote:</span><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
On 30/07/07, Chad Scherrer <<a href="mailto:email@example.com">firstname.lastname@example.org</a>> wrote:<br>> I'm trying to do something I thought would be pretty simple, but it's<br>> giving me trouble.
<br>><br>> Given a list, say [1,2,3], I'd like to be able to generate an infinite<br>> list of random elements from that list, in this case maybe<br>> [1,2,1,3,2,1,3,2,3,1,2,...]. I'm using IO for random purely due to
<br>> laziness (my own, not Haskell's).<br>><br>> I was thinking the best way to do this might be to first write this function:<br>><br>> randomElts :: [a] -> [IO a]<br>> randomElts  = <br>> randomElts [x] = repeat (return x)
<br>> randomElts xs = repeat r<br>> where<br>> bds = (1, length xs)<br>> xArr = listArray bds xs<br>> r = do<br>> i <- randomRIO bds<br>> return (xArr ! i)<br>><br>> Then I should be able to do this in ghci:
<br>><br>> > sequence . take 5 $ randomElts [1,2,3]<br>> [*** Exception: stack overflow<br>><br>> Any idea what's going on? I thought laziness (Haskell's, not my own)<br>> would save me on this one.
<br><br>I don't get that result. However, you can't compute an infinite random<br>list in IO without using something like unsafeInterleaveIO. However,<br>you will probably be interested in randoms/randomRs, which take a
<br>random generator, and give an infinite list of results.<br><br>Using that, we could write something like:<br><br>randomElts :: [a] -> IO [a]<br>randomElts  = return <br>randomElts xs = do g <- newStdGen<br> return (map (xArr !) (randomRs bds g))
<br> where bds = (1, length xs)<br> xArr = listArray bds xs<br><br>which for a nonempty input list, gives an infinite list of<br>pseudorandom elements of that input list.<br><br> - Cale<br>_______________________________________________
<br>Haskell-Cafe mailing list<br><a href="mailto:Haskell-Cafe@haskell.org">Haskell-Cafe@haskell.org</a><br><a href="http://www.haskell.org/mailman/listinfo/haskell-cafe">http://www.haskell.org/mailman/listinfo/haskell-cafe