There is a given sequence of floats (between 0 and 1) of finite length N which denotes a distribution function over integers 0..N-1. We are trying to draw a random number from this distribution. One way of doing it is to draw a uniform random variable in [0, 1] (float), and then calculate the inverse cumulative distribution function for that number.
If the distribution was in an array, the code would look something like this:
let matched distribution draw =
let rec matchRest distribution draw start =
if start = Array.length distribution then start-1
else
let left = draw - distribution.[start]
if left <= 0 then start
else matchRest distribution left (start+1)
matchRest distribution draw 0
where distribution
is the distribution function and draw
is the uniform [0,1] number.
How can I rewrite this function to work when distribution is any sequence? Obviously I could create a temporary array, but it doesn't seem to be an elegant solution...