Your Ad Here

Posted By

rtperson on 09/10/11


Tagged

problems 99 randomization


Versions (?)

Haskell 99 Problems - Problem 23


 / Published in: Haskell
 

URL: http://haskell.org/haskellwiki/99_questions/21_to_28

problem 23, Extract a given number of randomly selected elements from a list. Example:

Prelude System.Random>rnd_select "abcdefgh" 3 >>= putStrLn

    "eda"

Two problems: 1) How to return a list, and 2) how to sample without duplication
  1. -- ah, randomization. Always fun in Haskell.
  2. rnd_select_one :: [a] -> IO [a]
  3. rnd_select_one xs = do
  4. let len = (length xs) - 1
  5. n' <- randomRIO (0, len)
  6. return [(xs!!n')]
  7.  
  8. -- this version allows resampling.
  9. rnd_select n xs = sequence (replicate n (rnd_select_one xs))
  10.  
  11. -- Ideally, to prevent re-sampling, we would use partition from Data.List
  12. -- like so:
  13. -- partition (`elem` "g") "abcdefghijklmn"
  14. -- --> ("g", "abcdefhijklmn")
  15. -- I'll have to revisit this one when I have a chance to
  16. -- play around with partitioning.

Report this snippet  

You need to login to post a comment.