## Choose a random item from a list in one pass

Posted on March 15, 2018

Tags: Haskell

Adapted from here.

```
import System.Random
choose :: (Foldable f, RandomGen g) => f a -> g -> (a, g)
= h (foldl f (0 :: Integer, error "choose: empty list", g) xs)
choose xs g where
= (x,g)
h (_,x,g) = case randomR (0,c) g of
f (c,y,g) x 0,g') -> (c+1,x,g')
(-> (c+1,y,g') (_,g')
```