[Haskell-cafe] infinite list of random elements

Lauri Alanko la at iki.fi
Mon Jul 30 18:03:06 EDT 2007

On Mon, Jul 30, 2007 at 02:40:35PM -0700, Chad Scherrer wrote:
> 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).

You can be even lazier and let the Random library do more of the work
for you, seeing that it includes randomRs:

randomElts rg xs = map (arr !) (randomRs bds rg)
  where bds = (1, length xs)
        arr = listArray bds xs


More information about the Haskell-Cafe mailing list