Personal tools

Random list

From HaskellWiki

(Difference between revisions)
Jump to: navigation, search
(idea from #haskell)
 
(Added section "See also" with a link to "Examples/Random list")
 
(One intermediate revision by one user not shown)
Line 24: Line 24:
  
 
     let ns  = randomRs (0,length args-1) g
 
     let ns  = randomRs (0,length args-1) g
         strs = map (\n -> args !! n) ns
+
         strs = map (args !!) ns
 
     mapM_ putStrLn strs
 
     mapM_ putStrLn strs
  
Line 59: Line 59:
 
     quick
 
     quick
 
     ...
 
     ...
 +
 +
 +
== See also ==
 +
 +
* [[Examples/Random list]]
 +
  
 
[[Category:Code]]
 
[[Category:Code]]

Latest revision as of 12:52, 26 June 2017

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
   ...


[edit] See also