<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en-us"><generator uri="https://gohugo.io/" version="0.170.0">Hugo</generator><title type="html">Monads on sunshowers</title><subtitle type="html">thoughts and ideas</subtitle><link href="https://sunshowers.io/tags/monads/" rel="alternate" type="text/html" title="html"/><link href="https://sunshowers.io/tags/monads/index.xml" rel="alternate" type="application/rss+xml" title="rss"/><link href="https://sunshowers.io/tags/monads/atom.xml" rel="self" type="application/atom+xml" title="atom"/><updated>2026-11-15T23:03:09+00:00</updated><rights>© Rain 2020-present. Licensed under CC BY-NC-SA 4.0 unless marked otherwise.</rights><author><name>Rain</name></author><id>https://sunshowers.io/tags/monads/</id><entry><title type="html">Demystifying monads in Rust through property-based testing</title><link href="https://sunshowers.io/posts/monads-through-pbt/?utm_source=atom_feed" rel="alternate" type="text/html"/><id>https://sunshowers.io/posts/monads-through-pbt/</id><published>2025-02-19T00:00:00+00:00</published><updated>2025-02-20T00:00:00+00:00</updated><content type="html"><![CDATA[<blockquote>A jargon-free, practical explanation of monads as a design pattern.</blockquote><div class="sectioned-post">
<p>In programming pedagogy, <a href="https://en.wikipedia.org/wiki/Monad_%28functional_programming%29">monads</a> have a place as a mystical object from the functional programming world that&rsquo;s hard to understand and even harder to explain. The stereotype about monad explanations is that they fall into two buckets: either comparisons to some kind of <a href="https://blog.plover.com/prog/burritos.html">food item</a>, or throwing complex mathematical jargon at you, <a href="https://stackoverflow.com/questions/3870088/a-monad-is-just-a-monoid-in-the-category-of-endofunctors-whats-the-problem"><em>what&rsquo;s the problem?</em></a></p>
<p>But monads aren&rsquo;t esoteric or magical at all, nor do they only occur in functional programming. In essence, a monad is a <em>design pattern</em> that allows you to chain together operations within a framework. Noticing monadic design can be quite helpful for programmers in any environment, particularly because it&rsquo;s often <strong>undesirable</strong>! In many situations, monads have observable tradeoffs, and sometimes (as here) we can even collect concrete data to back this up.</p>
<p>I&rsquo;m going to try and explain monads in a way that is:</p>
<ul>
<li><strong>Geared towards Rust developers</strong>, with code samples in Rust, though I hope any sufficiently curious programmer can follow along</li>
<li><strong>Free of jargon:</strong> no mathematical formalism whatsoever</li>
<li><strong>Without analogies</strong> of any kind, and grounded in real programming problems</li>
<li><strong>Non-trivial:</strong> focusing on a production-worthy example with objectively measurable implications</li>
<li><strong>Practical:</strong> with advice all of us coders can use</li>
</ul>
<p>In other words, I&rsquo;m going to try and write the monad tutorial that I personally would have appreciated when I was younger. And I&rsquo;m going to start at a place that&rsquo;s unconventional: through <em>property-based testing</em>, where monads have profound performance characteristics.</p>
<p><em>Note: While this article&rsquo;s primary goal is to explain monads, it also serves as a practical introduction to property-based testing and fault injection techniques. If you&rsquo;re new to these, you&rsquo;ll find an introduction to both alongside the monad explanation.</em></p>
<p>This post consists of five sections:</p>
<ol>
<li><a href="/posts/monads-through-pbt/#1-property-based-testing"><em>Property-based testing</em></a> goes over the basics</li>
<li><a href="/posts/monads-through-pbt/#2-drawing-the-rest-of-the-owl"><em>Drawing the rest of the owl</em></a> talks about a complex scenario: using property-based testing to inject faults</li>
<li><a href="/posts/monads-through-pbt/#3-integrated-shrinking"><em>Integrated shrinking</em></a> shows how to reduce inputs of challenging complexity to smaller sizes</li>
<li><a href="/posts/monads-through-pbt/#4-monads-finally"><em>Monads, finally</em></a> is where we introduce monads in this context, and provide data for how costly they can be</li>
<li><a href="/posts/monads-through-pbt/#5-rediscovering-structure"><em>Rediscovering structure</em></a> discusses some ways to mitigate the tradeoffs of monads in property-based testing</li>
</ol>
<h2 id="1-property-based-testing">1. Property-based testing</h2>
<p>Testing is fundamentally about building models for how your code should behave, at just the right level of complexity: they should match the scope of what you&rsquo;re testing, without going overboard and reinventing the whole system a second time.</p>
<p>The best explication of this general idea I&rsquo;ve seen is in <a href="https://kwarc.info/teaching/TDM/Borges.pdf">this piece</a> by the great Argentinian writer <a href="https://en.wikipedia.org/wiki/Jorge_Luis_Borges">Jorge Luis Borges</a>:</p>
<blockquote>
<p>…In that Empire, the Art of Cartography attained such Perfection that the map of a single Province occupied the entirety of a City, and the map of the Empire, the entirety of a Province. In time, those Unconscionable Maps no longer satisfied, and the Cartographers Guilds struck a Map of the Empire whose size was that of the Empire, and which coincided point for point with it…”</p>
<p><em>—On Exactitude in Science</em>, Jorge Luis Borges</p>
</blockquote>
<p>Nothing quite exemplifies testing-as-modeling like property-based testing—an approach where instead of specifying exact examples, you define models in terms of <strong>properties</strong>, or invariants, that your code should satisfy. Then, you test your models against randomly generated inputs.</p>
<p>Let&rsquo;s take a simple example of a sort function, say <code>my_sort</code>, defined over a slice of integers:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">my_sort</span><span class="p">(</span><span class="n">slice</span>: <span class="kp">&amp;</span><span class="nc">mut</span><span class="w"> </span><span class="p">[</span><span class="kt">u64</span><span class="p">])</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// ...
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>How should we go about testing it?</p>
<p>The most common way to do this is to list out a bunch of inputs and ensure they are correctly sorted, through <em>example-based tests</em>.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="cp">#[test]</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">test_my_sort</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kd">let</span><span class="w"> </span><span class="k">mut</span><span class="w"> </span><span class="n">input</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">0</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">0</span><span class="p">,</span><span class="w"> </span><span class="mi">5</span><span class="p">,</span><span class="w"> </span><span class="mi">6</span><span class="p">,</span><span class="w"> </span><span class="mi">9</span><span class="p">,</span><span class="w"> </span><span class="mi">0</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">,</span><span class="w"> </span><span class="mi">1</span><span class="p">];</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">my_sort</span><span class="p">(</span><span class="o">&amp;</span><span class="k">mut</span><span class="w"> </span><span class="n">input</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="fm">assert_eq!</span><span class="p">(</span><span class="n">input</span><span class="p">,</span><span class="w"> </span><span class="p">[</span><span class="mi">0</span><span class="p">,</span><span class="w"> </span><span class="mi">0</span><span class="p">,</span><span class="w"> </span><span class="mi">0</span><span class="p">,</span><span class="w"> </span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">,</span><span class="w"> </span><span class="mi">5</span><span class="p">,</span><span class="w"> </span><span class="mi">6</span><span class="p">,</span><span class="w"> </span><span class="mi">9</span><span class="p">]);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// More examples listed out.
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>Example-based tests are quite valuable, because they are easy to write and quite direct about what happens. But even in a simple example like sorting, it&rsquo;s easy to imagine cases where your examples don&rsquo;t quite cover every edge case.</p>
<p>How can more edge cases be covered? Well, one way to do so is to step back and ask, what is the sort trying to do? The goal of a sort function is to ensure that all the elements are in ascending order. Can we test that directly?</p>
<p>The first thing we&rsquo;d need is to get some inputs to test with. All we care about is a list of numbers here, which <em>seems</em> like it should be easy to generate using a random number generator.</p>
<p>So maybe we write something like:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="cp">#[test]</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">test_my_sort_2</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// Run the test 1024 times.
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="n">_</span><span class="w"> </span><span class="k">in</span><span class="w"> </span><span class="mi">0</span><span class="o">..</span><span class="mi">1024</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// Generate a random list of, say, 0 to 512 elements, with values
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// between 0 and 10000.
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="kd">let</span><span class="w"> </span><span class="n">input</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="cm">/* ... */</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="kd">let</span><span class="w"> </span><span class="k">mut</span><span class="w"> </span><span class="n">output</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">input</span><span class="p">.</span><span class="n">clone</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// Call the sort function on it.
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">my_sort</span><span class="p">(</span><span class="o">&amp;</span><span class="k">mut</span><span class="w"> </span><span class="n">output</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// Check that all values are in ascending order.
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">for</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="k">in</span><span class="w"> </span><span class="mi">1</span><span class="o">..</span><span class="n">output</span><span class="p">.</span><span class="n">len</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="fm">assert!</span><span class="p">(</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="n">output</span><span class="p">[</span><span class="n">i</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="mi">1</span><span class="p">]</span><span class="w"> </span><span class="o">&lt;=</span><span class="w"> </span><span class="n">output</span><span class="p">[</span><span class="n">i</span><span class="p">],</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="s">&#34;input {input:?} failed at index {i}, output {output:?}&#34;</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>We now have a model of sorting that we&rsquo;ve written down in code form: any pair of values must be in ascending order. (In this view, example-based tests are also simple models: for input X, the output should be Y.)</p>
<p>Now, we run the test, and…</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">thread &#39;test_my_sort_2&#39; panicked at tests/tests.rs:33:13:
</span></span><span class="line"><span class="cl">input [7496, 2087, 6900, 7927, 3840, 3065, 6472, 1186, 6464, 4512, 251, 5591, 3410, 2033, 5367, 2202, 5544, 2434, 6491, 8999, 9818, 2885, 8683, 1201, 6115, 2584, 2473, 6817, 5765, 5196, 9389, 5799, 9012, 293, 38, 1024, 9569, 4654, 7449, 7389, 8088, 5074, 3110, 938, 4944, 3859, 7368, 8978, 7524, 9503, 7406, 7591, 8213, 6445, 7000, 7354, 8967, 5549, 7935, 1866, 4048, 4043, 8905, 3154, 4771, 2364, 3982, 5088, 7317, 233, 3396, 1810, 3022, 9065, 454, 6181, 8257, 9598, 3982, 920, 5880, 4165, 4164, 930, 560, 9062, 5587, 6271, 5878, 2495, 9055, 3877, 4352, 1228, 8287, 8901, 3442, 373, 3635, 5316, 4423, 7688, 7919, 4465, 8991, 7043, 7696, 6875, 1478, 2428, 5127, 6809, 6175, 1415, 7263, 5145, 4153, 876, 1528, 6781, 5627, 6750, 3665, 2567, 6855, 141, 2144, 4491, 9121, 7982, 4131, 6337, 1926, 8797, 9382, 1702, 9559, 3910, 1715, 6661, 269, 4366, 6185, 5616, 365, 808, 4864, 3657, 9574, 3057, 7760, 6375, 2326, 7273, 6303, 7018, 8988, 6271, 988, 7796, 2390, 1689, 4279, 9586, 151, 9738, 3659, 7064, 1529, 8237, 4211, 2272, 8909, 7638] failed at index 173, output [38, 141, 151, 233, 251, 269, 293, 365, 373, 454, 560, 808, 876, 920, 930, 938, 988, 1024, 1186, 1201, 1228, 1415, 1478, 1528, 1529, 1689, 1702, 1715, 1810, 1866, 1926, 2033, 2087, 2144, 2202, 2272, 2326, 2364, 2390, 2428, 2434, 2473, 2495, 2567, 2584, 2885, 3022, 3057, 3065, 3110, 3154, 3396, 3410, 3442, 3635, 3657, 3659, 3665, 3840, 3859, 3877, 3910, 3982, 3982, 4043, 4048, 4131, 4153, 4164, 4165, 4211, 4279, 4352, 4366, 4423, 4465, 4491, 4512, 4654, 4771, 4864, 4944, 5074, 5088, 5127, 5145, 5196, 5316, 5367, 5544, 5549, 5587, 5591, 5616, 5627, 5765, 5799, 5878, 5880, 6115, 6175, 6181, 6185, 6271, 6271, 6303, 6337, 6375, 6445, 6464, 6472, 6491, 6661, 6750, 6781, 6809, 6817, 6855, 6875, 6900, 7000, 7018, 7043, 7064, 7263, 7273, 7317, 7354, 7368, 7389, 7406, 7449, 7496, 7524, 7591, 7638, 7688, 7696, 7760, 7796, 7919, 7927, 7935, 7982, 8088, 8213, 8237, 8257, 8287, 8683, 8797, 8901, 8905, 8909, 8967, 8978, 8988, 8991, 8999, 9012, 9055, 9062, 9065, 9121, 9382, 9389, 9503, 9559, 9569, 9574, 9586, 9598, 9818, 9738]
</span></span><span class="line"><span class="cl">note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
</span></span></code></pre></div><p>Whoops, looks like the function has a bug. (Scroll the above example to the right!)</p>
<p>This example is quite unhelpful and hard to understand! It is possible to use this as an input to debug with, but it is quite painful. If we could use automation to turn this test case into a much smaller one that can still reproduce the bug, debugging becomes significantly easier. The process of doing so is called test case <strong>shrinking</strong> or <strong>reduction</strong>.</p>
<p>To recap—property-based testing consists of two components:</p>
<ul>
<li>Test case <strong>generation</strong> using a source of randomness.</li>
<li>On failing a test, <strong>shrinking</strong> it down to a smaller, more understandable size.</li>
</ul>
<h3 id="implementing-a-manual-shrinker">Implementing a manual shrinker</h3>
<p>What counts as &ldquo;smaller&rdquo;? For a list of numbers, ideally we&rsquo;d be able to minimize both the number of items in the list and the integers themselves. This suggests an algorithm for how to write a shrinker by hand:</p>
<ul>
<li>
<p>First, try and minimize the size of the list using a binary search algorithm. For example:</p>
<ul>
<li>Try the first half of the list against the function.</li>
<li>If that exhibits an error, attempt to recursively shrink this half.</li>
<li>If that doesn&rsquo;t work, try it with the last half of the list.</li>
<li>If neither work or if the list has 1 or fewer elements, move on to the next step.</li>
</ul>
</li>
<li>
<p>Once the list has been shrunk, start shrinking the elements within the list, applying binary search to each element.</p>
</li>
</ul>
<p>After you&rsquo;re done writing this algorithm, you&rsquo;re well on your way towards creating the original property-based testing library, <a href="https://en.wikipedia.org/wiki/QuickCheck">QuickCheck</a>. This approach has you write two functions: a <em>generator</em> and a <em>shrinker</em>.</p>
<p>With this, you can get much more reasonable-looking output:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">input [58, 33] failed at index 1, output [58, 33]
</span></span></code></pre></div><p>And for relatively simple cases like lists of integers, this kind of shrinking works quite well!</p>
<p>But we&rsquo;re not here to test simple cases. We&rsquo;re here for the difficult ones.</p>
<h2 id="2-drawing-the-rest-of-the-owl">2. Drawing the rest of the owl</h2>

  <figure class="floatright" >
    
    <img src="/images/how-to-really-draw-an-owl.jpg"  alt="A drawing guide with instructions for a front-facing owl face, a side/45° profile view, and a front-facing owl with body. Each series has 6 steps. The instructions are quite helpful, and a subversion of the &#34;draw the rest of the owl&#34; meme."   />
    
    
      <figcaption class="center" >Subverting the <a href="https://www.reddit.com/r/funny/comments/eccj2/how_to_draw_an_owl/">meme</a>, we&rsquo;re going to deal with real-world complexity in this section.</figcaption>
    
  </figure>


