/ Published in: Haskell
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
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
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
-- ah, randomization. Always fun in Haskell. -- this selects only one letter. Not what we want... rnd_select_one xs = do n <- randomRIO (0, len) -- this version allows resampling. rnd_select xs n = do -- Here's how to prevent re-sampling, using partition from Data.List -- like so: -- partition (`elem` "g") "abcdefghijklmn" -- --> ("g", "abcdefhijklmn") -- -- It would also be fairly trivial to use removeAt from Problem 20 rnd_select_one' (acc, xs) n = do d <- randomRIO (0, len) let el = (xs!!d) let ret = (acc ++ g, ys) rnd_select_one' ret (n-1) rnd_select' xs n = do j <- rnd_select_one' ([], xs) n
URL: http://haskell.org/haskellwiki/99_questions/21_to_28