Skip to content

Instantly share code, notes, and snippets.

@jrraymond
Created April 6, 2014 06:56
Show Gist options
  • Save jrraymond/10002367 to your computer and use it in GitHub Desktop.
Save jrraymond/10002367 to your computer and use it in GitHub Desktop.
Picks a random number from a stream with uniform probability. O(1) space.
import System.Random
f :: [a] -> IO a
f xs = f' xs [] 1 where
f' :: [a] -> [a] -> Int -> IO a
f' [] z _ = return $ head z
f' (x:xs) z i = do r <- randomRIO (1,i)
if r == 1
then f' xs [x] (i + 1)
else f' xs z (i + 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment