<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:g='http://base.google.com/ns/1.0'>
  <title>Reasonably Polymorphic</title>
  <updated>2026-11-15T11:39:00Z</updated>
  <author><name>Sandy Maguire</name></author>
  <id>http://reasonablypolymorphic.com</id>
  <link rel='self' href='https://reasonablypolymorphic.com'/>

    <entry>
      <title>Musical Notes and Scales</title>
      <id>blog/notes-scales/index.html</id>
      <link href='blog/notes-scales/index.html'/>
      <published>2026-11-15T11:39:00Z</published>
      <updated>2026-11-15T11:39:00Z</updated>

      <content type="html" xml:base="https://reasonablypolymorphic.com">
        <![CDATA[
        <p>Sorry for the delay. Everyone in my household came down with egregious sicknesses. And I had a bunch of unsatisfying things in my music theory that needed to get worked out. But we’re mostly better and the theoretical issues are resolved, so we’re BACK baby.</p>
<hr />
<p>Over the last two posts we discussed <a href="/blog/pitches-1/">abstract musical pitches</a> and (some) <a href="/blog/voice-leadings/">efficient voice leadings</a> which help move us smoothly between different configurations in musical space.</p>
<p>It’s been all very interesting <em>musically</em>, but you must admit there hasn’t been much in the way of functional programming going on. Today we’re going to get back to brass tacks and see about making all of these notions precise, compositional, and fun to work with.</p>
<p>Where we left things is with a <code>Fin n</code> type:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Fin</span><span class="ot"> ::</span> <span class="dt">Nat</span> <span class="ot">-&gt;</span> <span class="dt">Type</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Fin</span> n</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span>  <span class="dt">KnownNat</span> n          <span class="ot">=&gt;</span> <span class="dt">Enum</span>    (<span class="dt">Fin</span> n)</span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> (<span class="dt">KnownNat</span> n, <span class="dv">1</span> <span class="op">&lt;=</span> n) <span class="ot">=&gt;</span> <span class="dt">Bounded</span> (<span class="dt">Fin</span> n)</span></code></pre></div>
<p>which has exactly <code>n</code> distinct values. We then made a <code>Deg n</code> type, whose semantics are “exactly one of <code>n</code> distinct values, with an octave component.” We represent this implicitly by way of an <code>Int</code>:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Deg</span><span class="ot"> ::</span> <span class="dt">Nat</span> <span class="ot">-&gt;</span> <span class="dt">Type</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">Deg</span> n <span class="ot">=</span> <span class="dt">Deg</span></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> getDeg ::</span> <span class="dt">Int</span></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>  }</span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> stock (<span class="dt">Generic</span>)</span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> <span class="kw">newtype</span> (<span class="dt">Eq</span>, <span class="dt">Ord</span>, <span class="dt">Show</span>, <span class="dt">Num</span>, <span class="dt">Enum</span>, <span class="dt">Real</span>, <span class="dt">Integral</span>)</span></code></pre></div>
<p>and give its semantics by way of a function:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="ot">degToPC ::</span> <span class="dt">KnownNat</span> n <span class="ot">=&gt;</span> <span class="dt">Deg</span> n <span class="ot">-&gt;</span> (<span class="dt">Int</span>, <span class="dt">Fin</span> n)</span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>degToPC (<span class="dt">Deg</span> d) <span class="ot">=</span></span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> (oct, pc) <span class="ot">=</span> <span class="fu">divMod</span> d n</span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a>   <span class="kw">in</span> (oct, <span class="fu">toEnum</span> pc)</span></code></pre></div>
<p>where the output <code>Int</code> is which octave the degree ended up in.</p>
<p>We have then been discussing “scales” as mappings of the form <code>Fin m -&gt; Fin n</code>. These have always been in scare quotes because this is not really how musicians traditionally think about scales! Whatever this mapping concept <em>is,</em> it doesn’t really have a standard name in musical vocabulary. But scales are the closest thing semantically, so we’re going to just shadow that name and go about our business.</p>
<p>It’s a bit of a tricky line to balance. So whenever we’re talking about the loose musical idea, we’ll use the word “scale.” And whenever we mean this mapping, we’ll go with <code>Scale</code>.</p>
<h2 id="some-failed-attempts-at-pinnning-down-scales">Some Failed Attempts at Pinnning Down Scales</h2>
<p>However, it’s been a bit of a simplification to say a <code>Scale</code> is a mapping <code>Fin n -&gt; Fin m</code>. We’d like our <code>Scale</code>s to be <em>monotone mappings,</em> which is to say that if <code>i :: Deg m &lt;= j :: Deg m</code>, then <code>(applyScale sc i) :: Deg n &lt;= (applyScale sc j) :: Deg n</code>. Enforcing monotonicity on <code>Fin</code>-to-<code>Fin</code> mappings is possible, but it requires us to preserve the ordering of pitch classes <em>within a single octave.</em> That is to say, it means we can’t do any sort of permutation.</p>
<p>Thus, perhaps we should think about <code>Scale</code>s as mappings <code>Fin m -&gt; Deg n</code>. This is much closer to what we want (although it has some shortcomings that we will see shortly.) But let’s move forward with this attempt in order to motivate some of the later decisions:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Scale</span><span class="ot"> ::</span> <span class="dt">Nat</span> <span class="ot">-&gt;</span> <span class="dt">Nat</span> <span class="ot">-&gt;</span> <span class="dt">Type</span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">Scale</span> m n <span class="ot">=</span> <span class="dt">Scale</span> (<span class="dt">Fin</span> m <span class="ot">-&gt;</span> <span class="dt">Deg</span> n)</span></code></pre></div>
<p>We can introduce a new scale by way of <code>mkScale</code>:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="ot">mkScale ::</span> (<span class="dt">KnownNat</span> m, <span class="dv">1</span> <span class="op">&lt;=</span> m) <span class="ot">=&gt;</span> (<span class="dt">Fin</span> m <span class="ot">-&gt;</span> <span class="dt">Deg</span> n) <span class="ot">-&gt;</span> <span class="dt">Scale</span> m n</span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a>mkScale f <span class="ot">=</span></span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> image <span class="ot">=</span> <span class="fu">sort</span> <span class="op">$</span> <span class="kw">do</span></span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a>        m <span class="ot">&lt;-</span> [<span class="dv">0</span> <span class="op">..</span> <span class="fu">maxBound</span> <span class="op">@</span>(<span class="dt">Fin</span> m)]</span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a>        <span class="fu">pure</span> <span class="op">$</span> f m</span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a>   <span class="kw">in</span> <span class="dt">Scale</span> <span class="op">$</span> \m <span class="ot">-&gt;</span> image <span class="op">!!</span> <span class="fu">fromEnum</span> m</span></code></pre></div>
<p>which enumerates all values in <code>f</code>, sorts them (in order to ensure monotonicity), and then builds a <code>Scale</code> that uses the <code>Fin m</code> to select from the sorted values.</p>
<p>We can apply a scale to a <code>Deg</code> by way of <code>applyScale</code>:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a>applyScale</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a><span class="ot">    ::</span> <span class="kw">forall</span> m n</span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a>     <span class="op">.</span> <span class="dt">Scale</span> m n</span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> <span class="dt">Deg</span> m</span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> <span class="dt">Deg</span> n</span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true" tabindex="-1"></a>applyScale (<span class="dt">Scale</span> f) (<span class="dt">Deg</span> dm) <span class="ot">=</span></span>
<span id="cb6-7"><a href="#cb6-7" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> (oct, pc) <span class="ot">=</span> <span class="fu">divMod</span> dm <span class="op">$</span> scaleSize <span class="op">@</span>m</span>
<span id="cb6-8"><a href="#cb6-8" aria-hidden="true" tabindex="-1"></a>      <span class="dt">Deg</span> dn <span class="ot">=</span> f <span class="op">$</span> <span class="fu">toEnum</span> pc</span>
<span id="cb6-9"><a href="#cb6-9" aria-hidden="true" tabindex="-1"></a>   <span class="kw">in</span> <span class="dt">Deg</span> (dn <span class="op">+</span> oct <span class="op">*</span> scaleSize <span class="op">@</span>n)</span></code></pre></div>
<p>which ensures we preserve the necessary semantics of <code>degToPC</code> given earlier.</p>
<p>All is so far well and good. But not for long.</p>
<p>In some cases we might want to reverse a <code>Scale</code>’s mapping, eg going from <code>Deg 7</code> to <code>Deg 3</code>. This makes a lot of sense musically. For example, we might want to include a <a href="https://en.wikipedia.org/wiki/Nonchord_tone#Neighbor_tone">neighbor note</a>, or a <a href="https://en.wikipedia.org/wiki/Nonchord_tone#Passing_tone">passing tone</a> when writing out otherwise-triadic music. More directly, projecting down to a smaller abstract pitch class is the exact mechanism of <a href="https://en.wikipedia.org/wiki/Tintinnabuli">tintinnabuli</a>.</p>
<p>Unfortunately however, reversing a mapping <code>Fin m -&gt; Deg n</code> is obvious hogwash from the perspective of our functional programming ivory tower. In the usual case that <code>m &lt;= n</code>, this is a very non-injective function, so we have no chance of turning it around.</p>
<p>And yet, it’s musically meaningful. So, regardless of whether we <em>can</em> do it in Haskell, we somehow <strong>must.</strong> Otherwise whatever it is we’ve built is modeling the wrong thing.</p>
<p>Our mental pattern matchers that say “you can’t reverse a non-bijective function” are absolutely correct. But it’s worth taking a moment to think about <em>why exactly</em> we can’t in this case. Consider the musically-common case of working in a <code>Scale 3 7 = Fin 3 -&gt; Deg 7</code>. Here, some of the <code>Deg 7</code>s are targeted by the <code>Fin 3</code>. In particular, <code>0, 2, 4 :: Deg 7</code> get targeted by the <code>triad</code> scale introduced in a previous post.</p>
<p>So reversing <code>0, 2, 4 :: Fin 7</code> is easy enough — we just send them to <code>0, 1, 2 :: Deg 3</code>. The hard part is deciding where ought we send <code>1, 3, 5, 6 :: Fin 7</code>. Well, why don’t we just send them to <em>themselves</em>?</p>
<p>Sounds a little crazy, I know, but check this out. If we could attach <em>other scalar degree offsets</em> to each note, we could invert a scale by mapping the image directly to the domain whenever possible. And when it’s not possible, we could represent it as an offset from the nearest thing in the domain.</p>
<p>A little example might help. Say we have <code>0..7 :: Fin 7</code> and we’d like to reverse them across a <code>Scale 3 7</code>. If we represent exact points in <code>Deg 3</code> as white note heads, and “offsets” as black note heads, one possible reverse mapping looks like this:</p>
<figure>
<img src="/images/music7/out1.cropped.png" alt="Offsets Above" /><figcaption aria-hidden="true">Offsets Above</figcaption>
</figure>
<!-- \header { tagline = "" } -->
<!-- \absolute -->
<!--   \new Staff = "up" -->
<!--   << -->
<!--     \accidentalStyle piano-cautionary -->
<!--     \new Voice -->
<!--     { \omit Staff.TimeSignature -->
<!--       \cadenzaOn -->
<!--       \fixed c { <c'>2 -->
<!--                  <c' \tweak duration-log #2 d'> -->
<!--                  <e'> -->
<!--                  <e' \tweak duration-log #2 f'> -->
<!--                  <g'> -->
<!--                  <g' \tweak duration-log #2 a'> -->
<!--                  <g' \tweak duration-log #2 b'> -->
<!--                  <c''> -->
<!--                  } } -->
<!--   >> -->
<!-- \paper { -->
<!-- ragged-last = ##t -->
<!-- } -->
<p>If we assume we have some operation <code>(/+) :: Fin 3 -&gt; Deg 7 -&gt; Note 3</code>, this diagram corresponds to:</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a>[<span class="dv">0</span>, <span class="dv">0</span> <span class="op">/+</span> <span class="dv">1</span>, <span class="dv">1</span>, <span class="dv">1</span> <span class="op">/+</span> <span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">2</span> <span class="op">/+</span> <span class="dv">1</span>, <span class="dv">2</span> <span class="op">/+</span> <span class="dv">2</span>, <span class="dv">3</span>]</span></code></pre></div>
<p>Of course, such a mapping is not unique. For example, we can also do a “round up, offset down” approach:</p>
<figure>
<img src="/images/music7/out2.cropped.png" alt="Offsets Below" /><figcaption aria-hidden="true">Offsets Below</figcaption>
</figure>
<p>which is similarly:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a>[<span class="dv">0</span>, <span class="dv">1</span> <span class="op">/-</span> <span class="dv">1</span>, <span class="dv">1</span>, <span class="dv">2</span> <span class="op">/-</span> <span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span> <span class="op">/-</span> <span class="dv">2</span>, <span class="dv">3</span> <span class="op">/-</span> <span class="dv">1</span>, <span class="dv">3</span>]</span></code></pre></div>
<p>All of this is to say that <code>Deg</code>s aren’t quite what we’re looking for!</p>
<h2 id="enter-notes">Enter Notes</h2>
<p>As we’ve seen, <code>Deg</code>s aren’t quite powerful enough to represent these offsets. So we’ll first need to make a type to hold the offsets. The closest standard-musical terminology here is “ornamentation,” so that’s what we’ll go with.</p>
<p>An <code>Ornaments</code> is a mapping from scalar sizes to offsets. Rather than keeping the scalar sizes around in the type system (as we have done for <code>Fin</code> and <code>Deg</code> and <code>Scale</code>), here we’re going to simplify things down to an <code>IntMap</code>:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">Ornaments</span> a <span class="ot">=</span> <span class="dt">Ornaments</span></span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> getOrnaments ::</span> <span class="dt">IntMap</span> a</span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a>  }</span>
<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> stock (<span class="dt">Generic</span>, <span class="dt">Functor</span>)</span>
<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> <span class="kw">newtype</span> (<span class="dt">Show</span>)</span>
<span id="cb9-6"><a href="#cb9-6" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> (<span class="dt">Semigroup</span>, <span class="dt">Monoid</span>) via <span class="dt">MonoidalIntMap</span> (<span class="dt">Sum</span> a)</span></code></pre></div>
<p>Two <code>Ornaments</code> are equal when they have the same non-zero elements:</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="ot">normalizeOrnaments ::</span> (<span class="dt">Num</span> a, <span class="dt">Eq</span> a) <span class="ot">=&gt;</span> <span class="dt">Ornaments</span> a <span class="ot">-&gt;</span> <span class="dt">Ornaments</span> a</span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a>normalizeOrnaments <span class="ot">=</span> <span class="dt">Ornaments</span> <span class="op">.</span> IM.filter (<span class="op">/=</span> <span class="dv">0</span>) <span class="op">.</span> getOrnaments</span>
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> (<span class="dt">Eq</span> a, <span class="dt">Num</span> a) <span class="ot">=&gt;</span> <span class="dt">Eq</span> (<span class="dt">Ornaments</span> a) <span class="kw">where</span></span>
<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a>  (<span class="op">==</span>) <span class="ot">=</span> on (<span class="op">==</span>) (getOrnaments <span class="op">.</span> normalizeOrnaments)</span>
<span id="cb10-6"><a href="#cb10-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-7"><a href="#cb10-7" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> (<span class="dt">Ord</span> a, <span class="dt">Num</span> a) <span class="ot">=&gt;</span> <span class="dt">Ord</span> (<span class="dt">Ornaments</span> a) <span class="kw">where</span></span>
<span id="cb10-8"><a href="#cb10-8" aria-hidden="true" tabindex="-1"></a>  <span class="fu">compare</span> <span class="ot">=</span> on <span class="fu">compare</span> (getOrnaments <span class="op">.</span> normalizeOrnaments)</span></code></pre></div>
<p>We can also introduce <code>Ornaments</code>:</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="ot">ornament ::</span> <span class="kw">forall</span> n a<span class="op">.</span> <span class="dt">KnownNat</span> n <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Ornaments</span> a</span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a>ornament <span class="ot">=</span> <span class="dt">Ornaments</span> <span class="op">.</span> IM.singleton (scaleSize <span class="op">@</span>n)</span></code></pre></div>
<p>and eliminate them:</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a>decompOrnament</span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a><span class="ot">    ::</span> <span class="kw">forall</span> n</span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a>     <span class="op">.</span> <span class="dt">KnownNat</span> n</span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=&gt;</span> <span class="dt">Ornaments</span> <span class="dt">Int</span></span>
<span id="cb12-5"><a href="#cb12-5" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> (<span class="dt">Ornaments</span> <span class="dt">Int</span>, <span class="dt">Deg</span> n)</span>
<span id="cb12-6"><a href="#cb12-6" aria-hidden="true" tabindex="-1"></a>decompOrnament o</span>
<span id="cb12-7"><a href="#cb12-7" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=</span> <span class="fu">maybe</span></span>
<span id="cb12-8"><a href="#cb12-8" aria-hidden="true" tabindex="-1"></a>      (o, <span class="dv">0</span>)</span>
<span id="cb12-9"><a href="#cb12-9" aria-hidden="true" tabindex="-1"></a>      ( (coerce (IM.filterWithKey <span class="op">@</span><span class="dt">Int</span> (\k _ <span class="ot">-&gt;</span> k <span class="op">/=</span> scaleSize <span class="op">@</span>n)) o, )</span>
<span id="cb12-10"><a href="#cb12-10" aria-hidden="true" tabindex="-1"></a>      <span class="op">.</span> <span class="dt">Deg</span></span>
<span id="cb12-11"><a href="#cb12-11" aria-hidden="true" tabindex="-1"></a>      )</span>
<span id="cb12-12"><a href="#cb12-12" aria-hidden="true" tabindex="-1"></a>  <span class="op">$</span> IM.lookup (scaleSize <span class="op">@</span>n)</span>
<span id="cb12-13"><a href="#cb12-13" aria-hidden="true" tabindex="-1"></a>  <span class="op">$</span> getOrnaments o</span>
<span id="cb12-14"><a href="#cb12-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-15"><a href="#cb12-15" aria-hidden="true" tabindex="-1"></a><span class="ot">getOrnament ::</span> <span class="kw">forall</span> n<span class="op">.</span> <span class="dt">KnownNat</span> n <span class="ot">=&gt;</span> <span class="dt">Ornaments</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Deg</span> n</span>
<span id="cb12-16"><a href="#cb12-16" aria-hidden="true" tabindex="-1"></a>getOrnament <span class="ot">=</span> <span class="fu">snd</span> <span class="op">.</span> decompOrnament</span></code></pre></div>
<p>Here <code>decompOrnament @n</code> returns the <code>Deg n</code> ornament, and returns a new <code>Ornaments</code> with that scale degree removed. If you don’t care about the removal, you’re welcome to call <code>getOrnament</code> directly.</p>
<p>Armed with <code>Ornaments</code>, we can now make <code>Note</code>, which wraps a degree with ornaments:</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Note</span><span class="ot"> ::</span> <span class="dt">Nat</span> <span class="ot">-&gt;</span> <span class="dt">Type</span></span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Note</span> n <span class="ot">=</span> <span class="dt">Note</span> (<span class="dt">Deg</span> n) (<span class="dt">Ornaments</span> <span class="dt">Int</span>)</span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> stock (<span class="dt">Generic</span>, <span class="dt">Eq</span>, <span class="dt">Ord</span>)</span></code></pre></div>
<p><code>Note</code>s admit a <code>Num</code> instance, which combines ornaments pointwise:</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Num</span> (<span class="dt">Note</span> n) <span class="kw">where</span></span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">fromInteger</span> n <span class="ot">=</span> <span class="dt">Note</span> (<span class="fu">fromInteger</span> n) <span class="fu">mempty</span></span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Note</span> a as <span class="op">+</span> <span class="dt">Note</span> b bs <span class="ot">=</span> <span class="dt">Note</span> (a <span class="op">+</span> b) <span class="op">$</span> as <span class="op">&lt;&gt;</span> bs</span>
<span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Note</span> a as <span class="op">-</span> <span class="dt">Note</span> b bs <span class="ot">=</span> <span class="dt">Note</span> (a <span class="op">-</span> b) <span class="op">$</span> as <span class="op">&lt;&gt;</span> <span class="fu">fmap</span> <span class="fu">negate</span> bs</span>
<span id="cb14-5"><a href="#cb14-5" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Note</span> a (<span class="dt">Ornaments</span> as) <span class="op">*</span> <span class="dt">Note</span> b (<span class="dt">Ornaments</span> bs) <span class="ot">=</span></span>
<span id="cb14-6"><a href="#cb14-6" aria-hidden="true" tabindex="-1"></a>    <span class="dt">Note</span> (a <span class="op">*</span> b) <span class="op">$</span> <span class="dt">Ornaments</span> <span class="op">$</span> IM.intersectionWith (<span class="op">*</span>) as bs</span>
<span id="cb14-7"><a href="#cb14-7" aria-hidden="true" tabindex="-1"></a>  <span class="fu">abs</span>    (<span class="dt">Note</span> a as) <span class="ot">=</span> <span class="dt">Note</span> (<span class="fu">abs</span> a)    <span class="op">$</span> <span class="fu">fmap</span> <span class="fu">abs</span>    as</span>
<span id="cb14-8"><a href="#cb14-8" aria-hidden="true" tabindex="-1"></a>  <span class="fu">signum</span> (<span class="dt">Note</span> a as) <span class="ot">=</span> <span class="dt">Note</span> (<span class="fu">signum</span> a) <span class="op">$</span> <span class="fu">fmap</span> <span class="fu">signum</span> as</span></code></pre></div>
<p>and we can add an ornamental offset to a <code>Note</code> by way of <code>stepIn @c</code>:</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="ot">stepIn ::</span> <span class="kw">forall</span> c n<span class="op">.</span> (<span class="dt">KnownNat</span> c, <span class="dt">KnownNat</span> n) <span class="ot">=&gt;</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Note</span> n <span class="ot">-&gt;</span> <span class="dt">Note</span> n</span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a>stepIn k (<span class="dt">Note</span> a as) <span class="ot">=</span></span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a>  <span class="kw">case</span> scaleSize <span class="op">@</span>c <span class="op">==</span> scaleSize <span class="op">@</span>n <span class="kw">of</span></span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a>    <span class="dt">True</span> <span class="ot">-&gt;</span> <span class="dt">Note</span> (a <span class="op">+</span> <span class="dt">Deg</span> k) as</span>
<span id="cb15-5"><a href="#cb15-5" aria-hidden="true" tabindex="-1"></a>    <span class="dt">False</span> <span class="ot">-&gt;</span> <span class="dt">Note</span> a <span class="op">$</span> as <span class="op">&lt;&gt;</span> ornament <span class="op">@</span>c k</span></code></pre></div>
<p>An invariant enforced by <code>stepIn</code> is that you never have an ornament of size <code>n</code> attached to a note also of size <code>n</code>. If you attempt to, we just change the <code>Deg n</code> instead.</p>
<h2 id="scales-revisited">Scales Revisited</h2>
<p>Now that we have <code>Note</code>s, we can define <code>Scale</code>s in terms of them, and we are rewarded with a convenient place to stick offsets when we invert scales. <code>Scale</code> and <code>mkScale</code> change only in that we reference <code>Note</code> instead of <code>Deg</code>:</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Scale</span><span class="ot"> ::</span> <span class="dt">Nat</span> <span class="ot">-&gt;</span> <span class="dt">Nat</span> <span class="ot">-&gt;</span> <span class="dt">Type</span></span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">Scale</span> m n <span class="ot">=</span> <span class="dt">Scale</span> (<span class="dt">Fin</span> m <span class="ot">-&gt;</span> <span class="dt">Note</span> n)</span></code></pre></div>
<div class="sourceCode" id="cb17"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a><span class="ot">mkScale ::</span> (<span class="dt">KnownNat</span> m, <span class="dv">1</span> <span class="op">&lt;=</span> m) <span class="ot">=&gt;</span> (<span class="dt">Fin</span> m <span class="ot">-&gt;</span> <span class="dt">Note</span> n) <span class="ot">-&gt;</span> <span class="dt">Scale</span> m n</span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a>mkScale f <span class="ot">=</span></span>
<span id="cb17-3"><a href="#cb17-3" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> image <span class="ot">=</span> <span class="fu">sort</span> <span class="op">$</span> <span class="kw">do</span></span>
<span id="cb17-4"><a href="#cb17-4" aria-hidden="true" tabindex="-1"></a>        m <span class="ot">&lt;-</span> [<span class="dv">0</span> <span class="op">..</span> <span class="fu">maxBound</span> <span class="op">@</span>(<span class="dt">Fin</span> m)]</span>
<span id="cb17-5"><a href="#cb17-5" aria-hidden="true" tabindex="-1"></a>        <span class="fu">pure</span> <span class="op">$</span> f m</span>
<span id="cb17-6"><a href="#cb17-6" aria-hidden="true" tabindex="-1"></a>   <span class="kw">in</span> <span class="dt">Scale</span> <span class="op">$</span> \m <span class="ot">-&gt;</span> image <span class="op">!!</span> <span class="fu">fromEnum</span> m</span></code></pre></div>
<p>However, <code>applyScale</code> needs to do slightly more work: it must respect incoming and outgoing ornamentation. The <code>Note m</code> might have a <code>n</code>-sized ornament, in which case we must add it immediately. And then we must combine the remaining ornaments with any which might arise from the <code>Scale</code>’s mapping:</p>
<div class="sourceCode" id="cb18"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a>applyScale</span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a><span class="ot">    ::</span> <span class="kw">forall</span> m n</span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a>     <span class="op">.</span> <span class="dt">Scale</span> m n</span>
<span id="cb18-4"><a href="#cb18-4" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> <span class="dt">Note</span> m</span>
<span id="cb18-5"><a href="#cb18-5" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> <span class="dt">Note</span> n</span>
<span id="cb18-6"><a href="#cb18-6" aria-hidden="true" tabindex="-1"></a>applyScale (<span class="dt">Scale</span> f) (<span class="dt">Note</span> (<span class="dt">Deg</span> dm) os) <span class="ot">=</span></span>
<span id="cb18-7"><a href="#cb18-7" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> (oct, pc) <span class="ot">=</span> <span class="fu">divMod</span> dm <span class="op">$</span> scaleSize <span class="op">@</span>m</span>
<span id="cb18-8"><a href="#cb18-8" aria-hidden="true" tabindex="-1"></a>      (<span class="dt">Note</span> (<span class="dt">Deg</span> dn) os&#39;) <span class="ot">=</span> f <span class="op">$</span> <span class="fu">toEnum</span> pc</span>
<span id="cb18-9"><a href="#cb18-9" aria-hidden="true" tabindex="-1"></a>      (os&#39;&#39;, od) <span class="ot">=</span> decompOrnament <span class="op">@</span>n os</span>
<span id="cb18-10"><a href="#cb18-10" aria-hidden="true" tabindex="-1"></a>   <span class="kw">in</span> <span class="dt">Note</span> (od <span class="op">+</span> <span class="dt">Deg</span> (dn <span class="op">+</span> oct <span class="op">*</span> scaleSize <span class="op">@</span>n)) <span class="op">$</span> os&#39; <span class="op">&lt;&gt;</span> os&#39;&#39;</span></code></pre></div>
<p>With all of this work, we’re now ready to tackle inverting scales. The thrust of the idea here is a relatively simple algorithm:</p>
<ol type="1">
<li>Compute the image of the scale. Take the resulting pitch class, and associate it with the corresponding input pitch class. Negate the octave and ornaments when doing this.</li>
<li>Check if the inverse pitch class exist directly in your image map. If so, return it directly.</li>
<li>If not, select the best candidate of the image with respect to the inverse pitch class. Compute how far the best candidate is away from the input, and add that distance as an extra ornament.</li>
</ol>
<p>Of course, the devil is in the details. Getting the “best candidate” might require looking in a different octave. We wrap the candidate logic into a chooser:</p>
<div class="sourceCode" id="cb19"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a>(<span class="kw">forall</span> x<span class="op">.</span> <span class="dt">Ord</span> x <span class="ot">=&gt;</span> <span class="dt">Fin</span> b <span class="ot">-&gt;</span> [(<span class="dt">Fin</span> b, x)] <span class="ot">-&gt;</span> (<span class="dt">Int</span>, x))</span></code></pre></div>
<p>which receives the desired pitch class, the image, and must return one element of the image along with an octave displacement. Since the entire thing is stuck in a <code>forall x</code>, the chooser is allowed only to look at the <code>Fin b</code>s to determine what is the best candidate. As a little illustration here, we might want to round up to the nearest pitch class in the image. So we’d want to filter the image by anything <code>&gt;= pc</code>. But if <code>pc</code> is already the largest thing in the image, we’d instead want to return the smallest thing in the image with a +1 octave offset.</p>
<p>If you’re curious, the logic in its full glory is thus:</p>
<div class="sourceCode" id="cb20"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a>invertScale</span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a><span class="ot">    ::</span> <span class="kw">forall</span> a b</span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a>     <span class="op">.</span> (<span class="dv">1</span> <span class="op">&lt;=</span> a)</span>
<span id="cb20-4"><a href="#cb20-4" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=&gt;</span> (<span class="kw">forall</span> x<span class="op">.</span> <span class="dt">Ord</span> x <span class="ot">=&gt;</span> <span class="dt">Fin</span> b <span class="ot">-&gt;</span> [(<span class="dt">Fin</span> b, x)] <span class="ot">-&gt;</span> (<span class="dt">Int</span>, x))</span>
<span id="cb20-5"><a href="#cb20-5" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> <span class="dt">Scale</span> a b</span>
<span id="cb20-6"><a href="#cb20-6" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> <span class="dt">Scale</span> b a</span>
<span id="cb20-7"><a href="#cb20-7" aria-hidden="true" tabindex="-1"></a>invertScale choose (<span class="dt">Scale</span> f) <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb20-8"><a href="#cb20-8" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span><span class="ot"> img ::</span> [(<span class="dt">Fin</span> b, <span class="dt">Note</span> a)]</span>
<span id="cb20-9"><a href="#cb20-9" aria-hidden="true" tabindex="-1"></a>      img <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb20-10"><a href="#cb20-10" aria-hidden="true" tabindex="-1"></a>        a <span class="ot">&lt;-</span> [<span class="dv">0</span> <span class="op">..</span> <span class="fu">maxBound</span> <span class="op">@</span>(<span class="dt">Fin</span> a)]</span>
<span id="cb20-11"><a href="#cb20-11" aria-hidden="true" tabindex="-1"></a>        <span class="kw">let</span> (<span class="dt">Note</span> (<span class="dt">Deg</span> db) os) <span class="ot">=</span> f a</span>
<span id="cb20-12"><a href="#cb20-12" aria-hidden="true" tabindex="-1"></a>        <span class="kw">let</span> (o, pc) <span class="ot">=</span> <span class="fu">divMod</span> db <span class="op">$</span> scaleSize <span class="op">@</span>b</span>
<span id="cb20-13"><a href="#cb20-13" aria-hidden="true" tabindex="-1"></a>        <span class="kw">let</span> b <span class="ot">=</span> <span class="fu">toEnum</span> <span class="op">@</span>(<span class="dt">Fin</span> b) pc</span>
<span id="cb20-14"><a href="#cb20-14" aria-hidden="true" tabindex="-1"></a>        <span class="fu">pure</span> ( b</span>
<span id="cb20-15"><a href="#cb20-15" aria-hidden="true" tabindex="-1"></a>             , <span class="dt">Note</span> (<span class="fu">fromIntegral</span> a <span class="op">-</span> <span class="dt">Deg</span> (scaleSize <span class="op">@</span>a <span class="op">*</span> o))</span>
<span id="cb20-16"><a href="#cb20-16" aria-hidden="true" tabindex="-1"></a>                 <span class="op">$</span> <span class="fu">fmap</span> <span class="fu">negate</span> os</span>
<span id="cb20-17"><a href="#cb20-17" aria-hidden="true" tabindex="-1"></a>             )</span>
<span id="cb20-18"><a href="#cb20-18" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Scale</span> <span class="op">$</span> \b <span class="ot">-&gt;</span></span>
<span id="cb20-19"><a href="#cb20-19" aria-hidden="true" tabindex="-1"></a>    <span class="kw">case</span> <span class="fu">lookup</span> b img <span class="kw">of</span></span>
<span id="cb20-20"><a href="#cb20-20" aria-hidden="true" tabindex="-1"></a>      <span class="dt">Just</span> a <span class="ot">-&gt;</span> a</span>
<span id="cb20-21"><a href="#cb20-21" aria-hidden="true" tabindex="-1"></a>      <span class="dt">Nothing</span> <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb20-22"><a href="#cb20-22" aria-hidden="true" tabindex="-1"></a>        <span class="kw">let</span> (ox, chosen) <span class="ot">=</span> choose b img</span>
<span id="cb20-23"><a href="#cb20-23" aria-hidden="true" tabindex="-1"></a>            (b&#39;, <span class="dt">Note</span> da os) <span class="ot">=</span></span>
<span id="cb20-24"><a href="#cb20-24" aria-hidden="true" tabindex="-1"></a>              <span class="kw">case</span> find ((<span class="op">==</span> chosen) <span class="op">.</span> <span class="fu">snd</span>) img <span class="kw">of</span></span>
<span id="cb20-25"><a href="#cb20-25" aria-hidden="true" tabindex="-1"></a>                <span class="dt">Just</span> c <span class="ot">-&gt;</span> c</span>
<span id="cb20-26"><a href="#cb20-26" aria-hidden="true" tabindex="-1"></a>                <span class="dt">Nothing</span> <span class="ot">-&gt;</span> <span class="fu">error</span> <span class="st">&quot;impossible&quot;</span></span>
<span id="cb20-27"><a href="#cb20-27" aria-hidden="true" tabindex="-1"></a>            diff <span class="ot">=</span> <span class="fu">fromIntegral</span> b <span class="op">-</span> (<span class="fu">fromIntegral</span> b&#39; <span class="op">+</span> ox <span class="op">*</span> scaleSize <span class="op">@</span>b)</span>
<span id="cb20-28"><a href="#cb20-28" aria-hidden="true" tabindex="-1"></a>        <span class="dt">Note</span> (da <span class="op">+</span> <span class="dt">Deg</span> (ox <span class="op">*</span> scaleSize <span class="op">@</span>a)) <span class="op">$</span> os <span class="op">&lt;&gt;</span> ornament <span class="op">@</span>b diff</span></code></pre></div>
<p>which we specialize with a few different choices of chooser:</p>
<div class="sourceCode" id="cb21"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="ot">invertScaleAbove   ::</span> (<span class="dv">1</span> <span class="op">&lt;=</span> a) <span class="ot">=&gt;</span> <span class="dt">Scale</span> a b <span class="ot">-&gt;</span> <span class="dt">Scale</span> b a</span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a><span class="ot">invertScaleBelow   ::</span> (<span class="dv">1</span> <span class="op">&lt;=</span> a) <span class="ot">=&gt;</span> <span class="dt">Scale</span> a b <span class="ot">-&gt;</span> <span class="dt">Scale</span> b a</span>
<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a><span class="ot">invertScaleNearest ::</span> (<span class="dv">1</span> <span class="op">&lt;=</span> a) <span class="ot">=&gt;</span> <span class="dt">Scale</span> a b <span class="ot">-&gt;</span> <span class="dt">Scale</span> b a</span></code></pre></div>
<p>As a little aside, I haven’t found a great way of naming the first two functions. Here “above” means “round down and offset up”, and below is the opposite. Any suggestions for more obvious names here would be greatly appreciated.</p>
<p>That’s all for today. In the next post we’ll investigate the types behind voice leadings, with a similar attention to precision.</p>
        ]]>
      </content>
    </entry>
    <entry>
      <title>Voice Leadings on Abstract Musical Pitches</title>
      <id>blog/voice-leadings/index.html</id>
      <link href='blog/voice-leadings/index.html'/>
      <published>2026-11-10T06:18:00Z</published>
      <updated>2026-11-10T06:18:00Z</updated>

      <content type="html" xml:base="https://reasonablypolymorphic.com">
        <![CDATA[
        <p>In the last post, we discussed the notion of <a href="/blog/pitches-1">abstract musical pitches</a>. I was writing that under a haze of covid-inspired single-parenting, so we’re going to take a few more minutes to try to clarify some of the claims made in that one, before moving on to doing more interesting things with the concept.</p>
<p>In Haskell we have this function <code>quotRem :: Integral a =&gt; a -&gt; a -&gt; (a, a)</code>, which computes the quotient and remainder of one number divided by another. For example, <code>quotRem 25 5 == (5, 0)</code>, <code>quotRem 25 6 == (4, 1)</code>, <code>quotRem 25 7 == (3, 4)</code>. You get the picture.</p>
<p>Our <code>Deg n</code> type from yesterday operates over <code>quotRem _ n</code>. That is, any degree we might have, say <code>k :: Deg n</code>, we compute its <code>quotRem k n</code> to get <code>(octave, pitchClass)</code>. This motivates why we were using functions <code>Fin n -&gt; Fin m</code> to model “scales” mapping from <code>Deg n</code> into <code>Deg m</code> — we want to map <em>only</em> the <code>pitchClass</code> part of the <code>quotRem</code>.</p>
<p>To be more precise, if we want to map a <code>Deg n</code> into <code>Deg m</code>, we run this function:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="ot">scale ::</span> (<span class="dt">Fin</span> n <span class="ot">-&gt;</span> <span class="dt">Fin</span> m) <span class="ot">-&gt;</span> <span class="dt">Deg</span> n <span class="ot">-&gt;</span> <span class="dt">Deg</span> m</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>scale f (<span class="dt">Deg</span> dn) <span class="ot">=</span></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> (oct, pc) <span class="ot">=</span> <span class="fu">quotRem</span> dn n</span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a>   <span class="kw">in</span> <span class="dt">Deg</span> <span class="op">$</span> <span class="fu">fromEnum</span> (f (<span class="fu">toEnum</span> pc)) <span class="op">+</span> oct <span class="op">*</span> m</span></code></pre></div>
<p>This mapping only of pitch classes ensures we maintain the quotienting structure of <code>Deg n</code> that requires <code>k + n</code> to be the same pitch class as <code>k</code>.</p>
<p>Musically, none of this should be unfamiliar. In a diatonic scale, you have 7 distinct notes — let’s label them “do, re, mi, fa, sol, la, ti.” These correspond to <code>0, 1, 2, 3, 4, 5, 6 :: Deg 7</code>. If you start at any of these notes and go up (or down) 7 times, you will get back to the same pitch class an octave higher (or lower.)</p>
<p>The same argument works for the chromatic scale, where we have 12 notes, labeled “A, A#, B, C, C#, D, D#, E, F, F#, G, G#”. Express these as <code>0, 1, ..., 11 :: Deg 12</code>, and then go up or down 12 spots and you end up back where you were, modulo an octave.</p>
<p>Similarly, if we want to map from the diatonic scale (<code>Deg 7</code>) to the chromatic scale (<code>Deg 12</code>), we choose 7 pitch classes from the 12 available, and respect the octave equivalence (this mapping is given implicitly by a <em>key signature</em> and, in notated music, a <em>clef.</em>)</p>
<p>If none of these music words make any sense to you, don’t worry. It doesn’t matter.</p>
<h2 id="intrinsic-scales">Intrinsic Scales</h2>
<p>Check this out: nothing says we need to have a statically-known-at-compile-time <code>n</code> for our <code>Deg n</code>. As an illustration, here’s the beginning of the Star Wars theme:</p>
<figure>
<img src="/images/music6/out1.cropped.svg" alt="Star Wars Theme" /><figcaption aria-hidden="true">Star Wars Theme</figcaption>
</figure>
<p>Out of the 7 diatonic pitch classes, this segment of the theme uses only five: <strong>do</strong>, <strong>re</strong>, mi, fa, <strong>sol</strong>, <strong>la</strong>, <strong>ti</strong>. So we can project the Star Wars theme down to a 5-note clef:</p>
<figure>
<img src="/images/music6/out2.cropped.svg" alt="Intrinsic Star Wars Theme" /><figcaption aria-hidden="true">Intrinsic Star Wars Theme</figcaption>
</figure>
<!--
threeClef = {
  \override Staff.Clef.stencil = #ly:text-interface::print

  \override Staff.Clef.text = \markup {
    \vcenter \fontsize #6 \bold "5"
  }

  \set Staff.clefPosition = 0

  \set Staff.middleCPosition = 0
}
-->
<p>and give a mapping:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="ot">starWarsScale ::</span> <span class="dt">Deg</span> <span class="dv">5</span> <span class="ot">-&gt;</span> <span class="dt">Deg</span> <span class="dv">7</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>starWarsScale <span class="dv">0</span> <span class="ot">=</span> <span class="dv">0</span></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>starWarsScale <span class="dv">1</span> <span class="ot">=</span> <span class="dv">1</span></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>starWarsScale <span class="dv">2</span> <span class="ot">=</span> <span class="dv">4</span></span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a>starWarsScale <span class="dv">3</span> <span class="ot">=</span> <span class="dv">5</span></span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a>starWarsScale <span class="dv">4</span> <span class="ot">=</span> <span class="dv">6</span></span></code></pre></div>
<p>which, of course, when we apply that mapping back to the 5-note version, gives us back the song we started with. But before transforming it back, we can do funny things, like <code>fmap (+ 1)</code> in the 5-note scale:</p>
<figure>
<img src="/images/music6/out3.cropped.svg" alt="(+1) Intrinsic Star Wars Theme" /><figcaption aria-hidden="true">(+1) Intrinsic Star Wars Theme</figcaption>
</figure>
<p>Mapping this back to <code>Deg 7</code> (and then all the way to concrete pitches) gives us this neat little take on Star Wars:</p>
<figure>
<img src="/images/music6/out4.cropped.svg" alt="“Developed” Star Wars Theme" /><figcaption aria-hidden="true">“Developed” Star Wars Theme</figcaption>
</figure>
<audio controls>
<source src="/images/music6/starwars2.mp3" type="audio/mpeg">
</audio>
<p>Not as good as John Williams’ to be sure, but it’s interesting that we can do this transformation!</p>
<p>All of this is to say that for <em>any</em> <code>Foldable</code> and <code>Functor</code> collection of notes, we can get its intrinsic scale via <code>intrinsic</code>:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a>intrinsic</span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  ::</span> (<span class="dt">Foldable</span> f, <span class="dt">Functor</span> f)</span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=&gt;</span> f (<span class="dt">Deg</span> n)</span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> (<span class="kw">forall</span> i<span class="op">.</span> (<span class="dt">Fin</span> i <span class="ot">-&gt;</span> <span class="dt">Fin</span> n) <span class="ot">-&gt;</span> f (<span class="dt">Deg</span> i) <span class="ot">-&gt;</span> r)</span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> r</span></code></pre></div>
<p>which is “you give me some collection of <code>Deg n</code>s, and I’ll give you back a collection of <code>Deg i</code>s, as well as a scale from <code>Fin i -&gt; Fin n</code>”. Where <code>i</code> is some unknown-at-compile-time number corresponding to however many unique pitch-classes were in your collection.</p>
<p>As we have seen with the Star Wars example, we can find the <code>intrinsic</code> scale for horizontal structures.<a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a> But of course, this is parameterized over any <code>Functor</code>/<code>Foldable</code> type constructor <code>f</code>. So we can find lots of intrinsic scales — think chords and vertical structures. But probably also more things if I were more imaginative!</p>
<h2 id="efficient-voice-leadings">Efficient Voice Leadings</h2>
<p>We are going to need a few “scales” to work with in this section. We’ll take two common mappings from Western tonal music, namely the 3-in-7 mapping (“triads”), and the 7-in-12 mapping (“the diatonic scale”.)</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ot">triad ::</span> <span class="dt">Fin</span> <span class="dv">3</span> <span class="ot">-&gt;</span> <span class="dt">Fin</span> <span class="dv">7</span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>triad <span class="dv">0</span> <span class="ot">=</span> <span class="dv">0</span></span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>triad <span class="dv">1</span> <span class="ot">=</span> <span class="dv">2</span></span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a>triad <span class="dv">2</span> <span class="ot">=</span> <span class="dv">4</span></span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a><span class="ot">diatonic ::</span> <span class="dt">Fin</span> <span class="dv">7</span> <span class="ot">-&gt;</span> <span class="dt">Fin</span> <span class="dv">12</span></span>
<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a>diatonic <span class="dv">0</span> <span class="ot">=</span> <span class="dv">0</span></span>
<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a>diatonic <span class="dv">1</span> <span class="ot">=</span> <span class="dv">2</span></span>
<span id="cb4-9"><a href="#cb4-9" aria-hidden="true" tabindex="-1"></a>diatonic <span class="dv">2</span> <span class="ot">=</span> <span class="dv">4</span></span>
<span id="cb4-10"><a href="#cb4-10" aria-hidden="true" tabindex="-1"></a>diatonic <span class="dv">3</span> <span class="ot">=</span> <span class="dv">5</span></span>
<span id="cb4-11"><a href="#cb4-11" aria-hidden="true" tabindex="-1"></a>diatonic <span class="dv">4</span> <span class="ot">=</span> <span class="dv">7</span></span>
<span id="cb4-12"><a href="#cb4-12" aria-hidden="true" tabindex="-1"></a>diatonic <span class="dv">5</span> <span class="ot">=</span> <span class="dv">9</span></span>
<span id="cb4-13"><a href="#cb4-13" aria-hidden="true" tabindex="-1"></a>diatonic <span class="dv">6</span> <span class="ot">=</span> <span class="dv">11</span></span></code></pre></div>
<p>If you are not classically-trained in music, don’t worry very much about this. You’d recognize these sounds if you heard them. For example, the triad mapping sounds like any of the examples from the Wikipedia page on <a href="https://en.wikipedia.org/wiki/Arpeggio">arpeggios</a>. The diatonic mapping sounds like <a href="https://youtu.be/vTJhpjIA0Fc?t=10">this</a>. We’re just arbitrarily choosing some ways of mapping between our abstract degrees (in a way that happens to line up with the arbitrariness of Western musical tradition.)</p>
<p>In <a href="https://dmitri.mycpanel.princeton.edu/tonality-an-owners-manual.html">Tonality</a> Tymoczko points out that these mappings happen to pretty evenly divide the octave. To illustrate what this means, look at <code>triad</code>: it maps <code>0..6 :: Deg 3</code> to <code>0, 2, 4, 7, 9, 11 :: Deg 7</code>, which if you take the difference between any two subsequent degrees in the image is <code>2, 2, 3, 2, 2</code>. That’s about as evenly as you <em>could</em> map these things! There’s a tiny little bump in the pattern going from 4 to 7.</p>
<p>The same thing happens in <code>diatonic</code>. We map <code>0..8 :: Deg 7</code> to <code>0, 2, 4, 5, 7, 9, 11, 12, 14 :: Deg 12</code>, which again, taking the difference between subsequent numbers is <code>2, 2, 1, 2, 2, 2, 1, 2</code>. Very evenly spaced!</p>
<p>Note that this doesn’t actually need to have been the case! This is a property of <code>triad</code> and <code>diatonic</code>, not of <code>Deg {3,7,12}</code>. And Tymoczko makes a pretty compelling argument that this property is <em>why</em> Western music has historically been organized around <code>triad</code> and <code>diatonic</code>.</p>
<p>So why is this important? It’s to do with the <em>slight non-regularity</em> in scale degrees. A big theme of <a href="https://dmitri.mycpanel.princeton.edu/tonality-an-owners-manual.html">Tonality</a> is that we can very-nearly offset movement in <code>Deg m</code> with an opposite movement in <code>Deg n</code>, and that this is musically interesting (and ubiquitous!)</p>
<p>For example, when working with <code>triad</code>, it happens that moving <em>up</em> by two steps in the intrinsic scale (<code>Deg 3</code>) is almost exactly cancelled out by moving <em>down</em> five steps in the containing scale (<code>Deg 7</code>):</p>
<figure>
<img src="/images/music6/out5.cropped.svg" alt="Up by 2, down by 5" /><figcaption aria-hidden="true">Up by 2, down by 5</figcaption>
</figure>
<p>The second chord (black note-heads) here is the first one moved up by <code>2 :: Deg 3</code>, while the third chord is the second one moved down by <code>5 :: Deg 7</code>. As you can see, we end up <em>almost exactly</em> where we started, except that the bottom pitch has moved one step down.</p>
<p>In fact, this phenomenon happens again and again if we continue performing these moves. As before, the movement in the intrinsic scale is shown with black note-heads, while the movement in the containing scale is shown with white ones.</p>
<figure>
<img src="/images/music6/out6.cropped.svg" alt="Again and again" /><figcaption aria-hidden="true">Again and again</figcaption>
</figure>
<p>Sure enough, this makes pretty pictures. And if you can read the musical notation, you’ll know that what we happen to be computing here are <em>efficient voice leadings</em> from a root note to the diatonic third above it.</p>
<p>In fact, if we remove the in-between black notes, we end up with this:</p>
<figure>
<img src="/images/music6/out7.cropped.svg" alt="Efficient Voice Leadings" /><figcaption aria-hidden="true">Efficient Voice Leadings</figcaption>
</figure>
<p>which sounds like this:</p>
<audio controls>
<source src="/images/music6/voiceleading.mp3" type="audio/mpeg">
</audio>
<p>This is likely the sort of thing which is pretty exciting if you’re a musician, and “who cares” if you’re not. It doesn’t really <em>sound</em> like music, but this is in a very real sense <em>a fundamental building block</em> of (Western) music. It’s a way of smoothly getting from one place to another in a musical space. Any time you <em>don’t</em> notice a jarring chord change, this is likely the mechanism by which the music is moving.</p>
<h2 id="modal-modulations">Modal Modulations</h2>
<p>We can do the same move with 7-in-12 modulations. If we look at the notes of the diatonic (C major) scale as a vertical chord:</p>
<figure>
<img src="/images/music6/out8.cropped.svg" alt="C Major" /><figcaption aria-hidden="true">C Major</figcaption>
</figure>
<!-- \header { tagline = "" } -->
<!-- \absolute -->
<!--   \new Staff = "up" -->
<!--   << -->
<!--     \accidentalStyle forget -->
<!--     \new Voice -->
<!--     { -->
<!--       \omit Staff.TimeSignature -->
<!--       \cadenzaOn -->
<!--       \fixed c { <c' d' e' f' g' a' b'>2 -->
<!--                  } } -->
<!--   >> -->
<!-- \paper { -->
<!-- ragged-last = ##t -->
<!-- } -->
<p>Now if we map it up by 4 scale degrees, and down by 7 chromatic degrees we end up here:</p>
<figure>
<img src="/images/music6/out9.cropped.svg" alt="C Mixolydian" /><figcaption aria-hidden="true">C Mixolydian</figcaption>
</figure>
<!-- \header { tagline = "" } -->
<!-- \absolute -->
<!--   \new Staff = "up" -->
<!--   << -->
<!--     \accidentalStyle forget -->
<!--     \new Voice -->
<!--     { -->
<!--       \omit Staff.TimeSignature -->
<!--       \cadenzaOn -->
<!--       \fixed c { <c' d' e' f' g' a' b'>2 -->
<!--                  <g' a' b' c'' d'' e'' f''>4 -->
<!--                  <c' d' e' f' g' a' bes'>2 -->
<!--                  } } -->
<!--   >> -->
<!-- \paper { -->
<!-- ragged-last = ##t -->
<!-- } -->
<p>which is either <a href="https://en.wikipedia.org/wiki/Mixolydian_mode">C mixolydian</a>, or a smooth voice-leading into F major, depending on how you look at it.</p>
<p>Making the same up 4 down 7 move again now moves us into <a href="https://en.wikipedia.org/wiki/Dorian_mode">C dorian</a>, or Bb major, again, depending on your perspective.</p>
<figure>
<img src="/images/music6/out10.cropped.svg" alt="C Dorian" /><figcaption aria-hidden="true">C Dorian</figcaption>
</figure>
<p>Of course, I didn’t just pick the +4-7 thing out of my brain. Tymoczko has a <a href="https://www.madmusicalscience.com/cs.html">great tool</a> for computing the moves involved here, and it works for any sized chord inside of any sized scale.</p>
<h2 id="wrapping-up">Wrapping Up</h2>
<p>A weird one today. Not much in the way of Haskell, and either <em>fascinating</em> or dead boring (depending on how much imagination you have) if you’re into the music theory. In the next post we’ll see about how to formalize all of this into first-class objects. And then we might be getting somewhat close to actually making some music. Maybe?</p>
<section class="footnotes" role="doc-endnotes">
<hr />
<ol>
<li id="fn1" role="doc-endnote"><p>With some finagling, granted. Those <code>Event</code>s end up being pretty annoying to have to work around! This is a pretty good indication that everyone emailing me saying “you don’t need to model discreteness” are probably right, but I don’t actually know how to make that happen.<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</section>
        ]]>
      </content>
    </entry>
    <entry>
      <title>Abstract Musical Pitches</title>
      <id>blog/pitches-1/index.html</id>
      <link href='blog/pitches-1/index.html'/>
      <published>2026-11-09T10:26:00Z</published>
      <updated>2026-11-09T10:26:00Z</updated>

      <content type="html" xml:base="https://reasonablypolymorphic.com">
        <![CDATA[
        <p>This is my seventh blog post in a series about “solving music”, in terms of giving it a precise and useful constructive algebra. And somehow despite 10,000 words on the topic, we have yet to discuss any notion of the common musical ideas of “scales” or “harmony” or “pitches.”</p>
<p>Today we’re going to tackle those things</p>
<p>I’d like to preface this by saying: <strong>all of the music theory here comes from <a href="https://dmitri.mycpanel.princeton.edu/index.html">Dmitri Tymoczko</a>.</strong> I’ve spent the last year reading (and rereading, and re-rereading) his amazing book <a href="https://dmitri.mycpanel.princeton.edu/tonality-an-owners-manual.html">Tonality</a> which is the clearest approach to music I have ever found. Shoutouts to <a href="https://github.com/sporkl">Dmitri Volkov</a> who put me <a href="https://github.com/isovector/reasonablypolymorphic.com/issues/64#issuecomment-3621529779">onto the trail</a>.</p>
<p>To the extent that I’ve done anything of substance on this matter, it is merely in finding representations of these ideas in terms of types!</p>
<h2 id="finite-numbers">Finite Numbers</h2>
<p>Let’s set the stage with a little appetizer. Consider the finite numbers:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Fin</span><span class="ot"> ::</span> <span class="dt">Nat</span> <span class="ot">-&gt;</span> <span class="dt">Type</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Fin</span> n</span></code></pre></div>
<p>The type <code>Fin n</code> has <code>n</code> distinct values, which we label 0, 1, …, n. For example <code>Fin 0</code> has 0 values, <code>Fin 3</code> has 3 values, and so on and so forth.</p>
<p>Encoding <code>Fin</code> in Haskell is tricky and rather unsatisfying regardless of how you do it. For our purposes, we’re going to do this:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Fin</span><span class="ot"> ::</span> <span class="dt">Nat</span> <span class="ot">-&gt;</span> <span class="dt">Type</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Fin</span> n <span class="kw">where</span></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>  <span class="dt">FZ</span><span class="ot"> ::</span> (<span class="dv">1</span> <span class="op">&lt;=</span> n) <span class="ot">=&gt;</span> <span class="dt">Fin</span> n</span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>  <span class="dt">FS</span><span class="ot"> ::</span> (<span class="dv">1</span> <span class="op">&lt;=</span> n) <span class="ot">=&gt;</span> <span class="op">!</span>(<span class="dt">Fin</span> (n <span class="op">-</span> <span class="dv">1</span>)) <span class="ot">-&gt;</span> <span class="dt">Fin</span> n</span></code></pre></div>
<p>which lets us encode 0 as <code>FZ</code>, 1 as <code>FS FZ</code>, etc. The funny <code>1 &lt;= n</code> constraints are there to help GHC learn that these patterns are complete. Like I said, rather unsatisfying, but what are you going to do.</p>
<p>The advantage of doing things this way is that when combined with <a href="https://hackage.haskell.org/package/ghc-typelits-natnormalise">ghc-typelits-natnormalise</a>, GHC can deduce that eg <code>isOdd</code> is defined over all possible inputs:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="ot">isOdd ::</span> <span class="dt">Fin</span> <span class="dv">3</span> <span class="ot">-&gt;</span> <span class="dt">Bool</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>isOdd <span class="dt">FZ</span> <span class="ot">=</span> <span class="dt">True</span></span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a>isOdd (<span class="dt">FS</span> <span class="dt">FZ</span>) <span class="ot">=</span> <span class="dt">False</span></span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a>isOdd (<span class="dt">FS</span> (<span class="dt">FS</span> <span class="dt">FZ</span>)) <span class="ot">=</span> <span class="dt">True</span></span></code></pre></div>
<p>We will give the following instances over <code>Fin n</code>:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="kw">deriving</span> <span class="kw">instance</span> <span class="dt">Eq</span> (<span class="dt">Fin</span> n)</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a><span class="kw">deriving</span> <span class="kw">instance</span> <span class="dt">Ord</span> (<span class="dt">Fin</span> n)</span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> (<span class="op">...</span>) <span class="ot">=&gt;</span> <span class="dt">Num</span> (<span class="dt">Fin</span> n) <span class="kw">where</span></span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a>  <span class="fu">fromInteger</span> <span class="ot">=</span> unsafeFromNum <span class="op">.</span> <span class="fu">flip</span> <span class="fu">mod</span> (natSize <span class="op">@</span>n)</span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a>  n <span class="op">+</span> m <span class="ot">=</span> <span class="fu">fromInteger</span> (<span class="fu">toInteger</span> n <span class="op">+</span> <span class="fu">toInteger</span> m)</span>
<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a>  n <span class="op">*</span> m <span class="ot">=</span> <span class="fu">fromInteger</span> (<span class="fu">toInteger</span> n <span class="op">*</span> <span class="fu">toInteger</span> m)</span>
<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a>  n <span class="op">-</span> m <span class="ot">=</span> <span class="fu">fromInteger</span> (<span class="fu">toInteger</span> n <span class="op">-</span> <span class="fu">toInteger</span> m)</span></code></pre></div>
<p>where the <code>Num</code> instances are up to <code>mod n</code>. That is, <code>(2 :: Fin 3) + 2</code> is equal to <code>1 :: Fin 3</code> (because 4 mod 3 is 1.) While GHC will happily allow us to use integer literals to define pattern matches against <code>Fin n</code>, it <em>won’t</em> be able to tell that they’re total. Alas. Alack. Nevertheless, for reasons of presentation we will pretend like GHC can. So we will prefer to write <code>isOdd</code> like this:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="ot">isOdd ::</span> <span class="dt">Fin</span> <span class="dv">3</span> <span class="ot">-&gt;</span> <span class="dt">Bool</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a>isOdd <span class="dv">0</span> <span class="ot">=</span> <span class="dt">True</span></span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a>isOdd <span class="dv">1</span> <span class="ot">=</span> <span class="dt">False</span></span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a>isOdd <span class="dv">2</span> <span class="ot">=</span> <span class="dt">True</span></span></code></pre></div>
<h2 id="scalar-degrees">Scalar Degrees</h2>
<p>Let’s talk music now.</p>
<p>We begin with the idea of a “scale degree”, which is just an integer acting as a coordinate in some “musical space”, to be made precise later. Our type is <code>Deg n</code>, where <code>n</code> is the size of the scale.</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Deg</span><span class="ot"> ::</span> <span class="dt">Nat</span> <span class="ot">-&gt;</span> <span class="dt">Type</span></span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">Deg</span> n <span class="ot">=</span> <span class="dt">Deg</span></span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> getDeg ::</span> <span class="dt">Int</span></span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a>  }</span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> stock (<span class="dt">Generic</span>)</span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> <span class="kw">newtype</span> (<span class="dt">Eq</span>, <span class="dt">Ord</span>, <span class="dt">Show</span>, <span class="dt">Num</span>, <span class="dt">Enum</span>, <span class="dt">Real</span>, <span class="dt">Integral</span>)</span></code></pre></div>
<p>Really, we just keep the <code>n</code> around to ensure you don’t accidentally add <code>Deg</code>s that belong in different coordinate systems.</p>
<p>However, unlike <code>Int</code>, we are going to do some quotienty stuff with <code>Deg n</code>. Namely, we will say that <code>(k + n) :: Deg n</code> is “the same thing, only higher” than <code>k :: Deg n</code>.</p>
<p>In musical terms, <code>n</code> is the number of pitch classes available to us (notes like A, B, C#, Db, etc.). And so our claim about <code>k + n</code> is like saying <code>(C4 + an octave) = C5</code> is the “same thing” as <code>C4</code> (only higher.) Except that we have generalized away the exact number of pitch classes.</p>
<p>If you don’t already “read music,” you are likely at an advantage here, in that you don’t need to <em>unlearn</em> things to understand what might be going on here. Feel free to skim for a bit if things don’t make much sense — the following is an attempt to disabuse classically-trained musicians of some ubiquitous points of confusion.</p>
<p>We can imagine each <code>Deg n</code> space as defining an “abstract clef.” For example, the pattern <code>[0, 1, -2, 3] :: Deg 3</code> might look something like this:</p>
<figure>
<img src="/images/music5/out1.cropped.svg" alt="0-1-(-2)-3 in the “3 Clef”" /><figcaption aria-hidden="true">0-1-(-2)-3 in the “3 Clef”</figcaption>
</figure>
<p>What pitches do these correspond to? <strong>They don’t!</strong> They are just points in some abstract musical scale. Without knowing the scale, we can’t say anything about what pitches these correspond to.</p>
<p>We’ll make all of this Haskell-precise in a moment, but let’s carry on. We can imagine a “scale” that maps <code>Fin 3</code> notes into <code>Fin 7</code> notes via “inclusion” (namely, just reinterpret the degree):</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="ot">inclusion ::</span> <span class="dt">Fin</span> <span class="dv">3</span> <span class="ot">-&gt;</span> <span class="dt">Fin</span> <span class="dv">7</span></span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a>inclusion n <span class="ot">=</span> unsafeCoerce n</span></code></pre></div>
<p>If we map this “scale” over our earlier pattern, we get this odd beast:</p>
<figure>
<img src="/images/music5/out2.cropped.svg" alt="Inclusion into the “7 Clef”" /><figcaption aria-hidden="true">Inclusion into the “7 Clef”</figcaption>
</figure>
<p>What the hell is going on here? We are mapping <code>0 :: Deg 3</code> to <code>0 :: Deg 7</code>, which is why the first note in both is on the middle line. Similarly, <code>1 :: Deg 3</code> maps to <code>1 :: Deg 7</code>, which is why the second note in both is the space above the middle line.</p>
<p>However, we can rewrite <code>(-2) :: Deg 3</code> as <code>(-3) + 1 :: Deg 3</code>, and by our quotienting rule, <code>(-3) :: Deg</code> is the same pitch class as <code>0 :: Deg</code>. Thus <code>(-2) :: Deg 3</code> must be the same pitch class as <code>1 :: Deg 3</code>, only an “octave” lower. So when we include into <code>Deg 7</code>, we see that the third note is 7 degrees below the second note. Similarly, <code>3 :: Deg 3</code> ought to be one “octave” above <code>0 :: Deg 3</code>. And since we map <code>0 :: Deg 3</code> to <code>0 :: Deg 7</code>, we must map <code>3 :: Deg 3</code> to <code>7 :: Deg 7</code>.</p>
<p>What a mouthful!</p>
<p>All of this is to say that in <code>Deg n</code>, we have exactly <code>n</code> pitch classes, and if you wrap around you have to go up or down an “octave.”</p>
<p>This likely feels pretty roundabout. But it admits many cool musical phenomena. For example, we can (but not are not required to) interpret <code>Deg 3</code> as notes of a triad. Then given <code>[0, 1, 2, 3] :: Deg 3</code>:</p>
<figure>
<img src="/images/music5/out3.cropped.svg" alt="0-1-2-3 in the “3 Clef”" /><figcaption aria-hidden="true">0-1-2-3 in the “3 Clef”</figcaption>
</figure>
<p>and a scale that maps <code>Deg 3 -&gt; Deg 7</code>, namely:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="ot">triad ::</span> <span class="dt">Fin</span> <span class="dv">3</span> <span class="ot">-&gt;</span> <span class="dt">Fin</span> <span class="dv">7</span></span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>triad <span class="dv">0</span> <span class="ot">=</span> <span class="dv">0</span></span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a>triad <span class="dv">1</span> <span class="ot">=</span> <span class="dv">2</span></span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a>triad <span class="dv">2</span> <span class="ot">=</span> <span class="dv">4</span></span></code></pre></div>
<p>we arpeggiate a triad:<a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a></p>
<figure>
<img src="/images/music5/out4.cropped.svg" alt="Arpeggiation" /><figcaption aria-hidden="true">Arpeggiation</figcaption>
</figure>
<p>How cool is that??</p>
<p>Well, ok, you’re probably not <em>that</em> impressed. But that’s because you don’t yet fully appreciate the power of this.</p>
<h2 id="a-quick-note-on-off-by-one-errors">A Quick Note on Off-By-One Errors</h2>
<p>Fucking music, man. Clearly not invented by computer scientists. There are off-by-one errors <em>everywhere</em> in this domain. The most egregious is that the distance between a note and itself is considered to be 1. They call this the “unison.”</p>
<p>The distance between a note and its immediate neighbor is a “second.” The distance to the note after that is a “third”. Ok, fine, at least it’s monotonic.</p>
<p>But then you get into weird issues where if put a third on top of a third you end up with a fifth.</p>
<p>Idiotic.</p>
<p>To work around this there’s all these rules like to <em>subtract</em> a distance you need to subtract it from 9 (despite the fact that there are only 7 notes), because now you’ve <em>double counted</em> the unison.</p>
<p>BUT THE BUCK STOPS HERE. We’re going to just right the wrong and make everything 0-indexed. That’s why in the definition of <code>triad</code> above, we map the “root of the chord” to note 0, the “third” to note 2, and the “fifth” to note 4.</p>
<h2 id="back-to-music">Back to Music</h2>
<p>(In my opinion) Tymoczko’s big insight is that we can generate a huge amount of musical phenomena simply by applying transformations at different degrees. For example, a musical voice might be moving up and down a <code>Deg 3</code> (which as we’ve seen, might correspond to arpeggiation). We can then transform that into a <code>Deg 7</code>, but add a time-pointwise offset (which corresponds to <a href="https://en.wikipedia.org/wiki/Chord_progression">chord changes</a>.) We can then map that into <code>Deg 12</code>, and add a new time-pointwise offset (corresponding to a <a href="https://en.wikipedia.org/wiki/Modulation_(music)">scalar modulation</a>.)</p>
<p>And if you’ve been following along <a href="/tags/music.html">through the series so far</a>, you might consider that we could model the above as a <code>Signal (Event (Span (Deg 3)))</code> describing the voice moving, with a <code>Signal (Deg 7)</code> describing the chord change offsets and a <code>Signal (Deg 12)</code> describing the key changes.</p>
<p>But that’s just the beginning. Nobody says our mappings between <code>Deg m</code> and <code>Deg n</code> need to stay constant! Or that we can’t stick a transformation to <code>Deg p</code> in between <code>m</code> and <code>n</code> for a few bars.</p>
<p>That’s enough for today. Big vibes day I guess. Next time we’ll look at making all of this actually precise, as well as digging into some of Tymoczko’s other interesting ideas.</p>
<section class="footnotes" role="doc-endnotes">
<hr />
<ol>
<li id="fn1" role="doc-endnote"><p>Assuming we also have some canonical way of turning <code>Deg 7</code> into actual pitches. Here we assume <code>0 :: Deg 7</code> is middle C, and that we are using the diatonic scale.<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</section>
        ]]>
      </content>
    </entry>
    <entry>
      <title>Musically Horizontal Monads</title>
      <id>blog/horizontal-monads/index.html</id>
      <link href='blog/horizontal-monads/index.html'/>
      <published>2026-11-08T10:55:00Z</published>
      <updated>2026-11-08T10:55:00Z</updated>

      <content type="html" xml:base="https://reasonablypolymorphic.com">
        <![CDATA[
        <p>Sorry for the delay! My household has had a couple of chaotic days of everyone-being-very-very-sick and house guests and 4:30am airport drop-offs. But we’re back! This blog post got written in several parts over several days, so it might be a little disjointed. Apologies.</p>
<p>Anyway…</p>
<p>In the <a href="/blog/musical-spans/">last post</a> we discussed a way of attaching durations to instantaneous musical events: just wrap them with a duration, stupid! Then we wrote a function</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="ot">spanning ::</span> <span class="dt">SF</span> (<span class="dt">Event</span> (), <span class="dt">Event</span> a) (<span class="dt">Event</span> (<span class="dt">Span</span> a))</span></code></pre></div>
<p>which takes an event stream of stopping points, as well as an event stream of starting points<a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a>. It then spans each starting event until the next stop or start. The stops are there so that we can add silence if necessary.</p>
<p>Having a function like <code>spanning</code> around is cool because it means we can just emit starting and stopping events from whatever upstream process we might like, and it will automatically turn them into “rhythm.” And of course, that upstream process is welcome to derive the stop stream from the start stream (or vice versa), if you don’t want to have to think about it.</p>
<p>Anyway, that’s all and good. But musicians have a lot of intellectual moment behind <em>not</em> thinking about music that way. Instead they usually just think of having durations intrinsically attached to notes — that is to say, they conceive of the note and the duration at the same time. Since we have an explicit desideratum here of making it easy to get good results, we ought to provide some more conventional ways of thinking about writing lines.</p>
<p>Writing lines is usually done as “pick a note and a duration, then after that duration, pick another note and another duration. Rinse and repeat.” Of course, there’s some wiggle room where you can instead choose to <em>not</em> select a note and leave silence in its place. Depending on how functional-programming-pilled you are, this either sounds like a monoid or a monad. Let’s explore both ideas, starting with the monoid.</p>
<p>A horizontal monoid seems like it ought to sequence one piece of music before another, in a temporal-sense. That is, <code>a &lt;&gt; b</code> should play <code>a</code>, and then once <code>a</code> is done, it should play <code>b</code>.</p>
<p>Recall that <code>Signal</code> already has <code>Semigroup/Monoid</code> instances, but looking at the type, they necessarily can’t be the right thing:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Signal</span> a <span class="ot">=</span> <span class="dt">Signal</span> (<span class="dt">Time</span> <span class="ot">-&gt;</span> a) [(<span class="dt">Time</span>, <span class="dt">Segment</span> a)]</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> stock <span class="dt">Functor</span></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> (<span class="dt">Semigroup</span>, <span class="dt">Monoid</span>) via <span class="dt">Ap</span> <span class="dt">Signal</span> a</span></code></pre></div>
<p>If you’re unfamiliar with the <a href="https://hackage-content.haskell.org/package/base-4.22.0.0/docs/Data-Monoid.html#t:Ap"><code>Ap</code></a> newtype, it lifts the <code>Semigroup</code> and <code>Monoid</code> instances over the <code>Applicative</code> structure. That is, we’ve effectively derived the following instances:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Semigroup</span> a <span class="ot">=&gt;</span> <span class="dt">Semigroup</span> (<span class="dt">Signal</span> a) <span class="kw">where</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>  (<span class="op">&lt;&gt;</span>) <span class="ot">=</span> liftA2 (<span class="op">&lt;&gt;</span>)</span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Monoid</span> a <span class="ot">=&gt;</span> <span class="dt">Monoid</span> (<span class="dt">Signal</span> a) <span class="kw">where</span></span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a>  <span class="fu">mempty</span> <span class="ot">=</span> <span class="fu">pure</span> <span class="fu">mempty</span></span></code></pre></div>
<p>The clue that this is doing the wrong thing for our purposes is the <code>Semigroup a =&gt;</code> constraint. If we were putting one <code>Signal a</code> after another <em>in time</em>, we’d never need to combine <code>a</code>s, and thus we would have no need for a <code>Semigroup a</code> instance. Thus, this instance <em>must</em> be doing a point-wise zip of times. Which is all to say that this is no good to us.</p>
<p>What we instead must do is build a wrapper type which provides the correct temporal-sequencing monoid. Let’s take a moment to pour over our primitives and see if any of them are feasible for actually making that happen.</p>
<p>The relevant primitive happens to be <code>switchS</code>:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ot">switchS ::</span> <span class="dt">Signal</span> (a, <span class="dt">Event</span> b) <span class="ot">-&gt;</span> (b <span class="ot">-&gt;</span> <span class="dt">Signal</span> a) <span class="ot">-&gt;</span> <span class="dt">Signal</span> a</span></code></pre></div>
<p>which long-time readers might recall has <a href="/blog/yampa-switching/">seen some action on this blog</a> in the past. The idea is that we will run the first <code>Signal</code> until the first occurrence of the <code>Event c</code>, then use that in order to switch to the given continuation.</p>
<p>So <code>switchS</code> gives us the “do one thing after another” semantics we want (notice its lack of a <code>Semigroup a</code> constraint!) This happens to be most of the work done, now it’s just a matter of accumulating the rest of the bits we need: the actual notes we’re playing, the start points, and the stop points. Let’s package all of that up into a little datatype:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">HState</span> a <span class="ot">=</span> <span class="dt">HState</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> hs_out ::</span> a</span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a>  ,<span class="ot"> hs_starts ::</span> <span class="dt">Event</span> ()</span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a>  ,<span class="ot"> hs_stops ::</span> <span class="dt">Event</span> ()</span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a>  }</span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> stock (<span class="dt">Functor</span>, <span class="dt">Generic</span>)</span>
<span id="cb5-7"><a href="#cb5-7" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> (<span class="dt">Semigroup</span>, <span class="dt">Monoid</span>) via <span class="dt">Generically</span> (<span class="dt">HState</span> a)</span></code></pre></div>
<p>A horizontal structure then is some sort of newtype over <code>Signal (HState a)</code>. As it happens, writing the monadic horizontal structure is going to be a little more informative at this point, since we can lift the monoidal version out directly. But we can immediately put <code>HState</code> to work!</p>
<p>In the exact style of <a href="/blog/yampa-switching/">Yampa Switching</a>, we will use the <a href="https://hackage-content.haskell.org/package/mtl-2.3.2/docs/Control-Monad-Cont.html#t:Cont"><code>Cont</code>inuation monad</a>, which allows us to bind over the <code>a</code> in some function <code>(a -&gt; b) -&gt; b</code> — in our case, this will be the <code>(a -&gt; Signal b) -&gt; Signal b</code> that curries out of <code>switchS</code>. This is already well-treaded territory on this blog, so you can go read the Yampa Switching post if you’re curious about the exact details here.</p>
<p>As a first approximation, wrapping this up gives us the type:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">Horizontal</span> o a <span class="ot">=</span> <span class="dt">Horizontal</span></span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> unHorizontal ::</span> <span class="dt">Cont</span> (<span class="dt">Signal</span> (<span class="dt">HState</span> o)) a</span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a>  }</span></code></pre></div>
<p>However, this is somewhat unsatisfactory. <code>Signal</code>s are covariant in their output (here <code>HState o</code>), but <code>Cont</code> is <em>invariant</em> in that parameter. Blinding moving forward with <code>Horizontal</code> as written would mean we wouldn’t have an operation <code>mapOut :: (o -&gt; o') -&gt; Horizontal o a -&gt; Horizontal o' a</code> which in practice turns out to be quite a limitation indeed!</p>
<p>Instead we can do a little bit of a <a href="https://hackage-content.haskell.org/package/kan-extensions-5.2.8/docs/Data-Functor-Yoneda.html#t:Yoneda">Yoneda</a>-style encoding, where we hold onto a function that maps from <code>o</code> into the eventual result of the invariant <code>r</code> parameter. Check this thing out:</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">Yo</span> f o a <span class="ot">=</span> <span class="dt">Yo</span></span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> unYo ::</span> <span class="kw">forall</span> b<span class="op">.</span> (o <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> <span class="dt">Cont</span> (f b) a</span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a>}</span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a><span class="kw">deriving</span> stock <span class="dt">Functor</span></span>
<span id="cb7-5"><a href="#cb7-5" aria-hidden="true" tabindex="-1"></a><span class="kw">deriving</span> (<span class="dt">Semigroup</span>, <span class="dt">Monoid</span>) via <span class="dt">Ap</span> (<span class="dt">Yo</span> f o) a</span></code></pre></div>
<p>The idea is that we delay building up our <code>Cont</code> until you hand us a way of mapping from <code>o</code> into whatever type <code>b</code> you eventually end up wanting. We usually use a trick like this to get a free <em>functor</em>, but here we’re using it to get a free <em>bifunctor</em>:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Bifunctor</span> (<span class="dt">Yo</span> f) <span class="kw">where</span></span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>  bimap f g (<span class="dt">Yo</span> y) <span class="ot">=</span> <span class="dt">Yo</span> <span class="op">$</span> \k <span class="ot">-&gt;</span> <span class="fu">fmap</span> g <span class="op">$</span> y <span class="op">$</span> k <span class="op">.</span> f</span></code></pre></div>
<p>The <code>Applicative</code> and <code>Monad</code> instances also come already-paid-for, but we must write them out ourselves:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Applicative</span> (<span class="dt">Yo</span> r o) <span class="kw">where</span></span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">pure</span> a <span class="ot">=</span> <span class="dt">Yo</span> <span class="op">$</span> <span class="fu">const</span> <span class="op">$</span> <span class="fu">pure</span> a</span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a>  liftA2 f (<span class="dt">Yo</span> a) (<span class="dt">Yo</span> b) <span class="ot">=</span> <span class="dt">Yo</span> <span class="op">$</span> \k <span class="ot">-&gt;</span> liftA2 f (a k) (b k)</span>
<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Monad</span> (<span class="dt">Yo</span> r o) <span class="kw">where</span></span>
<span id="cb9-6"><a href="#cb9-6" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Yo</span> m <span class="op">&gt;&gt;=</span> f <span class="ot">=</span> <span class="dt">Yo</span> <span class="op">$</span> \k <span class="ot">-&gt;</span> m k <span class="op">&gt;&gt;=</span> \a <span class="ot">-&gt;</span> unYo (f a) k</span></code></pre></div>
<p>This concludes our diversion into writing <code>Yo</code>. Popping the stack: recall we’re still trying to write a monadic horizontal structure. Which we can now write out as <code>Horizontal r o a</code> (with <code>r</code> being left intentionally unmotivated for the time being), getting all our relevant instances for free:</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">Horizontal</span> r o a <span class="ot">=</span> <span class="dt">Horizontal</span></span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> unHorizontal ::</span> <span class="kw">forall</span> b<span class="op">.</span> (o <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> <span class="dt">Cont</span> (<span class="dt">Signal</span> (<span class="dt">HState</span> b)) a</span>
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a>  }</span>
<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> (<span class="dt">Bifunctor</span>)</span>
<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a>    via <span class="dt">Yo</span> (<span class="dt">Compose</span> <span class="dt">Signal</span> <span class="dt">HState</span>)</span>
<span id="cb10-6"><a href="#cb10-6" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> (<span class="dt">Functor</span>, <span class="dt">Applicative</span>, <span class="dt">Monad</span>)</span>
<span id="cb10-7"><a href="#cb10-7" aria-hidden="true" tabindex="-1"></a>    via <span class="dt">Yo</span> (<span class="dt">Compose</span> <span class="dt">Signal</span> <span class="dt">HState</span>) o</span>
<span id="cb10-8"><a href="#cb10-8" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> (<span class="dt">Semigroup</span>, <span class="dt">Monoid</span>)</span>
<span id="cb10-9"><a href="#cb10-9" aria-hidden="true" tabindex="-1"></a>    via <span class="dt">Yo</span> (<span class="dt">Compose</span> <span class="dt">Signal</span> <span class="dt">HState</span>) o a</span></code></pre></div>
<p>Take a moment to appreciate how <em>amazing</em> GHC is here; each of those deriving vias is lifting an unrelated type through a polytype <code>forall b</code> <em>and</em> through a <code>Compose</code>, the latter of which doesn’t have most instances we’re actually intersted in!<a href="#fn2" class="footnote-ref" id="fnref2" role="doc-noteref"><sup>2</sup></a></p>
<p>Our primary introduction form for <code>Horizontal</code> is <code>mkHorizontal</code>, which acts as one <code>Signal o</code> for some amount of time, before rendering a continuation of type <code>a</code>:</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# LANGUAGE ApplicativeDo #-}</span></span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a><span class="ot">mkHorizontal ::</span> <span class="dt">Signal</span> o <span class="ot">-&gt;</span> <span class="dt">Time</span> <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Horizontal</span> r o a</span>
<span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a>mkHorizontal so t a <span class="ot">=</span> <span class="dt">Horizontal</span> <span class="op">$</span> \k <span class="ot">-&gt;</span> cont <span class="op">$</span> switchS <span class="op">$</span> <span class="kw">do</span></span>
<span id="cb11-5"><a href="#cb11-5" aria-hidden="true" tabindex="-1"></a>  o <span class="ot">&lt;-</span> so</span>
<span id="cb11-6"><a href="#cb11-6" aria-hidden="true" tabindex="-1"></a>  start <span class="ot">&lt;-</span> atS <span class="dv">0</span> ()</span>
<span id="cb11-7"><a href="#cb11-7" aria-hidden="true" tabindex="-1"></a>  stop <span class="ot">&lt;-</span> atS t ()</span>
<span id="cb11-8"><a href="#cb11-8" aria-hidden="true" tabindex="-1"></a>  ea <span class="ot">&lt;-</span> atS t a</span>
<span id="cb11-9"><a href="#cb11-9" aria-hidden="true" tabindex="-1"></a>  <span class="fu">pure</span> (<span class="dt">HState</span> (k o) start stop, ea)</span></code></pre></div>
<p>Note that we issue a start event at time 0, and both a stop event and switch event at time <code>t</code>. From this we can derive <code>fill</code> and <code>hit</code>, both of which use a constant value across their <code>Signal o</code>, differing only in what they return as a monadic continuation:</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="ot">fill ::</span> <span class="dt">Time</span> <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Horizontal</span> r a a</span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a>fill t a <span class="ot">=</span> mkHorizontal (<span class="fu">pure</span> a) t a</span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a><span class="ot">hit ::</span> <span class="dt">Time</span> <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Horizontal</span> r a ()</span>
<span id="cb12-5"><a href="#cb12-5" aria-hidden="true" tabindex="-1"></a>hit t <span class="ot">=</span> void <span class="op">.</span> fill t</span></code></pre></div>
<p>And of course, the <code>mapOut</code> function we had to invent the <code>Yo</code> machinery in order to provide:</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="ot">mapOut ::</span> (o <span class="ot">-&gt;</span> o&#39;) <span class="ot">-&gt;</span> <span class="dt">Horizontal</span> r o a <span class="ot">-&gt;</span> <span class="dt">Horizontal</span> r o&#39; a</span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a>mapOut <span class="ot">=</span> <span class="fu">flip</span> bimap <span class="fu">id</span></span></code></pre></div>
<h2 id="a-musical-aside">A Musical Aside</h2>
<p>It’s probably worth taking a moment to discuss <em>what exactly the hell</em> is going on with all of this crazy yoneda continuation monad stuff. What does it <em>buy</em> us?</p>
<p>Lets write a little motif:</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="ot">motif ::</span> <span class="dt">Note</span> <span class="ot">-&gt;</span> <span class="dt">Horizontal</span> r <span class="dt">Note</span> <span class="dt">Note</span></span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a>motif n <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a>  hit (<span class="dv">1</span><span class="op">/</span><span class="dv">4</span>) n</span>
<span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a>  hit (<span class="dv">1</span><span class="op">/</span><span class="dv">4</span>) <span class="op">$</span> n <span class="op">+</span> <span class="dv">4</span></span>
<span id="cb14-5"><a href="#cb14-5" aria-hidden="true" tabindex="-1"></a>  hit (<span class="dv">1</span><span class="op">/</span><span class="dv">4</span>) <span class="op">$</span> n <span class="op">+</span> <span class="dv">3</span></span>
<span id="cb14-6"><a href="#cb14-6" aria-hidden="true" tabindex="-1"></a>  <span class="fu">pure</span> <span class="op">$</span> n <span class="op">+</span> <span class="dv">2</span></span></code></pre></div>
<p>notice that this emits notes relative to its input. In somewhat-standard notation, <code>motif F</code> looks like this<a href="#fn3" class="footnote-ref" id="fnref3" role="doc-noteref"><sup>3</sup></a>:</p>
<figure>
<img src="/images/music4/out1.cropped.svg" alt="Motif" /><figcaption aria-hidden="true">Motif</figcaption>
</figure>
<p>using this triangle symbol to indicate the continuation. But now check this out. We can bind the result in order to build a musical sequence; <code>motif F &gt;&gt;= motif</code> looks like this:</p>
<figure>
<img src="/images/music4/out2.cropped.svg" alt="Sequencing Motif" /><figcaption aria-hidden="true">Sequencing Motif</figcaption>
</figure>
<p>This happens to be the underlying machinery in Tymoczko’s work on sequences (chapter 4 of <a href="https://dmitri.mycpanel.princeton.edu/tonality-an-owners-manual.html">Tonality</a>), though it is not presented as such (and I suspect he didn’t have monads in mind when writing it.)</p>
<h2 id="back-to-haskell">Back to Haskell</h2>
<p>Revitalized with a real connection to real musical ideas, we press on through the mires of abstract nonsense. The most pressing problem remaining is how do we eliminate <code>Horizontal</code>? By means of <code>unsafeRunHorizontal</code><a href="#fn4" class="footnote-ref" id="fnref4" role="doc-noteref"><sup>4</sup></a>:</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a>unsafeRunHorizontal</span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  ::</span> <span class="dt">Horizontal</span> r o a</span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> <span class="dt">Signal</span> o)</span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">Signal</span> (<span class="dt">HState</span> o)</span>
<span id="cb15-5"><a href="#cb15-5" aria-hidden="true" tabindex="-1"></a>unsafeRunHorizontal (<span class="dt">Horizontal</span> f) k <span class="ot">=</span></span>
<span id="cb15-6"><a href="#cb15-6" aria-hidden="true" tabindex="-1"></a>  runCont (f <span class="fu">id</span>) <span class="op">$</span> \a <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb15-7"><a href="#cb15-7" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- Add a final stop point at the beginning of our switch.</span></span>
<span id="cb15-8"><a href="#cb15-8" aria-hidden="true" tabindex="-1"></a>    stop <span class="ot">&lt;-</span> atS <span class="dv">0</span> ()</span>
<span id="cb15-9"><a href="#cb15-9" aria-hidden="true" tabindex="-1"></a>    o <span class="ot">&lt;-</span> k a</span>
<span id="cb15-10"><a href="#cb15-10" aria-hidden="true" tabindex="-1"></a>    <span class="fu">pure</span> <span class="op">$</span> <span class="dt">HState</span> o <span class="dt">NoEvent</span> stop</span></code></pre></div>
<p>which isn’t actually unsafe, but <em>will be</em> due to a few additions to our API in a second. But a nicer eliminator is <code>horizontal</code>, which as originally promised, calls <code>spanning</code> on our behalf:</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="ot">horizontal ::</span> <span class="dt">Horizontal</span> r o a <span class="ot">-&gt;</span> <span class="dt">Signal</span> (<span class="dt">Event</span> (<span class="dt">Span</span> o))</span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a>horizontal h</span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=</span> <span class="fu">flip</span> runSF</span>
<span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a>      ( unsafeRunHorizontal h</span>
<span id="cb16-5"><a href="#cb16-5" aria-hidden="true" tabindex="-1"></a>      <span class="op">$</span> <span class="fu">const</span></span>
<span id="cb16-6"><a href="#cb16-6" aria-hidden="true" tabindex="-1"></a>      <span class="op">$</span> <span class="fu">pure</span></span>
<span id="cb16-7"><a href="#cb16-7" aria-hidden="true" tabindex="-1"></a>      <span class="op">$</span> <span class="fu">error</span> <span class="st">&quot;impossible: horizontal sampled too late&quot;</span></span>
<span id="cb16-8"><a href="#cb16-8" aria-hidden="true" tabindex="-1"></a>      )</span>
<span id="cb16-9"><a href="#cb16-9" aria-hidden="true" tabindex="-1"></a>  <span class="op">$</span> proc (<span class="dt">HState</span> o starts stops) <span class="ot">-&gt;</span> spanning <span class="op">-&lt;</span> (stops, o <span class="op">&lt;$</span> starts)</span></code></pre></div>
<p>Here we use <code>unsafeRunHorizontal</code> and pass it a dummy continuation, since we know we’re never going to actually sample it past the duration of our <code>Horizontal</code>. Then we take the output <code>HState</code>, sample <code>o</code> <em>only at the start points</em>, and pass the stop points through unmolested.</p>
<p>It can also be useful to turn a <code>Horizontal</code> directly into an event stream, ignoring its spans:</p>
<div class="sourceCode" id="cb17"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a><span class="ot">getHorizontal ::</span> <span class="dt">Horizontal</span> r o a <span class="ot">-&gt;</span> <span class="dt">Signal</span> (<span class="dt">Event</span> o)</span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a>getHorizontal <span class="ot">=</span> <span class="fu">fmap</span> (<span class="fu">fmap</span> getSpan) <span class="op">.</span> horizontal</span></code></pre></div>
<h2 id="putting-everything-to-rest">Putting Everything to Rest</h2>
<p>The final two mysteries remaining are the unmotivated <code>r</code> parameter in <code>Horizontal r o a</code>, and why <code>unsafeRunHorizontal</code> is unsafe.</p>
<p>Recall that musicians often think about periods of silence, or <em>rests.</em> While we could model rests as a <code>Nothing</code> value in a <code>Maybe</code>-typed <code>Horizontal</code>, this would get rather in the way of our nice combinators! In particular, nothing says we must interpret a <code>Horizontal</code> as a discrete function; if it’s continuous, then the <code>Nothing</code> value would make sense. But if we’re exporting discrete function, then the <code>Nothing</code>s never actually show up and the <code>Just</code>s are unnecessary.</p>
<p>So here’s the trick; this phantom <code>r</code> type in <code>Horizontal r o a</code> corresponds to “are there any rests in this value?” We can use a <code>DataKinds</code> to get ourselves a type-level value to play with:</p>
<div class="sourceCode" id="cb18"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Restful</span> <span class="ot">=</span> <span class="dt">HasRests</span></span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Horizontal</span><span class="ot"> ::</span> <span class="dt">Restful</span> <span class="ot">-&gt;</span> <span class="dt">Type</span> <span class="ot">-&gt;</span> <span class="dt">Type</span> <span class="ot">-&gt;</span> <span class="dt">Type</span></span>
<span id="cb18-4"><a href="#cb18-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb18-5"><a href="#cb18-5" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> role <span class="dt">Horizontal</span> nominal representational representational</span></code></pre></div>
<p>Our new <code>rest</code> combinator is the only thing that uses the <code>r</code> parameter:</p>
<div class="sourceCode" id="cb19"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="ot">rest ::</span> <span class="dt">Time</span> <span class="ot">-&gt;</span> <span class="dt">Horizontal</span> <span class="dt">HasRests</span> a ()</span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a>rest t <span class="ot">=</span> <span class="dt">Horizontal</span> <span class="op">$</span> <span class="fu">const</span> <span class="op">$</span> cont <span class="op">$</span> switchS <span class="op">$</span> <span class="kw">do</span></span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a>  stop <span class="ot">&lt;-</span> atS <span class="dv">0</span> ()</span>
<span id="cb19-4"><a href="#cb19-4" aria-hidden="true" tabindex="-1"></a>  ea <span class="ot">&lt;-</span> atS t ()</span>
<span id="cb19-5"><a href="#cb19-5" aria-hidden="true" tabindex="-1"></a>  <span class="fu">pure</span> ( <span class="dt">HState</span> (<span class="fu">error</span> <span class="st">&quot;impossible: rest can&#39;t be sampled&quot;</span>) <span class="dt">NoEvent</span> stop</span>
<span id="cb19-6"><a href="#cb19-6" aria-hidden="true" tabindex="-1"></a>       , ea</span>
<span id="cb19-7"><a href="#cb19-7" aria-hidden="true" tabindex="-1"></a>       )</span></code></pre></div>
<p>Notice that <code>rest</code> sets a stop point at t=0, and doesn’t create any new start points. Furthermore, the actual value of type <code>a</code> here is an <code>error</code> value. It claims to be “impossible,” which we will enforce momentarily.</p>
<p>Something peculiar here is that we only have a single type of kind <code>Restful</code>, namely <code>HasRests</code>. How can we differentiate <code>Horizontal</code>s that use <code>rest</code> from those that don’t? Our old friend <a href="https://wiki.haskell.org/Monad/ST#An_explanation_in_Haskell-Cafe">the ST trick</a> comes knocking, requiring that <code>r</code> remain fully polymorphic:</p>
<div class="sourceCode" id="cb20"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a>switchHorizontal</span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a><span class="ot">    ::</span> (<span class="kw">forall</span> r<span class="op">.</span> <span class="dt">Horizontal</span> r o a)</span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> <span class="dt">Signal</span> o)</span>
<span id="cb20-4"><a href="#cb20-4" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> <span class="dt">Signal</span> (<span class="dt">HState</span> o)</span>
<span id="cb20-5"><a href="#cb20-5" aria-hidden="true" tabindex="-1"></a>switchHorizontal h <span class="ot">=</span> unsafeRunHorizontal h</span></code></pre></div>
<p>Now <code>switchHorizontal</code> can give us a continuous function <em>only when the <code>Horizontal</code> doesn’t contain any <code>rest</code>s!</em> Usage of <code>unsafeRunHorizontal</code> makes no such guarantees, and thus will crash with the impossible error when used on a <code>rest</code>.</p>
<p>Note that <code>horizontal</code> has no such compunctions; it samples its function only at the designated start points, which <code>rest</code> doesn’t provide. And since our semigroup/applicative instances are all temporally end-to-end, nothing can introduce a start point inside of a <code>rest</code>.</p>
<h2 id="our-temporal-monoid">Our Temporal Monoid</h2>
<p>We began all of this looking for a temporal monoid whose multiplication would glue horizontal structures end-to-end. We then switched over to making a monad that did the same thing, but we don’t need to give up on our dreams of monoids!</p>
<p>In fact, <code>Horizontal</code> is already the monoid we want, with a minor niggle in that it wants a semigroup/monoid over the continuation value. If we tie that to be <code>()</code> everything falls out for free:</p>
<div class="sourceCode" id="cb21"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">HM</span> r o <span class="ot">=</span> <span class="dt">HM</span> {<span class="ot"> unHM ::</span> <span class="dt">Horizontal</span> r o () }</span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> <span class="kw">newtype</span> (<span class="dt">Semigroup</span>, <span class="dt">Monoid</span>)</span>
<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Get a functor instance via our Bifunctor</span></span>
<span id="cb21-4"><a href="#cb21-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> <span class="dt">Functor</span> via <span class="dt">Data.Bifunnctor.Flip.Flip</span> (<span class="dt">Horizontal</span> r) ()</span></code></pre></div>
<p>I don’t actually think this type is worth using, since it means our introduction forms need to be lifted into this newtype. But it’s nice to know that we could do such a thing if we wanted to!</p>
<h2 id="next-time">Next Time</h2>
<p>That’s all I have to say about rhythm for now. I don’t consider this to be the last word, but it’s as far as I’ve figured anything out. I’ve been reading a ton of textbooks on the topic, and the author who seems to be the <em>least</em> confused about it is <a href="https://en.wikipedia.org/wiki/Peter_Westergaard&#39;s_tonal_theory#Operations_on_rhythm">Peter Westergaard</a>. His formulation is in terms of “if you want a listener to mentally parse a hierarchical structure out of your notes, what properties would make that parsing easy?”</p>
<p>That’s a thing I’d like to explore further, but I’m on a <a href="https://nano2.org/">publishing deadline</a> here, so I can’t take too much time to do research in between blog posts. Next time we’ll discuss <a href="https://dmitri.mycpanel.princeton.edu/tonality-an-owners-manual.html">Tymoczko’s theory of harmony</a>, which will dramatically power up our ability to make something that sounds like <em>music.</em> Until then!</p>
<section class="footnotes" role="doc-endnotes">
<hr />
<ol>
<li id="fn1" role="doc-endnote"><p>Edited 2026-11-09. The original code had a bug that accidentally forgot a final stop point, which in turn swallowed the last note of the monad.<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn2" role="doc-endnote"><p>As a little aside, if you’re not <code>deriving</code> 90%+ of your instances, you should start. Good places to look for opportunities involve the wrappers in <code>Data.Monoid</code> and <code>GHC.Generics</code>.<a href="#fnref2" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn3" role="doc-endnote"><p>In glorious SVG. Sorry for the shitty image quality in previous posts!<a href="#fnref3" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn4" role="doc-endnote"><p>Edited 2026-11-09. The original code had a bug that accidentally forgot a final stop point, which in turn swallowed the last note of the monad.<a href="#fnref4" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</section>
        ]]>
      </content>
    </entry>
    <entry>
      <title>From Instantaneous Events to Musical Spans</title>
      <id>blog/musical-spans/index.html</id>
      <link href='blog/musical-spans/index.html'/>
      <published>2026-11-05T08:59:00Z</published>
      <updated>2026-11-05T08:59:00Z</updated>

      <content type="html" xml:base="https://reasonablypolymorphic.com">
        <![CDATA[
        <p>We’ve been thinking a lot about musical structures over these last few posts. Today we’re going to look into some rhythmic concerns, and in particular, figure out how to turn a discrete signal of instantaneous events into something that <em>actually looks like music.</em></p>
<p>Recall that we’ve been working with a <code>Signal a</code> type, which is a continuous function of <code>Time -&gt; a</code>, packaged along with a set of “interesting times” that we might be interested in looking at. We smuggle <em>discrete</em> events into these interesting times. But what makes a time interesting?</p>
<p>One immediate answer, musically, is “when something happens.” That something could be a point in the meter, a chord change, the beginning of a note, the end of a note, a modulation, the return of a motif, every time an A is played, etc. Essentially, whenever you might think a time is interesting :)</p>
<p>Of these, we’re primarily going to focus on the beginning and end of notes today. Since once we’ve sorted that bit out, we have the better part of a musical MVP. It’s not going to be anywhere close to the <a href="/blog/music-overview/">vision</a>, but it’s a necessary step along the path.</p>
<p>So what we’ve built so far is an <code>Event</code> type, which demarks instantaneous and momentary things. We have a <code>Signal</code> type which models things-over-time. It seems likely that in order to play notes we’re going to want a <code>Signal</code> of <code>Event</code>s of something. Let’s say <a href="https://en.wikipedia.org/wiki/MIDI">MIDI notes</a> for now, since it’s an obvious sort of “computer music” interface.</p>
<p>The problem of course is that <code>Event</code>s are instantaneous, but audible things are not; they necessarily have a duration. I played around with data structures in the style of <a href="https://en.wikipedia.org/wiki/Interval_tree">interval trees</a> for a <a href="/blog/more-algebraic-music/">long time</a> before coming to the conclusion that that way lies folly.</p>
<p>Instead what seems to be the play is to explicitly model <code>Span</code>s:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Span</span> a <span class="ot">=</span> <span class="dt">Span</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> duration ::</span> <span class="dt">Time</span></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>  ,<span class="ot"> getSpan ::</span> a</span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a>  }</span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> stock (<span class="dt">Eq</span>, <span class="dt">Ord</span>, <span class="dt">Show</span>, <span class="dt">Functor</span>, <span class="dt">Foldable</span>, <span class="dt">Traversable</span>, <span class="dt">Generic</span>)</span></code></pre></div>
<p>and then just generate them in our <code>Signal</code>. So rather than talk about <code>Event MIDINote</code>, we instead use <code>Event (Span MIDINote)</code>. This is very much in the style of “regular old music scores” where there is <em>explicit syntax</em> for encoding the span of a note:</p>
<figure>
<img src="/images/music3/out1.cropped.png" alt="Rhythmic symbols" /><figcaption aria-hidden="true">Rhythmic symbols</figcaption>
</figure>
<p>If you’re not familiar with music notation, the top line contains (after the funny “c” thing) the symbols for sounded notes. The first symbol takes up one unit of time, the next takes half that, and so on and so forth. The bottom line, in corresponding columns, are the same durations, except for silences rather than for sounded notes.</p>
<p>Anyway, the point here is namely that musicians are very much in the habit of thinking about “how long does this note sound for?” So attaching the <code>Span</code> to the note we want to play isn’t a very far-fetched idea at all.</p>
<p>That being said…</p>
<p>It turns out to be a <em>drag</em> to have to always be sticking durations on things. I suspect the pain is already internalized in some sort of Stockholm Syndrome, because every written notation and every computer program for music requires you to write down the damn durations.</p>
<p>As it happens, writing down the durations in advance is not very compositional. For example, if we stretch the time domain of our <code>Signal</code> (which is very reasonable and possible, since it’s just a function <code>Time -&gt; a</code>), we’d expect the note durations to stretch too! But they can’t, since we’d have the type:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="ot">stretch ::</span> <span class="dt">Rational</span> <span class="ot">-&gt;</span> <span class="dt">Signal</span> a <span class="ot">-&gt;</span> <span class="dt">Signal</span> a</span></code></pre></div>
<p>which you’ll notice is polymorphic in <code>a</code>. Of course, we could do some ad-hoc bullshit where we stick in a typeclass constraint for “stretchable things” but this is the way of madness.</p>
<p>What if, instead, we were to <em>derive</em> the durations? After all, we already know <em>when</em> everything <em>is</em>, temporally-speaking. The first type that comes to mind for something like this would be:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="dt">SF</span> (<span class="dt">Event</span> a)  (<span class="dt">Event</span> (<span class="dt">Span</span> a))</span></code></pre></div>
<p>that is, a function over <code>Signal</code>s, which takes an input stream of events and outputs a stream of events with a duration attached to them. What duration? Presumably until the next event! While this is a perfectly fine type (and isn’t very hard to implement), it has the obvious downside that it can’t represent silence. If a sound spans until the next sound, then there’s nowhere to stick any silence!</p>
<p>What I ended up with was to take <em>two</em> input event streams:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ot">spanning ::</span> <span class="dt">SF</span> (<span class="dt">Event</span> (), <span class="dt">Event</span> a) (<span class="dt">Event</span> (<span class="dt">Span</span> a))</span></code></pre></div>
<p>where the <code>Event ()</code> stream indicates <em>changes</em> and the <code>Event a</code> stream indicates <em>beginnings of notes.</em> Thus a note spans until the next <code>Event a</code> or <code>Event ()</code> — whichever comes first.</p>
<p>The implementation is not very tricky. We use our primitive</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="ot">ev2ev ::</span> ([(<span class="dt">Time</span>, a)] <span class="ot">-&gt;</span> [(<span class="dt">Time</span>, b)]) <span class="ot">-&gt;</span> <span class="dt">SF</span> (<span class="dt">Event</span> a) (<span class="dt">Event</span> b)</span></code></pre></div>
<p>and zip together the events with the tail of the events, taking the difference in their times. All that’s left is to combine the event streams, which is exactly what the <code>Alternative</code> instance on <code>Event</code> does:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="ot">spanning ::</span> <span class="dt">SF</span> (<span class="dt">Event</span> (), <span class="dt">Event</span> a) (<span class="dt">Event</span> (<span class="dt">Span</span> a))</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a>spanning <span class="ot">=</span> proc (end, a) <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> merged <span class="ot">=</span> <span class="dt">Just</span> <span class="op">&lt;$&gt;</span> a <span class="op">&lt;|&gt;</span> <span class="dt">Nothing</span> <span class="op">&lt;$</span> end</span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a>  ev2ev</span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a>    (\es <span class="ot">-&gt;</span> catMaybes</span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true" tabindex="-1"></a>      <span class="op">$</span> <span class="fu">zipWith</span></span>
<span id="cb6-7"><a href="#cb6-7" aria-hidden="true" tabindex="-1"></a>          (\(t1, ema) (t2, _) <span class="ot">-&gt;</span> <span class="kw">case</span> ema <span class="kw">of</span></span>
<span id="cb6-8"><a href="#cb6-8" aria-hidden="true" tabindex="-1"></a>            <span class="dt">Just</span> a <span class="ot">-&gt;</span> <span class="dt">Just</span> (t1, <span class="dt">Span</span> (t2 <span class="op">-</span> t1) a)</span>
<span id="cb6-9"><a href="#cb6-9" aria-hidden="true" tabindex="-1"></a>            <span class="dt">Nothing</span> <span class="ot">-&gt;</span> <span class="dt">Nothing</span></span>
<span id="cb6-10"><a href="#cb6-10" aria-hidden="true" tabindex="-1"></a>          )</span>
<span id="cb6-11"><a href="#cb6-11" aria-hidden="true" tabindex="-1"></a>          es</span>
<span id="cb6-12"><a href="#cb6-12" aria-hidden="true" tabindex="-1"></a>      <span class="op">$</span> <span class="fu">drop</span> <span class="dv">1</span> es</span>
<span id="cb6-13"><a href="#cb6-13" aria-hidden="true" tabindex="-1"></a>    ) <span class="op">-&lt;</span> merged</span></code></pre></div>
<p>I don’t know about you, but I think this is <a href="https://www.youtube.com/watch?v=S1gHv6jdE3E">pretty cool</a>. For two different reasons. The first is that we’ve accidentally just derived the notion of a <a href="https://en.wikipedia.org/wiki/Part_(music)">musical voice</a>, which is to say a logical grouping of musical events into something that could be sung by a person, or played on an instrument. Voices and (most) instruments only make one note at a time, which is exactly the postcondition of <code>spanning</code>.</p>
<p>The other cool thing here is that now we can change note lengths in the same way we can change chords and modulations — namely by doing transformations in <code>SF</code>. You can imagine a <code>Signal Tension</code> which describes how much tension the composer wants you to feel through the journey of the song. By deriving an event stream out of the modulating <code>Tension</code>, where events happen frequently in high tension situations, and less often under low tension, we can automatically <em>drive note durations</em> from our <code>Tension</code> parameter! I haven’t used a lot of DAWs, but my understanding is (and the clankers agree) that almost(?) no DAWs support duration as an automation. So we might be in terra nova over here!</p>
<p>Perhaps you’re starting to get a taste that maybe all of this <a href="/blog/music-overview/">“solving music”</a> isn’t such a pipe dream after all. There’s clearly still a huge distance to travel before we’re anywhere close to anything useful, but the primitives do seem to be pulling their weight.</p>
<p>Of course, nobody wants to call <code>spanning</code> by hand, so next time we’ll see about finding nicer ways of generating horizontal structures.</p>
        ]]>
      </content>
    </entry>
    <entry>
      <title>Musical Signal Functions</title>
      <id>blog/music-arrows/index.html</id>
      <link href='blog/music-arrows/index.html'/>
      <published>2026-11-04T12:42:00Z</published>
      <updated>2026-11-04T12:42:00Z</updated>

      <content type="html" xml:base="https://reasonablypolymorphic.com">
        <![CDATA[
        <p>We’ve been chatting for a few days about my vision for a constructive model of music. So far it’s been rather loosey-goosey; lots of vibes, some semantics, but nothing in the way of implementation. Today let’s get our boots muddy and do enough implementation that we have something concrete to talk about.</p>
<h2 id="events-and-signals">Events and Signals</h2>
<p>In particular, in <a href="/blog/music-signals/">Musical Signals</a> we discussed a <code>Signal</code> type that is a continuous function of time, equipped with a set of interesting times that we actually care about. In addition, we proposed an <code>Event</code> type that we will use in conjunction with <code>Signal</code>s to signify sparse, discrete functions over time.</p>
<p>Let’s begin with <code>Event</code>. It’s just a little newtype wrapper around <code>Maybe</code>:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">Event</span> a <span class="ot">=</span> <span class="dt">MkEvent</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> eventToMaybe ::</span> <span class="dt">Maybe</span> a</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>  }</span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> stock (<span class="dt">Foldable</span>, <span class="dt">Traversable</span>, <span class="dt">Generic</span>)</span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> <span class="kw">newtype</span></span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a>    (<span class="dt">Functor</span>, <span class="dt">Applicative</span>, <span class="dt">Monad</span>, <span class="dt">Eq</span>, <span class="dt">Ord</span>, <span class="dt">Show</span>, <span class="dt">Alternative</span>, <span class="dt">Semigroup</span>, <span class="dt">Monoid</span>)</span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# COMPLETE Event, NoEvent #-}</span></span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a><span class="kw">pattern</span> <span class="dt">Event</span><span class="ot"> ::</span> a <span class="ot">-&gt;</span> <span class="dt">Event</span> a</span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a><span class="kw">pattern</span> <span class="dt">Event</span> a <span class="ot">=</span> <span class="dt">MkEvent</span> (<span class="dt">Just</span> a)</span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a><span class="kw">pattern</span> <span class="dt">NoEvent</span><span class="ot"> ::</span> <span class="dt">Event</span> a</span>
<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a><span class="kw">pattern</span> <span class="dt">NoEvent</span> <span class="ot">=</span> <span class="dt">MkEvent</span> <span class="dt">Nothing</span></span>
<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a><span class="ot">event ::</span> b <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> <span class="dt">Event</span> a <span class="ot">-&gt;</span> b</span>
<span id="cb1-16"><a href="#cb1-16" aria-hidden="true" tabindex="-1"></a>event b f <span class="ot">=</span> <span class="fu">maybe</span> b f <span class="op">.</span> eventToMaybe</span></code></pre></div>
<p>As discussed in the <a href="/blog/music-signals/#fn1">footnote</a> on that page, perhaps we want to not export the <code>Event</code> pattern, the <code>MkEvent</code> constructor, or the <code>Applicative</code>/<code>Monad</code> instances. That seems likely like the way to go, but I haven’t yet put much thought into whether it solves all the problems. So let’s export them for now (because they are genuinely useful!) and circle back at some point in the future.</p>
<p>My idea for implementing <code>Signal</code> is to keep around a bunch of continuous segments of function, each of which might have a time-of-interest at the exact instant that the segment starts. A <code>Segment</code> is defined thusly:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Segment</span> a <span class="ot">=</span> <span class="dt">Segment</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> segVal ::</span> <span class="dt">Maybe</span> a</span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>  ,<span class="ot"> segment ::</span> <span class="dt">Time</span> <span class="ot">-&gt;</span> a</span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- ^ Must be meaningfully defined for the *entirety* of time!</span></span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a>  }</span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> stock <span class="dt">Functor</span></span></code></pre></div>
<p>The obvious <code>Applicative Segment</code> instance has the wrong semantics here, so we don’t provide it. The problem being that <code>segVal</code> corresponds to a value of the function at a time of interest. Which is to say, that if <code>segVal</code> is ever <code>Just</code>, it must <em>remain</em> <code>Just</code> as we <code>ap</code> our way through it! But <code>Applicative</code> isn’t powerful enough to do that, because filling in the missing data would require us to know what <code>Time</code> we should be sampling the function at.</p>
<p>We address the problem with a new <code>combine</code> function:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- | Like &#39;liftA2&#39; for &#39;Segment&#39;, when we have a concrete time to sample at.</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="ot">combine ::</span> <span class="dt">Time</span> <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> c) <span class="ot">-&gt;</span> <span class="dt">Segment</span> a <span class="ot">-&gt;</span> <span class="dt">Segment</span> b <span class="ot">-&gt;</span> <span class="dt">Segment</span> c</span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a>combine t f (<span class="dt">Segment</span> a fa) (<span class="dt">Segment</span> b fb) <span class="ot">=</span></span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Segment</span></span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a>    ( asum</span>
<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a>       [ liftA2 f a b</span>
<span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a>       , <span class="fu">fmap</span> (f (fa t)) b</span>
<span id="cb3-8"><a href="#cb3-8" aria-hidden="true" tabindex="-1"></a>       , <span class="fu">fmap</span> (<span class="fu">flip</span> f (fb t)) a</span>
<span id="cb3-9"><a href="#cb3-9" aria-hidden="true" tabindex="-1"></a>       ])</span>
<span id="cb3-10"><a href="#cb3-10" aria-hidden="true" tabindex="-1"></a>    (liftA2 f fa fb)</span></code></pre></div>
<p>The <code>asum</code> here attempts to fill in the interesting value by combining the <code>Maybe</code>s. If that fails, it then tries to fill it in by fmapping over either individual interesting value.</p>
<p>Collecting our <code>Segment</code>s into a <code>Signal</code> requires a few helper functions: <code>merge</code> takes two sorted lists of pairs, and computes a sorted list of <a href="https://hackage.haskell.org/package/strict-0.5.1/docs/Data-Strict-These.html#t:These"><code>These</code></a>. The idea being that if both lists have a key at the same index, we keep both of them around. If only one has a value, we tag it with which list it came from:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- | Specialized &#39;Data.Align.align&#39; for sorted pairs.</span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a><span class="ot">merge ::</span> <span class="dt">Ord</span> a <span class="ot">=&gt;</span> [(a, b)] <span class="ot">-&gt;</span> [(a, c)] <span class="ot">-&gt;</span> [(a, <span class="dt">These</span> b c)]</span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>merge [] ys       <span class="ot">=</span> <span class="fu">fmap</span> (<span class="fu">fmap</span> <span class="dt">That</span>) ys</span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a>merge (x <span class="op">:</span> xs) [] <span class="ot">=</span> <span class="fu">fmap</span> (<span class="fu">fmap</span> <span class="dt">This</span>) (x <span class="op">:</span> xs)</span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a>merge xx<span class="op">@</span>((tx, x) <span class="op">:</span> xs) yy<span class="op">@</span>((ty, y) <span class="op">:</span> ys) <span class="ot">=</span></span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a>  <span class="kw">case</span> <span class="fu">compare</span> tx ty <span class="kw">of</span></span>
<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a>    <span class="dt">LT</span> <span class="ot">-&gt;</span> (tx, <span class="dt">This</span> x) <span class="op">:</span> merge xs yy</span>
<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a>    <span class="dt">GT</span> <span class="ot">-&gt;</span> (ty, <span class="dt">That</span> y) <span class="op">:</span> merge xx ys</span>
<span id="cb4-9"><a href="#cb4-9" aria-hidden="true" tabindex="-1"></a>    <span class="dt">EQ</span> <span class="ot">-&gt;</span> (tx, <span class="dt">These</span> x y) <span class="op">:</span> merge xs ys</span></code></pre></div>
<p>We use <code>merge</code> to define <code>joining</code>, which does a <code>scanl</code> of two sorted lists of <code>Segment</code>s. The idea here is that the two lists are effectively interval trees, and the intervals are not guaranteed to line up. So we use a <code>scanl</code> hold onto the old value of each until it gets replaced with a new value.</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a>joining</span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a><span class="ot">    ::</span> <span class="dt">Ord</span> a</span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=&gt;</span> <span class="dt">Segment</span> b</span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> <span class="dt">Segment</span> c</span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> [(a, <span class="dt">Segment</span> b)]</span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> [(a, <span class="dt">Segment</span> c)]</span>
<span id="cb5-7"><a href="#cb5-7" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> [(a, (<span class="dt">Segment</span> b, <span class="dt">Segment</span> c))]</span>
<span id="cb5-8"><a href="#cb5-8" aria-hidden="true" tabindex="-1"></a>joining a0 b0 as bs</span>
<span id="cb5-9"><a href="#cb5-9" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=</span> <span class="fu">drop</span> <span class="dv">1</span></span>
<span id="cb5-10"><a href="#cb5-10" aria-hidden="true" tabindex="-1"></a>  <span class="op">$</span> <span class="fu">scanl</span></span>
<span id="cb5-11"><a href="#cb5-11" aria-hidden="true" tabindex="-1"></a>    (\(_, (a, b)) (t, th) <span class="ot">-&gt;</span></span>
<span id="cb5-12"><a href="#cb5-12" aria-hidden="true" tabindex="-1"></a>      <span class="kw">case</span> th <span class="kw">of</span></span>
<span id="cb5-13"><a href="#cb5-13" aria-hidden="true" tabindex="-1"></a>        <span class="dt">This</span> a&#39;     <span class="ot">-&gt;</span> (t, (a&#39;, open b))</span>
<span id="cb5-14"><a href="#cb5-14" aria-hidden="true" tabindex="-1"></a>        <span class="dt">That</span> b&#39;     <span class="ot">-&gt;</span> (t, (open a, b&#39;))</span>
<span id="cb5-15"><a href="#cb5-15" aria-hidden="true" tabindex="-1"></a>        <span class="dt">These</span> a&#39; b&#39; <span class="ot">-&gt;</span> (t, (a&#39;, b&#39;))</span>
<span id="cb5-16"><a href="#cb5-16" aria-hidden="true" tabindex="-1"></a>    )</span>
<span id="cb5-17"><a href="#cb5-17" aria-hidden="true" tabindex="-1"></a>    ( <span class="fu">error</span> <span class="st">&quot;unused initial time argument&quot;</span></span>
<span id="cb5-18"><a href="#cb5-18" aria-hidden="true" tabindex="-1"></a>    , (a0, b0)</span>
<span id="cb5-19"><a href="#cb5-19" aria-hidden="true" tabindex="-1"></a>    )</span>
<span id="cb5-20"><a href="#cb5-20" aria-hidden="true" tabindex="-1"></a>  <span class="op">$</span> merge as bs</span>
<span id="cb5-21"><a href="#cb5-21" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb5-22"><a href="#cb5-22" aria-hidden="true" tabindex="-1"></a><span class="ot">open ::</span> <span class="dt">Segment</span> a <span class="ot">-&gt;</span> <span class="dt">Segment</span> a</span>
<span id="cb5-23"><a href="#cb5-23" aria-hidden="true" tabindex="-1"></a>open s <span class="ot">=</span> s { segVal <span class="ot">=</span> <span class="dt">Nothing</span> }</span></code></pre></div>
<p>With all that ceremony out of the way, we’re ready to define <code>Signal</code>s, which contain an original <code>Time -&gt; a</code> function with no interesting timepoints, and then a sorted list of new <code>Segment</code>s.</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- | A piecewise function, built out of &#39;Segment&#39; intervals.</span></span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Signal</span> a</span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=</span> <span class="dt">Signal</span></span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a>      (<span class="dt">Time</span> <span class="ot">-&gt;</span> a)</span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a>      <span class="co">-- ^ The function before we have switched to any &#39;Segment&#39;.</span></span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true" tabindex="-1"></a>      [(<span class="dt">Time</span>, <span class="dt">Segment</span> a)]</span>
<span id="cb6-7"><a href="#cb6-7" aria-hidden="true" tabindex="-1"></a>      <span class="co">-- ^ Sorted by time.</span></span>
<span id="cb6-8"><a href="#cb6-8" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> stock <span class="dt">Functor</span></span></code></pre></div>
<p>Of course, this is not the only possible implementation of <code>Signal</code>, nor am I claiming it’s the best one. It’s just one that I came up with that satisfied all the laws and wasn’t slower than molasses. I’ve also got a relatively-fresh new baby, so a lot of this got written on very little sleep. Anyway…</p>
<p>Despite <code>Segment</code> not admitting an <code>Applicative</code> instance, <code>Signal</code> does, because it keeps track of where each <code>Segment</code> begins.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Applicative</span> <span class="dt">Signal</span> <span class="kw">where</span></span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">pure</span> a <span class="ot">=</span> <span class="dt">Signal</span> (<span class="fu">pure</span> a) <span class="fu">mempty</span></span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a>  liftA2 f (<span class="dt">Signal</span> a as) (<span class="dt">Signal</span> b bs)</span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=</span> <span class="dt">Signal</span> (liftA2 f a b)</span>
<span id="cb7-5"><a href="#cb7-5" aria-hidden="true" tabindex="-1"></a>    <span class="op">$</span> <span class="fu">fmap</span> (<span class="fu">uncurry</span> <span class="op">$</span> \t <span class="ot">-&gt;</span> (t,) <span class="op">.</span> <span class="fu">uncurry</span> (combine t f))</span>
<span id="cb7-6"><a href="#cb7-6" aria-hidden="true" tabindex="-1"></a>    <span class="op">$</span> joining (<span class="dt">Segment</span> <span class="dt">Nothing</span> a) (<span class="dt">Segment</span> <span class="dt">Nothing</span> b) as bs</span></code></pre></div>
<p>We can show that <code>Signal</code> preserves the <a href="/blog/music-signals/">semantics we gave</a> by giving projections out of it into the semantic domain:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="ot">sample ::</span> <span class="dt">Signal</span> a <span class="ot">-&gt;</span> (<span class="dt">Time</span> <span class="ot">-&gt;</span> a)</span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>sample (<span class="dt">Signal</span> fa []) t <span class="ot">=</span> fa t</span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a>sample (<span class="dt">Signal</span> fa ((t0, sa) <span class="op">:</span> as)) t <span class="ot">=</span></span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">case</span> <span class="fu">compare</span> t t0 <span class="kw">of</span></span>
<span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a>    <span class="dt">LT</span> <span class="ot">-&gt;</span> fa t</span>
<span id="cb8-6"><a href="#cb8-6" aria-hidden="true" tabindex="-1"></a>    <span class="dt">EQ</span> <span class="ot">-&gt;</span></span>
<span id="cb8-7"><a href="#cb8-7" aria-hidden="true" tabindex="-1"></a>      <span class="kw">case</span> sa <span class="kw">of</span></span>
<span id="cb8-8"><a href="#cb8-8" aria-hidden="true" tabindex="-1"></a>        <span class="dt">Segment</span> <span class="dt">Nothing</span> f <span class="ot">-&gt;</span> f t</span>
<span id="cb8-9"><a href="#cb8-9" aria-hidden="true" tabindex="-1"></a>        <span class="dt">Segment</span> (<span class="dt">Just</span> a) _ <span class="ot">-&gt;</span> a</span>
<span id="cb8-10"><a href="#cb8-10" aria-hidden="true" tabindex="-1"></a>    <span class="dt">GT</span> <span class="ot">-&gt;</span> sample (<span class="dt">Signal</span> (segment sa) as) t</span></code></pre></div>
<p>This function is the continuous-<code>μ</code> given by our semantics. The discrete-<code>μ</code> is called <code>values</code>:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="ot">values ::</span> <span class="dt">Signal</span> a <span class="ot">-&gt;</span> [(<span class="dt">Time</span>, a)]</span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a>values (<span class="dt">Signal</span> _ as) <span class="ot">=</span> mapMaybe (<span class="fu">traverse</span> segVal) as</span></code></pre></div>
<p>which returns a sorted list of interesting times (and their associated values.) In the <code>Signal (Event a)</code> case, we have a more useful function, which gets only those values which <em>actually contain a discrete value</em>:</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="ot">events ::</span> <span class="dt">Signal</span> (<span class="dt">Event</span> a) <span class="ot">-&gt;</span> [(<span class="dt">Time</span>, a)]</span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a>events <span class="ot">=</span> mapMaybe (<span class="fu">traverse</span> eventToMaybe) <span class="op">.</span> values</span></code></pre></div>
<h2 id="arrows">Arrows</h2>
<p><code>Signal</code>s are nice representations of interesting-things-over-time. But the mental model of <a href="/blog/musical-vision/">abstract modular synthesizers</a> is not about interesting-things-over-time. It’s about ways of <em>transforming and combining</em> interesting-things-over-time.</p>
<p>Haskell has some deep-cut notation for this, namely the <code>-XArrows</code> extension and its related <code>proc</code> notation. Long-time readers of the blog will know that we’re <a href="/blog/arrowized-frp/">no</a> <a href="/blog/arrows-to-arrows/">strangers</a> to <a href="/blog/reviewing-again/">arrows</a> here!</p>
<p>But as a <em>very</em> quick recap, given instances of <code>Category</code> and <code>Arrow</code>:</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> <span class="dt">Category</span> a <span class="kw">where</span></span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  id  ::</span> a x x</span>
<span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a><span class="ot">  (.) ::</span> a y z <span class="ot">-&gt;</span> a x y <span class="ot">-&gt;</span> a x z</span>
<span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-5"><a href="#cb11-5" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> <span class="dt">Category</span> a <span class="ot">=&gt;</span> <span class="dt">Arrow</span> a <span class="kw">where</span></span>
<span id="cb11-6"><a href="#cb11-6" aria-hidden="true" tabindex="-1"></a><span class="ot">  arr   ::</span> (b <span class="ot">-&gt;</span> c) <span class="ot">-&gt;</span> a b c</span>
<span id="cb11-7"><a href="#cb11-7" aria-hidden="true" tabindex="-1"></a><span class="ot">  (***) ::</span> a b c <span class="ot">-&gt;</span> a b&#39; c&#39; <span class="ot">-&gt;</span> a (b, b&#39;) (c, c&#39;)</span></code></pre></div>
<p>we gain access to <code>proc</code> notation, which is very convenient for composing arrow values:</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a>proc input <span class="ot">-&gt;</span></span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a> a <span class="ot">&lt;-</span> foo <span class="op">-&lt;</span> input</span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a> b <span class="ot">&lt;-</span> bar <span class="op">-&lt;</span> (input, a)</span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> output <span class="ot">=</span> qux a b</span>
<span id="cb12-5"><a href="#cb12-5" aria-hidden="true" tabindex="-1"></a> returnA <span class="op">-&lt;</span> output</span></code></pre></div>
<p>This notation is syntactic sugar for the egregious:</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a>  arr qux</span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a><span class="op">.</span> <span class="fu">id</span> <span class="op">***</span> bar</span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a><span class="op">.</span> arr (\i <span class="ot">-&gt;</span> (<span class="fu">snd</span> i, i))</span>
<span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a><span class="op">.</span> <span class="fu">id</span> <span class="op">***</span> foo</span>
<span id="cb13-5"><a href="#cb13-5" aria-hidden="true" tabindex="-1"></a><span class="op">.</span> arr (\i <span class="ot">-&gt;</span> (i, i))</span></code></pre></div>
<p>which I think we can all agree is <em>slightly</em> less readable than the <code>proc</code> notation.</p>
<p>The rough vibes here is that <code>Category a</code> abstracts the notion of what a function is. Rather than using Haskell <code>-&gt;</code> arrows, we can instead use <code>a</code>-arrows. The <code>Category</code> methods <code>(.)</code> and <code>id</code> do exactly what you’d expect — composition and identity of <code>a</code>-arrows.</p>
<p>The <code>Arrow a</code> class extends this with some way of turning arbitrary Haskell arrows into <code>a</code>-arrows, as well as a way to run two different <code>a</code>-arrows on the <code>fst</code> and <code>snd</code> of a (Haskell) product type. The exact semantics of what that looks like depends on your <code>a</code>-arrow type (much like the exact semantics of <code>do</code> notation depend on your choice of a monad!)</p>
<p>Anyway, to pull back to musical transformations. If we were to find some sort of music-aware <code>Arrow</code> instance, <code>proc</code>-notation is exactly what we’d want in order to “run patches” in our abstract modular synthesizer. That is to say, it provides the plumbing for moving music in and out of transformations. As a teaser for what’s to come, here’s a little example from my sandbox:</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- A horizontal pattern describing an unfolding dyadic voice-leading that</span></span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a><span class="co">-- descends by fifth, before swapping the voices by moving away from one</span></span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a><span class="co">-- another.</span></span>
<span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a>divergence <span class="ot">=</span> replicateH <span class="dv">12</span> <span class="op">$</span> <span class="fu">foldMap</span> dnote</span>
<span id="cb14-5"><a href="#cb14-5" aria-hidden="true" tabindex="-1"></a>  [ voiceLead <span class="dv">0</span> <span class="dv">3</span></span>
<span id="cb14-6"><a href="#cb14-6" aria-hidden="true" tabindex="-1"></a>  , expand <span class="dv">0</span> <span class="dv">1</span></span>
<span id="cb14-7"><a href="#cb14-7" aria-hidden="true" tabindex="-1"></a>  ]</span>
<span id="cb14-8"><a href="#cb14-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb14-9"><a href="#cb14-9" aria-hidden="true" tabindex="-1"></a>song <span class="ot">=</span> horizontal <span class="op">$</span> resize <span class="fl">0.25</span> <span class="op">$</span> proc i <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb14-10"><a href="#cb14-10" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Compute an abstract voice leading over time</span></span>
<span id="cb14-11"><a href="#cb14-11" aria-hidden="true" tabindex="-1"></a>  vl <span class="ot">&lt;-</span> liftH msumE <span class="op">&lt;&lt;&lt;</span> divergence <span class="op">-&lt;</span> i</span>
<span id="cb14-12"><a href="#cb14-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb14-13"><a href="#cb14-13" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Apply that voice leading to the first two notes of a triad</span></span>
<span id="cb14-14"><a href="#cb14-14" aria-hidden="true" tabindex="-1"></a>  ns <span class="ot">&lt;-</span> replicateH <span class="dv">12</span> <span class="op">$</span> with <span class="fu">id</span> <span class="op">-&lt;</span> applyVoiceLeading vl <span class="op">$</span> chord triad</span>
<span id="cb14-15"><a href="#cb14-15" aria-hidden="true" tabindex="-1"></a>  returnA <span class="op">-&lt;</span> ns</span></code></pre></div>
<p>which describes this this nice little dyad expansion:</p>
<figure>
<img src="/images/music2/out1.cropped.png" alt="Dyad Expansion" /><figcaption aria-hidden="true">Dyad Expansion</figcaption>
</figure>
<p>If we replace the last line with:</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Convert the &quot;polyphony&quot; into &quot;counterpoint&quot;</span></span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> (lo <span class="op">:&gt;</span> hi <span class="op">:&gt;</span> <span class="dt">Nil</span>) <span class="ot">=</span> toV ns</span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Clamp the lo voice so it stays within its register</span></span>
<span id="cb15-5"><a href="#cb15-5" aria-hidden="true" tabindex="-1"></a>  lo&#39; <span class="ot">&lt;-</span> liftH <span class="op">$</span> clampOctave (<span class="op">-</span><span class="dv">9</span>, <span class="dv">0</span>) <span class="fl">0.5</span> <span class="op">-&lt;</span> lo</span>
<span id="cb15-6"><a href="#cb15-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb15-7"><a href="#cb15-7" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Convert the &quot;counterpoint&quot; back into &quot;polyphony&quot;</span></span>
<span id="cb15-8"><a href="#cb15-8" aria-hidden="true" tabindex="-1"></a>  returnA <span class="op">-&lt;</span> fromV <span class="op">$</span> lo&#39; <span class="op">:&gt;</span> hi <span class="op">:&gt;</span> <span class="dt">Nil</span></span></code></pre></div>
<p>we get this:</p>
<figure>
<img src="/images/music2/out2.cropped.png" alt="Clamped Dyad Expansion" /><figcaption aria-hidden="true">Clamped Dyad Expansion</figcaption>
</figure>
<p>and of course we can also clamp the upper voice:</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Clamp the voices so they stay within their registers</span></span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a>  lo&#39; <span class="ot">&lt;-</span> liftH <span class="op">$</span> clampOctave (<span class="op">-</span><span class="dv">9</span>, <span class="dv">0</span>) <span class="fl">0.5</span> <span class="op">-&lt;</span> lo</span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a>  hi&#39; <span class="ot">&lt;-</span> liftH <span class="op">$</span> clampOctave (<span class="dv">0</span>, <span class="dv">7</span>) <span class="fl">0.5</span> <span class="op">-&lt;</span> hi</span>
<span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb16-5"><a href="#cb16-5" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Convert the &quot;counterpoint&quot; back into &quot;polyphony&quot;</span></span>
<span id="cb16-6"><a href="#cb16-6" aria-hidden="true" tabindex="-1"></a>  returnA <span class="op">-&lt;</span> fromV <span class="op">$</span> lo&#39; <span class="op">:&gt;</span> hi&#39; <span class="op">:&gt;</span> <span class="dt">Nil</span></span></code></pre></div>
<p>and we get this:</p>
<figure>
<img src="/images/music2/out3.cropped.png" alt="Doubly-Clamped Dyad Expansion" /><figcaption aria-hidden="true">Doubly-Clamped Dyad Expansion</figcaption>
</figure>
<p>Now I’ll be the first to admit that this is a completely unusable DSL. But it does actually work! And if you squint, you can sort of see the modular synthesizer idea at play. Inside the proc notation, we are sampling all of our <code>Signal</code>s simultaneously, but routing the output of (eg) the voice leading into the input of <code>replicateH $ with id</code>, which is what builds out the rhythmic pattern. Then we take the output of that, separate it into <code>Signal</code>s of its constituent voices, and feed those into <code>clampOctave</code>, which moves a <code>Signal</code>’s notes into the given range of scale degrees.</p>
<p>Something cool but not pictured here, <code>clampOctave</code> takes a second argument (the <code>0.5</code>) which tells it to look <em>into the future</em> and not perform any displacement if it would need to move again within that 0.5 of a measure. This is some sort of “retro-hysteresis” where signals can depend on their future values! Which sounds crazy when you’re thinking about wiring up synthesizers, but much less crazy when you’re sitting down writing out a score. Of course the notes in your score can depend on notes that happen later on in the song! One of the many benefits of <em>explicitly modeling time</em> in <code>Signal</code>s.</p>
<h2 id="signal-functions">Signal Functions</h2>
<p>Hopefully you’re excited to see how we go about doing any of this acausal wizardry stuff. But it all starts from getting <code>proc</code> notation working. Which, recall, means we need a type to give an <code>Arrow</code> instance to.</p>
<p>Behold, the signal function (<code>SF</code>):</p>
<div class="sourceCode" id="cb17"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">SF</span> a b <span class="ot">=</span> <span class="dt">SF</span></span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> runSF ::</span> <span class="dt">Signal</span> a <span class="ot">-&gt;</span> <span class="dt">Signal</span> b</span>
<span id="cb17-3"><a href="#cb17-3" aria-hidden="true" tabindex="-1"></a>  }</span>
<span id="cb17-4"><a href="#cb17-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> (<span class="dt">Functor</span>, <span class="dt">Applicative</span>) via <span class="dt">WrappedArrow</span> <span class="dt">SF</span> a</span>
<span id="cb17-5"><a href="#cb17-5" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> (<span class="dt">Semigroup</span>, <span class="dt">Monoid</span>) via <span class="dt">Ap</span> (<span class="dt">SF</span> a) b</span></code></pre></div>
<p>which you will note is <em>literally a function between <code>Signal</code>s.</em> Its <code>Category</code> instance comes immediately from Haskell functions’ instance:</p>
<div class="sourceCode" id="cb18"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Category</span> <span class="dt">SF</span> <span class="kw">where</span></span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">id</span> <span class="ot">=</span> <span class="dt">SF</span> <span class="fu">id</span></span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a>  <span class="dt">SF</span> g <span class="op">.</span> <span class="dt">SF</span> f <span class="ot">=</span> <span class="dt">SF</span> (g <span class="op">.</span> f)</span></code></pre></div>
<p>The <code>Arrow</code> instance is similarly straightforward — separate out the product, run the functions on each half, then use the applicative instance to combine them back into a single <code>Signal</code>:</p>
<div class="sourceCode" id="cb19"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Arrow</span> <span class="dt">SF</span> <span class="kw">where</span></span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a>  arr <span class="ot">=</span> <span class="dt">SF</span> <span class="op">.</span> <span class="fu">fmap</span></span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a>  <span class="dt">SF</span> f <span class="op">***</span> <span class="dt">SF</span> g <span class="ot">=</span> <span class="dt">SF</span> <span class="op">$</span> \sg <span class="ot">-&gt;</span></span>
<span id="cb19-4"><a href="#cb19-4" aria-hidden="true" tabindex="-1"></a>    liftA2 (,) (f <span class="op">$</span> <span class="fu">fmap</span> <span class="fu">fst</span> sg) (g <span class="op">$</span> <span class="fu">fmap</span> <span class="fu">snd</span> sg)</span></code></pre></div>
<p>That’s really all there is to it! We can give some means of introducing <code>SF</code>s:</p>
<div class="sourceCode" id="cb20"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="ot">constS ::</span> <span class="dt">Signal</span> a <span class="ot">-&gt;</span> <span class="dt">SF</span> x a</span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a>constS <span class="ot">=</span> <span class="dt">SF</span> <span class="op">.</span> <span class="fu">const</span></span></code></pre></div>
<p>as well as a few primitives whose definition we don’t have time to get into:</p>
<div class="sourceCode" id="cb21"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- | Create a single occurrence of an Event at the given time.</span></span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a><span class="ot">at ::</span> <span class="dt">Time</span> <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">SF</span> x (<span class="dt">Event</span> a)</span>
<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-4"><a href="#cb21-4" aria-hidden="true" tabindex="-1"></a><span class="co">-- | Convert a discrete stream into a continuous one, by holding the value of</span></span>
<span id="cb21-5"><a href="#cb21-5" aria-hidden="true" tabindex="-1"></a><span class="co">-- the last event seen.</span></span>
<span id="cb21-6"><a href="#cb21-6" aria-hidden="true" tabindex="-1"></a><span class="ot">hold ::</span> a <span class="ot">-&gt;</span> <span class="dt">SF</span> (<span class="dt">Event</span> a) a</span>
<span id="cb21-7"><a href="#cb21-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-8"><a href="#cb21-8" aria-hidden="true" tabindex="-1"></a><span class="co">-- | Like &#39;hold&#39;, but backwards in time. Hold the value of the /next/ event that</span></span>
<span id="cb21-9"><a href="#cb21-9" aria-hidden="true" tabindex="-1"></a><span class="co">-- will occur.</span></span>
<span id="cb21-10"><a href="#cb21-10" aria-hidden="true" tabindex="-1"></a><span class="ot">fhold ::</span> a <span class="ot">-&gt;</span> <span class="dt">SF</span> (<span class="dt">Event</span> a) a</span>
<span id="cb21-11"><a href="#cb21-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-12"><a href="#cb21-12" aria-hidden="true" tabindex="-1"></a><span class="co">-- | Stateful folds over Events</span></span>
<span id="cb21-13"><a href="#cb21-13" aria-hidden="true" tabindex="-1"></a><span class="ot">scanE ::</span> (s <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> (s, b)) <span class="ot">-&gt;</span> s <span class="ot">-&gt;</span> <span class="dt">SF</span> (<span class="dt">Event</span> a) (<span class="dt">Event</span> b)</span>
<span id="cb21-14"><a href="#cb21-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-15"><a href="#cb21-15" aria-hidden="true" tabindex="-1"></a><span class="co">-- | Full-scale rewrites of Event streams</span></span>
<span id="cb21-16"><a href="#cb21-16" aria-hidden="true" tabindex="-1"></a><span class="ot">ev2ev ::</span> ([(<span class="dt">Time</span>, a)] <span class="ot">-&gt;</span> [(<span class="dt">Time</span>, b)]) <span class="ot">-&gt;</span> <span class="dt">SF</span> (<span class="dt">Event</span> a) (<span class="dt">Event</span> b)</span>
<span id="cb21-17"><a href="#cb21-17" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-18"><a href="#cb21-18" aria-hidden="true" tabindex="-1"></a><span class="co">-- | Run the first SF until the &#39;Event&#39; occurs, then switch into the</span></span>
<span id="cb21-19"><a href="#cb21-19" aria-hidden="true" tabindex="-1"></a><span class="co">-- continuation.</span></span>
<span id="cb21-20"><a href="#cb21-20" aria-hidden="true" tabindex="-1"></a><span class="ot">switch ::</span> <span class="dt">SF</span> a (b, <span class="dt">Event</span> c) <span class="ot">-&gt;</span> (c <span class="ot">-&gt;</span> <span class="dt">SF</span> a b) <span class="ot">-&gt;</span> <span class="dt">SF</span> a b</span></code></pre></div>
<p>(for completeness’ sake, there ought to be time-reverse versions of <code>scanE</code> and <code>switch</code> too!)</p>
<p>This seems like a good place to leave it for now. In the next post we’ll discuss how to turn all of this abstract machinery into something that actually resembles music.</p>
        ]]>
      </content>
    </entry>
    <entry>
      <title>What Composing Music Could Look Like</title>
      <id>blog/musical-vision/index.html</id>
      <link href='blog/musical-vision/index.html'/>
      <published>2026-11-03T15:30:00Z</published>
      <updated>2026-11-03T15:30:00Z</updated>

      <content type="html" xml:base="https://reasonablypolymorphic.com">
        <![CDATA[
        <p>In the last post, we discussed the <a href="/blog/music-signals/">algebraic structure of horizontal structures</a>. But I realized I haven’t actually communicated the argument behind <em>why we might care</em> about that algebraic structure. So rather than diving directly into the technical stuff I had planned for today, let’s hash that out first.</p>
<p>If you recall, where we ended up was an abstract type <code>Signal a</code> which I claim is a precursor to horizontal musical structures, with the following common algebras:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Signal</span> a</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Functor</span> <span class="dt">Signal</span></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Applicative</span> <span class="dt">Signal</span></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Foldable</span> <span class="dt">Signal</span></span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Semigroup</span> a <span class="ot">=&gt;</span> <span class="dt">Semigroup</span> (<span class="dt">Signal</span> a)</span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Semigroup</span> a <span class="ot">=&gt;</span> <span class="dt">Monoid</span> (<span class="dt">Signal</span> a)</span></code></pre></div>
<p>It’s worth considering what each of these ideas means, musically. And once we’ve sorted that out, it’s worth thinking about what other musical structure we might want on top.</p>
<p>We can think about a <code>Signal a</code> as being a continuous function of <code>a</code>s over time, combined with a set of times that we’re <em>actually interested in.</em> So what exactly does that mean? The continuous function part is just there to fill in the details when we change our minds about what times we want to look at.</p>
<p>With our <code>Functor</code> instance, we can do per-note (or per-whatever is held in the horizontal structure) transformations. For example, <code>fmap (+ 1)</code> transforms</p>
<figure>
<img src="/images/music1/out1.cropped.png" alt="C-D-E-F" /><figcaption aria-hidden="true">C-D-E-F</figcaption>
</figure>
<p>into</p>
<figure>
<img src="/images/music1/out2.cropped.png" alt="D-E-F-G" /><figcaption aria-hidden="true">D-E-F-G</figcaption>
</figure>
<p>But it also does more interesting things; <code>fmap (!! 1)</code> (where <code>!! n</code> selects voice <code>n</code>) transforms</p>
<figure>
<img src="/images/music1/out3.cropped.png" alt="Inversions of C" /><figcaption aria-hidden="true">Inversions of C</figcaption>
</figure>
<p>into</p>
<figure>
<img src="/images/music1/out4.cropped.png" alt="E-G-C-E" /><figcaption aria-hidden="true">E-G-C-E</figcaption>
</figure>
<p>Furthermore, nobody says the <code>a</code> in <code>Signal a</code> need be something that is musically meaningful. A <code>Signal</code> is just a function from time to something; so we could do something crazy like building a <code>Signal DayName</code> that is a week-long signal moving from <code>Monday</code> to <code>Sunday</code> at a rate of one a day. We could then use the <code>Functor</code> instance to transform these labels into something more musically meaningful — perhaps into motifs or numbers of repeats, or something like that.</p>
<p>Our <code>Semigroup</code> instance gives us a <code>&lt;&gt;</code> operation, which combines things that happen at the same time. What it means to “combine things” depends on the things being combined. But as a little vibe check, we can use <code>&lt;&gt;</code> to smush together two little motifs:</p>
<figure>
<img src="/images/music1/out5.cropped.png" alt="C-x-E-x" /><figcaption aria-hidden="true">C-x-E-x</figcaption>
</figure>
<figure>
<img src="/images/music1/out6.cropped.png" alt="C-F-G-x" /><figcaption aria-hidden="true">C-F-G-x</figcaption>
</figure>
<p>into</p>
<figure>
<img src="/images/music1/out7.cropped.png" alt="C-F-EG-x" /><figcaption aria-hidden="true">C-F-EG-x</figcaption>
</figure>
<p>This example one is very vibes, so don’t read TOO much into it. The important part is that “things that happen at the same time get smushed together.” We’ll discuss in MUCH MORE DETAIL sometime in the future what sorts of smushing might be musically meaningful.</p>
<p>The <code>Applicative</code> structure is very similar to the <code>Semigroup</code>, except that instead of smushing things together, we can run a function that depends on the values in both things. This one is unfortunately impossible to show in standard musical notation, and wiring up some custom visualization isn’t a good use of my nanowrimo time.</p>
<p>But let’s use our IMAGINATION instead. Imagine a voice-leading that looks like this (realized over a C-major triad):</p>
<figure>
<img src="/images/music1/out8.cropped.png" alt="Abstract voice leading" /><figcaption aria-hidden="true">Abstract voice leading</figcaption>
</figure>
<p>We can use our applicative instance to retarget the voice leading over any other chord. For example, given this one:</p>
<figure>
<img src="/images/music1/out9.cropped.png" alt="C-D-B" /><figcaption aria-hidden="true">C-D-B</figcaption>
</figure>
<p>Invoking <code>liftA2 applyVoiceLeading</code> over these two musical pieces gives us this remarkable chord progression:</p>
<figure>
<img src="/images/music1/out10.cropped.png" alt="Something odd" /><figcaption aria-hidden="true">Something odd</figcaption>
</figure>
<p>If you’re familiar with lots of harmony, you can see that both progressions are structurally equivalent — a <a href="https://en.wikipedia.org/wiki/Neo-Riemannian_theory#Triadic_transformations_and_voice_leading">neo-Riemannian P transform</a>, followed by an efficient voice leading from CM to E#M, followed by the outer two voices switching pitch classes by moving in opposite directions.<a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a></p>
<p>Of course, nothing requires us to use the <em>same</em> chord throughout. We can apply our same voice leading pattern to a series of changing chords, for example:</p>
<figure>
<img src="/images/music1/out11.cropped.png" alt="Changing chords" /><figcaption aria-hidden="true">Changing chords</figcaption>
</figure>
<p>which results in</p>
<figure>
<img src="/images/music1/out12.cropped.png" alt="Voice leading over changing chords" /><figcaption aria-hidden="true">Voice leading over changing chords</figcaption>
</figure>
<p>You’ll notice we’re getting <em>very interesting</em> results without doing much work at all. I picked some random voice leadings and some random chords, and the computer did all of the work of figuring out what notes I’m gesturing at.</p>
<p>Some other things you could do with this: instead of voice leadings, put scalar modulations. Or note durations! Or put voice numberings and project chords down to individual voices (which is different than the functor case, because here we can <em>change</em> which voice gets to sound.) Better yet, do all of the above, continuously, at different time scales.</p>
<p>What I think this ends up looking like in practice is something akin to a modular synthesizer. You can plug the outputs of different signals into the inputs of others. But unlike any modular synthesizer you’ve ever played with, here our signals are allowed to carry macroharmonies, voice leadings, modulations, tension, motifs, rhythm, registral expansion, dynamics, timbre, or even just arbitrary mathematical functions.</p>
<p>That’s probably enough for now. In the next post we’ll actually get around to looking at the implementation of <code>Signal</code> and then giving better composable semantics around it.</p>
<section class="footnotes" role="doc-endnotes">
<hr />
<ol>
<li id="fn1" role="doc-endnote"><p>I extracted all the moves here from Tymoczko’s masterpiece <a href="https://dmitri.mycpanel.princeton.edu/tonality-an-owners-manual.html">Tonality: An Owner’s Manual</a>.<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</section>
        ]]>
      </content>
    </entry>
    <entry>
      <title>Musical Signals</title>
      <id>blog/music-signals/index.html</id>
      <link href='blog/music-signals/index.html'/>
      <published>2026-11-03T05:01:00Z</published>
      <updated>2026-11-03T05:01:00Z</updated>

      <content type="html" xml:base="https://reasonablypolymorphic.com">
        <![CDATA[
        <p>The <a href="/blog/music-overview/">last blog</a> post served as an overview of my music project — what it is, why it is, and roughly what success will look like. Today we’ll get into some of the nitty gritty details that will help put the project onto a firm footing.</p>
<p>In order to have any chance of <a href="https://www.youtube.com/watch?v=rlyqoYoUumc">not confusing ourselves</a>, we must first be precise about what exactly it is we’re talking about. That means we’ll have to model out some types, and, importantly <em>what those types mean.</em> Recall that one of our <a href="/blog/music-overview/">desiderata</a> is that whatever it is we’re building must be capable of expressing any music from any culture from any time period, including those times and cultures which do not yet exist.</p>
<p>The trick then is to make a series of <em>extensible</em> types, each one providing some aspect of functionality, and letting people compose them together for themselves. Future users can add their own types with their own functionality, and reuse as much of the system that is meaningful to reuse.</p>
<p>By my reckoning, music is made up of some combination of the following:</p>
<ol type="1">
<li><em>some notion of time,</em> generally considered to be rhythmic content, or “horizontal structures.”</li>
<li><em>some notion of simultaneity,</em> generally considered to be chords, polyphony, or “vertical structures.”</li>
<li><em>things that can happen,</em> generally considered to be musical content of some sort. Perhaps this is pitches (as in musical scores), or waveforms (as in musical playback.)</li>
</ol>
<p>As a placeholder to get our bearings, let’s imagine the first two elements as types:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Horizontal</span> a</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Vertical</span> a</span></code></pre></div>
<p>and postulate both a <code>Pitch</code> and <code>Waveform</code> type for item three:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Pitch</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Waveform</span></span></code></pre></div>
<p>By composing these types in different ways, different ideas of music fall out. Several examples:</p>
<ol type="1">
<li><code>Horizontal ()</code> describes purely time-based structures; eg. rhythmic ideas</li>
<li><code>Horizontal Pitch</code> is a simple tune, the sort you can whistle</li>
<li><code>Vertical Pitch</code> is a single chord.</li>
<li><code>Horizontal (Vertical Pitch)</code> is what you get at a campfire from someone who only knows how to play chords on the guitar. In the jargon, this is “polyphonic” music.</li>
<li><code>Vertical (Horizontal Pitch)</code> is multiple independent tunes happening simultaneously. In the jargon, this is <a href="https://en.wikipedia.org/wiki/Counterpoint">“contrapuntal” music</a>.</li>
<li><code>Vertical (Horizontal Waveform)</code> is what you get in a <a href="https://en.wikipedia.org/wiki/Digital_audio_workstation">DAW</a> — independent tracks, each of which lets you move recorded samples along its own timeline.</li>
</ol>
<p>Of course, this is all vibes right now, since we haven’t discussed what exactly any of these types <em>actually are.</em> But this should be enough to wet your whistle; if we can deliver types that match these vibes, we clearly have an amazing starting point.</p>
<p>As a point of note, this first step is where I went wrong in my <a href="/blog/more-algebraic-music/">last public attempt</a>. There I postulated that <em>all</em> music is what here would be described as <code>Vertical (Horizontal a)</code>. And I gave unsatisfying answers for what <code>Vertical</code> and <code>Horizontal</code> are, to boot!</p>
<p>Shame. Sorrow.</p>
<p>Anyway. Let’s leave <code>Vertical</code> alone for now, and focus our attention on <code>Horizontal</code>, since it seems to be the crux of the interesting stuff here. However, rather than using up the musically-relevant name <code>Horizontal</code>, let’s go with <code>Signal</code>, since we’re going to be building up this idea in several pieces.</p>
<p>By our vibes, a <code>Signal</code> is a time-based structure. Which is to say, it ought to describe two things: 1) what happens, and 2) when it happens. That’s a pretty big constraint on the search space; the only other question is whether it ought to be continuous or discrete. In the continuous case, we have:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a>μ (<span class="dt">Signal</span> a) <span class="ot">=</span> <span class="dt">Time</span> <span class="ot">-&gt;</span> a</span></code></pre></div>
<p>and in the discrete:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a>μ (<span class="dt">Signal</span> a) <span class="ot">=</span> [(<span class="dt">Time</span>, a)]  <span class="co">-- ordered by monotonically ascending Time</span></span></code></pre></div>
<p>where <code>μ</code> should be read as “the meaning of.” That is to say, we’re trying to pin down the <em>semantics</em> of <code>Signal</code> without saying anything about <em>how we’re actually going to implement this thing.</em></p>
<p><strong>This is my first point of confusion.</strong> Composition (in the programming sense) is significantly better with the <code>Time -&gt; a</code> denotation, but when I <em>listen to music</em> I “hear” it “discretely.” I think. Maybe. Like I said, I am confused.</p>
<p>Rather than choose between these two options, I am <strong>cheating</strong> and choosing BOTH. HA HA HA. This is intellectually dishonest, but it’s a decision that needs to be made early on, and making progress seems to be dependent on choosing <em>something.</em> Hopefully when everything has clarified down the road, we can return to this decision and make a better choice.</p>
<p>Sorry, let me back up. What the hell am I talking about? I have the advantage of knowing where I’m going, so I imagine it’s pretty disjointed without that. Concretely, I am torn between a few things:</p>
<ol type="1">
<li>The discrete choice <em>vibes better</em> with my classical piano training, where “music” is rendered as a score with discrete symbols on a page</li>
<li>I have a strong bias towards being able to generate these symbols on a page with this system I’m making</li>
<li>But the discrete choice doesn’t admit nearly as much algebraic structure. For example, it seems very desirable to have an applicative structure on <code>Signal</code>. The usual list applicative is seems musically meaningless (taking the cartesian product of all the notes in a piece? yeah ok). What seems more likely is a pointwise “zippy” applicative. But in a discrete framing, <em>there isn’t enough data</em> to combine two <code>Signal</code> structures that are out of phase with one another.</li>
</ol>
<p>So, the unsatisfying solution here is to just do both. Rather than picking between a discrete and a continuous representation, just keep both around:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a>μ (<span class="dt">Signal</span> a) <span class="ot">=</span> (<span class="dt">Time</span> <span class="ot">-&gt;</span> a, <span class="dt">Set</span> <span class="dt">Time</span>)</span></code></pre></div>
<p>That is, represent the <code>Signal</code> structure as a continuous function out of time, <em>but also keep track of a set of interesting times!</em></p>
<p>We get quite a lot of nice algebraic structure on top of this thing:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a>μ (<span class="dt">Signal</span> a) <span class="ot">=</span> (<span class="dt">Time</span> <span class="ot">-&gt;</span> a, <span class="dt">Set</span> <span class="dt">Time</span>)</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Functor</span> <span class="dt">Signal</span> <span class="kw">where</span></span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a>  μ (<span class="fu">fmap</span> f a) <span class="ot">=</span> first (<span class="fu">fmap</span> f) (μ a)</span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Applicative</span> <span class="dt">Signal</span> <span class="kw">where</span></span>
<span id="cb6-7"><a href="#cb6-7" aria-hidden="true" tabindex="-1"></a>  μ (<span class="fu">pure</span> a) <span class="ot">=</span> (<span class="fu">const</span> a, <span class="fu">mempty</span>)</span>
<span id="cb6-8"><a href="#cb6-8" aria-hidden="true" tabindex="-1"></a>  μ (liftA2 f a b) <span class="ot">=</span> (liftA2 f <span class="op">***</span> (<span class="op">&lt;&gt;</span>)) (μ a) (μ b)</span>
<span id="cb6-9"><a href="#cb6-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-10"><a href="#cb6-10" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Semigroup</span> a <span class="ot">=&gt;</span> <span class="dt">Semigroup</span> (<span class="dt">Signal</span> a) <span class="kw">where</span></span>
<span id="cb6-11"><a href="#cb6-11" aria-hidden="true" tabindex="-1"></a>  μ (a <span class="op">&lt;&gt;</span> b) <span class="ot">=</span> μ a <span class="op">&lt;&gt;</span> μ b</span>
<span id="cb6-12"><a href="#cb6-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-13"><a href="#cb6-13" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Monoid</span> a <span class="ot">=&gt;</span> <span class="dt">Monoid</span> (<span class="dt">Signal</span> a) <span class="kw">where</span></span>
<span id="cb6-14"><a href="#cb6-14" aria-hidden="true" tabindex="-1"></a>  μ <span class="fu">mempty</span> <span class="ot">=</span> <span class="fu">mempty</span></span>
<span id="cb6-15"><a href="#cb6-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-16"><a href="#cb6-16" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Foldable</span> <span class="dt">Signal</span> <span class="kw">where</span></span>
<span id="cb6-17"><a href="#cb6-17" aria-hidden="true" tabindex="-1"></a>  μ (<span class="fu">foldMap</span> f a) <span class="ot">=</span> <span class="fu">uncurry</span> <span class="fu">foldMap</span> (μ a)</span></code></pre></div>
<p>which I always take as a sign that I’m on the right track.</p>
<p>Armed with <code>Signal</code>, we can give some rudimentary combinators on it. For example, we can lift functions:</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="ot">lift ::</span> (<span class="dt">Time</span> <span class="ot">-&gt;</span> a) <span class="ot">-&gt;</span> <span class="dt">Signal</span> a</span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a>μ (lift f) <span class="ot">=</span> (f, <span class="fu">mempty</span>)</span></code></pre></div>
<p>and we can generate stepwise signals:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="ot">stepwise ::</span> a <span class="ot">-&gt;</span> [(<span class="dt">Time</span>, a)] <span class="ot">-&gt;</span> <span class="dt">Signal</span> a</span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>μ (stepwise a0 []) <span class="ot">=</span> <span class="fu">pure</span> a0</span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a>μ (stepwise a0 ((t0, a) <span class="op">:</span> as)) <span class="ot">=</span> \t <span class="ot">-&gt;</span></span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">case</span> t <span class="op">&lt;</span> t0 <span class="kw">of</span></span>
<span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a>    <span class="dt">True</span> <span class="ot">-&gt;</span> a0</span>
<span id="cb8-6"><a href="#cb8-6" aria-hidden="true" tabindex="-1"></a>    <span class="dt">False</span> <span class="ot">-&gt;</span> μ (stepwise a as)</span></code></pre></div>
<p>Attentive readers will notice that nothing yet ever actually introduces any times-of-interest into a <code>Signal</code>. Here is where my earlier belly-aching comes back to bite. I’d LIKE VERY MUCH to be able to say “discrete <code>Signal</code>s have a different type than continuous ones.” So maybe we add an <code>Event</code> type:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a>μ (<span class="dt">Event</span> a) <span class="ot">=</span> <span class="dt">Maybe</span> a</span></code></pre></div>
<p>and then say we can make <em>discrete</em> signals:</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="ot">discrete ::</span> [(<span class="dt">Time</span>, a)] <span class="ot">-&gt;</span> <span class="dt">Signal</span> (<span class="dt">Event</span> a)</span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a>μ (discrete as) <span class="ot">=</span> (\t <span class="ot">-&gt;</span> <span class="fu">lookup</span> t as, Set.fromList <span class="op">$</span> <span class="fu">fmap</span> <span class="fu">fst</span> as)</span></code></pre></div>
<p>with the implicit promise that if you have a <code>Signal (Event a)</code> <em>then it must be a discrete <code>Signal</code>!</em> Unfortunately, this is not the sort of promise we can keep; it’s trivial to construct a densely packed <code>Signal</code> of <code>Event</code>s:</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="ot">notActuallyDiscrete ::</span> <span class="dt">Signal</span> a <span class="ot">-&gt;</span> <span class="dt">Signal</span> (<span class="dt">Event</span> a)</span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a>μ notActuallyDiscrete <span class="ot">=</span> <span class="fu">fmap</span> <span class="dt">Just</span> <span class="op">.</span> μ</span></code></pre></div>
<p>Alas. Shame. Sorrow.</p>
<p>Nevertheless, we are just going to <strong>ignore</strong> this issue, and <strong>pretend</strong> like any <code>Signal (Event a)</code> must be discrete and sparse! I am eminently aware of how disappointed <a href="http://conal.net/">Conal</a> would be by my motivated reasoning here. I’m disappointed in myself! Unfortunately I don’t have a better answer other than to split up the continuous and discrete cases, but that throws away a bunch of the compositionality that I want. <strong>I am confident there is a better solution here</strong> but damned if I know what it is.<a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a></p>
<p>Anyway, I’m writing this in the darkness at 5am before my family awakens, but I hear stirring so it’s probably time to stop. If you have any lovely ideas about how to solve this discrete/continuous discrepancy, I’d love to hear them.</p>
<p>Next we’ll look at signal functions, and give to-my-knowledge a novel application of <code>Arrow</code>s for music.</p>
<section class="footnotes" role="doc-endnotes">
<hr />
<ol>
<li id="fn1" role="doc-endnote"><p>One titillating idea is to simply not expose any introductory forms for <code>Event</code>. I haven’t explored this much, since it would mean we don’t get an applicative functor over <code>Event</code>. Thinking about it now, it’d still be fine to expose the <code>Nothing</code>-analogous constructor, so we could still give <code>mempty</code>. And perhaps this is the first motivating case I’ve ever found for giving only a <a href="https://hackage-content.haskell.org/package/semigroupoids-6.0.2/docs/Data-Functor-Apply.html#g:2"><code>Apply</code></a> instance instead of a full <code>Applicative</code>.<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</section>
        ]]>
      </content>
    </entry>
    <entry>
      <title>An Overview of an Ambitious Music Project</title>
      <id>blog/music-overview/index.html</id>
      <link href='blog/music-overview/index.html'/>
      <published>2026-11-02T15:23:00Z</published>
      <updated>2026-11-02T15:23:00Z</updated>

      <content type="html" xml:base="https://reasonablypolymorphic.com">
        <![CDATA[
        <p>It’s November. And you know what that means. <a href="https://nano2.org/">National Novel Writing Month</a>. Rather than writing a novel, I thought it’d be fun to do something like in 2016 when I wrote <a href="https://reasonablypolymorphic.com/book/preface">my first textbook</a>. But this time around, I’m going to bash out all of the ideas about a constructive theory of music that have been banging around in my head for a few years.</p>
<p>Many years ago, I read <a href="https://www.microsoft.com/en-us/research/publication/composing-contracts-an-adventure-in-financial-engineering/">Composing Contracts: an adventure in financial engineering</a>, in which Haskell King Simon Peyton Jones descends unwittingly into the world of financial instruments. And being a “red-blooded functional programmer,” he designs a bunch of combinators which model the entire complexity of dozens of financial instruments, as well as an infinitely many that nobody had ever thought to ask for.</p>
<p>This paper has always been wildly inspirational to me, and alongside <a href="https://conal.net/papers/compiling-to-categories/compiling-to-categories.pdf">Compiling to Categories</a>, is the clearest example of the power of pure, strongly-typed, functional programming, and its ability to model the wider, messier world.</p>
<p>So, wanting to learn how to flex these muscles for myself, I set off many years ago on a quest to try to tackle the hardest problem I could think of, that I felt like I had any chance whatsoever of succeeding at — music. After all, <a href="https://www.lesswrong.com/posts/WLJwTJ7uGPA5Qphbp/trying-to-try">“so much of life’s failure consists in holding yourself to too low a standard.”</a></p>
<p>The goal is, and has always been, to develop something equivalent to <a href="https://byorgey.github.io/blog/">Brent Yorgey’s</a> amazing <a href="https://diagrams.github.io/gallery.html">diagrams</a> library. Diagrams is a combinator library in Haskell which abstracts away the “how” of drawing a picture from the “what picture do you want to draw?” For example, here’s how you draw a <a href="triangle">Sierpinski triangle</a>:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a>sierpinski <span class="dv">1</span> <span class="ot">=</span> triangle <span class="dv">1</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>sierpinski n <span class="ot">=</span>     s</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>                 <span class="op">===</span></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a>              (s <span class="op">|||</span> s) <span class="op">#</span> centerX</span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a>  <span class="kw">where</span> s <span class="ot">=</span> sierpinski (n<span class="op">-</span><span class="dv">1</span>)</span></code></pre></div>
<p>which you might notice <em>is exactly the obvious definition of what a Sierpinski triangle is</em> — recursive copies of itself arranged in a triangle.</p>
<p>So the question I’ve been chasing for years is “what is an equivalently elegant approach to composing music?” I spent a <a href="/blog/algebraic-music/">good</a> <a href="/more-algebraic-music/">chunk</a> of my holiday season last year struggling to find a good starting point here. With the benefit of hindsight, and of being a year older and wiser, I’ve made a great deal of progress since then.</p>
<p>But before diving into exactly what that progress means, I think it’s worth discussing what explicitly the goals here are (and what they are <em>not.</em>) Some desiderata:</p>
<ol type="1">
<li>The system must be capable of expressing any music, from any culture, from any time (this includes <em>music and styles that do not yet exist.</em>)</li>
<li>It must be easy to get good results out of the system.</li>
<li>Understanding the system should teach you something about music.</li>
</ol>
<p>These three desiderata are an extreme set of constraints on the solution space. Desideratum 1 means that we can’t take <em>anything</em> for granted. For example, we cannot assume that there are 12 pitch classes, since this would immediately eliminate microtonal music. Nor can we privilege <a href="https://en.wikipedia.org/wiki/Function_(music)">harmonic function</a>, since this isn’t an idea that seems to be shared by non-Western traditional music.</p>
<p>Desideratum 2 means that we can’t be happy with only a mathematical model. Yes, to a first approximation, set theory can describe anything, but lots of things are pretty egregious to articulate in set theory! This gives rise to the need for <em>musically-meaningful combinators.</em> I think the [kaleidoscope diagram] is a striking visual example of this idea. It’s a piece of code that <em>given any image whatsoever</em> can produce a new image <em>which is a kaleidoscope of that thing.</em> With a little hand waving here, you can imagine a set of musical combinators which approach a given motif, which ramp up the tension, which introduce syncopation, which produce senses of resolution. This also means we must put a great deal of thought into how musical ideas are represented, and how they can be combined.</p>
<p>Desideratum 3 means we can’t just hand the problem off to some LLM or some other probabilistic mechanism.</p>
<p>Under these constraints, it’s immediately evident that almost no existing music theory is up to the task. As best I can tell, the field of music theory is primarily focused on <em>analysis of existing music</em> rather than on <em>general techniques for creating new music.</em> Perhaps an argument can be made that you must be able to spot greatness in order to produce it for yourself, but this is relatively unconvincing to me. Attempting to perform post-hoc analysis of music without a constructive theory seems analogous to decompiling computer code <em>without a language to decompile it into.</em> At best you might find some statistical patterns (V chords often go to I), but this doesn’t seem like it ought to lend itself much to <em>actually writing good music.</em> Will it out-compete a <a href="https://en.wikipedia.org/wiki/Markov_chain">Markov chain</a> trained on the same probabilities?</p>
<p>The best we can do with most existing music theory is (to the extent that it is constructive [which is extremely few and far between]) relegate it to combinator status. A grammar of functional harmony can exist as a DSL on top of the core music structures. <a href="https://dmitri.mycpanel.princeton.edu/tonality-an-owners-manual.html">Voice leading spaces</a> ala <a href="https://dmitri.mycpanel.princeton.edu/index.html">Tymoczko</a><a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a> can be expressed by their own notions of pitch, alongside operations and elimination forms.</p>
<p>So that’s the overview. All in all, it’s a very ambitious project. I am not interested in hearing from you if you think this cannot be done. If you’re right, I’ll end up with egg on my face, but that’s my problem. However, if this is the sort of thing that piques your interest as much as it has mine, please do get in touch.</p>
<p>In the next post we’ll discuss the denotative elements of music.</p>
<section class="footnotes" role="doc-endnotes">
<hr />
<ol>
<li id="fn1" role="doc-endnote"><p>Dmitri Tymoczko has the distinction of being the only music theorist I’ve found who is precise enough to be more than <a href="https://en.wikipedia.org/wiki/Not_even_wrong">not even wrong</a>. Rather amazingly, he also seems to be <em>right!</em> Coincidence?<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</section>
        ]]>
      </content>
    </entry>
    <entry>
      <title>Reviewing Again</title>
      <id>blog/reviewing-again/index.html</id>
      <link href='blog/reviewing-again/index.html'/>
      <published>2026-08-24T23:26:00Z</published>
      <updated>2026-08-24T23:26:00Z</updated>

      <content type="html" xml:base="https://reasonablypolymorphic.com">
        <![CDATA[
        <p>Last time, we took a stroll down memory lane to review some ancient code I wrote, and see what/how I’d do things differently now. That was fun, and I have a new banger for us today.</p>
<p>Today’s example comes from the same place — a little vim-like text editor I was working on. Vim has this “repeat” operator which just does the same thing you did last time. It’s nice. Delete a word. Running repeat deletes another word. Kinda dinky in this example, but it can also rerun “increment every number in the next four paragraphs.”</p>
<p>Anyway, so that’s the feature I was trying to duplicate. But the action I was running might have done some IO, and I didn’t want to repeat the IO (because maybe the IO was to gather some input from the user, and repeating shouldn’t ask again.)</p>
<p>I was still <a href="https://sandymaguire.me/blog/jurisdiction-of-heaven/">high on my own supply of writing monads</a>, so I approached this problem with a custom monad. The gist of the API was:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- | A monad transformer adding the ability to record the results of IO actions</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="co">-- and later replay them.</span></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Again</span> m a</span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Monad</span> m <span class="ot">=&gt;</span> <span class="dt">Monad</span> (<span class="dt">Again</span> m)</span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">MonadIO</span> m <span class="ot">=&gt;</span> <span class="dt">MonadIO</span> (<span class="dt">Again</span> m)</span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">MonadTrans</span> <span class="dt">Again</span></span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a><span class="co">-- | Runs an action and records all of its sampled IO. Returns a action which</span></span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a><span class="co">-- when invoked will use the recorded IO.</span></span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a>runAgain</span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a><span class="ot">    ::</span> <span class="dt">Monad</span> m</span>
<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=&gt;</span> <span class="dt">Again</span> m a</span>
<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> m (m a)</span>
<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a><span class="co">-- | Marks an IO action to be memoized after its first invocation.</span></span>
<span id="cb1-16"><a href="#cb1-16" aria-hidden="true" tabindex="-1"></a>again</span>
<span id="cb1-17"><a href="#cb1-17" aria-hidden="true" tabindex="-1"></a><span class="ot">    ::</span> ( <span class="dt">MonadIO</span> m</span>
<span id="cb1-18"><a href="#cb1-18" aria-hidden="true" tabindex="-1"></a>       , <span class="dt">Typeable</span> r</span>
<span id="cb1-19"><a href="#cb1-19" aria-hidden="true" tabindex="-1"></a>       )</span>
<span id="cb1-20"><a href="#cb1-20" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=&gt;</span> <span class="dt">IO</span> r</span>
<span id="cb1-21"><a href="#cb1-21" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> <span class="dt">Again</span> m r</span></code></pre></div>
<p>I’m actually pretty impressed with past-me on this one. That’s a clean API, and the implementation was pretty cute.</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">Again</span> m a <span class="ot">=</span> <span class="dt">Again</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> runAgain&#39; ::</span> <span class="dt">RWST</span> () [<span class="dt">Dynamic</span>] [<span class="dt">Dynamic</span>] m a</span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>  }</span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a>once</span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a><span class="ot">    ::</span> <span class="kw">forall</span> m r</span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a>     <span class="op">.</span> ( <span class="dt">MonadIO</span> m</span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a>       , <span class="dt">Typeable</span> r</span>
<span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb2-10"><a href="#cb2-10" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=&gt;</span> <span class="dt">IO</span> r</span>
<span id="cb2-11"><a href="#cb2-11" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> <span class="dt">Again</span> m r</span>
<span id="cb2-12"><a href="#cb2-12" aria-hidden="true" tabindex="-1"></a>once action <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb2-13"><a href="#cb2-13" aria-hidden="true" tabindex="-1"></a>    a <span class="ot">&lt;-</span> dequeue <span class="op">&gt;&gt;=</span> \<span class="kw">case</span></span>
<span id="cb2-14"><a href="#cb2-14" aria-hidden="true" tabindex="-1"></a>        <span class="dt">Just</span> x  <span class="ot">-&gt;</span> <span class="fu">return</span> <span class="op">.</span> fromJust <span class="op">$</span> fromDynamic x</span>
<span id="cb2-15"><a href="#cb2-15" aria-hidden="true" tabindex="-1"></a>        <span class="dt">Nothing</span> <span class="ot">-&gt;</span> liftIO action</span>
<span id="cb2-16"><a href="#cb2-16" aria-hidden="true" tabindex="-1"></a>    tell [toDyn a]</span>
<span id="cb2-17"><a href="#cb2-17" aria-hidden="true" tabindex="-1"></a>    <span class="fu">return</span> a</span>
<span id="cb2-18"><a href="#cb2-18" aria-hidden="true" tabindex="-1"></a>  <span class="kw">where</span></span>
<span id="cb2-19"><a href="#cb2-19" aria-hidden="true" tabindex="-1"></a><span class="ot">    dequeue ::</span> <span class="dt">MonadState</span> [r] m <span class="ot">=&gt;</span> m (<span class="dt">Maybe</span> r)</span>
<span id="cb2-20"><a href="#cb2-20" aria-hidden="true" tabindex="-1"></a>    dequeue <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb2-21"><a href="#cb2-21" aria-hidden="true" tabindex="-1"></a>        get <span class="op">&gt;&gt;=</span> \<span class="kw">case</span></span>
<span id="cb2-22"><a href="#cb2-22" aria-hidden="true" tabindex="-1"></a>            []     <span class="ot">-&gt;</span> <span class="fu">return</span> <span class="dt">Nothing</span></span>
<span id="cb2-23"><a href="#cb2-23" aria-hidden="true" tabindex="-1"></a>            (x<span class="op">:</span>xs) <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb2-24"><a href="#cb2-24" aria-hidden="true" tabindex="-1"></a>                put xs</span>
<span id="cb2-25"><a href="#cb2-25" aria-hidden="true" tabindex="-1"></a>                <span class="fu">return</span> <span class="op">$</span> <span class="dt">Just</span> x</span></code></pre></div>
<p>The trick here is to keep <code>MonadState [Dynamic]</code> and a <code>MonadWriter [Dynamic]</code> instances around. This code uses the <code>MonadState</code> to pop off IO actions it’s already run, and the <code>MonadWriter</code> to keep track of new IO actions it needs to cache. The “magic” happens in <code>runAgain</code>, which runs it through once with an empty state, and then returns a new action with the MonadWriter results moved into the state for the next time around:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a>runAgain</span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="ot">    ::</span> <span class="dt">Monad</span> m</span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=&gt;</span> <span class="dt">Again</span> m a</span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> m (m a)</span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a>runAgain action <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a>    (a, w) <span class="ot">&lt;-</span> evalRWST (runAgain&#39; action) () []</span>
<span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a>    <span class="fu">return</span> <span class="op">$</span> <span class="kw">do</span></span>
<span id="cb3-8"><a href="#cb3-8" aria-hidden="true" tabindex="-1"></a>        evalRWST (runAgain&#39; action) () w</span>
<span id="cb3-9"><a href="#cb3-9" aria-hidden="true" tabindex="-1"></a>        <span class="fu">return</span> a</span></code></pre></div>
<p>Simple. Clean. Elegant. Too bad it doesn’t actually work.</p>
<p>The following program crashes with an error coming from the unsafe use of <code>fromJust</code> in <code>once</code>:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ot">oops ::</span> <span class="dt">Again</span> (<span class="dt">StateT</span> <span class="dt">Bool</span> <span class="dt">IO</span>) ()</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>oops <span class="ot">=</span></span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Branch on the StateT</span></span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a>  lift get <span class="op">&gt;&gt;=</span> \<span class="kw">case</span></span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- The first time around...</span></span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a>    <span class="dt">False</span> <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a>      <span class="co">-- Cache a unit value</span></span>
<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a>      once <span class="op">$</span> <span class="fu">print</span> ()</span>
<span id="cb4-9"><a href="#cb4-9" aria-hidden="true" tabindex="-1"></a>      <span class="co">-- Change the state value</span></span>
<span id="cb4-10"><a href="#cb4-10" aria-hidden="true" tabindex="-1"></a>      lift <span class="op">$</span> put <span class="dt">True</span></span>
<span id="cb4-11"><a href="#cb4-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-12"><a href="#cb4-12" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- Since the state changed at the end of the first branch, we will take this</span></span>
<span id="cb4-13"><a href="#cb4-13" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- branch the second time around...</span></span>
<span id="cb4-14"><a href="#cb4-14" aria-hidden="true" tabindex="-1"></a>    <span class="dt">True</span> <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb4-15"><a href="#cb4-15" aria-hidden="true" tabindex="-1"></a>      <span class="co">-- Calling &#39;once&#39; the second time around gets its value from the cache,</span></span>
<span id="cb4-16"><a href="#cb4-16" aria-hidden="true" tabindex="-1"></a>      <span class="co">-- which has type @()@. But at this callsite, it ought to have type</span></span>
<span id="cb4-17"><a href="#cb4-17" aria-hidden="true" tabindex="-1"></a>      <span class="co">-- @Bool -&gt; Bool@. Uh oh!</span></span>
<span id="cb4-18"><a href="#cb4-18" aria-hidden="true" tabindex="-1"></a>      f <span class="ot">&lt;-</span> once <span class="op">$</span> <span class="fu">pure</span> <span class="fu">not</span></span>
<span id="cb4-19"><a href="#cb4-19" aria-hidden="true" tabindex="-1"></a>      lift <span class="op">$</span> <span class="fu">print</span> (<span class="st">&quot;uh oh!&quot;</span>, f <span class="dt">True</span>)</span>
<span id="cb4-20"><a href="#cb4-20" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-21"><a href="#cb4-21" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-22"><a href="#cb4-22" aria-hidden="true" tabindex="-1"></a><span class="ot">ohNo ::</span> <span class="dt">IO</span> ((), <span class="dt">Bool</span>)</span>
<span id="cb4-23"><a href="#cb4-23" aria-hidden="true" tabindex="-1"></a>ohNo <span class="ot">=</span> <span class="fu">flip</span> runStateT <span class="dt">False</span> <span class="op">$</span> <span class="kw">do</span></span>
<span id="cb4-24"><a href="#cb4-24" aria-hidden="true" tabindex="-1"></a>  m <span class="ot">&lt;-</span> runAgain oops</span>
<span id="cb4-25"><a href="#cb4-25" aria-hidden="true" tabindex="-1"></a>  m</span></code></pre></div>
<p>The attack here comes from the fact that we can force the <code>Again</code> program down a different code path its second time around. And that second time, it encounters a call to <code>once</code> which has a different type than the one it cached. Thus, trying to reuse the cache leads to what is effectively a type error at runtime.</p>
<p>What actually went wrong here? The problem is that <a href="https://chrispenner.ca/posts/expressiveness-spectrum">monads are too powerful</a>. Since the only way to compose monads is via bind (<code>m a -&gt; (a -&gt; m b) -&gt; m b</code>), we are forced to extend a monadic value of type <code>m a</code> by a <em>function</em> of type <code>a -&gt; m b</code>. Which is to say that the “next thing to do” in a monadic computation is always going to be a function. And functions are completely opaque. So, once we’re given a monad, there’s simply no way to know what it’s going to do without actually running the continuation.</p>
<p>The problem arises from the fact that that continuation can invisibly branch. My <code>Again</code> monad was attempting to <em>statically analyze</em> the monadic computation, and cache the IO results in a queue. But as <code>oops</code> shows, it’s trivial to break this sort of static analysis. Because the branch is hidden inside of a function, and there’s no way to determine which branches a function <em>didn’t take.</em></p>
<p>But I didn’t know that eleven years ago, so I give myself a pass on this one. Nevertheless, let’s tackle this problem with the wisdom of ages.</p>
<h2 id="no-more-monads">No More Monads</h2>
<p>So if the problem with my previous implementation of <code>Again</code> is that it’s a monad, what options do we have? As it happens, there are two very nice options available to us here: <em>arrows</em> and <em>selective applicative functors.</em> We’ll discuss arrows for now, and come back to selectives.</p>
<p>Long time readers might remember a <a href="/tags/yampa.html">series on arrows from a few years back.</a> But if you don’t, that’s OK; you’re still welcome here. A quick recap:</p>
<p>Arrows are a generalization of functions. Like functions, they take two type parameters (an input and an output). Like functions, they come with an identity arrow. They compose “end to end” just like functions do. These three properties are expressed as a <code>Category</code> superclass, which we usually call <code>c</code> and write infix:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> <span class="dt">Category</span> (<span class="ot">c ::</span> <span class="dt">Type</span> <span class="ot">-&gt;</span> <span class="dt">Type</span> <span class="ot">-&gt;</span> <span class="dt">Type</span>) <span class="kw">where</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  id  ::</span> x <span class="ot">`c`</span> x</span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a><span class="ot">  (.) ::</span> (y <span class="ot">`c`</span> z) <span class="ot">-&gt;</span> (x <span class="ot">`c`</span> y) <span class="ot">-&gt;</span> (x <span class="ot">`c`</span> z)</span></code></pre></div>
<p>In addition to being categories, arrows also come with a means of transforming regular functions into arrows, and of mapping arrows over pairs:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> <span class="dt">Category</span> c <span class="ot">=&gt;</span> <span class="dt">Arrow</span> c <span class="kw">where</span></span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  arr ::</span> (x <span class="ot">-&gt;</span> y) <span class="ot">-&gt;</span> (x <span class="ot">`c`</span> y)</span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a><span class="ot">  (***) ::</span> (x <span class="ot">`c`</span> x&#39;) <span class="ot">-&gt;</span> (y <span class="ot">`c`</span> y&#39;) <span class="ot">-&gt;</span> ((x, y) <span class="ot">`c`</span> (x&#39;, y&#39;))</span></code></pre></div>
<p>What’s neat about arrows is that their values are function-like things, rather than being <em>actually functions.</em> That means when we compose arrows, we compose values whose internals we get to choose. Which in turn, means that static analysis is possible again!</p>
<p>Attentive readers will notice that there isn’t actually any way for arrows-as-such to be able to branch. To gain that capability, they require an additional <code>ArrowChoice</code>, which equips them with the ability to lift arrows over <code>Either</code>:</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> <span class="dt">Arrow</span> c <span class="ot">=&gt;</span> <span class="dt">ArrowChoice</span> c <span class="kw">where</span></span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  (+++) ::</span> (x <span class="ot">`c`</span> x&#39;) <span class="ot">-&gt;</span> (y <span class="ot">`c`</span> y&#39;) <span class="ot">-&gt;</span> (<span class="dt">Either</span> x y <span class="ot">`c`</span> <span class="dt">Either</span> x&#39; y&#39;)</span></code></pre></div>
<p>To wet our whistle, let’s write a little helper <code>Arrow</code> that shows that the composition of an applicative functor with an arrow is itself an arrow:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">Static</span> m c x y <span class="ot">=</span> <span class="dt">Static</span></span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> unStatic ::</span> m (c x y)</span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a>  }</span></code></pre></div>
<p>The arrow instances for <code>(Applicative m, Arrow c) =&gt; Static m c</code> are the usual trick of using applicative functions to lift operations into the right place. For example, identity is just <code>pure id, and composition is</code>liftA2` of composition:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> (<span class="dt">Category</span> c, <span class="dt">Applicative</span> m) <span class="ot">=&gt;</span> <span class="dt">Category</span> (<span class="dt">Static</span> m c) <span class="kw">where</span></span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">id</span> <span class="ot">=</span> <span class="dt">Static</span> <span class="op">$</span> <span class="fu">pure</span> <span class="fu">id</span></span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Static</span> g <span class="op">.</span> <span class="dt">Static</span> f <span class="ot">=</span> <span class="dt">Static</span> <span class="op">$</span> liftA2 (<span class="op">.</span>) g f</span></code></pre></div>
<p>We can do the same trick for <code>arr</code> and <code>(***)</code>:</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> (<span class="dt">Arrow</span> c, <span class="dt">Applicative</span> m) <span class="ot">=&gt;</span> <span class="dt">Arrow</span> (<span class="dt">Static</span> m c) <span class="kw">where</span></span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a>  arr <span class="ot">=</span> <span class="dt">Static</span> <span class="op">.</span> <span class="fu">pure</span> <span class="op">.</span> arr</span>
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Static</span> f <span class="op">***</span> <span class="dt">Static</span> g <span class="ot">=</span> <span class="dt">Static</span> <span class="op">$</span> liftA2 (<span class="op">***</span>) f g</span></code></pre></div>
<p>as well as for <code>(+++)</code>:</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> (<span class="dt">ArrowChoice</span> c, <span class="dt">Applicative</span> m) <span class="ot">=&gt;</span> <span class="dt">ArrowChoice</span> (<span class="dt">Static</span> m c) <span class="kw">where</span></span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Static</span> f <span class="op">+++</span> <span class="dt">Static</span> g <span class="ot">=</span> <span class="dt">Static</span> <span class="op">$</span> liftA2 (<span class="op">+++</span>) f g</span></code></pre></div>
<p>What’s nice about this <code>Static</code> construct we’ve built is that it gives us two degrees of freedom. We’re free to choose an arrow whose structure we’re going to reuse, and an underlying applicative functor (which can give us “static” effects as we’re <em>building</em> the underlying arrow.)</p>
<p>The idea here is that we can put the cache-<em>building</em> machinery inside of the applicative functor, but the cache-<em>reading</em> machinery inside of the underlying arrow.</p>
<h3 id="constructing-again-again">Constructing Again, Again</h3>
<p>It’s worth knowing about the Kleisli arrow:</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">Kleisli</span> m a b <span class="ot">=</span> <span class="dt">Kleisli</span></span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> runKleisli ::</span> a <span class="ot">-&gt;</span> m b</span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a>  }</span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-5"><a href="#cb12-5" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Monad</span> m <span class="ot">=&gt;</span> <span class="dt">Category</span> (<span class="dt">Kleisli</span> m)</span>
<span id="cb12-6"><a href="#cb12-6" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Monad</span> m <span class="ot">=&gt;</span> <span class="dt">Arrow</span> (<span class="dt">Kleisli</span> m)</span>
<span id="cb12-7"><a href="#cb12-7" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Monad</span> m <span class="ot">=&gt;</span> <span class="dt">ArrowChoice</span> (<span class="dt">Kleisli</span> m)</span></code></pre></div>
<p>which says that any monadic bind function is itself an arrow. Implementing the instances yourself is a fun exercise if you’re new to this stuff. We can reuse <code>Kleisli</code> as our underlying arrow, which when you expand everything out, we get:</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">Again</span> m a b <span class="ot">=</span> <span class="dt">Again</span></span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> unAgain ::</span> <span class="dt">Static</span> m (<span class="dt">Kleisli</span> m) a b</span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a>  }</span>
<span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> <span class="kw">newtype</span> (<span class="dt">Category</span>, <span class="dt">Arrow</span>, <span class="dt">ArrowChoice</span>)</span>
<span id="cb13-5"><a href="#cb13-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-6"><a href="#cb13-6" aria-hidden="true" tabindex="-1"></a><span class="ot">runAgain ::</span> <span class="dt">Monad</span> m <span class="ot">=&gt;</span> <span class="dt">Again</span> m a b <span class="ot">-&gt;</span> m (a <span class="ot">-&gt;</span> m b)</span>
<span id="cb13-7"><a href="#cb13-7" aria-hidden="true" tabindex="-1"></a>runAgain <span class="ot">=</span> <span class="fu">fmap</span> runKleisli <span class="op">.</span> unStatic <span class="op">.</span> unAgain</span></code></pre></div>
<p>What I think is particularly cool about this is that <code>runAgain</code> is just the composition of the newtype unwrappers, and yet its type is extremely reminiscent of my ten-year-ago implementation:</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a>runAgain  <span class="co">-- the original</span></span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a><span class="ot">    ::</span> <span class="dt">Monad</span> m</span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=&gt;</span> <span class="dt">Again</span> m a</span>
<span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> m (m a)</span></code></pre></div>
<p>This is an instance of a more general principle, which is that the final “observation” you want to make of your type is always a good <em>representation</em> of that type. It’s not the only representation, but it’s always a reasonable choice. Appropriately enough, this is known as a <em>final encoding.</em></p>
<p>Anyway. How can we implement <code>once</code>? By way of <code>onceF</code>:</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="ot">onceF ::</span> (<span class="dt">MonadIO</span> m, <span class="dt">Ord</span> a) <span class="ot">=&gt;</span> (a <span class="ot">-&gt;</span> <span class="dt">IO</span> b) <span class="ot">-&gt;</span> <span class="dt">Again</span> m a b</span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a>onceF m <span class="ot">=</span> <span class="dt">Again</span> <span class="op">$</span> <span class="dt">Static</span> <span class="op">$</span> <span class="kw">do</span></span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a>  cache <span class="ot">&lt;-</span> liftIO <span class="op">$</span> newIORef <span class="fu">mempty</span></span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a>  <span class="fu">pure</span> <span class="op">$</span> <span class="dt">Kleisli</span> <span class="op">$</span> \a <span class="ot">-&gt;</span> liftIO <span class="op">$</span> <span class="kw">do</span></span>
<span id="cb15-5"><a href="#cb15-5" aria-hidden="true" tabindex="-1"></a>    cacheMap <span class="ot">&lt;-</span> readIORef cache</span>
<span id="cb15-6"><a href="#cb15-6" aria-hidden="true" tabindex="-1"></a>    <span class="kw">case</span> M.lookup a cacheMap <span class="kw">of</span></span>
<span id="cb15-7"><a href="#cb15-7" aria-hidden="true" tabindex="-1"></a>      <span class="dt">Just</span> b <span class="ot">-&gt;</span> <span class="fu">pure</span> b</span>
<span id="cb15-8"><a href="#cb15-8" aria-hidden="true" tabindex="-1"></a>      <span class="dt">Nothing</span> <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb15-9"><a href="#cb15-9" aria-hidden="true" tabindex="-1"></a>        b <span class="ot">&lt;-</span> m a</span>
<span id="cb15-10"><a href="#cb15-10" aria-hidden="true" tabindex="-1"></a>        modifyIORef&#39; cache <span class="op">$</span> M.insert a b</span>
<span id="cb15-11"><a href="#cb15-11" aria-hidden="true" tabindex="-1"></a>        <span class="fu">pure</span> b</span>
<span id="cb15-12"><a href="#cb15-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb15-13"><a href="#cb15-13" aria-hidden="true" tabindex="-1"></a><span class="ot">once ::</span> <span class="dt">MonadIO</span> m <span class="ot">=&gt;</span> <span class="dt">IO</span> b <span class="ot">-&gt;</span> <span class="dt">Again</span> m a b</span>
<span id="cb15-14"><a href="#cb15-14" aria-hidden="true" tabindex="-1"></a>once m <span class="ot">=</span> arr (<span class="fu">const</span> ()) <span class="op">&gt;&gt;&gt;</span> onceF (<span class="fu">const</span> m)</span></code></pre></div>
<p><code>onceF</code> works by constructing a <code>cache :: IORef (Map a b)</code> at the <code>Static</code> level. Each call to <code>onceF</code> gets a unique cache. Then we drop into the implementation of the <code>Kleisli</code> arrow (which recall happens at <em>runtime</em>.) Inside the <code>Kleisli</code>, we check to see if the map has a value at the requested <code>a</code>, and if so, return the cached <code>b</code>. If not, we run our function and cache it.</p>
<p>Since there’s no <code>Dynamic</code> tomfoolery here that is existentializing away our types, we don’t need to worry about the <code>oops</code> attack; Haskell’s type system guarantees we can’t construct such a thing.</p>
<p>Because <code>Again</code> isn’t a <code>Monad</code>, it can’t be a <code>MonadIO</code> either. But it’s nice to be able to provide the equivalent of <code>liftIO</code>:</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="ot">againF ::</span> <span class="dt">MonadIO</span> m <span class="ot">=&gt;</span> (a <span class="ot">-&gt;</span> <span class="dt">IO</span> b) <span class="ot">-&gt;</span> <span class="dt">Again</span> m a b</span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a>againF <span class="ot">=</span> <span class="dt">Again</span> <span class="op">.</span> <span class="dt">Static</span> <span class="op">.</span> <span class="fu">pure</span> <span class="op">.</span> <span class="dt">Kleisli</span> <span class="op">.</span> <span class="fu">fmap</span> liftIO</span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a><span class="ot">again ::</span> <span class="dt">MonadIO</span> m <span class="ot">=&gt;</span> <span class="dt">IO</span> a <span class="ot">-&gt;</span> <span class="dt">Again</span> m x a</span>
<span id="cb16-5"><a href="#cb16-5" aria-hidden="true" tabindex="-1"></a>again m <span class="ot">=</span> arr (<span class="fu">const</span> ()) <span class="op">&gt;&gt;&gt;</span> againF (<span class="fu">const</span> m)</span></code></pre></div>
<p>So that completes our arrow-based implementation of <code>Again</code>. But there’s still something left undone.</p>
<h3 id="circling-back-to-selectives">Circling Back to Selectives</h3>
<p>I said earlier that selective applicative functors would be an alternative approach to implementing <code>Again</code>. Selectives rightfully sit between <code>Applicative</code> and <code>Monad</code> in the functor hierarchy, but were <a href="https://dl.acm.org/doi/10.1145/3341694">discovered too late</a>, and everyone was still kind of annoyed about having had just stuck <code>Applicative</code> into the hierarchy.</p>
<p>What, precisely is a selective functor? It’s a different solution to the problem of “monads are too powerful” which gives us a branching primitive to play with. Behold:</p>
<div class="sourceCode" id="cb17"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> <span class="dt">Applicative</span> f <span class="ot">=&gt;</span> <span class="dt">Selective</span> f <span class="kw">where</span></span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  select ::</span> f (<span class="dt">Either</span> a b) <span class="ot">-&gt;</span> f (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> f b</span></code></pre></div>
<p><code>select</code> says that you might have an <code>a</code>, in which case you must run the provided <code>f (a -&gt; b)</code>. But maybe you have a <code>b</code>, in which case you <em>may</em> run the effects of the <code>f (a -&gt; b)</code>. But nobody’s forcing you to.</p>
<p>Since there are still no raw function continuations to be seen here, we can use <code>select</code> to provide branching to our programs. But all of the branches can be identified statically, since we’re only operating on <code>f</code> values, again, whose internals we can control.</p>
<p>In fact, by aggressively nesting <code>select</code> calls, you can get back a version of monadic bind — so long as you have a finite number of select calls you’d need to make:</p>
<div class="sourceCode" id="cb18"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a>bindS</span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a><span class="ot">    ::</span> (<span class="dt">Selective</span> f, <span class="dt">Enum</span> a, <span class="dt">Bounded</span> a, <span class="dt">Eq</span> a)</span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=&gt;</span> f a</span>
<span id="cb18-4"><a href="#cb18-4" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> f b)</span>
<span id="cb18-5"><a href="#cb18-5" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> f b</span></code></pre></div>
<p>(the implementation of which is fun if you’re looking for a challenge)</p>
<p>Anyway, all of this is to say that we could have equally structured our <code>Again</code> as a selective functor rather than as an arrow! But <code>ArrowChoice</code> is at least as powerful as <code>Selective</code>, so given all of our hard work already, we can pull out a <code>Selective</code> instance for free.</p>
<p>What do I mean when I say “at least as powerful?” It means we can derive it for free, given an <code>ArrowChoice</code> instance. Behold, the <code>GenericArrow</code> newtype, which exists only for us to have something to attach some instances to.</p>
<div class="sourceCode" id="cb19"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">GenericArrow</span> c x a <span class="ot">=</span> <span class="dt">GenericArrow</span></span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> unGenericArrow ::</span> c x a</span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a>  }</span>
<span id="cb19-4"><a href="#cb19-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> <span class="kw">newtype</span> (<span class="dt">Category</span>, <span class="dt">Arrow</span>, <span class="dt">ArrowChoice</span>)</span></code></pre></div>
<p>Here we use newtype deriving to say that if <code>c</code> is a category/arrow/arrowchoice, then <code>GenericArrow c</code> is too. But now we can show that having <code>Arrow</code> is enough to get <code>Functor</code> and <code>Applicative</code> instance:</p>
<div class="sourceCode" id="cb20"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Arrow</span> c <span class="ot">=&gt;</span> <span class="dt">Functor</span> (<span class="dt">GenericArrow</span> c x) <span class="kw">where</span></span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">fmap</span> f c <span class="ot">=</span> arr f <span class="op">.</span> c</span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb20-4"><a href="#cb20-4" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Arrow</span> c <span class="ot">=&gt;</span> <span class="dt">Applicative</span> (<span class="dt">GenericArrow</span> c x) <span class="kw">where</span></span>
<span id="cb20-5"><a href="#cb20-5" aria-hidden="true" tabindex="-1"></a>  <span class="fu">pure</span> <span class="ot">=</span> arr <span class="op">.</span> <span class="fu">const</span></span>
<span id="cb20-6"><a href="#cb20-6" aria-hidden="true" tabindex="-1"></a>  liftA2 f x y <span class="ot">=</span> (x <span class="op">&amp;&amp;&amp;</span> y) <span class="op">&gt;&gt;&gt;</span> arr (<span class="fu">uncurry</span> f)</span></code></pre></div>
<p>Then, given an <code>ArrowChoice</code>, we can get an implementation of <code>select</code>:</p>
<div class="sourceCode" id="cb21"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">ArrowChoice</span> c <span class="ot">=&gt;</span> <span class="dt">Selective</span> (<span class="dt">GenericArrow</span> c x) <span class="kw">where</span></span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a>  select te tk <span class="ot">=</span> proc b <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a>    e <span class="ot">&lt;-</span> te <span class="op">-&lt;</span> b</span>
<span id="cb21-4"><a href="#cb21-4" aria-hidden="true" tabindex="-1"></a>    <span class="kw">case</span> e <span class="kw">of</span></span>
<span id="cb21-5"><a href="#cb21-5" aria-hidden="true" tabindex="-1"></a>      <span class="dt">Left</span> x <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb21-6"><a href="#cb21-6" aria-hidden="true" tabindex="-1"></a>        k <span class="ot">&lt;-</span> tk <span class="op">-&lt;</span> b</span>
<span id="cb21-7"><a href="#cb21-7" aria-hidden="true" tabindex="-1"></a>        returnA <span class="op">-&lt;</span> k x</span>
<span id="cb21-8"><a href="#cb21-8" aria-hidden="true" tabindex="-1"></a>      <span class="dt">Right</span> y <span class="ot">-&gt;</span> returnA <span class="op">-&lt;</span> y</span></code></pre></div>
<p>Here we don’t have the option of choosing to invoke <code>tk</code> in the <code>Right</code> case. But that’s OK, because in <code>Again</code>, doing so would correspond to creating caches for branches that don’t need it.</p>
<p>Given all of this, we can now derive <code>Functor</code> up to <code>Selective</code> for <code>Again</code>:</p>
<div class="sourceCode" id="cb22"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">Again</span> m a b <span class="ot">=</span> <span class="dt">Again</span></span>
<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> unAgain ::</span> <span class="dt">Static</span> m (<span class="dt">Kleisli</span> m) a b</span>
<span id="cb22-3"><a href="#cb22-3" aria-hidden="true" tabindex="-1"></a>  }</span>
<span id="cb22-4"><a href="#cb22-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> <span class="kw">newtype</span> (<span class="dt">Category</span>, <span class="dt">Arrow</span>, <span class="dt">ArrowChoice</span>)</span>
<span id="cb22-5"><a href="#cb22-5" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> (<span class="dt">Functor</span>, <span class="dt">Applicative</span>, <span class="dt">Selective</span>) via <span class="dt">GenericArrow</span> (<span class="dt">Again</span> m) a</span></code></pre></div>
<p>which means that users can now choose between the arrow hierarchy and the functor hierarchy for how they’d like to think about building <code>Again</code> actions. And to nudge them even a little further, we can introduce something that looks like a monad transformer, removing the input parameter:</p>
<div class="sourceCode" id="cb23"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb23-1"><a href="#cb23-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">AgainT</span> m <span class="ot">=</span> <span class="dt">Again</span> m ()</span>
<span id="cb23-2"><a href="#cb23-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb23-3"><a href="#cb23-3" aria-hidden="true" tabindex="-1"></a><span class="ot">runAgainT ::</span> <span class="dt">Monad</span> m <span class="ot">=&gt;</span> <span class="dt">AgainT</span> m a <span class="ot">-&gt;</span> m (m a)</span>
<span id="cb23-4"><a href="#cb23-4" aria-hidden="true" tabindex="-1"></a>runAgainT <span class="ot">=</span> <span class="fu">fmap</span> (<span class="op">$</span> ()) <span class="op">.</span> runAgain</span></code></pre></div>
<p>Clean. Tidy. Actually works this time around.</p>
        ]]>
      </content>
    </entry>
</feed>

