Created
July 2, 2013 09:57
-
-
Save timcowlishaw/5908092 to your computer and use it in GitHub Desktop.
Tidying up the example at http://www.lshift.net/blog/2013/06/30/tail-calls-vs-laziness
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
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