<h2 id="intro">Intro</h2>
<p>We’re going to have a look how to select random item from weighted list. There isn’t that much code this time, but it certainly took many tries to get it working and looking nice.</p>
<h2 id="analogy">Analogy</h2>
<p>Imagine stack of building blocks of different heights stacked on top of each other. Height of the each block is chance of how often it will be selected. Selection is done by chopping a stick so that its length at maximum is height of the stack. Place stick next to the stack and select the block that stick reaches at.</p>
<h2 id="explanation-of-algorithm">Explanation of algorithm</h2>
<p>We have list of items and associated weight, defined as <code>Frequency a = Frequency Int a</code>.</p>
<p>Total is sum of all the weights and we select a random number <code>n</code> between 1 and total.</p>
<p><code>pick</code> function has signature of <code>[Frequency a] -&gt; n -&gt; Maybe a</code>. Empty list will result <code>Nothing</code>. When picking item, if <code>n</code> is equal or less than weight of the first item, return that item. Otherwise, drop the first item, subtract weight of that first item from <code>n</code> and try again. Eventually we either arrive to item which weight is greater than <code>n</code> or to empty list.</p>
<h2 id="quick-detour-on-random-number-generators">Quick detour on random number generators</h2>
<p>Haskell functions are pure, meaning that with same input, you are guaranteed to get the same output (safe for some specific cases). Which makes concept of random numbers at first glance to be impossible. This is solved by passing in a random number generator, which can supply you a random value a new random number generator. Using this new random number generator to generate a value yields you a yet another value and yet another random number generator.</p>
<p>Passing these random number generators around in code gets tedious, but there’s different solution: <code>MonadRandom</code>. Using it will thread along generators automatically behind the scenes, ensuring that you always have access to a fresh generator. There’s several functions that can be used to generate random values, but we’re using this one: <code>getRandomR :: Random a =&gt; (a, a) -&gt; m a</code>. Given a lower and upper bound, it will return you a random value wrapped in context that carries that new random number generator.</p>
<p>In the end, we need to take our computation (that can be complex and use multiple calls to random number generator) and turn that <code>m a</code> into <code>a</code>. This is done with <code>runRand :: RandomGen g =&gt; Rand g a -&gt; g -&gt; (a, g)</code>. We give it our computation and a <code>RandomGen g</code> that can generate random values and receive <code>(a, g)</code> where <code>a</code> is our result and <code>g</code> new random number generator. In cases where we aren’t going to use the new generator, we can use <code>evalRand :: RandomGen g =&gt; Rand g a -&gt; g -&gt; a</code>, which discards it and returns just <code>a</code>.</p>
<h2 id="actual-implementation-with-explanation">Actual implementation with explanation</h2>
<p>First, <code>Frequency</code> for expressing weight of individual item. It’s parametrized, so can be used with any data.</p>
<pre><code>data Frequency a = Frequency Int a
    deriving (Show, Read, Eq)</code></pre>
<p>Next, determining which item to choose, based on stack and measuring stick. In case a value outside of valid range has been selected, we end up with <code>Nothing</code>, otherwise with <code>Just a</code>. First case is for empty list (either we called this originally with empty list or picked number that is greater than total sum of weights), second one either picks the first item of list or recursive calls itself removing first item.</p>
<pre><code>pick :: [Frequency a] -&gt; Int -&gt; Maybe a
pick [] _ = Nothing

pick (Frequency x item:xs) i
    | i &lt;= x = Just item
    | otherwise = pick xs (i - x)</code></pre>
<p>Finally, function for calculating total of weights and choosing random number. We’re using that <code>Rand g (Maybe a)</code> I explained earlier. First case is for empty list again and latter case for list with at least one item.</p>
<pre><code>choose :: RandomGen g =&gt; [Frequency a] -&gt; Rand g (Maybe a)
choose [] =
    return Nothing

choose items = do
    let total = sum $ fmap (\(Frequency x _) -&gt; x) items
    n &lt;- getRandomR (1, total)
    return $ pick items n</code></pre>
<p>Notice how we can get random number by <code>n &lt;- getRandomR (1, total)</code>, without talking about generators. <code>MonadRandom</code> is handling generators and making sure that there’s always a fresh generator available and new generator is stored ready to be used.</p>
<p>And that’s all the code this time (I told the amount of code is small this time).</p>
<h2 id="in-closing">In closing</h2>
<p>This probably sounds a lot more complicated than it actually is. I arrived to the result after quite many detours, but the end result looks pretty nice.</p>
<p>Next time we’re going to have a look where to use our <code>choose</code> function.</p>
<p>In the meantime, questions, comments and feedback are welcomed. Best way to reach me is email or fediverse where I’m <code>Tuula@mastodon.social</code>. Or even better, record your own Hacker Public Radio episode.</p>
