Created
July 24, 2012 20:56
-
-
Save sleepynate/3172614 to your computer and use it in GitHub Desktop.
problem23.hs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{- | |
- Problem 23 | |
- Extract a given number of randomly selected elements from a list. | |
- Example: | |
- Prelude System.Random>rnd_select "abcdefgh" 3 >>= show | |
- "eda" | |
-} | |
pure_rnd_select :: [a] -> Int -> [a] | |
pure_rnd_select x y = unsafePerformIO $ rnd_select x y | |
rnd_select :: [a] -> Int -> IO [a] | |
rnd_select _ 0 = return [] | |
rnd_select [] _ = return [] | |
rnd_select l n = do r <- randomRIO (0, (length l) - 1) | |
result <- (rnd_select ((take r l) ++ (drop (r+1) l)) (n - 1)) | |
return ((l!!r) : result) | |
problem23 = test ["Extract given number of randomly selected elements from list" | |
~: (length $ (pure_rnd_select "abcdefgh" 3)) | |
~=? 3 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment