[Haskell-cafe] infinite list of random elements

Chad Scherrer chad.scherrer at gmail.com
Mon Jul 30 17:40:35 EDT 2007


I'm trying to do something I thought would be pretty simple, but it's
giving me trouble.

Given a list, say [1,2,3], I'd like to be able to generate an infinite
list of random elements from that list, in this case maybe
[1,2,1,3,2,1,3,2,3,1,2,...]. I'm using IO for random purely due to
laziness (my own, not Haskell's).

I was thinking the best way to do this might be to first write this function:

randomElts :: [a] -> [IO a]
randomElts [] = []
randomElts [x] = repeat (return x)
randomElts xs = repeat r
  where
  bds = (1, length xs)
  xArr = listArray bds xs
  r = do
    i <- randomRIO bds
    return (xArr ! i)

Then I should be able to do this in ghci:

> sequence . take 5 $ randomElts [1,2,3]
[*** Exception: stack overflow

Any idea what's going on? I thought laziness (Haskell's, not my own)
would save me on this one.

Thanks!
Chad


More information about the Haskell-Cafe mailing list