Skip to content

Instantly share code, notes, and snippets.

@oisdk
Created March 18, 2018 23:14
Show Gist options
  • Save oisdk/44637f464f6c57d7b188f7a0e06fb55f to your computer and use it in GitHub Desktop.
Save oisdk/44637f464f6c57d7b188f7a0e06fb55f to your computer and use it in GitHub Desktop.
{-# LANGUAGE BangPatterns #-}
import System.Random
import GHC.Base (oneShot)
choose :: (Foldable f, RandomGen g) => f a -> g -> (Maybe a, g)
choose xs = foldr f (const (,)) xs (0 :: Integer) Nothing
where
f x a = oneShot (\ !c m g -> case m of
Nothing -> a 1 (Just x) g
Just y -> case randomR (0,c) g of
(0,g') -> a (c+1) (Just x) g'
(_,g') -> a (c+1) (Just y) g')
{-# INLINE f #-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment