[Haskell-cafe] infinite list of random elements

Sebastian Sylvan sebastian.sylvan at gmail.com
Mon Jul 30 18:15:11 EDT 2007

On 30/07/07, Lennart Augustsson <lennart at augustsson.net> wrote:
> Why this obsession with IO?  There should be no IO involved in this, except
> for getting the initial generator.
> Using IO just confuses what is going on.

Indeed. Here's my version:

-- first define a shuffle function, completely pure!
pick 1 (x:xs) = (x, xs)
pick n (x:xs) = (y, x:ys)
	where (y, ys) = pick (n-1) xs

shuffle gen xs = shuffle' gen xs (length xs)

shuffle' _ [] _ = []
shuffle' gen xs n = p : shuffle' gen' xs' (n-1)
		(r, gen') = randomR (1,n) gen
		(p, xs') = pick r xs

-- a function for giving us an infinite list of generators from
-- an initial generator
gens g = unfoldr (Just . split) g

-- shuffles the given list an infinite number of times
-- with a different generator each time
shuffles xs g = zipWith shuffle (gens g) (repeat xs)

You can then pass in whatever generator you wish to shuffles. E.g.
create a pure one with mkStdGen or create one in the IO monad with
Sebastian Sylvan
UIN: 44640862

More information about the Haskell-Cafe mailing list