In order to use getStdRandom and randomR here, we need import module System.Random.

In order to use getStdRandom and randomR here, we need import module System.Random.

+

+

A more elegant solution using randomRs:

+

+

<haskell>

+

rnd_select xs n = do

+

gen <- getStdGen

+

return $ take n [ xs !! x | x <- randomRs (0, (length xs) - 1) gen]

+

</haskell>

or using sequence all the way:

or using sequence all the way:

Line 103:

Line 111:

Note, all of these return IO [a]. Some recent version of GHCi added the ability to display <haskell>IO a</haskell> values at the top level. Hugs (and older GHCi) behaves differently, so an action to actually do IO (putStrLn in the example) is required.

Note, all of these return IO [a]. Some recent version of GHCi added the ability to display <haskell>IO a</haskell> values at the top level. Hugs (and older GHCi) behaves differently, so an action to actually do IO (putStrLn in the example) is required.

+

+

The same solution using the global number generator and returning IO [a] (thanks to applicatives, $ is simply replaced by <$>):

If the number of items we want is the same as the number of items in the list, then we just return the list. Otherwise we remove a random item from the list and then recurse.

Another Alternative Solution:

Since the above Alternative Solution works by removing things to create the target list, it's most efficient when the target list length is > (orig list / 2). Here's another solution that's efficient in the other way (target < (orig list / 2)) by constructing an accumulator list of selected random elements. (This one also uses removeAt from problem 20)