<p>Most real-world sort implementations don&rsquo;t just work over a list of integers. They&rsquo;re written to be polymorphic over anything which can be sorted. In Rust parlance, this means anything that implements the <a href="https://doc.rust-lang.org/std/cmp/trait.Ord.html"><code>Ord</code></a> trait; and even if not, a <a href="https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by">custom comparator function</a> can be provided.</p>
<p>But <code>Ord</code> can be written by hand, and custom comparators are virtually always written by hand.</p>
<p>One immediate consequence is that it&rsquo;s possible that the comparator function says two elements are equal, but they are actually different. In that case, should the order of elements be preserved?</p>
<ul>
<li>A sort implementation which preserves the order is called a <strong>stable sort</strong>.</li>
<li>An implementation which does not is called an <strong>unstable sort</strong>.</li>
</ul>
<p>Unstable sorts tend to be faster than stable ones, and there are valid reasons for preferring each at different times. (The Rust standard library has separate implementations for <a href="https://doc.rust-lang.org/std/primitive.slice.html#method.sort">stable</a> and <a href="https://doc.rust-lang.org/std/primitive.slice.html#method.sort_unstable">unstable</a> sorts.)</p>
<p>Additionally, hand-written implementations mean <strong>users can make mistakes</strong>! A production-grade sort algorithm must behave reasonably in the face of arbitrary user input, not just in the actual elements being sorted but also in the comparator function (full credit to <a href="https://github.com/Voultapher">Lukas Bergdoll</a> for his <a href="https://github.com/Voultapher/sort-research-rs/blob/main/writeup/sort_safety/text.md">extensive research</a> here):</p>
<ul>
<li>
<p><strong>Ord safety:</strong> Users can write a comparator that&rsquo;s simply incorrect. An easy way is to introduce a difference between ordering and equality, for example by <a href="https://doc.rust-lang.org/std/cmp/enum.Ordering.html#variant.Less">returning <code>Ordering::Less</code></a> for two elements that are actually equal. Users could also return different answers for the same comparison when called at different times<sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup>.</p>
</li>
<li>
<p><strong>Panic safety:</strong> The comparator can panic in the middle of execution. Since panics <a href="https://doc.rust-lang.org/std/panic/fn.catch_unwind.html">can be caught</a>, the input should be in some kind of valid state afterwards.</p>
</li>
<li>
<p><strong>Observation safety:</strong> If any of the inputs are mutated by the comparator, those mutations must be carried through to the final output. (With Rust, mutation through shared references is possible via <a href="https://doc.rust-lang.org/book/ch15-05-interior-mutability.html">interior mutability</a>, as seen in <a href="https://doc.rust-lang.org/std/cell/struct.RefCell.html"><code>RefCell</code></a> or <a href="https://doc.rust-lang.org/std/sync/struct.Mutex.html"><code>Mutex</code></a>).</p>
</li>
</ul>
<p>In these cases, completing the sort successfully becomes impossible. But it&rsquo;s important that we leave the input in a reasonable state.</p>
<p>How do we go about testing this? Trying to think of all the different failure modes seems really hard! But property-based testing can address this need through randomized <strong>fault injection</strong>.</p>
<p>Let&rsquo;s focus on Ord safety for now, with a comparator that flips around the result 20% of the time:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="cp">#[derive(Clone, Copy, Debug)]</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">enum</span> <span class="nc">OrdBehavior</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">Regular</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">Flipped</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">struct</span> <span class="nc">BadType</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">value</span>: <span class="kt">u64</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">ord_behavior</span>: <span class="nc">RefCell</span><span class="o">&lt;</span><span class="nb">Vec</span><span class="o">&lt;</span><span class="n">OrdBehavior</span><span class="o">&gt;&gt;</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">impl</span><span class="w"> </span><span class="nb">Ord</span><span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="n">BadType</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">fn</span> <span class="nf">cmp</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">,</span><span class="w"> </span><span class="n">other</span>: <span class="kp">&amp;</span><span class="nc">Self</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="nc">Ordering</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// Get the next behavior from the list.
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">match</span><span class="w"> </span><span class="bp">self</span><span class="p">.</span><span class="n">ord_behavior</span><span class="p">.</span><span class="n">borrow_mut</span><span class="p">().</span><span class="n">pop</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nb">Some</span><span class="p">(</span><span class="n">OrdBehavior</span>::<span class="n">Regular</span><span class="p">)</span><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="nb">None</span><span class="w"> </span><span class="o">=&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="bp">self</span><span class="p">.</span><span class="n">value</span><span class="p">.</span><span class="n">cmp</span><span class="p">(</span><span class="o">&amp;</span><span class="n">other</span><span class="p">.</span><span class="n">value</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="n">OrdBehavior</span>::<span class="n">Flipped</span><span class="w"> </span><span class="o">=&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="c1">// Flip the behavior.
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="n">other</span><span class="p">.</span><span class="n">value</span><span class="p">.</span><span class="n">cmp</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">.</span><span class="n">value</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>To generate a <code>BadType</code>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">generate_bad_type</span><span class="p">()</span><span class="w"> </span>-&gt; <span class="nc">BadType</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// Generate a value between 0 and 10000;
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kd">let</span><span class="w"> </span><span class="n">value</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="cm">/* ... */</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// Generate a list of behaviors of length 0..128, where the elements are
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// Regular 4/5 times and Flipped 1/5 times.
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kd">let</span><span class="w"> </span><span class="n">ord_behavior</span>: <span class="nb">Vec</span><span class="o">&lt;</span><span class="n">OrdBehavior</span><span class="o">&gt;</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="cm">/* ... */</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">BadType</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">value</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">ord_behavior</span>: <span class="nc">RefCell</span>::<span class="n">new</span><span class="p">(</span><span class="n">ord_behavior</span><span class="p">),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>And to test this:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="cp">#[test]</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">test_my_sort_3</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// Run the test 1024 times.
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="n">_</span><span class="w"> </span><span class="k">in</span><span class="w"> </span><span class="mi">0</span><span class="o">..</span><span class="mi">1024</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// Generate a list of BadTypes using generate_bad_type.
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="kd">let</span><span class="w"> </span><span class="n">input</span>: <span class="nb">Vec</span><span class="o">&lt;</span><span class="n">BadType</span><span class="o">&gt;</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="cm">/* ... */</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// Call sort as before.
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="kd">let</span><span class="w"> </span><span class="k">mut</span><span class="w"> </span><span class="n">output</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">input</span><span class="p">.</span><span class="n">clone</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">my_sort</span><span class="p">(</span><span class="o">&amp;</span><span class="k">mut</span><span class="w"> </span><span class="n">output</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// Sorting isn&#39;t really well-defined in this case, but we can
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// ensure two properties:
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">//
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// 1. my_sort doesn&#39;t panic (implicitly checked by getting here)
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// 2. all the input values are still present in the output
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="kd">let</span><span class="w"> </span><span class="k">mut</span><span class="w"> </span><span class="n">input_values</span>: <span class="nb">Vec</span><span class="o">&lt;</span><span class="kt">u64</span><span class="o">&gt;</span><span class="w"> </span><span class="o">=</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="n">input</span><span class="p">.</span><span class="n">iter</span><span class="p">().</span><span class="n">map</span><span class="p">(</span><span class="o">|</span><span class="n">v</span><span class="o">|</span><span class="w"> </span><span class="n">v</span><span class="p">.</span><span class="n">value</span><span class="p">).</span><span class="n">collect</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="kd">let</span><span class="w"> </span><span class="k">mut</span><span class="w"> </span><span class="n">output_values</span>: <span class="nb">Vec</span><span class="o">&lt;</span><span class="kt">u64</span><span class="o">&gt;</span><span class="w"> </span><span class="o">=</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="n">output</span><span class="p">.</span><span class="n">iter</span><span class="p">().</span><span class="n">map</span><span class="p">(</span><span class="o">|</span><span class="n">v</span><span class="o">|</span><span class="w"> </span><span class="n">v</span><span class="p">.</span><span class="n">value</span><span class="p">).</span><span class="n">collect</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// Sort the input and output values, and assert that they match.
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">my_sort</span><span class="p">(</span><span class="o">&amp;</span><span class="k">mut</span><span class="w"> </span><span class="n">input_values</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">my_sort</span><span class="p">(</span><span class="o">&amp;</span><span class="k">mut</span><span class="w"> </span><span class="n">output_values</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="fm">assert_eq!</span><span class="p">(</span><span class="n">input_values</span><span class="p">,</span><span class="w"> </span><span class="n">output_values</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>Our original approach continues to work well—that is, right until the test finds a bug and we need to shrink a failing input.</p>
<h2 id="3-integrated-shrinking">3. Integrated shrinking</h2>
<p>How does one go about writing a shrinker for <code>Vec&lt;BadType&gt;</code>? Doing so seemed relatively straightforward for a list of integers. But this is a list where the elements are pairs of an integer <em>and another list</em>. Also:</p>
<ul>
<li>
<p>We&rsquo;ve just tested Ord safety so far—once we&rsquo;ve added fault injection for other kinds of safety, the complexity seems endless.</p>
</li>
<li>
<p>And even more importantly, there isn&rsquo;t a great way to compose smaller shrinkers together to form larger ones. Writing shrinkers is a lot of work already, and what&rsquo;s the point if you have to keep doing all of it over and over?</p>
</li>
</ul>
<p>The practical result is that most of the time, writing a shrinker for types like <code>Vec&lt;BadType&gt;</code> is quite difficult. And writing one is also technically optional, since:</p>
<ul>
<li>If the test passes, shrinkers are never invoked. Simply write correct code, and shrinking just isn&rsquo;t an issue!</li>
<li>If the test fails, developers can debug using the original input. It&rsquo;s painful but possible.</li>
</ul>
<p>All in all, given the choice of writing a shrinker by hand or just moving on with their lives, most developers tend to choose the latter<sup id="fnref:2"><a href="#fn:2" class="footnote-ref" role="doc-noteref">2</a></sup>. Because of this, most modern property-based testing frameworks, like <a href="https://docs.rs/proptest"><strong>proptest</strong></a> in Rust, try and take care of shrinking for you through some notion of <em>integrated shrinking</em>.</p>
<p>The idea behind integrated shrinking is: When you generate a random input, you don&rsquo;t just generate the value itself. You also generate some context that is helpful for reducing the size of the input.</p>
<ul>
<li>In proptest, this combined value and context is called a <a href="https://docs.rs/proptest/latest/proptest/strategy/trait.ValueTree.html"><strong>value tree</strong></a>.</li>
<li>Any implementation that accepts a random number generator and turns it into a value tree is called a <a href="https://docs.rs/proptest/latest/proptest/strategy/trait.Strategy.html"><strong>strategy</strong></a>.</li>
</ul>
<p>The proptest library comes with many different kinds of strategies that can be composed together to create more complex ones. To generate an instance of <code>OrdBehavior</code>, we&rsquo;re going to use two strategies:</p>
<ul>
<li>The <a href="https://docs.rs/proptest/latest/proptest/strategy/struct.Just.html"><strong><code>Just</code> strategy</strong></a>, which &ldquo;just&rdquo; returns a single value.</li>
<li>The <a href="https://docs.rs/proptest/latest/proptest/macro.prop_oneof.html"><strong><code>prop_oneof</code> strategy</strong></a>, which generates values from one of a possible list of strategies, where each choice has a given probability. (A function that takes one or more strategies as input, and produces a strategy as its output, is called a <strong>combinator</strong>.)</li>
</ul>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">generate_ord_behavior</span><span class="p">()</span><span class="w"> </span>-&gt; <span class="nc">impl</span><span class="w"> </span><span class="n">Strategy</span><span class="o">&lt;</span><span class="n">Value</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">OrdBehavior</span><span class="o">&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="fm">prop_oneof!</span><span class="p">[</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// 4/5 chance that the Regular implementation is generated.
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="mi">4</span><span class="w"> </span><span class="o">=&gt;</span><span class="w"> </span><span class="n">Just</span><span class="p">(</span><span class="n">OrdBehavior</span>::<span class="n">Regular</span><span class="p">),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// 1/5 chance that it&#39;s flipped.
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="mi">1</span><span class="w"> </span><span class="o">=&gt;</span><span class="w"> </span><span class="n">Just</span><span class="p">(</span><span class="n">OrdBehavior</span>::<span class="n">Flipped</span><span class="p">),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">]</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>To generate <code>BadType</code>, we&rsquo;re going to use <code>generate_ord_behavior</code>, as well as:</p>
<ul>
<li>A <a href="https://docs.rs/proptest/latest/proptest/strategy/trait.Strategy.html#impl-Strategy-for-Range%3Cu64%3E"><strong>range strategy</strong></a> such as <code>0..10000_u64</code>, which generates values within the range uniformly at random.</li>
<li>The <a href="https://docs.rs/proptest/latest/proptest/collection/fn.vec.html"><strong><code>vec</code> combinator</strong></a>, which accepts a strategy for elements and a size parameter.</li>
</ul>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">generate_bad_type</span><span class="p">()</span><span class="w"> </span>-&gt; <span class="nc">impl</span><span class="w"> </span><span class="n">Strategy</span><span class="o">&lt;</span><span class="n">Value</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">BadType</span><span class="o">&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// Use the range strategy to generate values uniformly at random.
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kd">let</span><span class="w"> </span><span class="n">value_strategy</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">0</span><span class="o">..</span><span class="mi">10000_</span><span class="k">u64</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// Use the vec strategy to generate a list of behaviors: 0..128 items.
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kd">let</span><span class="w"> </span><span class="n">ord_behavior_strategy</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">vec</span><span class="p">(</span><span class="n">generate_ord_behavior</span><span class="p">(),</span><span class="w"> </span><span class="mi">0</span><span class="o">..</span><span class="mi">128</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// Now what? We need to compose these strategies together. With proptest,
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// the way to do this is to first create a tuple of strategies.
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kd">let</span><span class="w"> </span><span class="n">tuple_strategy</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">(</span><span class="n">value_strategy</span><span class="p">,</span><span class="w"> </span><span class="n">ord_behavior_strategy</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// A tuple of strategies is also a strategy! Generated values are a tuple
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// of constituents.
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">//
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// With this in hand, we can use a function called `prop_map` to turn the
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// tuple into a BadType.
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">tuple_strategy</span><span class="p">.</span><span class="n">prop_map</span><span class="p">(</span><span class="o">|</span><span class="p">(</span><span class="n">value</span><span class="p">,</span><span class="w"> </span><span class="n">ord_behavior</span><span class="p">)</span><span class="o">|</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">BadType</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="n">value</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="n">ord_behavior</span>: <span class="nc">RefCell</span>::<span class="n">new</span><span class="p">(</span><span class="n">ord_behavior</span><span class="p">),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">})</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div>
  <figure class="floatright" >
    
    <img src="/images/proptest-composition.png"  alt="A flowchart to show how smaller strategies flow into larger ones. See code comments in sample above for a full explanation."   />
    
    
      <figcaption class="center" >Composing smaller strategies into a larger one for <code>BadType</code>.</figcaption>
    
  </figure>


<p>You might be wondering where all the shrinking code is. It&rsquo;s actually implemented on the corresponding value trees for each strategy:</p>
<ul>
<li>Range strategies use binary search to make values smaller.</li>
<li>The <code>Just</code> strategy doesn&rsquo;t do any shrinking, since it just returns a single value.</li>
<li>The <code>prop_oneof</code> combinator shrinks towards the beginning of the choices: in this case, <code>Flipped</code> is shrunk into <code>Regular</code>.</li>
<li>The <code>vec</code> combinator implements roughly the algorithm in <a href="/posts/monads-through-pbt/#implementing-a-manual-shrinker"><em>Implementing a manual shrinker</em></a> above.</li>
</ul>
<p>You can see how the base strategies get turned into successively larger ones through combinators like <code>prop_oneof</code>. It&rsquo;s very similar to <a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html"><code>Iterator</code></a>, where you can keep calling <code>.map</code>, <code>.filter</code>, <code>.enumerate</code> and so on over and over<sup id="fnref:3"><a href="#fn:3" class="footnote-ref" role="doc-noteref">3</a></sup>.</p>
<p>In my experience, composability across different scales is where this model shines. You can build bigger strategies out of smaller ones, up to a surprising amount of complexity. This means that your team can invest in a library of ever-more-complex strategies, and continue to derive value out of that library across everything from the smallest of unit tests to large integration tests.</p>
<p>But there is one <em>massive</em> wrinkle with integrated shrinking. And that wrinkle is <em>exactly</em> what monads are about.</p>
<h2 id="4-monads-finally">4. Monads, finally</h2>
<p>In the previous few sections, we&rsquo;ve built up all the context we need. We&rsquo;re now going to look at the fundamental operation that introduces monadic composition to proptest: <a href="https://docs.rs/proptest/latest/proptest/strategy/trait.Strategy.html#method.prop_flat_map"><code>prop_flat_map</code></a>.</p>

  <figure class="floatright" >
    
    <img src="/images/map-shrink.png"  alt="Diagram comparing prop_map behavior before and after shrinking. Left panel labeled &#39;original&#39; shows value=100 passing through prop_map(x²) to produce value=10000. Right panel labeled &#39;shrink&#39; shows value=50 passing through the same prop_map(x²) function to produce value=2500. An arrow connects the two panels, illustrating how prop_map preserves the same transformation during shrinking, just with smaller values."   />
    
    
      <figcaption class="center" ><code>prop_map</code> from <em>x</em> to <em>x²</em>. When values are shrunk, they transparently pass through the map function.</figcaption>
    
  </figure>


<p>In the example above, there&rsquo;s a function called <a href="https://docs.rs/proptest/latest/proptest/strategy/trait.Strategy.html#method.prop_map"><code>prop_map</code></a>, which we use to turn a tuple of components into a <code>BadType</code> value. What happens when you try and shrink a value through a <code>prop_map</code>? It&rsquo;s very simple:</p>
<ul>
<li>Attempt to get a smaller value from the underlying value tree.</li>
<li>Call the map function on the value.</li>
</ul>
<p>So <code>prop_map</code> is just a conduit that values pass through: it simply maps a value to another value, and does not change the structure of the value tree in any way.</p>
<p>Now let&rsquo;s say we want to test out pairs of <code>BadType</code> instances, where the way the second <code>BadType</code> is generated depends on the first. This is a situation where we don&rsquo;t just want to map a value to another value—we need to generate a whole new <em>strategy</em> based on a value.</p>
<p>This is a <strong>fundamental shift</strong>:</p>
<ul>
<li>As above, <code>prop_map</code> transforms a value into another, but preserves the original structure.</li>
<li>This new method, <code>prop_flat_map</code>, goes well beyond that. Based on the value generated, it creates a brand new <em>strategy</em> with a structure all of its own.</li>
</ul>
<p>This is monadic composition in action. The result of one operation controls, at runtime, the entire shape of the next operation.</p>
<p>For example, here&rsquo;s one way to go about generating pairs of <code>BadType</code>s, where the second value is always greater than the first:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">generate_bad_type_pair</span><span class="p">()</span><span class="w"> </span>-&gt; <span class="nc">impl</span><span class="w"> </span><span class="n">Strategy</span><span class="o">&lt;</span><span class="n">Value</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">(</span><span class="n">BadType</span><span class="p">,</span><span class="w"> </span><span class="n">BadType</span><span class="p">)</span><span class="o">&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// First generate a BadType.
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">generate_bad_type</span><span class="p">().</span><span class="n">prop_flat_map</span><span class="p">(</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="o">|</span><span class="n">first_bad_type</span><span class="o">|</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="c1">// Now generate a second BadType with a value greater than the first.
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="p">(</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="p">(</span><span class="n">first_bad_type</span><span class="p">.</span><span class="n">value</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">1</span><span class="p">)</span><span class="o">..</span><span class="mi">20000_</span><span class="k">u64</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="n">vec</span><span class="p">(</span><span class="n">generate_ord_behavior</span><span class="p">(),</span><span class="w"> </span><span class="mi">0</span><span class="o">..</span><span class="mi">128</span><span class="p">),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="p">.</span><span class="n">prop_map</span><span class="p">(</span><span class="k">move</span><span class="w"> </span><span class="o">|</span><span class="p">(</span><span class="n">second_value</span><span class="p">,</span><span class="w"> </span><span class="n">ord_behavior</span><span class="p">)</span><span class="o">|</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="c1">// Generate the second value.
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="kd">let</span><span class="w"> </span><span class="n">second_bad_type</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">BadType</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                    </span><span class="n">value</span>: <span class="nc">second_value</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                    </span><span class="n">ord_behavior</span>: <span class="nc">RefCell</span>::<span class="n">new</span><span class="p">(</span><span class="n">ord_behavior</span><span class="p">),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="p">};</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="c1">// Return the pair.
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="p">(</span><span class="n">first_bad_type</span><span class="p">.</span><span class="n">clone</span><span class="p">(),</span><span class="w"> </span><span class="n">second_bad_type</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="p">})</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>Your first reaction might be: <em>wow, this seems really powerful</em>. And you would be right! You can write <em>whatever you like</em> in the body of a <code>prop_flat_map</code>:</p>
<ul>
<li>You can conditionally return one strategy or another, reimplementing <a href="https://docs.rs/proptest/latest/proptest/macro.prop_oneof.html"><code>prop_oneof</code></a>.</li>
<li>You can first generate a size and then return a vector with those many elements, reimplementing the <code>vec</code> combinator.</li>
<li>You can call <code>prop_flat_map</code> again, as many times as you like.</li>
</ul>
<p>In a real and quite rigorous sense, <code>prop_flat_map</code> is maximally powerful. Every combinator we&rsquo;ve talked about, and in fact most of the proptest library, can be written in terms of <code>prop_flat_map</code>.</p>
<p>So why do all these combinators exist? Why don&rsquo;t we just use <code>prop_flat_map</code> everywhere?</p>
<p>The function actually works reasonably well in practice. It generates random values with the right shape, and shrinks them correctly on a failing input.</p>
<p><em>But.</em></p>
<p>Shrinking is <em>really, really slow.</em></p>
<p><em>Exponentially</em> slow.</p>

  <figure class="center" >
    
    <img src="/images/flat-map-shrink.png"  alt="Diagram comparing prop_flat_map behavior before and after shrinking. Left panel labeled &#39;original&#39; shows value=100 passing through prop_flat_map(0..x²) to create strategy:0..10000, which produces value=8634. Right panel labeled &#39;shrink&#39; shows value=50 passing through the same function to create a completely new strategy:0..2500 (highlighted in pink), which generates multiple different outputs (value=389, value=1653, value=...). An arrow connects the original strategy to the new one, illustrating how shrinking creates an entirely new structure rather than preserving the original one."   />
    
    
      <figcaption class="center" ><code>prop_flat_map</code> with a map from <em>x</em> to the strategy <em>0..x²</em>. Each time the original value is shrunk, a brand-new strategy is created (highlighted in red) and the shrinker has to start over.</figcaption>
    
  </figure>


<p>Why is that the case? Consider what happens when we want to shrink a value through a <code>prop_flat_map</code>. As before:</p>
<ul>
<li>We would attempt to get a smaller value from the underlying value tree.</li>
<li>And then, because we would call the <code>prop_flat_map</code> callback to generate a new strategy, we would <em>throw away the previously-generated value tree entirely</em>.</li>
</ul>
<p>Because <code>prop_flat_map</code> generates brand new value trees each time it&rsquo;s called, shrinking has to be started again, from scratch, each time! This is the essence of monadic composition: powerful, unconstrained, and fundamentally <strong>unpredictable</strong>.</p>
<h3 id="measuring-the-impact">Measuring the impact</h3>
<p>We can measure the impact of monadic composition quite directly, along two related axes: the amount of time it takes to complete iterations, and the number of iterations the shrink completes in.</p>
<p>For this post I wrote <a href="https://github.com/sunshowers-code/proptest-shrink-tests">a small Rust program</a> which collects metrics about shrinking for:</p>
<ul>
<li>The <code>prop_flat_map</code> implementations for <code>BadType</code> pairs above, and a non-monadic implementation with <code>prop_map</code> (see below)</li>
<li>The same for <code>(BadType, BadType, BadType)</code> triples: a non-monadic implementation with <code>prop_map</code>, and a monadic one with two levels of <code>prop_flat_map</code>.</li>
</ul>
<p>With this program, I collected 512 samples on my workstation and analyzed the data. (I ran the program with <a href="https://doc.rust-lang.org/cargo/reference/profiles.html#opt-level"><code>opt-level</code> set to 1</a>, to mimic typical dev builds in larger Rust projects<sup id="fnref:4"><a href="#fn:4" class="footnote-ref" role="doc-noteref">4</a></sup>).</p>
<p>First, the amount of time it took to shrink values down, by key <a href="https://en.wikipedia.org/wiki/Percentile">percentile</a>:</p>
<table>
	<thead>
			<tr>
					<th style="text-align: center">Metric</th>
					<th style="text-align: right">Pairs (<code>prop_map</code>)</th>
					<th style="text-align: right">Triples (<code>prop_map</code>)</th>
					<th style="text-align: right">Pairs (<code>prop_flat_map</code>)</th>
					<th style="text-align: right">Triples (<code>prop_flat_map</code>)</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td style="text-align: center"><strong>min</strong></td>
					<td style="text-align: right">11 µs</td>
					<td style="text-align: right">48 µs</td>
					<td style="text-align: right">3.85 ms</td>
					<td style="text-align: right">8.95 ms</td>
			</tr>
			<tr>
					<td style="text-align: center"><strong>p50</strong></td>
					<td style="text-align: right">1.70 ms</td>
					<td style="text-align: right">2.52 ms</td>
					<td style="text-align: right">8.52 ms</td>
					<td style="text-align: right">181 ms</td>
			</tr>
			<tr>
					<td style="text-align: center"><strong>p75</strong></td>
					<td style="text-align: right">3.74 ms</td>
					<td style="text-align: right">5.77 ms</td>
					<td style="text-align: right">10.04 ms</td>
					<td style="text-align: right">307 ms</td>
			</tr>
			<tr>
					<td style="text-align: center"><strong>p90</strong></td>
					<td style="text-align: right">5.25 ms</td>
					<td style="text-align: right">8.41 ms</td>
					<td style="text-align: right">11.76 ms</td>
					<td style="text-align: right">435 ms</td>
			</tr>
			<tr>
					<td style="text-align: center"><strong>max</strong></td>
					<td style="text-align: right">7.00 ms</td>
					<td style="text-align: right">10.55 ms</td>
					<td style="text-align: right">15.53 ms</td>
					<td style="text-align: right">1808 ms</td>
			</tr>
	</tbody>
</table>
<p>In this table, <strong>p50</strong> represents the median completion time, while <strong>p75</strong> and <strong>p90</strong> show the times that 75% and 90% of the samples completed within. With <code>prop_map</code>, the amount of time scales somewhat linearly as we go from pairs to triples. But with just one additional level of <code>prop_flat_map</code>, the performance degrades dramatically, going from under 20 milliseconds to almost 2 seconds! That&rsquo;s over 100x slower.</p>
<p>The difference in the number of iterations is even more striking:</p>
<table>
	<thead>
			<tr>
					<th style="text-align: center">Metric</th>
					<th style="text-align: right">Pairs (<code>prop_map</code>)</th>
					<th style="text-align: right">Triples (<code>prop_map</code>)</th>
					<th style="text-align: right">Pairs (<code>prop_flat_map</code>)</th>
					<th style="text-align: right">Triples (<code>prop_flat_map</code>)</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td style="text-align: center"><strong>min</strong></td>
					<td style="text-align: right">48</td>
					<td style="text-align: right">93</td>
					<td style="text-align: right">1228</td>
					<td style="text-align: right">11223</td>
			</tr>
			<tr>
					<td style="text-align: center"><strong>p50</strong></td>
					<td style="text-align: right">215</td>
					<td style="text-align: right">306</td>
					<td style="text-align: right">6722</td>
					<td style="text-align: right">281016</td>
			</tr>
			<tr>
					<td style="text-align: center"><strong>p75</strong></td>
					<td style="text-align: right">270</td>
					<td style="text-align: right">354</td>
					<td style="text-align: right">9315</td>
					<td style="text-align: right">481996</td>
			</tr>
			<tr>
					<td style="text-align: center"><strong>p90</strong></td>
					<td style="text-align: right">310</td>
					<td style="text-align: right">410</td>
					<td style="text-align: right">10722</td>
					<td style="text-align: right">693358</td>
			</tr>
			<tr>
					<td style="text-align: center"><strong>max</strong></td>
					<td style="text-align: right">387</td>
					<td style="text-align: right">530</td>
					<td style="text-align: right">12242</td>
					<td style="text-align: right">884729</td>
			</tr>
	</tbody>
</table>
<p>From hundreds of iterations to almost a million! And we&rsquo;re working with pretty simple structures here, too. Just one more level of <code>prop_flat_map</code> would make shrinking quite noticeably slow, and another one after that would be disastrous.</p>
<p>The data here spans several orders of magnitude. A good way to visualize this kind of data is via a <a href="https://en.wikipedia.org/wiki/Cumulative_distribution_function">CDF</a> plotted on a logarithmic scale. In these graphs, the x-axis shows the time or iterations, and the y-axis shows the cumulative probability. Curves that are further to the right are worse, and the logarithmic scale reveals that the differences are in orders of magnitude.</p>

  <figure class="center" >
    
    <img src="/images/proptest-performance-cdf.png"  alt="There are two log‐log scale CDF (cumulative distribution function) plots, each showing four lines labeled “pair map,” “triple map,” “pair flat_map,” and “triple flat_map.” For the top plot (cdf of shrink execution time), the x‐axis ranges roughly from 10 µs to 1 × 10^6 µs (log scale) and the y‐axis shows cumulative probability from 0.01 to 1.0 (also log scale). The “pair map” (green) and “triple map” (purple) curves overlap around 100 µs to about 1,000 µs, reaching 100% probability before the “pair flat_map” (blue) and “triple flat_map” (orange) lines. The blue line peaks around tens of thousands of microseconds, while the orange line extends further toward 1 × 10^6 µs before leveling off. For the bottom plot (cdf of number of shrink iterations), the x‐axis is the number of iterations (10 to 1 × 10^6 on a log scale) and the y‐axis is cumulative probability (0.01 to 1.0 on a log scale). Again, “pair map” (green) and “triple map” (purple) are at lower iteration counts (roughly tens to hundreds) and reach 100% probability faster. “Pair flat_map” (blue) extends to thousands of iterations, and “triple flat_map” (orange) continues to tens or hundreds of thousands of iterations before reaching 100%. A legend in the top‐right corner identifies each line’s label. In the bottom right is system information (Ryzen 7950X, Linux 6.12, Rust 1.84.1, opt‐level 1)."   />
    
    
      <figcaption class="center" >Cumulative distribution functions for <code>prop_map</code> and <code>prop_flat_map</code> pairs and triples. This is a logarithmic scale, so the differences are in orders of magnitude.</figcaption>
    
  </figure>


<h2 id="5-rediscovering-structure">5. Rediscovering structure</h2>
<p>What makes monadic composition so difficult to deal with? It has to do with the fact, mentioned above, that you can write <em>whatever you like</em> inside the <code>prop_flat_map</code>. Because a <code>prop_flat_map</code> can contain arbitrary computation inside of it, and that computation returns brand-new strategies, determining how a value will shrink through it is fundamentally unpredictable without actually executing it.</p>
<p>In other words, the <code>prop_flat_map</code> callback is quite opaque. Why is that? It&rsquo;s because the <code>prop_flat_map</code> callback is written in Rust, which is a powerful, <a href="https://en.wikipedia.org/wiki/Turing_completeness">Turing-complete</a> language. It is impossible to fully analyze the semantics of Turing-complete languages<sup id="fnref:5"><a href="#fn:5" class="footnote-ref" role="doc-noteref">5</a></sup>. (You might know this as the <a href="https://en.wikipedia.org/wiki/Halting_problem">halting problem</a>, or as <a href="https://en.wikipedia.org/wiki/Rice%27s_theorem">Rice&rsquo;s theorem</a>.)</p>
<p>But the fact that some analysis requires solving the halting problem is merely the start of the discussion, not the end of it! There is a rich literature on how to find approximate solutions for problems that are otherwise insoluble due to Rice&rsquo;s theorem. For shrinking, here are a few approaches that are known to work.</p>
<p>One option is to <strong>place limits</strong> on how long shrinking is done for. Note that <code>prop_flat_map</code> has no issues while generating values, just while shrinking them<sup id="fnref:6"><a href="#fn:6" class="footnote-ref" role="doc-noteref">6</a></sup>. The proptest library itself sets limits on shrink iterations, particularly <a href="https://docs.rs/proptest/latest/proptest/test_runner/struct.Config.html#structfield.max_flat_map_regens">across <code>prop_flat_map</code> instances</a>. This ensures that shrinking operations finish in a reasonable amount of time, even if they don&rsquo;t produce minimal values.</p>
<p>A better option is to <strong>rewrite generators to not use monadic composition</strong>. For the example above, it&rsquo;s not hugely difficult<sup id="fnref:7"><a href="#fn:7" class="footnote-ref" role="doc-noteref">7</a></sup>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">better_generate_bad_type_pair</span><span class="p">()</span><span class="w"> </span>-&gt; <span class="nc">impl</span><span class="w"> </span><span class="n">Strategy</span><span class="o">&lt;</span><span class="n">Value</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">(</span><span class="n">BadType</span><span class="p">,</span><span class="w"> </span><span class="n">BadType</span><span class="p">)</span><span class="o">&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// Generate two BadType instances.
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">(</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">generate_bad_type</span><span class="p">(),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">generate_bad_type</span><span class="p">(),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// Look, no prop_flat_map! This is non-monadic composition.
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">.</span><span class="n">prop_map</span><span class="p">(</span><span class="o">|</span><span class="p">(</span><span class="n">bad1</span><span class="p">,</span><span class="w"> </span><span class="k">mut</span><span class="w"> </span><span class="n">bad2</span><span class="p">)</span><span class="o">|</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// Add bad1.value to bad2.value. Because the two are non-negative
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// (unsigned integers), this ensures that bad2.value is always
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// bigger than bad1.value.
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">bad2</span><span class="p">.</span><span class="n">value</span><span class="w"> </span><span class="o">+=</span><span class="w"> </span><span class="n">bad1</span><span class="p">.</span><span class="n">value</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="p">(</span><span class="n">bad1</span><span class="p">,</span><span class="w"> </span><span class="n">bad2</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">})</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>But this can be quite challenging as complexity goes up! The proptest library comes with a number of helpers to write non-monadic strategies, particularly <a href="https://docs.rs/proptest/latest/proptest/strategy/trait.Strategy.html#method.prop_recursive"><code>prop_recursive</code></a> and <a href="https://docs.rs/proptest/latest/proptest/sample/struct.Index.html"><code>sample::Index</code></a>. But there are real situations, particularly with large and complex data structures (for example, randomly-generated programming language syntax trees), where none of those options suffice and you have to use the full power of <code>prop_flat_map</code>.</p>
<p>Last but not least, there&rsquo;s a set of approaches that I&rsquo;m going to put into the bucket of <em>rediscovering structure</em> across flat maps. Key to these is understanding that when you generate a random value, you&rsquo;re turning an RNG, which is a random stream of bits, into concrete, structured values. Can we somehow be clever about looking at the RNG bitstream?</p>
<ul>
<li>
<p>One option is to <strong>instrument the test</strong>, for example by using a <a href="https://github.com/rust-fuzz/cargo-fuzz">fuzzer</a>. Fuzzing is all about generating random data, looking at the branches explored, and tweaking the random data to ensure other branches are taken. It&rsquo;s a great fit for peering past the black box of monadic composition.</p>
</li>
<li>
<p>Another option is to <strong>be clever with random number generator</strong>. A random number ultimately generates a sequence of ones and zeroes. Can we poke at this sequence, possibly with the help of some hints from the strategies themselves? This is implemented by the <a href="https://github.com/HypothesisWorks/hypothesis">Hypothesis framework for Python</a>; see <a href="https://www.doc.ic.ac.uk/~afd/papers/2020/ECOOP_Hypothesis.pdf">this excellent paper about it</a>.</p>
</li>
</ul>
<p>Both of these approaches are heuristic and quite complex. But that&rsquo;s what you need to put together some structure again, after it&rsquo;s been through the blender of monadic composition.</p>
</div>
<hr>
<h2 id="conclusion-constraints-liberate-liberties-constrain">Conclusion: constraints liberate, liberties constrain</h2>

  <figure class="floatright" >
    
    <img src="/images/autobahn.jpg"  alt="A photo of a German autobahn (A9) near Munich showing clear lane discipline with multiple lanes in both directions. The highway features crisp white lane markings, minimal traffic, and blue directional signs indicating routes to Berlin, Nürnberg, and other destinations. The organized traffic flow demonstrates how structured constraints enable efficient movement."   />
    
    
      <figcaption class="center" >The Autobahn in Germany. Organized traffic flow and strict lane discipline means greater freedom: unlimited speed. <a href="https://commons.wikimedia.org/wiki/File:Autobahn_Muenchen.jpg">Tarboosh / Wikimedia Commons</a></figcaption>
    
  </figure>


<p>In this article, we looked at monads as a <em>design pattern</em>: a way for a user to compose operations within a framework. We looked at both monadic functions like <code>prop_flat_map</code>, and non-monadic ones such as <code>prop_map</code> and <code>prop_oneof</code>. Finally, we saw how in the context of property-based testing, monadic composition has a performance impact measured in orders of magnitude.</p>
<p>With this knowledge in mind, you can now spot monadic composition in all kinds of other places:</p>
<ul>
<li>
<p>Futures in Rust, where <code>.await</code> is monadic, but futures are awaited sequentially. To run futures concurrently, you have to use non-monadic operations like <a href="https://docs.rs/futures/latest/futures/future/fn.join.html"><code>future::join</code></a>.</p>
</li>
<li>
<p>Some <a href="https://www.microsoft.com/en-us/research/uploads/prod/2018/03/build-systems.pdf">build systems</a>, where individual build nodes can generate more nodes, making it impossible to generate a dependency graph without running the build. (Cargo is thankfully non-monadic.)</p>
</li>
<li>
<p>And even with iterators, where <a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map"><code>Iterator::map</code></a> returns an iterator with the same length as before, and <a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.filter_map"><code>filter_map</code></a> returns an iterator with the same or a smaller length, but the length of <a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.flat_map"><code>flat_map</code></a> is unbounded.</p>
</li>
<li>
<p><a href="https://doc.rust-lang.org/std/option/enum.Option.html#method.and_then"><code>Option::and_then</code></a>, <a href="https://doc.rust-lang.org/std/result/enum.Result.html#method.and_then"><code>Result::and_then</code></a>, and <a href="https://doc.rust-lang.org/std/result/enum.Result.html#method.or_else"><code>Result::or_else</code></a> all happen to be monadic operations as well, though they&rsquo;re all simple enough that they don&rsquo;t have any practical downsides.</p>
</li>
</ul>
<p>The common thread through all of these examples is that within a framework, monadic composition is not just from value to <em>value</em>. It is from value to a further instance of that <em>framework</em>. The return value of <code>future.await</code> can result in more futures being spawned, monadic build nodes can generate more build nodes, and <code>flat_map</code> turns individual values into iterators. This freedom is what makes monads both the most flexible kind of composition, and the hardest to predict the behavior of.</p>
<p>This is part of a general observation throughout programming, whenever there&rsquo;s an interaction between two parties or two sides. The more restrictions there are on one side, the freer the other side is to do what it likes. Monadic composition is an extreme version of that: the most powerful and least constrained form of composition for the user, but the most difficult to deal with for the framework.</p>
<p>Whether you&rsquo;re a user or a library designer, pay close attention to situations where your operations are monadic. They can provide a great deal of power, perhaps too much in some circumstances. If non-monadic operations are sufficient to help you achieve your goal, prefer them.</p>
<p>And when they aren&rsquo;t enough: well, now you know what you&rsquo;re getting into!</p>
<p><em>Thanks to <a href="https://infosec.exchange/@munin">Fiona</a> and <a href="https://cliffle.com/">Cliff Biffle</a> for reviewing drafts of this post. Any mistakes in it are my own.</em></p>
<p><em>Updated 2025-02-20: Clarified note about Turing completeness to indicate that it is not the composition itself that&rsquo;s Turing-complete—it&rsquo;s the language used to write the callback in that&rsquo;s at issue.</em></p>
<hr>
<h2 id="appendix">Appendix</h2>
<p>This section contains some jargon, but it&rsquo;s mostly here to satisfy the pedants who will inevitably Ctrl-F for &ldquo;monad laws&rdquo;. Please ignore this section if you didn&rsquo;t get here through a search for that string.</p>
<details>
      <summary>Click to expand</summary>
<p>Formally speaking, monads are any kind of structure with two operations <em>return</em> and <em>bind</em>, where these operations obey three <a href="https://wiki.haskell.org/index.php?title=Monad_laws">monad laws</a>. For <code>Strategy</code>, these functions would be:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">return</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span><span class="p">(</span><span class="n">x</span>: <span class="nc">T</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="nc">impl</span><span class="w"> </span><span class="n">Strategy</span><span class="o">&lt;</span><span class="n">Value</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">T</span><span class="o">&gt;</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">bind</span><span class="o">&lt;</span><span class="n">U</span><span class="p">,</span><span class="w"> </span><span class="no">ST</span><span class="p">,</span><span class="w"> </span><span class="n">F</span><span class="p">,</span><span class="w"> </span><span class="no">SU</span><span class="o">&gt;</span><span class="p">(</span><span class="n">base</span>: <span class="nc">ST</span><span class="p">,</span><span class="w"> </span><span class="n">f</span>: <span class="nc">F</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="nc">impl</span><span class="w"> </span><span class="n">Strategy</span><span class="o">&lt;</span><span class="n">Value</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">U</span><span class="o">&gt;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">where</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="no">ST</span>: <span class="nc">Strategy</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">F</span>: <span class="nb">Fn</span><span class="p">(</span><span class="no">ST</span>::<span class="n">Value</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="nc">SU</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="no">SU</span>: <span class="nc">Strategy</span><span class="o">&lt;</span><span class="n">Value</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">U</span><span class="o">&gt;</span><span class="p">;</span><span class="w">
</span></span></span></code></pre></div><p>For strategies, <em>return</em> is <code>Just</code>, and <em>bind</em> is <code>prop_flat_map</code>.</p>
<p>Here are the three monad laws expressed in terms of proptest:</p>
<ul>
<li>
<p><strong>Left identity:</strong> for any <code>value</code>, <code>Just(value).prop_flat_map(f)</code> should be the same as <code>f(value)</code>. That is indeed the case, both for generation and for shrinking. Since <code>Just</code> does not do any shrinking, the pathological <code>prop_flat_map</code> behavior doesn&rsquo;t take effect.</p>
</li>
<li>
<p><strong>Right identity:</strong> for any <code>strategy</code>, <code>strategy.prop_flat_map(Just)</code> should be the same as <code>strategy</code>. That is also the case. Every time <code>strategy</code> is shrunk, <code>prop_flat_map</code> has to discard the state returned by the dependent strategy. But <code>Just</code> is a trivial strategy that doesn&rsquo;t have any state, so it&rsquo;s effectively a no-op.</p>
</li>
<li>
<p><strong>Associativity:</strong> if you have a chain of two <code>prop_flat_map</code>s, you can apply the second one either &ldquo;inside&rdquo; or &ldquo;outside&rdquo; the first one. More specifically, for any <code>strategy</code>, with the definitions:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">strat1</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">strategy</span><span class="p">.</span><span class="n">prop_flat_map</span><span class="p">(</span><span class="n">f</span><span class="p">).</span><span class="n">prop_flat_map</span><span class="p">(</span><span class="n">g</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">strat2</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">strategy</span><span class="p">.</span><span class="n">prop_flat_map</span><span class="p">(</span><span class="o">|</span><span class="n">value</span><span class="o">|</span><span class="w"> </span><span class="n">f</span><span class="p">(</span><span class="n">value</span><span class="p">).</span><span class="n">prop_flat_map</span><span class="p">(</span><span class="n">g</span><span class="p">));</span><span class="w">
</span></span></span></code></pre></div><p>this law requires that <code>strat1</code> and <code>strat2</code> are the same. That&rsquo;s true as well, both for generation and for shrinking, though the latter is slightly harder to see.</p>
</li>
</ul>
<p>One might object by pointing out that in Rust, the above operations result in different types even if they have the same behavior. That is true, but also not particularly relevant, since you can always call <a href="https://docs.rs/proptest/latest/proptest/strategy/trait.Strategy.html#method.boxed"><code>Strategy::boxed</code></a> to erase the type.</p>
<p>One might also point out that we haven&rsquo;t talked about a <code>Monad</code> typeclass or trait here. That&rsquo;s a distraction! Monadic composition exists everywhere in programming, <em>regardless</em> of whether the language lets you express <code>Monad</code> as a reified type. You can express <code>Monad</code> in modern versions of Rust via <a href="https://blog.rust-lang.org/2022/10/28/gats-stabilization.html">GATs</a>, but there really isn&rsquo;t much utility to it.</p>
</details>
<p>Thank you!</p>
<div class="footnotes" role="doc-endnotes">
<hr>
<ol>
<li id="fn:1">
<p>Some of these examples might seem far too adversarial to ever be seen in the real world. But an implementation that can handle adversarially bad inputs can also handle inputs that are bad in more benign ways. For production-grade sort functions, it makes sense to design for the worst possible inputs.&#160;<a href="#fnref:1" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:2">
<p>This is not a moral failing on the part of those developers, because <a href="https://sunshowers.io/posts/there-is-no-free-will/">free will doesn&rsquo;t exist</a>. It&rsquo;s completely fine, and worth embracing! Integrated shrinking is altering the environment in action.&#160;<a href="#fnref:2" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:3">
<p>Just like with iterators, the type signatures also become quite long!&#160;<a href="#fnref:3" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:4">
<p>The default value of <code>opt-level</code>, 0, is fine for <code>prop_map</code>, but infeasible for <code>prop_flat_map</code> with triples.&#160;<a href="#fnref:4" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:5">
<p>The problem is not specific to Turing-complete languages—it even exists in non-Turing-complete ones. For example, if the callback were written in a language that <a href="https://en.wikipedia.org/wiki/Primitive_recursive_function">only had for loops, no while loops</a>, the framework would still not be able to peer past the shrinker.&#160;<a href="#fnref:5" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:6">
<p>I think this is the key insight that many monad tutorials miss. When writing about monads, it&rsquo;s tempting to focus on simple examples like <a href="https://doc.rust-lang.org/std/option/enum.Option.html#method.and_then"><code>Option::and_then</code></a>, where the monadic behavior doesn&rsquo;t have significant practical implications. Here, too, if we restrict ourselves to <em>generating</em> values, there&rsquo;s nothing wrong with <code>prop_flat_map</code>. It&rsquo;s only during <em>shrinking</em> that monadic composition rears its ugly head.</p>
<p>If you&rsquo;re explaining monads to an audience, consider emphasizing not just what monads are, but when their unconstrained power becomes a liability rather than an asset.&#160;<a href="#fnref:6" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:7">
<p>If you&rsquo;re playing close attention, you might notice that while this function meets the requirement we set out, the random distribution generated is somewhat different. In this case, it&rsquo;s possible to get a distribution equivalent to the <code>prop_flat_map</code> example through the use of <a href="https://docs.rs/proptest/latest/proptest/sample/struct.Index.html"><code>sample::Index</code></a>.&#160;<a href="#fnref:7" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
</ol>
</div>
]]></content><category scheme="https://sunshowers.io/tags/monads" term="monads" label="monads"/><category scheme="https://sunshowers.io/tags/property-based-testing" term="property-based-testing" label="property-based-testing"/></entry></feed>