Skip to content

Instantly share code, notes, and snippets.

@mitsuji
Created August 4, 2015 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitsuji/32c539ee9ba62b57d7a4 to your computer and use it in GitHub Desktop.
Save mitsuji/32c539ee9ba62b57d7a4 to your computer and use it in GitHub Desktop.
{-# LANGUAGE PackageImports #-}
import Control.Monad
import Control.Applicative ((<$>),(<*>))
import "mtl" Control.Monad.RWS
import qualified System.Random as R
main = do
g <- R.newStdGen
print $ pick g [0,1,2,3,4,5,6,7,8,9] 4
pick :: R.RandomGen g => g -> [a] -> Int -> [a]
pick g xs c = snd $ execRWS (
do
let c' = (length xs) - c
whileDo ( (c'<) . length . snd <$> get) $ do
(g',xs) <- get
let (i,g'') = R.randomR (0, (length xs)-1) g'
tell [xs !! i]
put (g'', reduce xs i)
) () (g,xs)
where
reduce :: [a] -> Int -> [a]
reduce xs n = (take n xs) ++ (drop (n+1) xs)
whileDo :: Monad m => m Bool -> m () -> m ()
whileDo fcond fbody = loop
where
loop = do
c <- fcond
if c
then fbody >> loop
else return ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment