Skip to content

Instantly share code, notes, and snippets.

@timcowlishaw
Created July 2, 2013 09:57
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 timcowlishaw/5908092 to your computer and use it in GitHub Desktop.
Save timcowlishaw/5908092 to your computer and use it in GitHub Desktop.
import qualified Data.Vector as V
import qualified System.Random as R
sample :: R.RandomGen g => g -> Int -> [a] -> V.Vector a
sample r n l = go r vec0 (succ n) remainder where
vec0 = V.fromList beginning
(beginning, remainder) = splitAt n l
go _ v _ [] = v
go r v i (x:xs) = v `seq` go r'' updated (succ i) xs
where
updated | p < n = v V.// upd
| otherwise = v
upd = [(idx, x)]
(p, r') = rand0 where rand0 = R.randomR (0, i-1) r
(idx, r'') = rand1 where rand1 = R.randomR (0, n-1) r'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment