Revision as of 11:36, 5 November 2006 by DonStewart (wibble)
The following question was asked on #haskell:
How would I print an infinite stream of random strings, generated from an argument list?
The easy way to do this is to use an infinite list of randoms, and use that to index the argument list. This illustrates the use of lazy, infinite lists quite nicely.
import System.Random import Control.Monad import System.Environment main = do g <- newStdGen -- get a new random generator args <- getArgs -- get the arguments -- do some error checking when (null args) $ print "Usage: ./a.out [arg1 ... argn]" -- generate an infinite list of random numbers -- and now use them to generate an infinite list of strings -- print them out let ns = randomRs (0,length args-1) g strs = map (args !!) ns mapM_ putStrLn strs
when run, produces:
$ runhaskell A.hs the quick brown fox the fox fox brown quick brown fox quick brown quick brown quick the brown brown quick brown brown quick brown fox quick quick the fox quick ...