<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:dc="http://purl.org/dc/elements/1.1/">
    <channel>
        <title>MorrowM</title>
        <link>https://morrowm.github.io/</link>
        <description><![CDATA[MorrowM's personal blog.]]></description>
        <atom:link href="https://morrowm.github.io//rss.xml" rel="self"
                   type="application/rss+xml" />
        <lastBuildDate>Tue, 19 Jul 2022 00:00:00 UT</lastBuildDate>
        <item>
    <title>One of a Kind: An Introduction to Kinds in Haskell</title>
    <link>https://morrowm.github.io//posts/2022-07-19-kinds.html</link>
    <description><![CDATA[<article>
    <section class="header">
        July 19, 2022
        
    </section>
    <section>
        <p>If you’ve been using Haskell you’ll know that it has an expressive static type system. This gives us a way to reason about how our programs will behave before we even run them, and, at least in my case, prevents a lot of dumb errors.</p>
<p>Just as Haskell has a type system to classify values, it has a <em>kind system</em> to classify types. It provides a way to reason about what <em>types</em> make sense to construct. Let’s see what it’s all about.</p>
<h2 id="types-types-everywhere"><code>Type</code>s, <code>Type</code>s Everywhere</h2>
<p>The most common kind of type<a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a> you’ll see are <code>Type</code>s (shocking, isn’t it?). These include <code>Int</code>, <code>Bool</code>, <code>Char</code>, as well as <code>Double -&gt; String</code>, <code>[Integer]</code>, and <code>Either Rational [Bool]</code>. Another name for the kind <code>Type</code> is <code>*</code>. We can check a type’s kind in GHCi with <code>:kind</code> or <code>:k</code> for short.</p>
<pre class="plaintext"><code>ghci&gt; :k [Integer]
[Integer] :: *</code></pre>
<p>If we turn on the language extension <a href="https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/exts/poly_kinds.html#extension-StarIsType="><code>NoStarIsType</code></a> GHCi will instead use the more modern name <code>Type</code> (which is located in the <code>Data.Kind</code> module).</p>
<pre class="plaintext"><code>ghci&gt; :set -XNoStarIsType
ghci&gt; :k [Integer]
[Integer] :: Type</code></pre>
<p>If you see that a type has kind <code>Type</code> that means it can appear on its own on the right-hand side of a <code>::</code><a href="#fn2" class="footnote-ref" id="fnref2" role="doc-noteref"><sup>2</sup></a>, as in</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">ints ::</span> [<span class="dt">Integer</span>]</span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>ints <span class="ot">=</span> [<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>]</span></code></pre></div>
<p>Of course, it’s hard to understand what being a <code>Type</code> means if you don’t know what types <em>don’t</em> have kind <code>Type</code>. An example of something with kind different from <code>Type</code> is <code>Maybe</code>. <code>Maybe</code> can’t show up on its own as a type signature, it just doesn’t make sense. The same thing goes for <code>Either</code>. However, if we apply <code>Maybe</code> to a type, for example, <code>Int</code>, and then we get a normal type, <code>Maybe Int</code>, which can appear on its own on the right of a <code>::</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">it&#39;sAnIntIPromise ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>it&#39;sAnIntIPromise <span class="ot">=</span> <span class="dt">Just</span> <span class="dv">42</span></span></code></pre></div>
<p>Also notice that we specifically have to give <code>Maybe</code> something of kind <code>Type</code>. It wouldn’t make sense to have a <code>Maybe Either</code>. So if we give <code>Maybe</code> a <code>Type</code>, it becomes a <code>Type</code>. So you might even say that the kind of <code>Maybe</code> is <code>Type -&gt; Type</code>. And indeed GHCi agrees with us:</p>
<pre class="plaintext"><code>ghci&gt; :k Maybe
Maybe :: Type -&gt; Type</code></pre>
<p>Now, what about <code>Either</code>? Just as with <code>Maybe</code> it doesn’t make sense to pass it something that’s not a <code>Type</code>. But even if we pass it a <code>Type</code>, we don’t get a <code>Type</code> just yet, I can’t have an <code>Either Bool</code> in my pocket. But if we pass <code>Either Bool</code> a <code>Type</code> we indeed get a normal bona fide <code>Type</code>, such as <code>Either Bool Int</code>. Meaning, <code>Either Bool</code> must have kind <code>Type -&gt; Type</code>, just like <code>Maybe</code>. But what that means is that if we pass <code>Either</code> a <code>Type</code> we get back a <code>Type -&gt; Type</code>, meaning <code>Either</code> must have kind <code>Type -&gt; (Type -&gt; Type)</code>.</p>
<p>Did you notice? This is currying! Since <code>-&gt;</code> associates to the right by default we can drop the parentheses and say that <code>Either</code> has kind <code>Type -&gt; Type -&gt; Type</code>. Just like with currying functions, there are two equivalent ways of looking at <code>Either</code>. We can look at it as a type that takes two <code>Type</code>s and becomes a <code>Type</code>, or as a type that takes a <code>Type</code> and returns a <code>Type -&gt; Type</code>. Check it in GHCi!</p>
<p>If we try to have something nonsensical like <code>Maybe Either</code> then GHC will give us a <em>kind error</em>:</p>
<pre class="plaintext"><code>λ&gt; type T = Maybe Either

&lt;interactive&gt;:1:16: error:
    • Expecting two more arguments to ‘Either’
      Expected a type, but ‘Either’ has kind ‘Type -&gt; Type -&gt; Type’
    • In the first argument of ‘Maybe’, namely ‘Either’
      In the type ‘Maybe Either’
      In the type declaration for ‘T’</code></pre>
<p>This is the bread and butter of what kinds are for, sanity checking.</p>
<p>Another thing we can notice is that <code>(-&gt;)</code> is just like <code>Either</code>, it takes two <code>Type</code>s and returns a <code>Type</code>, specifically a function type. Another important type to consider is <code>[]</code>, the list type. It takes a type, such as <code>Int</code>, and returns a <code>Type</code>. In fact, <code>[Int]</code> is the same as <code>[] Int</code>, it’s just syntax sugar, you can try it yourself.</p>
<p>Let’s look at a more complex example:</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">data</span> <span class="dt">OfInts</span> f <span class="ot">=</span> <span class="dt">MkOfInts</span> (f <span class="dt">Int</span>)</span></code></pre></div>
<p>This is a pretty weird type. It takes some <code>f</code> and stores an <code>f</code> of <code>Int</code>s. Let’s figure out the kind of <code>OfInts</code>. <code>f</code> must take a type as input since we see <code>f Int</code> appear. But then <code>f Int</code> must be a <code>Type</code> since <code>OfInts</code> stores a value of type <code>f Int</code>. So <code>f</code> must have kind <code>Type -&gt; Type</code>. Now, <code>OfInts f</code> must be a <code>Type</code>, since it’s a fully-fledged datatype that you can have values of. So putting this together, <code>OfInts</code> must take a <code>Type -&gt; Type</code> and returns a <code>Type</code>, meaning it has <code>(Type -&gt; Type) -&gt; Type</code>.</p>
<h3 id="exercises">Exercises</h3>
<ol type="1">
<li><p>Without using GHCi, what is the kind of <code>(,,)</code>, the type constructor for 3-tuples?</p></li>
<li><p>Consider the following datatype declaration:</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">MaybeT</span> m a <span class="ot">=</span> <span class="dt">MaybeT</span> {<span class="ot"> runMaybeT ::</span> m (<span class="dt">Maybe</span> a) }</span></code></pre></div>
<p>Without using GHCi, what is the kind of <code>MaybeT</code>? Note that <code>newtype</code> is the same thing as <code>data</code> as far as the kinds go.</p></li>
<li><p>Consider the following datatype declaration:</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">data</span> <span class="dt">Contrived</span> f g a <span class="ot">=</span> <span class="dt">MkContrived</span> (f <span class="dt">Maybe</span> (<span class="dt">Either</span> a (g <span class="dt">Bool</span>)))</span></code></pre></div>
<p>Without using GHCi, what is the kind of <code>Contrived</code>?</p></li>
</ol>
<h2 id="getting-classy-with-constraint">Getting Classy with <code>Constraint</code></h2>
<p>We’ve seen the kinds of various datatypes, and it seems they always have a kind which is some mix of <code>Type</code> and <code>-&gt;</code> perhaps with some parentheses. What about something a bit different, like <code>Num</code>? Well, as input, it only makes sense to pass <code>Num</code> a <code>Type</code>, such as <code>Int</code> or <code>Double</code>, or even <code>Bool</code>, since <code>Num</code> defines methods like <code>negate :: Num a =&gt; a -&gt; a</code>. Since the function arrow takes <code>Type</code>s as inputs (remember the kind of <code>(-&gt;)</code>?) it means that <code>a</code> must be a <code>Type</code>. What does <code>Num</code> return though? What is the kind of <code>Num Int</code>? Well, this is a new kind called <code>Constraint</code>. A type expression of kind <code>Constraint</code> is any type expression that can appear on the left of a <code>=&gt;</code> in a type signature. For example, the following is legal:</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="ot">what ::</span> <span class="dt">Num</span> <span class="dt">Bool</span> <span class="ot">=&gt;</span> <span class="dt">Bool</span></span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a>what <span class="ot">=</span> <span class="dt">True</span> <span class="op">+</span> <span class="dt">False</span></span></code></pre></div>
<p>This is a bit of an odd example, but it’s an important one to understand. <code>Bool</code> is a type of kind <code>Type</code>, so it’s legal to pass it to <code>Num</code>, and the resulting <code>Constraint</code> is completely valid. Beyond that, unrelated to the kind system, in the definition for <code>what</code> we’ve required that there be a <code>Num Bool</code> instance in scope at the call site. Therefore we can safely use <code>+</code> with our <code>Bool</code>s. Of course, we can’t actually <em>use</em> <code>what</code> without defining this instance. GHC will complain:</p>
<pre class="plaintext"><code>ghci&gt; what

&lt;interactive&gt;:5:1: error:
    • No instance for (Num Bool) arising from a use of ‘what’
    • In the expression: what
      In an equation for ‘it’: it = what</code></pre>
<p>So <code>Num</code> has kind <code>Type -&gt; Constraint</code> since it takes a <code>Type</code> and returns a <code>Constraint</code>. So do many other familiar type classes such as <code>Ord</code>, <code>Show</code>, and <code>Monoid</code>. An example of a typeclass with a more complex kind would be <code>Functor</code>. <code>Functor</code> doesn’t take a <code>Type</code>. For example, it doesn’t make sense to write a <code>Functor Bool</code> instance. To see exactly why let’s look at the type of <code>fmap</code>:</p>
<pre class="plaintext"><code>ghci&gt; :t fmap
fmap :: Functor f =&gt; (a -&gt; b) -&gt; f a -&gt; f b</code></pre>
<p>Since <code>a</code> appears next to a <code>-&gt;</code> it must have kind <code>Type</code>, and similarly <code>f a</code> appears next to a <code>-&gt;</code> so it must also have kind <code>Type</code>. Therefore <code>f</code> must have kind <code>Type -&gt; Type</code>, which makes sense as <code>f</code> could be <code>Maybe</code> or <code>Either Bool</code> for example. So <code>Functor</code> takes a <code>Type -&gt; Type</code> and yields a <code>Constraint</code>, meaning it has kind <code>(Type -&gt; Type) -&gt; Constraint</code>. <code>Applicative</code> must also have the same kind, even without looking at its methods. If we look at the class header for <code>Applicative</code> we see</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">class</span> <span class="dt">Functor</span> f <span class="ot">=&gt;</span> <span class="dt">Applicative</span> f <span class="kw">where</span></span></code></pre></div>
<p>Since <code>f</code> appears as an argument to <code>Functor</code> it must have kind <code>Type -&gt; Type</code> and therefore <code>Applicative</code> must have kind <code>(Type -&gt; Type) -&gt; Constraint</code>. For the same reason, <code>Monad</code> must also have that kind.</p>
<h3 id="exercises-1">Exercises</h3>
<ol type="1">
<li><p>Consider the following (trimmed down) definition of the <code>Bifunctor</code> class:</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">class</span> <span class="dt">Bifunctor</span> p <span class="kw">where</span></span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  bimap ::</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> (c <span class="ot">-&gt;</span> d) <span class="ot">-&gt;</span> p a c <span class="ot">-&gt;</span> p b d</span></code></pre></div>
<p>Without using GHCi, what is the kind of <code>Bifunctor</code>? Don’t worry about understanding what the class is for, just focus on the kinds.</p></li>
<li><p>Haskell has an extension called <a href="https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/exts/multi_param_type_classes.html#extension-MultiParamTypeClasses="><code>MultiParamTypeClasses</code></a>. It allows for typeclass with multiple type parameters. For example, take the following class:</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="kw">class</span> <span class="dt">Convert</span> a b <span class="kw">where</span></span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  convert ::</span> a <span class="ot">-&gt;</span> b</span></code></pre></div>
<p><code>Convert</code> has kind <code>Type -&gt; Type -&gt; Constraint</code>.</p>
<p>Consider the following (simplified) definition of the <code>MonadReader</code> class:</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> <span class="dt">Monad</span> m <span class="ot">=&gt;</span> <span class="dt">MonadReader</span> r m <span class="kw">where</span></span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  ask ::</span> m r</span></code></pre></div>
<p>Without using GHCi, what is the kind of <code>MonadReader</code>?</p></li>
<li><p>Consider the following (simplified) definition of the <code>MonadTrans</code> class:</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">MonadTrans</span> t <span class="kw">where</span></span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  lift ::</span> <span class="dt">Monad</span> m <span class="ot">=&gt;</span> m a <span class="ot">-&gt;</span> t m a</span></code></pre></div>
<p>Without using GHCi, what is the kind of <code>MonadTrans</code>?</p>
<p>Hint: <span class="spoiler">Recall <code>MaybeT</code> from earlier. There is an <code>instance MonadTrans MaybeT</code> defined in the <code>transformers</code> library.</span></p></li>
<li><p>Define your own type such that it could potentially have a <code>MonadTrans</code> instance, considering only the kinds involved.</p></li>
</ol>
<h2 id="yo-dawg-i-heard-you-like-types">Yo Dawg, I Heard You Like Types <!-- TypeInType --></h2>
<p>Consider this curious function:</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">import</span> <span class="dt">Data.Kind</span> (<span class="dt">Type</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="ot">myId ::</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>myId x <span class="ot">=</span> x</span></code></pre></div>
<p>GHC accepts this code, which seems very odd. What’s <code>Type</code> doing in a type signature? I thought <code>Type</code> was a kind? In truth, in modern GHC <em>there is no such thing as a kind</em>. By that, I mean that there’s no separate “kind level” with its own special values. Rather, all kinds are just types. The <code>-&gt;</code> in kinds is the normal function arrow. This is a relatively recent change introduced by the <a href="https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/exts/poly_kinds.html#extension-TypeInType="><code>TypeInType</code> language extension</a> in GHC 8.0 which later became the default way GHC handles kinds (deprecating the <code>TypeInType</code> extension).</p>
<p>If we ask GHCi the kind of <code>Type</code> we get back</p>
<pre class="plaintext"><code>ghci&gt; import Data.Kind
ghci&gt; :k Type
Type</code></pre>
<p>So <code>Type</code> is a normal type that could potentially have values. In actuality, it’s uninhabited like the <code>Void</code> datatype is. As a reminder, <code>Void</code> is an empty datatype, with no values (that don’t loop or crash when evaluated), defined as</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">data</span> <span class="dt">Void</span></span></code></pre></div>
<p>Just like you can have <code>undefined :: Void</code> and <code>myId :: Void -&gt; Void</code> so too you can have <code>undefined :: Type</code> and <code>myId :: Type -&gt; Type</code>.</p>
<p>It’s best to think of “kinds” as a relationship between types. <code>Type</code> “is the kind of” <code>Int</code>. <code>Type -&gt; Type</code> “is the kind of” <code>Maybe</code>. The only thing that differentiates “a kind” from “a type” is that a kind is just a type that happens to be the kind of another type. As an analogy, “a parent” is a person that happens to “be the parent of” another person.</p>
<p>This is cool and all, but perhaps this will make more sense once we learn about <code>DataKinds</code>.</p>
<h3 id="exercises-2">Exercises</h3>
<ol type="1">
<li><p>Write a function with the type <code>Void -&gt; Type</code>. I recommend taking a look at <a href="https://hackage.haskell.org/package/base-4.16.2.0/docs/Data-Void.html"><code>Data.Void</code></a> for this.</p></li>
<li><p>Write a function <code>preposterous :: Type -&gt; a</code>. You can make use of <a href="https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/exts/empty_case.html#extension-EmptyCase=">the <code>EmptyCase</code> extension</a> for this.</p></li>
</ol>
<h2 id="get-promoted-with-datakinds">Get Promoted with <code>DataKinds</code></h2>
<p>Up until now, the only kinds we’ve seen are <code>Type</code>/<code>*</code>, <code>Constraint</code>, and <code>k1 -&gt; k2</code> where <code>k1</code> and <code>k2</code> are themselves kinds. Keep in mind that “kind” here means a type that is the <em>kind of</em> another type. The <a href="https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/exts/data_kinds.html#extension-DataKinds="><code>DataKinds</code> extension</a> opens up the world of kinds and turns every algebraic datatype into a kind. As an example, normally <code>Bool</code> is a type but not a kind. There is no type expression with <code>Bool</code> as its kind. But with <code>DataKinds</code> we get two new type expressions, <code>'False</code> and <code>'True</code>, which both have kind <code>Bool</code>. Notice the tick marks, these are not the same as the term-level <em>values</em> <code>False</code> and <code>True</code>, they exist on the type level. It also doesn’t make sense to have a value whose type is <code>'True</code>, since it only makes sense to have values if your kind is <code>Type</code> and <code>'True</code> has kind <code>Bool</code>, not <code>Type</code>.</p>
<p>So what is this useful for? In general, <code>DataKinds</code> is mostly useful in conjunction with other extensions to the type system, since those extensions are all about manipulating types, and <code>DataKinds</code> gives us a plethora of new types to work with. You’ll notice that I’ve used them in every single one of my previous posts because they’re just that useful.</p>
<p>Just as an example, you can have a datatype that’s parameterized over a <code>Bool</code> type parameter.</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">NonZero</span> (<span class="ot">verified ::</span> <span class="dt">Bool</span>) <span class="ot">=</span> <span class="dt">NonZero</span> <span class="dt">Int</span></span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a>  <span class="co">--              ^^^^^^^^^^^^^^^^^</span></span>
<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a>  <span class="co">--      This is a kind signature, which lets us tell GHC</span></span>
<span id="cb21-4"><a href="#cb21-4" aria-hidden="true" tabindex="-1"></a>  <span class="co">--      what kind `verified` has. Without it, GHC will infer the kind</span></span>
<span id="cb21-5"><a href="#cb21-5" aria-hidden="true" tabindex="-1"></a>  <span class="co">--      to be `Type`.</span></span></code></pre></div>
<p>Then you can have code like</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="ot">mkNonZero ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">NonZero</span> <span class="dt">False</span></span>
<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a>mkNonZero <span class="ot">=</span> <span class="dt">NonZero</span></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="ot">verifyNonZero ::</span> <span class="dt">NonZero</span> <span class="dt">False</span> <span class="ot">-&gt;</span> <span class="dt">Maybe</span> (<span class="dt">NonZero</span> <span class="dt">True</span>)</span>
<span id="cb22-5"><a href="#cb22-5" aria-hidden="true" tabindex="-1"></a>verifyNonZero (<span class="dt">NonZero</span> <span class="dv">0</span>) <span class="ot">=</span> <span class="dt">Nothing</span></span>
<span id="cb22-6"><a href="#cb22-6" aria-hidden="true" tabindex="-1"></a>verifyNonZero (<span class="dt">NonZero</span> n) <span class="ot">=</span> <span class="dt">Just</span> (<span class="dt">NonZero</span> n)</span>
<span id="cb22-7"><a href="#cb22-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb22-8"><a href="#cb22-8" aria-hidden="true" tabindex="-1"></a><span class="ot">divSafe ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">NonZero</span> <span class="dt">True</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span></span>
<span id="cb22-9"><a href="#cb22-9" aria-hidden="true" tabindex="-1"></a>divSafe m (<span class="dt">NonZero</span> n) <span class="ot">=</span> <span class="fu">div</span> m n</span></code></pre></div>
<p>This is a bit of a dumb example since having an unverified <code>NonZero</code> isn’t very useful,
but you can imagine that it might be useful for something like an email address type, for example,
where an unverified email address is syntactically valid, while a verified email address is one
that has been verified to exist, perhaps by sending a verification email.</p>
<h3 id="exercises-3">Exercises</h3>
<ol type="1">
<li><p>Write the data/newtype declaration for an <code>Email</code> type as mentioned above.</p></li>
<li><p>Change the kind of the type parameter from <code>Bool</code> to <code>Verification</code>, where <code>Verification</code> is</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">data</span> <span class="dt">Verification</span> <span class="ot">=</span> <span class="dt">Unverified</span> <span class="op">|</span> <span class="dt">Verified</span></span></code></pre></div></li>
<li><p>Write a hypothetical API for such an email type as type signatures. You can fill in the definitions with <code>undefined</code> or <a href="https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/exts/typed_holes.html">typed holes</a> if you wish.</p></li>
</ol>
<h2 id="some-kind-of-conclusion">Some Kind of Conclusion</h2>
<p>There is much that this article hasn’t covered, such as <code>PolyKinds</code>, <code>TYPE r</code>, and more. The kind system pervades the GHC Haskell language more and more as more type-level programming features are added. This adds many interactions which could each be enough to fill their own article.</p>
<p>One last thing I will note is that since GHC 8.10 you can give your type declarations what are called standalone kind signatures, enabled by the (<em>gasp</em>) <a href="https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/exts/poly_kinds.html#extension-StandaloneKindSignatures="><code>StandaloneKindSignatures</code> language extension</a>. They look much like type signatures do, but with the <code>type</code> keyword in front of them. Some examples:</p>
<div class="sourceCode" id="cb24"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Foo</span><span class="ot"> ::</span> <span class="dt">Type</span> <span class="ot">-&gt;</span> <span class="dt">Type</span></span>
<span id="cb24-2"><a href="#cb24-2" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">Foo</span> a <span class="ot">=</span> <span class="dt">Foo</span> [a]</span>
<span id="cb24-3"><a href="#cb24-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-4"><a href="#cb24-4" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">C</span><span class="ot"> ::</span> <span class="dt">Type</span> <span class="ot">-&gt;</span> <span class="dt">Constraint</span></span>
<span id="cb24-5"><a href="#cb24-5" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> <span class="dt">C</span> a <span class="kw">where</span></span>
<span id="cb24-6"><a href="#cb24-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-7"><a href="#cb24-7" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">NonZero</span><span class="ot"> ::</span> <span class="dt">Bool</span> <span class="ot">-&gt;</span> <span class="dt">Type</span></span>
<span id="cb24-8"><a href="#cb24-8" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">NonZero</span> bool <span class="ot">=</span> <span class="dt">NonZero</span> <span class="dt">Int</span></span>
<span id="cb24-9"><a href="#cb24-9" aria-hidden="true" tabindex="-1"></a>  <span class="co">--     ^^^^</span></span>
<span id="cb24-10"><a href="#cb24-10" aria-hidden="true" tabindex="-1"></a>  <span class="co">--    This is a phantom type parameter of kind Bool</span></span>
<span id="cb24-11"><a href="#cb24-11" aria-hidden="true" tabindex="-1"></a>  <span class="co">--    using DataKinds.</span></span></code></pre></div>
<aside id="footnotes" class="footnotes footnotes-end-of-document" role="doc-endnotes">
<hr />
<ol>
<li id="fn1"><p>Using the more liberal interpretation of “type”, which refers to anything that appears in the type level namespace. This is the terminology the Haskell language report uses along with the more explicit “type expression”.<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn2"><p>I will purposefully be ignoring <code>TYPE r</code> in this post for simplicity.<a href="#fnref2" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</aside>
    </section>
</article>]]></description>
    <pubDate>Tue, 19 Jul 2022 00:00:00 UT</pubDate>
    <guid>https://morrowm.github.io//posts/2022-07-19-kinds.html</guid>
    <dc:creator>MorrowM</dc:creator>
</item>
<item>
    <title>From Partitions to Wordle - Type Safety with Phantom Types</title>
    <link>https://morrowm.github.io//posts/2022-04-04-phantom.html</link>
    <description><![CDATA[<article>
    <section class="header">
        April  4, 2022
        
    </section>
    <section>
        <p>Suppose you had a list that you wanted to split according to some predicate, like splitting it up into the portion that’s greater than 7, and the portion that’s less than 7. Then we could take advantage of the <code>partition</code> function from <code>Data.List</code>:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- A reminder, the type of partition is:</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="ot">partition ::</span> (a <span class="ot">-&gt;</span> <span class="dt">Bool</span>) <span class="ot">-&gt;</span> [a] <span class="ot">-&gt;</span> ([a], [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="co">-- | Moves the elements of a given list that are greater than 7 to the front.</span></span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a><span class="ot">greaterThan7sFirst ::</span> [<span class="dt">Int</span>] <span class="ot">-&gt;</span> [<span class="dt">Int</span>]</span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a>greaterThan7sFirst xs <span class="ot">=</span></span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> (lessThans, greaterThans) <span class="ot">=</span> partition (<span class="op">&gt;</span><span class="dv">7</span>) xs</span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a>  <span class="kw">in</span> greaterThans <span class="op">++</span> lessThans</span></code></pre></div>
<p>Pretty clean, right? Well when we run it:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>ghci<span class="op">&gt;</span> greaterThan7sFirst [<span class="dv">4</span>,<span class="dv">9</span>,<span class="dv">4</span>,<span class="dv">8</span>,<span class="dv">2</span>,<span class="dv">7</span>,<span class="dv">9</span>,<span class="dv">2</span>,<span class="dv">6</span>]</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>[<span class="dv">4</span>,<span class="dv">4</span>,<span class="dv">2</span>,<span class="dv">7</span>,<span class="dv">2</span>,<span class="dv">6</span>,<span class="dv">9</span>,<span class="dv">8</span>,<span class="dv">9</span>]</span></code></pre></div>
<p>Oops! It looks like we put things in the wrong order. The fix is simple, of course, just swap the order in the tuple.
But it’d be nice if we could prevent these sorts of mix-ups from happening in the first place. Also,
it would be nice if we could reflect this in the type signature of <code>partition</code>, that way we don’t even need to read the documentation
every time we want to remember which half of the tuple is which.</p>
<h2 id="the-separate-newtypes-approach">The “separate <code>newtype</code>s” Approach</h2>
<p>So we want to reflect the different meanings of the lists in the type system. So we can create a couple of newtypes:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">TruePart</span> a <span class="ot">=</span> <span class="dt">Trues</span> [a]</span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> (<span class="dt">Eq</span>, <span class="dt">Ord</span>, <span class="dt">Show</span>, <span class="dt">Read</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">newtype</span> <span class="dt">FalsePart</span> a <span class="ot">=</span> <span class="dt">Falses</span> [a]</span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> (<span class="dt">Eq</span>, <span class="dt">Ord</span>, <span class="dt">Show</span>, <span class="dt">Read</span>)</span></code></pre></div>
<p>Then our result tuple will simply contain a true part and a false part.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ot">partitionTyped ::</span> (a <span class="ot">-&gt;</span> <span class="dt">Bool</span>) <span class="ot">-&gt;</span> [a] <span class="ot">-&gt;</span> (<span class="dt">TruePart</span> a, <span class="dt">FalsePart</span> a)</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>partitionTyped p xs <span class="ot">=</span> </span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> (trues, falses) <span class="ot">=</span> partition p xs</span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">in</span> (<span class="dt">Trues</span> trues, <span class="dt">Falses</span> falses)</span></code></pre></div>
<p>Already we have more clarity in the type signature. Now we can adjust our <code>greaterThan7sFirst</code> function to use <code>partitionTyped'</code>:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- | Moves the elements of a given list that are greater than 7 to the front.</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a><span class="ot">greaterThan7sFirst ::</span> [<span class="dt">Int</span>] <span class="ot">-&gt;</span> [<span class="dt">Int</span>]</span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a>greaterThan7sFirst xs <span class="ot">=</span> </span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> (<span class="dt">Falses</span> lessThans, <span class="dt">Trues</span> greaterThans) <span class="ot">=</span> partitionTyped (<span class="op">&gt;</span><span class="dv">7</span>) xs</span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a>  <span class="kw">in</span> greaterThans <span class="op">++</span> lessThans</span></code></pre></div>
<p>Immediately we get a complaint:</p>
<pre class="plaintext"><code>• Couldn&#39;t match type ‘TruePart Int’ with ‘FalsePart a’
  Expected type: (FalsePart a, TruePart a1)
    Actual type: (TruePart Int, FalsePart Int)</code></pre>
<p>This is great! The type checker has successfully saved us from our own foolishness. Fixing our function
makes it type check:</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- | Moves the elements of a given list that are greater than 7 to the front.</span></span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a><span class="ot">greaterThan7sFirst ::</span> [<span class="dt">Int</span>] <span class="ot">-&gt;</span> [<span class="dt">Int</span>]</span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a>greaterThan7sFirst xs <span class="ot">=</span> </span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> (<span class="dt">Trues</span> greaterThans, <span class="dt">Falses</span> lessThans) <span class="ot">=</span> partitionTyped (<span class="op">&gt;</span><span class="dv">7</span>) xs</span>
<span id="cb7-5"><a href="#cb7-5" aria-hidden="true" tabindex="-1"></a>  <span class="kw">in</span> greaterThans <span class="op">++</span> lessThans</span></code></pre></div>
<p>And testing it out, we have our desired behaviour:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a>ghci<span class="op">&gt;</span> greaterThan7sFirst [<span class="dv">4</span>,<span class="dv">9</span>,<span class="dv">4</span>,<span class="dv">8</span>,<span class="dv">2</span>,<span class="dv">7</span>,<span class="dv">9</span>,<span class="dv">2</span>,<span class="dv">6</span>]</span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>[<span class="dv">9</span>,<span class="dv">8</span>,<span class="dv">9</span>,<span class="dv">4</span>,<span class="dv">4</span>,<span class="dv">2</span>,<span class="dv">7</span>,<span class="dv">2</span>,<span class="dv">6</span>]</span></code></pre></div>
<p>This approach does have the downside that we’ve had to introduce two new datatypes to accomplish the task. Any
instances we write for one of them need to be duplicated for the other. What if we had a single type that
did both jobs?</p>
<h2 id="the-phantom-types-approach">The Phantom Types Approach</h2>
<p>Consider the following type instead:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# LANGUAGE DataKinds #-}</span></span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# LANGUAGE KindSignatures #-}</span></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">newtype</span> <span class="dt">Part</span> (<span class="ot">bool ::</span> <span class="dt">Bool</span>) a <span class="ot">=</span> <span class="dt">Part</span> {<span class="ot"> unPart ::</span> [a] } </span></code></pre></div>
<p>This type has a seemingly extraneous type parameter with what appears to be a type signature on it, <code>(bool :: Bool)</code>.
This field is indeed “extraneous” in a sense, but what it does is that when we construct a <code>Part</code> we can choose
what we want <code>bool</code> to be. If we have two values where the value of <code>bool</code> is different, then we won’t be able to
confuse one for the other, since their types will be different, even if the actual runtime values are the same.
<code>bool</code> is called a phantom type parameter, since it doesn’t appear on the right-hand side of the <code>=</code>.</p>
<p>So what sorts of values can <code>bool</code> take on? Well, that syntax that looks like a type signature is actually a <em>kind signature</em>.
So <code>bool</code> exists on the type level and thus has a kind that dictates what sort of values it can take on. In this case,
its kind is <code>Bool</code>, so it can take on any of the values of <code>Bool</code>, meaning <code>True</code> or <code>False</code>. This can be a bit confusing
since normally <code>True</code> and <code>False</code> are runtime values. The <code>DataKinds</code> extension essentially creates two new types
called <code>'True</code> and <code>'False</code> with kind <code>Bool</code>. These are separate from the value level <code>True</code> and <code>False</code>. The compiler
allows us to leave off the tick marks if it’s still clear what we’re referring to. <a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a></p>
<p>What does this look like in practice? Here’s an example:</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="ot">truePart ::</span> <span class="dt">Part</span> <span class="dt">True</span> <span class="dt">Int</span></span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a>truePart <span class="ot">=</span> <span class="dt">Part</span> [<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>,<span class="dv">4</span>]</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="ot">falsePart ::</span> <span class="dt">Part</span> <span class="dt">False</span> <span class="dt">Int</span></span>
<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a>falsePart <span class="ot">=</span> <span class="dt">Part</span> [<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>,<span class="dv">4</span>]</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="co">-- The following gives a type error!</span></span>
<span id="cb10-8"><a href="#cb10-8" aria-hidden="true" tabindex="-1"></a>parts <span class="ot">=</span> [truePart, falsePart]</span></code></pre></div>
<pre class="plaintext"><code>• Couldn&#39;t match type ‘&#39;False’ with ‘&#39;True’
  Expected type: Part &#39;True Int
    Actual type: Part &#39;False Int</code></pre>
<p>So we can’t define <code>parts</code> since it would have two elements of different types, even though
their contents are the same. This is a good thing, we can use this to implement
a type-safe <code>partition</code>:</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="ot">partitionTyped ::</span> (a <span class="ot">-&gt;</span> <span class="dt">Bool</span>) <span class="ot">-&gt;</span> [a] <span class="ot">-&gt;</span> (<span class="dt">Part</span> <span class="dt">True</span> a, <span class="dt">Part</span> <span class="dt">False</span> a)</span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a>partitionTyped p xs <span class="ot">=</span> </span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> (trues, falses) <span class="ot">=</span> partition p xs</span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">in</span> (<span class="dt">Part</span> trues, <span class="dt">Part</span> falses)</span></code></pre></div>
<p>There’s an issue when we go to implement <code>greaterThan7sFirst</code>, though. We don’t have two
separate constructors to match on as we did with the newtypes. We can work around that,
but it’s not very ergonomic:</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="ot">greaterThan7sFirst ::</span> [<span class="dt">Int</span>] <span class="ot">-&gt;</span> [<span class="dt">Int</span>]</span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a>greaterThan7sFirst xs <span class="ot">=</span> </span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span><span class="ot"> greaterThans ::</span> <span class="dt">Part</span> <span class="dt">True</span> <span class="dt">Int</span></span>
<span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a><span class="ot">      lessThans ::</span> <span class="dt">Part</span> <span class="dt">False</span> <span class="dt">Int</span></span>
<span id="cb13-5"><a href="#cb13-5" aria-hidden="true" tabindex="-1"></a>      (greaterThans, lessThans) <span class="ot">=</span> partitionTyped (<span class="op">&gt;</span><span class="dv">7</span>) xs</span>
<span id="cb13-6"><a href="#cb13-6" aria-hidden="true" tabindex="-1"></a>  <span class="kw">in</span> unPart greaterThans <span class="op">++</span> unPart lessThans</span></code></pre></div>
<p>It would be much nicer to have separate constructors that we could match on like with the
two newtypes. Turns out pattern synonyms are just the thing we need!</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# LANGUAGE PatternSynonyms #-}</span></span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a><span class="kw">pattern</span> <span class="dt">Trues</span><span class="ot"> ::</span> [a] <span class="ot">-&gt;</span> <span class="dt">Part</span> <span class="dt">True</span> a</span>
<span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a><span class="kw">pattern</span> <span class="dt">Trues</span> xs <span class="ot">=</span> <span class="dt">Part</span> xs</span>
<span id="cb14-5"><a href="#cb14-5" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# COMPLETE Trues #-}</span></span>
<span id="cb14-6"><a href="#cb14-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb14-7"><a href="#cb14-7" aria-hidden="true" tabindex="-1"></a><span class="kw">pattern</span> <span class="dt">Falses</span><span class="ot"> ::</span> [a] <span class="ot">-&gt;</span> <span class="dt">Part</span> <span class="dt">False</span> a</span>
<span id="cb14-8"><a href="#cb14-8" aria-hidden="true" tabindex="-1"></a><span class="kw">pattern</span> <span class="dt">Falses</span> xs <span class="ot">=</span> <span class="dt">Part</span> xs</span>
<span id="cb14-9"><a href="#cb14-9" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# COMPLETE Falses #-}</span></span></code></pre></div>
<p>So pattern synonyms allow us to define, well, synonyms for existing patterns. In this case,
we’ve defined two patterns <code>Trues</code> and <code>Falses</code> that are the same as <code>Part</code>. The only difference
is that we’ve restricted their types. If we ask GHCi the type of <code>Part</code> we get:</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a>ghci<span class="op">&gt;</span> <span class="op">:</span>t <span class="dt">Part</span></span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a><span class="dt">Part</span><span class="ot"> ::</span> [a] <span class="ot">-&gt;</span> <span class="dt">Part</span> bool a</span></code></pre></div>
<p>So of course, <code>Part</code> can return a <code>Part</code> with any value of <code>bool</code> that we choose. In the case of <code>Trues</code> we
want to restrict its type to only match when the type of the receiving value has a <code>bool</code> parameter
equal to <code>True</code>. By giving <code>Trues</code> this restricted type we accomplish two things:</p>
<ol type="1">
<li>Any values <em>created</em> with <code>Trues</code> will have <code>True</code> as the <code>bool</code> type parameter.</li>
<li>Any values <em>matched on</em> by <code>Trues</code> must have <code>True</code> as the <code>bool</code> type parameter.</li>
</ol>
<p>In this case, we’re concerned with the second behaviour, but the first is nice to have as well. So if we go into GHCi we can witness these two facts in action:</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a>ghci<span class="op">&gt;</span> <span class="co">-- Fact 1:</span></span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a>ghci<span class="op">&gt;</span> <span class="op">:</span>t <span class="dt">Trues</span> <span class="st">&quot;abcd&quot;</span></span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a><span class="dt">Trues</span> <span class="st">&quot;abcd&quot;</span><span class="ot"> ::</span> <span class="dt">Part</span> <span class="dt">&#39;True</span> <span class="dt">Char</span></span>
<span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a>ghci<span class="op">&gt;</span> <span class="co">-- Fact 2:</span></span>
<span id="cb16-5"><a href="#cb16-5" aria-hidden="true" tabindex="-1"></a>ghci<span class="op">&gt;</span> <span class="dt">Trues</span> t <span class="ot">=</span> truePart</span>
<span id="cb16-6"><a href="#cb16-6" aria-hidden="true" tabindex="-1"></a>ghci<span class="op">&gt;</span> <span class="dt">Falses</span> f <span class="ot">=</span> truePart</span>
<span id="cb16-7"><a href="#cb16-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb16-8"><a href="#cb16-8" aria-hidden="true" tabindex="-1"></a><span class="op">&lt;</span>interactive<span class="op">&gt;:</span><span class="dv">9</span><span class="op">:</span><span class="dv">12</span><span class="op">:</span> <span class="fu">error</span><span class="op">:</span></span>
<span id="cb16-9"><a href="#cb16-9" aria-hidden="true" tabindex="-1"></a>    • <span class="dt">Couldn&#39;t</span> match <span class="kw">type</span> ‘<span class="dt">&#39;True</span>’ with ‘<span class="dt">&#39;False</span>’</span>
<span id="cb16-10"><a href="#cb16-10" aria-hidden="true" tabindex="-1"></a>      <span class="dt">Expected</span> <span class="kw">type</span><span class="op">:</span> <span class="dt">Part</span> <span class="dt">&#39;False</span> <span class="dt">Int</span></span>
<span id="cb16-11"><a href="#cb16-11" aria-hidden="true" tabindex="-1"></a>        <span class="dt">Actual</span> <span class="kw">type</span><span class="op">:</span> <span class="dt">Part</span> <span class="dt">&#39;True</span> <span class="dt">Int</span></span>
<span id="cb16-12"><a href="#cb16-12" aria-hidden="true" tabindex="-1"></a>    • <span class="dt">In</span> the expression<span class="op">:</span> truePart</span>
<span id="cb16-13"><a href="#cb16-13" aria-hidden="true" tabindex="-1"></a>      <span class="dt">In</span> a <span class="kw">pattern</span> binding<span class="op">:</span> <span class="dt">Falses</span> f <span class="ot">=</span> truePart</span></code></pre></div>
<p>The <code>COMPLETE</code> pragmas above are there to tell GHC that when pattern matching, matching only on
<code>Trues</code> (or only on <code>Falses</code>) constitutes a complete pattern match, this way GHC doesn’t give
us a “missing patterns” warning if we don’t provide a fallback case.</p>
<p>Now we can implement <code>greaterThan7sFirst</code> nicely:</p>
<div class="sourceCode" id="cb17"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a><span class="ot">greaterThan7sFirst ::</span> [<span class="dt">Int</span>] <span class="ot">-&gt;</span> [<span class="dt">Int</span>]</span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a>greaterThan7sFirst xs <span class="ot">=</span> </span>
<span id="cb17-3"><a href="#cb17-3" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> (<span class="dt">Trues</span> greaterThans, <span class="dt">Falses</span> lessThans) <span class="ot">=</span> partitionTyped (<span class="op">&gt;</span><span class="dv">7</span>) xs</span>
<span id="cb17-4"><a href="#cb17-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">in</span> greaterThans <span class="op">++</span> lessThans</span></code></pre></div>
<p>And if we mess up then we get an error:</p>
<div class="sourceCode" id="cb18"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="ot">greaterThan7sFirst ::</span> [<span class="dt">Int</span>] <span class="ot">-&gt;</span> [<span class="dt">Int</span>]</span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a>greaterThan7sFirst xs <span class="ot">=</span> </span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> (<span class="dt">Falses</span> lessThans, <span class="dt">Trues</span> greaterThans) <span class="ot">=</span> partitionTyped (<span class="op">&gt;</span><span class="dv">7</span>) xs</span>
<span id="cb18-4"><a href="#cb18-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">in</span> greaterThans <span class="op">++</span> lessThans</span></code></pre></div>
<pre class="plaintext"><code>• Couldn&#39;t match type ‘&#39;True’ with ‘&#39;False’
  Expected type: (Part &#39;False Int, Part &#39;True Int)
    Actual type: (Part &#39;True Int, Part &#39;False Int)</code></pre>
<p>Nice. As a bonus, let’s implement <code>Show</code> instances that display the results
using our pattern synonym syntax. We’ll need <code>FlexibleInstances</code> to convince GHC
that it’s okay to write separate instances for <code>True</code> and <code>False</code>.</p>
<div class="sourceCode" id="cb20"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# LANGUAGE FlexibleInstances #-}</span></span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Show</span> a <span class="ot">=&gt;</span> <span class="dt">Show</span> (<span class="dt">Part</span> <span class="dt">False</span> a) <span class="kw">where</span></span>
<span id="cb20-4"><a href="#cb20-4" aria-hidden="true" tabindex="-1"></a>  <span class="fu">showsPrec</span> n (<span class="dt">Falses</span> xs) <span class="ot">=</span> <span class="fu">showParen</span> (n <span class="op">&gt;</span> <span class="dv">10</span>) (<span class="fu">showString</span> <span class="st">&quot;Falses &quot;</span> <span class="op">.</span> <span class="fu">shows</span> xs) </span>
<span id="cb20-5"><a href="#cb20-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb20-6"><a href="#cb20-6" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Show</span> a <span class="ot">=&gt;</span> <span class="dt">Show</span> (<span class="dt">Part</span> <span class="dt">True</span> a) <span class="kw">where</span></span>
<span id="cb20-7"><a href="#cb20-7" aria-hidden="true" tabindex="-1"></a>  <span class="fu">showsPrec</span> n (<span class="dt">Trues</span> xs) <span class="ot">=</span> <span class="fu">showParen</span> (n <span class="op">&gt;</span> <span class="dv">10</span>) (<span class="fu">showString</span> <span class="st">&quot;Trues &quot;</span> <span class="op">.</span> <span class="fu">shows</span> xs)</span></code></pre></div>
<div class="sourceCode" id="cb21"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a>ghci<span class="op">&gt;</span> partitionTyped (<span class="op">&gt;</span><span class="dv">7</span>) [<span class="dv">4</span>,<span class="dv">9</span>,<span class="dv">4</span>,<span class="dv">8</span>,<span class="dv">2</span>,<span class="dv">7</span>,<span class="dv">9</span>,<span class="dv">2</span>,<span class="dv">6</span>]</span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a>(<span class="dt">Trues</span> [<span class="dv">9</span>,<span class="dv">8</span>,<span class="dv">9</span>],<span class="dt">Falses</span> [<span class="dv">4</span>,<span class="dv">4</span>,<span class="dv">2</span>,<span class="dv">7</span>,<span class="dv">2</span>,<span class="dv">6</span>])</span></code></pre></div>
<h2 id="wordle-guesses-and-masters">Wordle: Guesses and Masters</h2>
<p>This particular motivating example may feel a bit overcomplicated for what it’s trying to do, and
indeed the solution with two newtypes was already quite satisfactory. The benefits to using phantom types
with <code>DataKinds</code> really come up more in situations where you may want to work more with the type, unlike here where it exists purely to be pattern matched on immediately like in this example.</p>
<p>As an example, a while ago I wrote a
<a href="https://github.com/morrowm/turtlet">Wordle solver</a> that makes use of this technique to differentiate
between words that represent a guess versus words that represent a possible solution. In that case, I had
something like</p>
<div class="sourceCode" id="cb22"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- &quot;Wordlet&quot; is a cutesy word that I use to refer to a Wordle word.</span></span>
<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">WordletType</span> <span class="ot">=</span> <span class="dt">Guess</span> <span class="op">|</span> <span class="dt">Master</span></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">newtype</span> <span class="dt">Wordlet</span> (<span class="ot">wlty ::</span> <span class="dt">WordletType</span>) <span class="ot">=</span> <span class="dt">Wordlet</span> { <span class="op">...</span> }</span>
<span id="cb22-5"><a href="#cb22-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb22-6"><a href="#cb22-6" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">WordList</span> (<span class="ot">wlty ::</span> <span class="dt">WordletType</span>) <span class="ot">=</span> <span class="dt">WordList</span> {<span class="ot"> getWordList ::</span> <span class="dt">Data.Vector.Vector</span> (<span class="dt">Wordlet</span> wlty) }</span></code></pre></div>
<p>Because words and word lists are tagged, it means that on the one hand, I have type safety, so if I have a
function like</p>
<div class="sourceCode" id="cb23"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb23-1"><a href="#cb23-1" aria-hidden="true" tabindex="-1"></a><span class="ot">againstMaster ::</span> <span class="dt">Wordlet</span> <span class="dt">Guess</span> <span class="ot">-&gt;</span> <span class="dt">Wordlet</span> <span class="dt">Master</span> <span class="ot">-&gt;</span> <span class="dt">Colors</span></span></code></pre></div>
<p>which checks a given guess word against a candidate master word, then I can use
it to write the following function, which checks if a given guess word and feedback
to that guess word is consistent with some possible master word:</p>
<div class="sourceCode" id="cb24"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a><span class="ot">consistentWith ::</span> <span class="dt">Colors</span> <span class="ot">-&gt;</span> <span class="dt">Wordlet</span> <span class="dt">Guess</span> <span class="ot">-&gt;</span> <span class="dt">Wordlet</span> <span class="dt">Master</span> <span class="ot">-&gt;</span> <span class="dt">Bool</span></span>
<span id="cb24-2"><a href="#cb24-2" aria-hidden="true" tabindex="-1"></a>consistentWith colors guess master <span class="ot">=</span> guess <span class="ot">`againstMaster`</span> master <span class="op">==</span> colors</span></code></pre></div>
<p>This is just a small example, but the fact that words are tagged ensures that I can’t mess up
the argument order when applying <code>againstMaster</code>. Another example would be the <code>filterMasters</code>
function, which filters a word list full of master word candidates to only those that
are consistent with a given guess word and response to that guess word</p>
<div class="sourceCode" id="cb25"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a><span class="ot">filterMasters ::</span> <span class="dt">Colors</span> <span class="ot">-&gt;</span> <span class="dt">Wordlet</span> <span class="dt">Guess</span> <span class="ot">-&gt;</span> <span class="dt">WordList</span> <span class="dt">Master</span> <span class="ot">-&gt;</span> <span class="dt">WordList</span> <span class="dt">Master</span></span>
<span id="cb25-2"><a href="#cb25-2" aria-hidden="true" tabindex="-1"></a>filterMasters colors guess (<span class="dt">WordList</span> masters) <span class="ot">=</span></span>
<span id="cb25-3"><a href="#cb25-3" aria-hidden="true" tabindex="-1"></a>  <span class="dt">WordList</span> <span class="op">$</span> Data.Vector.filter (consistentWith colors guess) masters</span></code></pre></div>
<p>The types guide us towards a solution. We have a vector of <code>WordList Master</code>s and we want
to filter it. So of course we need <code>Data.Vector.filter</code>. The filtering function needs to combine
some <code>Colors</code>, a <code>Wordlet Guess</code> and a <code>WordLet Master</code> in some way to give us a <code>Bool</code>. This is
exactly <code>consistentWith</code>. <a href="#fn2" class="footnote-ref" id="fnref2" role="doc-noteref"><sup>2</sup></a></p>
<p>When I first added these phantom types to my code it indeed found a couple of places where I was
implicitly confusing a master word for a guess word.</p>
<p>As far as how this is beneficial over a couple of newtypes, it means that I don’t need separate functions
for dealing with guess words and master words in cases where it doesn’t matter. For example:</p>
<div class="sourceCode" id="cb26"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb26-1"><a href="#cb26-1" aria-hidden="true" tabindex="-1"></a><span class="ot">wordletToString ::</span> <span class="dt">Wordlet</span> wlty <span class="ot">-&gt;</span> <span class="dt">String</span></span>
<span id="cb26-2"><a href="#cb26-2" aria-hidden="true" tabindex="-1"></a><span class="ot">parseWordlet ::</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Either</span> <span class="dt">Text</span> (<span class="dt">Wordlet</span> wlty)</span></code></pre></div>
<p>In both of these cases it doesn’t matter whether we’re dealing with a guess word or a master word, and
the phantom types approach makes it very easy to be polymorphic over the type of word, since the implementation
is the same, and thus they only involve a single function body.</p>
<p>So we’ve learned today that phantom types give us the ability to both communicate more in our type signatures, and they
can help us prevent mistakes and misuses by allowing us to track where a value came from.</p>
<p><a href="https://gist.github.com/MorrowM/ba41e2cc9ab57ef6df8c651452aa53c5">Link to the full code for this post</a></p>
<aside id="footnotes" class="footnotes footnotes-end-of-document" role="doc-endnotes">
<hr />
<ol>
<li id="fn1"><p>If we had another type in scope that happened to be called <code>True</code> then we’d need to use ticks
in order for GHC to understand that we’re referring to the lifted version of the value <code>True</code> and
not the type <code>True</code>.<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn2"><p>Presumably, I used <code>againstMaster</code> directly first and then abstracted it out into <code>consistentWith</code>, but
the point still stands- <code>againstMaster</code> is the obvious choice for comparing some <code>Colors</code> combined
with a guess word and a master word, just by looking at the types involved.<a href="#fnref2" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</aside>
    </section>
</article>]]></description>
    <pubDate>Mon, 04 Apr 2022 00:00:00 UT</pubDate>
    <guid>https://morrowm.github.io//posts/2022-04-04-phantom.html</guid>
    <dc:creator>MorrowM</dc:creator>
</item>
<item>
    <title>Tying Shoes with GADTs</title>
    <link>https://morrowm.github.io//posts/2021-08-02-shoes.html</link>
    <description><![CDATA[<article>
    <section class="header">
        August  2, 2021
        
    </section>
    <section>
        <p>How do you put on your shoes?</p>
<p>Do you put them both on and then tie them both? In what order? Do you put on one shoe, tie it and then do the other one? That might be a bit odd, but it’s acceptable. Anyone who ties either of their shoes <em>before</em> putting them on is a no-go, though. And since my Haskell file is my world, and GHC is my enforcer, let’s make this state of affairs <em>unrepresentable</em>.</p>
<h2 id="a-brief-introduction-to-gadts">A brief introduction to GADTs</h2>
<p><code>Maybe</code> is an algebraic data type (ADT for short) that we all know and love. It’s defined as:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode hs"><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">Maybe</span> a <span class="ot">=</span> <span class="dt">Nothing</span> <span class="op">|</span> <span class="dt">Just</span> a</span></code></pre></div>
<p>We can ask GHCi the types of the data constructors:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>λ<span class="op">&gt;</span> <span class="op">:</span>t <span class="dt">Nothing</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="dt">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> a</span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>λ<span class="op">&gt;</span> <span class="op">:</span>t <span class="dt">Just</span></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a><span class="dt">Just</span><span class="ot"> ::</span> a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a</span></code></pre></div>
<p>Cool! This even defines what <code>Maybe</code> is. It would also be pretty cool if we could define <code>Maybe</code> that way.<a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a></p>
<div class="sourceCode" id="cb3"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Maybe</span> a <span class="kw">where</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> a</span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Just</span><span class="ot"> ::</span> a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a</span></code></pre></div>
<p>Of course, the return types of these constructors have to be the same. But what if things didn’t have to be that way?</p>
<p>Consider the following data type:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Expr</span> a <span class="kw">where</span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>  <span class="dt">ABool</span><span class="ot"> ::</span> <span class="dt">Bool</span> <span class="ot">-&gt;</span> <span class="dt">Expr</span> <span class="dt">Bool</span></span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>  <span class="dt">AnInt</span><span class="ot"> ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Expr</span> <span class="dt">Int</span></span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a>  <span class="dt">If</span><span class="ot">    ::</span> <span class="dt">Expr</span> <span class="dt">Bool</span> <span class="ot">-&gt;</span> <span class="dt">Expr</span> a <span class="ot">-&gt;</span> <span class="dt">Expr</span> a <span class="ot">-&gt;</span> <span class="dt">Expr</span> a</span></code></pre></div>
<p>If we could make such a data type, then an expression like <code>If (ABool True) (AnInt 5) (AnInt 7)</code> would be fine, while an expression <code>If  (AnInt 5) (AnInt 5) (AnInt 7)</code> wouldn’t type-check, since <code>If</code> expects an <code>Expr Bool</code> as its first argument. Similarly, the following expression would also not type-check: <code>If (ABool False) (AnInt 6) (ABool 5)</code>. <code>If</code> expects its second and third arguments to have the same type, which is not true in this case.</p>
<p>This sort of data type can indeed be defined if you enable the GHC <code>GADTs</code> language extension, a GADT being a generalized ADT. If we didn’t index our expressions by their types like this, we wouldn’t have been able to prevent the programmer from constructing these invalid expressions.</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode hs"><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">Expr</span> <span class="ot">=</span> <span class="dt">ABool</span> <span class="dt">Bool</span> <span class="op">|</span> <span class="dt">AnInt</span> <span class="dt">Int</span> <span class="op">|</span> <span class="dt">If</span> <span class="dt">Expr</span> <span class="dt">Expr</span> <span class="dt">Expr</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a>thisTypeChecks <span class="ot">=</span> <span class="dt">If</span> (<span class="dt">AnInt</span> <span class="dv">8</span>) (<span class="dt">ABool</span> <span class="dt">True</span>) (<span class="dt">AnInt</span> <span class="dv">4</span>)</span></code></pre></div>
<p>We can use a similar principle to construct valid shoe-tying methods.</p>
<h2 id="using-gadts-to-make-illegal-states-unrepresentable">Using GADTs to make illegal states unrepresentable</h2>
<p>First, we need to define what states a shoe can be in.</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">ShoeState</span> <span class="ot">=</span> <span class="dt">Off</span> <span class="op">|</span> <span class="dt">Untied</span> <span class="op">|</span> <span class="dt">On</span></span></code></pre></div>
<p>So a shoe is either completely off, on but untied, or on.</p>
<p>Let’s define what operations we can perform on our pair of shoes, by using a GADT.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Shoes</span> l r <span class="kw">where</span></span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- Both shoes can be off:</span></span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a>  <span class="dt">OffLR</span><span class="ot"> ::</span> <span class="dt">Shoes</span> <span class="dt">Off</span> <span class="dt">Off</span></span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- If a shoe is off, we can put it on:</span></span>
<span id="cb7-5"><a href="#cb7-5" aria-hidden="true" tabindex="-1"></a>  <span class="dt">PutOnL</span><span class="ot"> ::</span> <span class="dt">Shoes</span> <span class="dt">Off</span> r <span class="ot">-&gt;</span> <span class="dt">Shoes</span> <span class="dt">Untied</span> r </span>
<span id="cb7-6"><a href="#cb7-6" aria-hidden="true" tabindex="-1"></a>  <span class="dt">PutOnR</span><span class="ot"> ::</span> <span class="dt">Shoes</span> l <span class="dt">Off</span> <span class="ot">-&gt;</span> <span class="dt">Shoes</span> l <span class="dt">Untied</span></span>
<span id="cb7-7"><a href="#cb7-7" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- If a shoe is on, but untied, we can tie it:</span></span>
<span id="cb7-8"><a href="#cb7-8" aria-hidden="true" tabindex="-1"></a>  <span class="dt">TieL</span><span class="ot">   ::</span> <span class="dt">Shoes</span> <span class="dt">Untied</span> r <span class="ot">-&gt;</span> <span class="dt">Shoes</span> <span class="dt">On</span> r </span>
<span id="cb7-9"><a href="#cb7-9" aria-hidden="true" tabindex="-1"></a>  <span class="dt">TieR</span><span class="ot">   ::</span> <span class="dt">Shoes</span> l <span class="dt">Untied</span> <span class="ot">-&gt;</span> <span class="dt">Shoes</span> l <span class="dt">On</span></span></code></pre></div>
<p>This is pretty cool. We’re defining a set of valid state transitions, and enforcing it in the type system.</p>
<p>One other thing to note here is that we’re using the <code>DataKinds</code> extension to allow us to use these runtime values (<code>Off</code>, <code>Untied</code>, and <code>On</code>) in our types. We could have defined empty dummy types with no constructors (e.g <code>data Off</code>), but using <code>DataKinds</code> will give us tighter control over the types and give better error messages when we mess up.</p>
<p>We can also define a valid shoe tying method to be a function from <code>Off</code> shoes to <code>On</code> shoes.</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> <span class="dt">Method</span> <span class="ot">=</span> <span class="dt">Shoes</span> <span class="dt">Off</span> <span class="dt">Off</span> <span class="ot">-&gt;</span> <span class="dt">Shoes</span> <span class="dt">On</span> <span class="dt">On</span></span></code></pre></div>
<p>It almost reads like English, nice.<a href="#fn2" class="footnote-ref" id="fnref2" role="doc-noteref"><sup>2</sup></a> One last thing is we’ll define a flipped composition operator so that we can compose our constructors from left to right, as opposed to <code>(.)</code> which composes right to left.</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a>(<span class="op">&gt;&gt;&gt;</span>) <span class="ot">=</span> <span class="fu">flip</span> (<span class="op">.</span>)</span></code></pre></div>
<p>Let’s define our first method.</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="ot">rllr ::</span> <span class="dt">Method</span></span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a>rllr <span class="ot">=</span> <span class="dt">PutOnR</span> <span class="op">&gt;&gt;&gt;</span> <span class="dt">PutOnL</span> <span class="op">&gt;&gt;&gt;</span> <span class="dt">TieL</span> <span class="op">&gt;&gt;&gt;</span> <span class="dt">TieR</span></span></code></pre></div>
<p>It type-checks, great! Let’s see what happens when we try to tie our shoes before we put them on.</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="ot">don&#39;t ::</span> <span class="dt">Method</span></span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a>don&#39;t <span class="ot">=</span> <span class="dt">TieR</span> <span class="op">&gt;&gt;&gt;</span> <span class="dt">TieL</span> <span class="op">&gt;&gt;&gt;</span> <span class="dt">PutOnR</span> <span class="op">&gt;&gt;&gt;</span> <span class="dt">PutOnL</span></span></code></pre></div>
<p>We get a bunch of type errors, which is exactly what we wanted.</p>
<pre class="plaintext"><code>Shoe.hs: error:
    • Couldn&#39;t match type ‘&#39;Off’ with ‘&#39;On’
      Expected type: Shoes &#39;On &#39;On -&gt; Shoes &#39;On &#39;Untied
        Actual type: Shoes &#39;On &#39;Off -&gt; Shoes &#39;On &#39;Untied
   |
   | don&#39;t = TieR &gt;&gt;&gt; TieL &gt;&gt;&gt; PutOnR &gt;&gt;&gt; PutOnL
   |                           ^^^^^^</code></pre>
<p>One last thing we can do is since these are runtime values, we could print them as user-friendly instructions.</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="ot">describe ::</span> <span class="dt">Method</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> ()</span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a>describe method <span class="ot">=</span> go (method <span class="dt">OffLR</span>) <span class="op">*&gt;</span> <span class="fu">putStrLn</span> <span class="st">&quot;Done!&quot;</span></span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a>  <span class="kw">where</span></span>
<span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a><span class="ot">    go ::</span> <span class="dt">Shoes</span> l r <span class="ot">-&gt;</span> <span class="dt">IO</span> ()</span>
<span id="cb13-5"><a href="#cb13-5" aria-hidden="true" tabindex="-1"></a>    go <span class="dt">OffLR</span> <span class="ot">=</span> <span class="fu">putStrLn</span> <span class="st">&quot;Alright.&quot;</span></span>
<span id="cb13-6"><a href="#cb13-6" aria-hidden="true" tabindex="-1"></a>    go (<span class="dt">PutOnL</span> x) <span class="ot">=</span> go x <span class="op">*&gt;</span> <span class="fu">putStrLn</span> <span class="st">&quot;Put on the left shoe.&quot;</span></span>
<span id="cb13-7"><a href="#cb13-7" aria-hidden="true" tabindex="-1"></a>    go (<span class="dt">PutOnR</span> x) <span class="ot">=</span> go x <span class="op">*&gt;</span> <span class="fu">putStrLn</span> <span class="st">&quot;Put on the right shoe.&quot;</span></span>
<span id="cb13-8"><a href="#cb13-8" aria-hidden="true" tabindex="-1"></a>    go (<span class="dt">TieL</span> x) <span class="ot">=</span> go x <span class="op">*&gt;</span> <span class="fu">putStrLn</span> <span class="st">&quot;Tie the left shoe.&quot;</span></span>
<span id="cb13-9"><a href="#cb13-9" aria-hidden="true" tabindex="-1"></a>    go (<span class="dt">TieR</span> x) <span class="ot">=</span> go x <span class="op">*&gt;</span> <span class="fu">putStrLn</span> <span class="st">&quot;Tie the right shoe.&quot;</span></span></code></pre></div>
<p>Note that the type signature on <code>go</code> is required, the type-checker can’t infer it. This is part of the price we pay with GADTs, expressions don’t always have a principal<a href="#fn3" class="footnote-ref" id="fnref3" role="doc-noteref"><sup>3</sup></a> type.</p>
<p>We can run it, and finally, get some instructions on how to put on and tie our shoes.</p>
<pre class="plaintext"><code>λ&gt; describe rllr
Alright.
Put on the right shoe.
Put on the left shoe.
Tie the left shoe.
Tie the right shoe.
Done!</code></pre>
<p><a href="https://gist.github.com/MorrowM/6cd60264dd2efdd5633522c1a7242dde">Link to the complete code</a></p>
<aside id="footnotes" class="footnotes footnotes-end-of-document" role="doc-endnotes">
<hr />
<ol>
<li id="fn1"><p>We can, in fact, do this with the GHC language extension <code>GADTSyntax</code>, which will be on by default starting in GHC 9.2. Of course, we’re getting ahead of ourselves.<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn2"><p>In fact, we won’t even need <code>OffLR</code> to define a <code>Method</code>. We will need it if we want to pattern match on them though, which we’ll do later when writing the <code>describe</code> function.<a href="#fnref2" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
<li id="fn3"><p>Unambiguous and most general. A simple example is with our <code>Expr</code> type from earlier:</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a>foo (<span class="dt">ABool</span> b) <span class="ot">=</span> b</span></code></pre></div>
<p>Both <code>foo :: Expr a -&gt; a</code> and <code>foo :: Expr a -&gt; Bool</code> are valid types to give <code>foo</code> here, neither being more general than the other.<a href="#fnref3" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</aside>
    </section>
</article>]]></description>
    <pubDate>Mon, 02 Aug 2021 00:00:00 UT</pubDate>
    <guid>https://morrowm.github.io//posts/2021-08-02-shoes.html</guid>
    <dc:creator>MorrowM</dc:creator>
</item>
<item>
    <title>Associated Types In Two Different Ways</title>
    <link>https://morrowm.github.io//posts/2021-06-26-assoc.html</link>
    <description><![CDATA[<article>
    <section class="header">
        June 26, 2021
        
    </section>
    <section>
        <p>Suppose you wanted to write a type class for indexable containers. It might look something like this:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> <span class="dt">Indexed</span> f <span class="kw">where</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  (!?) ::</span> f a <span class="ot">-&gt;</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a</span></code></pre></div>
<p>We could then go on to write instances for our favorite types:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Indexed</span> [] <span class="kw">where</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>  [] <span class="op">!?</span> _ <span class="ot">=</span> <span class="dt">Nothing</span></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>  (x<span class="op">:</span>xs) <span class="op">!?</span> n</span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>    <span class="op">|</span> n <span class="op">==</span> <span class="dv">0</span>    <span class="ot">=</span> <span class="dt">Just</span> x</span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a>    <span class="op">|</span> n <span class="op">&gt;</span> <span class="dv">0</span>     <span class="ot">=</span> xs <span class="op">!?</span> (n <span class="op">-</span> <span class="dv">1</span>)</span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a>    <span class="op">|</span> <span class="fu">otherwise</span> <span class="ot">=</span> <span class="dt">Nothing</span></span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Indexed</span> <span class="dt">Vector</span> <span class="kw">where</span></span>
<span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a>  (<span class="op">!?</span>) <span class="ot">=</span> (<span class="op">V.!?</span>)</span>
<span id="cb2-10"><a href="#cb2-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-11"><a href="#cb2-11" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Indexed</span> <span class="dt">IntMap</span> <span class="kw">where</span></span>
<span id="cb2-12"><a href="#cb2-12" aria-hidden="true" tabindex="-1"></a>  (<span class="op">!?</span>) <span class="ot">=</span> (<span class="op">IntMap.!?</span>)</span></code></pre></div>
<p>But now, we decide that we also want to be able to index <code>Map</code>s as well. The issue is that we’ve already hard-coded the index type to be <code>Int</code>.</p>
<h2 id="associated-type-families">Associated Type Families</h2>
<p>One way to allow arbitrary index types is to use an associated type family:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# LANGUAGE TypeFamilies #-}</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> <span class="dt">Indexed</span> f <span class="kw">where</span></span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a>  <span class="kw">type</span> <span class="dt">Idx</span> f</span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a><span class="ot">  (!?) ::</span> f a <span class="ot">-&gt;</span> <span class="dt">Idx</span> f <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a</span>
<span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-8"><a href="#cb3-8" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Indexed</span> [] <span class="kw">where</span></span>
<span id="cb3-9"><a href="#cb3-9" aria-hidden="true" tabindex="-1"></a>  <span class="kw">type</span> <span class="dt">Idx</span> [] <span class="ot">=</span> <span class="dt">Int</span></span>
<span id="cb3-10"><a href="#cb3-10" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- ...</span></span>
<span id="cb3-11"><a href="#cb3-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-12"><a href="#cb3-12" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Ord</span> k <span class="ot">=&gt;</span> <span class="dt">Indexed</span> (<span class="dt">Map</span> k) <span class="kw">where</span></span>
<span id="cb3-13"><a href="#cb3-13" aria-hidden="true" tabindex="-1"></a>  <span class="kw">type</span> <span class="dt">Idx</span> (<span class="dt">Map</span> k) <span class="ot">=</span> k</span>
<span id="cb3-14"><a href="#cb3-14" aria-hidden="true" tabindex="-1"></a>  (<span class="op">!?</span>) <span class="ot">=</span> (<span class="op">Map.!?</span>)</span></code></pre></div>
<p>Say we want to write the following function:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ot">firstElem ::</span> <span class="dt">Indexed</span> f <span class="ot">=&gt;</span> f a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>firstElem f <span class="ot">=</span> f <span class="op">!?</span> (<span class="dv">0</span><span class="ot"> ::</span> <span class="dt">Int</span>)</span></code></pre></div>
<p>We’d get a type error:</p>
<pre class="plaintext"><code>• Couldn&#39;t match expected type ‘Idx f’ with actual type ‘Int’</code></pre>
<p>Fair enough, this function obviously won’t work for just any indexable container, only ones that are indexed by <code>Int</code>s. We can resolve this by adding a constraint:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="ot">firstElem ::</span> (<span class="dt">Indexed</span> f, <span class="dt">Idx</span> f <span class="op">~</span> <span class="dt">Int</span>) <span class="ot">=&gt;</span> f a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a>firstElem f <span class="ot">=</span> f <span class="op">!?</span> (<span class="dv">0</span><span class="ot"> ::</span> <span class="dt">Int</span>)</span></code></pre></div>
<p>For those unfamiliar, <code>~</code> here is an operator provided by GHC that yields a constraint that the type on the left equals the type on the right. In this case, by constraining <code>Idx f</code> to equal <code>Int</code>, GHC can now add that to its list of known facts, so we don’t get that type error anymore. <code>~</code> is enabled by both the <code>TypeFamilies</code> extension and the <code>GADTs</code> extension.</p>
<h2 id="multi-parameter-type-classes">Multi-parameter Type Classes</h2>
<p>Another way we can encode this information, the type of the index, would be to add an additional parameter to the type class.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# LANGUAGE MultiParamTypeClasses #-}</span></span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> <span class="dt">Indexed</span> f idx <span class="kw">where</span></span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a><span class="ot">  (!?) ::</span> f a <span class="ot">-&gt;</span> idx <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a</span>
<span id="cb7-5"><a href="#cb7-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-6"><a href="#cb7-6" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Indexed</span> [] <span class="dt">Int</span> <span class="kw">where</span></span>
<span id="cb7-7"><a href="#cb7-7" aria-hidden="true" tabindex="-1"></a>  <span class="co">-- ...</span></span>
<span id="cb7-8"><a href="#cb7-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-9"><a href="#cb7-9" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">Indexed</span> (<span class="dt">Map</span> k) k <span class="kw">where</span></span>
<span id="cb7-10"><a href="#cb7-10" aria-hidden="true" tabindex="-1"></a>  (<span class="op">!?</span>) <span class="ot">=</span> (<span class="op">Map.!?</span>)</span></code></pre></div>
<p>We can then write <code>firstElem</code> in a straightforward manner.</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="ot">firstElem ::</span> <span class="dt">Indexed</span> f <span class="dt">Int</span> <span class="ot">=&gt;</span> f a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a</span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>firstElem f <span class="ot">=</span> f <span class="op">!?</span> (<span class="dv">0</span><span class="ot"> ::</span> <span class="dt">Int</span>)</span></code></pre></div>
<p>Yes! This type checks just fine.</p>
<p>All is good, right? Well, let’s try and use this instance.</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="ot">c ::</span> <span class="dt">Maybe</span> <span class="dt">Char</span></span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a>c <span class="ot">=</span> <span class="st">&quot;hello&quot;</span> <span class="op">!?</span> <span class="dv">3</span></span></code></pre></div>
<p>Oh no! When we compile, we get errors:</p>
<pre class="plaintext"><code>• Ambiguous type variable ‘idx0’ arising from a use of ‘!?’
      prevents the constraint ‘(Indexed [] idx0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘idx0’ should be.

• Ambiguous type variable ‘idx0’ arising from the literal ‘3’
      prevents the constraint ‘(Num idx0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘idx0’ should be.</code></pre>
<p>Now sure, if we add a type signature to the literal <code>3</code>, then the error goes away, but this is really not ideal. Ideally, we’d like the compiler to infer right away that since we’re indexing a list, the index type <em>must</em> be <code>Int</code>. This is indeed what happens when we use an associated type family, but not here.</p>
<h3 id="functional-dependencies">Functional Dependencies</h3>
<p>The core issue here is that there’s nothing stopping someone from writing their own instance:</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode hs"><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">Indexed</span> [] <span class="dt">Integer</span> <span class="kw">where</span></span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a>    <span class="op">...</span></span></code></pre></div>
<p>This is a completely valid instance that doesn’t overlap with our own. Therefore, GHC can’t infer that the literal <code>0</code> must be an <code>Int</code>, since it can just as well be an <code>Integer</code>, or any number of types, really.</p>
<p>The solution is to add a functional dependency.</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="ot">{-# LANGUAGE FunctionalDependencies #-}</span></span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> <span class="dt">Indexed</span> f idx <span class="op">|</span> f <span class="ot">-&gt;</span> idx <span class="kw">where</span></span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a><span class="ot">  (!?) ::</span> f a <span class="ot">-&gt;</span> idx <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a</span>
<span id="cb12-5"><a href="#cb12-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-6"><a href="#cb12-6" aria-hidden="true" tabindex="-1"></a><span class="ot">x ::</span> <span class="dt">Maybe</span> <span class="dt">Char</span></span>
<span id="cb12-7"><a href="#cb12-7" aria-hidden="true" tabindex="-1"></a>x <span class="ot">=</span> <span class="st">&quot;hello&quot;</span> <span class="op">!?</span> <span class="dv">3</span></span></code></pre></div>
<p>What this syntax means is that the type variable <code>f</code> must <em>uniquely</em> determine the type variable <code>idx</code>. This has two effects. One, if we have an instance <code>instance Indexed [] Int</code>, then we can’t go ahead and write another instance <code>instance Indexed [] Integer</code>, since then <code>f</code> doesn’t uniquely determine <code>idx</code>. Two, GHC can now infer the type of <code>idx</code> just from knowing what <code>f</code> is, so our program will now type check. GHC will see we’re indexing a list, and therefore the index type <em>must</em> be <code>Int</code>, so the type of the literal <code>3</code> here must be <code>Int</code>.</p>
<p>Looking back, when we used a type family, we were doing the same thing, only implicitly. When we write <code>Idx f</code> it’s implicit that <code>Idx</code> gives back a single type when applied. In other words, <code>f</code> <em>uniquely</em> determines <code>Idx f</code>.<a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a></p>
<p>Both of these methods give very similar results, but it’s good to be familiar with both of them, as they can have different ergonomics. It’s also good to be able to recognize both of these patterns in other libraries, as they’re both used throughout Hackage.</p>
<aside id="footnotes" class="footnotes footnotes-end-of-document" role="doc-endnotes">
<hr />
<ol>
<li id="fn1"><p>Interestingly, we can go in the other direction with the <a href="https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/exts/type_families.html#extension-TypeFamilyDependencies"><code>TypeFamilyDependencies</code></a> extension.<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</aside>
    </section>
</article>]]></description>
    <pubDate>Sat, 26 Jun 2021 00:00:00 UT</pubDate>
    <guid>https://morrowm.github.io//posts/2021-06-26-assoc.html</guid>
    <dc:creator>MorrowM</dc:creator>
</item>
<item>
    <title>Write your own Discord bot in Haskell with Calamity</title>
    <link>https://morrowm.github.io//posts/2021-04-29-calamity.html</link>
    <description><![CDATA[<article>
    <section class="header">
        April 29, 2021
        
    </section>
    <section>
        <p><a href="https://hackage.haskell.org/package/calamity"><code>calamity</code></a> is the most fully-featured library for writing Discord bots on Hackage, rivaling frameworks like <code>discord.py</code> and <code>discord.js</code> in features, while offering all the benefits of Haskell: a strong type system, pure functions, and risk-free refactoring. It may however seem impenetrable at first glance, using many language extensions such as <code>TypeApplications</code>, <code>TypeFamilies</code>, and <code>DataKinds</code>. It also uses the <a href="https://hackage.haskell.org/package/polysemy"><code>polysemy</code></a> effect system rather than the more common <a href="https://hackage.haskell.org/package/mtl"><code>mtl</code></a>. The end result, however, is a very nice interface for making bots.</p>
<p>This post is intended to guide those less familiar with this part of the Haskell ecosystem on how to write their own bots using <code>calamity</code> and hopefully come out of the experience with a greater understanding of how to use these features and how they can be leveraged in their own programs and libraries. It’s possible to use <code>calamity</code> without understanding all the types involved, but it becomes significantly harder to debug and to understand any error messages you may get.</p>
<p>I recommend following along with the <a href="https://hackage.haskell.org/package/calamity">Hackage documentation</a> open. You can search the haddocks by pressing <code>s</code> to open a search dialogue.</p>
<h3 id="preface">Preface</h3>
<p>The code in this tutorial may not be updated to work with the latest version of calamity. I’ll try to keep the code at the associated <a href="https://github.com/MorrowM/calamity-tutorial">git repository</a> updated. If it doesn’t build for you, don’t be afraid to open an issue or pull request.</p>
<h2 id="libraries">Libraries</h2>
<h3 id="polysemy"><code>polysemy</code></h3>
<p>When writing real-world IO-heavy applications, it’s almost always advantageous to use an effect system for storing configuration data, error handling, incorporating state, etc. A common choice is <code>mtl</code>, the monad transformer library. <code>polysemy</code> is another such effect system that opts for working in a single monad, the <code>Sem r</code> monad, which is parameterized by a type-level list of effects, called the “effect row”.</p>
<p>Here’s an example snippet of code using <code>mtl</code>:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode hs"><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">Config</span> <span class="ot">=</span> <span class="dt">Config</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> cmdPrefix ::</span> <span class="dt">Text</span></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>  }</span></code></pre></div>
<div class="sourceCode" id="cb2"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>handleMessage </span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  ::</span> (<span class="dt">MonadReader</span> <span class="dt">Config</span> m, <span class="dt">MonadIO</span> m)</span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=&gt;</span> <span class="dt">String</span></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> m ()</span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a>handleMessage msg <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a>  prefix <span class="ot">&lt;-</span> asks cmdPrefix</span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a>  when (prefix <span class="ot">`isPrefixOf`</span> msg) <span class="op">$</span></span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a>    liftIO <span class="op">$</span> <span class="fu">putStrLn</span> <span class="st">&quot;Received a command: &quot;</span> <span class="op">&lt;&gt;</span> msg</span></code></pre></div>
<p>Using <code>polysemy</code> we’d instead work in the <code>Sem r</code> monad and require that the effect row contain the effects we need using <code>Member</code>, which takes an effect and an effect row and yields a constraint that the effect must be present in the effect row.</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a>handleMessage </span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  ::</span> (<span class="dt">Member</span> (<span class="dt">Reader</span> <span class="dt">Config</span>) r, <span class="dt">Member</span> (<span class="dt">Embed</span> <span class="dt">IO</span>) r)</span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=&gt;</span> <span class="dt">String</span></span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">Sem</span> r ()</span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a>handleMessage msg <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a>  prefix <span class="ot">&lt;-</span> asks <span class="op">@</span><span class="dt">Config</span> cmdPrefix</span>
<span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a>  when (prefix <span class="ot">`isPrefixOf`</span> msg) <span class="op">$</span></span>
<span id="cb3-8"><a href="#cb3-8" aria-hidden="true" tabindex="-1"></a>    embed <span class="op">.</span> <span class="fu">putStrLn</span> <span class="op">$</span> <span class="st">&quot;Received a command: &quot;</span> <span class="op">&lt;&gt;</span> msg</span></code></pre></div>
<p>As you can see, all we have to do is declare which effects we require to be present in the effect row. <code>polysemy</code> also encourages using more granular effects instead of using <code>IO</code>, so we could have used the <a href="https://hackage.haskell.org/package/polysemy-1.5.0.0/docs/Polysemy-Trace.html#t:Trace"><code>Trace</code></a> effect instead and called <a href="https://hackage.haskell.org/package/polysemy-1.5.0.0/docs/Polysemy-Trace.html#v:trace"><code>trace</code></a> function, which means all we require is that our effect row can log strings, whatever that may mean. This removes our dependency on the <code>IO</code> monad and makes our code more flexible.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a>handleMessage </span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  ::</span> (<span class="dt">Member</span> (<span class="dt">Reader</span> <span class="dt">Config</span>) r, <span class="dt">Member</span> <span class="dt">Trace</span> r)</span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=&gt;</span> <span class="dt">String</span></span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">Sem</span> r ()</span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a>handleMessage msg <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a>  prefix <span class="ot">&lt;-</span> asks <span class="op">@</span><span class="dt">Config</span> cmdPrefix</span>
<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a>  when (prefix <span class="ot">`isPrefixOf`</span> msg) <span class="op">$</span></span>
<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a>    trace <span class="op">$</span> <span class="st">&quot;Received a command: &quot;</span> <span class="op">&lt;&gt;</span> msg</span></code></pre></div>
<p>How these effects are interpreted, and which concrete effect row is inferred depends on which <em>effect interpreters</em> we choose. For the <code>Reader</code> effect there’s really only one interpreter that <code>polysemy</code> provides to us, <code>runReader :: i -&gt; Sem (Reader i ': r) a -&gt; Sem r a</code>. The type signature says that given some value <code>i</code> we can handle a <code>Reader i</code> effect from the effect row. Remember that the effect row is just a type-level list of effects, so <code>(Reader i ': r)</code> just pattern matches on that list, a list with <code>Reader i</code> as its head and <code>r</code> as its tail. So the interpreter essentially strips an effect off the head of the effect row.</p>
<p>For interpreting the <code>Trace</code> effect we have a few options. We could gather all the logged messages into a list with <code>runTraceList :: Sem (Trace ': r) a -&gt; Sem r ([String], a)</code>, we could also just ignore the messages with <code>ignoreTrace :: Sem (Trace ': r) a -&gt; Sem r a</code>. But in this case we’ll have the messages printed to <code>stdout</code> with <code>traceToIO :: Member (Embed IO) r =&gt; Sem (Trace ': r) a -&gt; Sem r a</code>. Note that this interpreter requires that <code>Embed IO</code> be present in our effect list, meaning that our monad must be able to handle arbitrary <code>IO</code> actions. That’s fine, but now we’ll have to handle that effect as well. Since our goal is to eventually peel this onion into the <code>IO</code> monad, we’ll want some function that can convert some <code>Sem r a</code> into an <code>IO a</code>. That function would be <code>runFinal :: Monad m =&gt; Sem '[Final m] a -&gt; m a</code> which takes a <code>Sem</code> with a singleton effect row containing just <code>Final m</code> for some monad <code>m</code> and returns a plain <code>m a</code>. To get such a <code>Final m</code> we can just use the <code>embedToFinal :: (Member (Final m) r, Functor m) =&gt; Sem (Embed m ': r) a -&gt; Sem r a</code> interpreter, which peels off an <code>Embed m</code> effect and delegates its effects to the <code>Final m</code> effect in our effect row.</p>
<p>Putting it all together:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="ot">main ::</span> <span class="dt">IO</span> ()</span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a>main <span class="ot">=</span> runFinal</span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> embedToFinal <span class="op">@</span><span class="dt">IO</span></span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> traceToIO</span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> runReader (<span class="dt">Config</span> <span class="st">&quot;!&quot;</span> <span class="op">...</span>)</span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a>  <span class="op">$</span> handleMessage <span class="st">&quot;!polysemy&quot;</span></span></code></pre></div>
<p>This may seem a bit complicated, but it’s a method that lets us easily deal with all the effects we need, one at a time. The result is very clean. Note that we never deal with an explicit effect row, the type checker infers it for us based on the interpreters we choose.</p>
<h3 id="di-and-di-polysemy"><code>di</code> and <code>di-polysemy</code></h3>
<p><code>di</code> is a fully-featured structured logging library. <code>di-polysemy</code> provides <code>polysemy</code> style effects for <code>di</code>. This is what <code>calamity</code> uses for logging.</p>
<h3 id="lens"><code>lens</code></h3>
<hr />
<p><strong>Update:</strong> As of <code>calamity-0.5.0.0</code>, the <code>optics</code> library is used instead of <code>lens</code> and <code>generic-lens</code>. <code>optics</code> is an alternative to <code>lens</code> which aims to provide better error messages. What this means in practice is:</p>
<ul>
<li>Some imports have changed.</li>
<li>Composition of lenses is done with the <code>(%)</code> operator from <code>optics</code> instead of <code>(.)</code>.</li>
<li><code>generic-lens</code> is no longer needed. Instead, <code>calamity</code> itself provides the appropriate instances required to make <code>OverloadedLabels</code> work.</li>
</ul>
<hr />
<p>For a full understanding of how lens works, there are better resources such as the excellent <a href="https://web.archive.org/web/20210521023726/https://artyom.me/lens-over-tea-1">lens over tea</a>. This will just be a quick overview of the basic usage of lenses for those who aren’t familiar with them.</p>
<p>A lens can be thought of as a value that focuses on some part of a larger structure, such as a field in a record. For example, <code>lens</code> provides the <code>_1</code> lens which focuses on the first element of a tuple. We can use a lens to extract part of a value with the <code>view</code> function or its operator counterpart, <code>(^.)</code>:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a>ghci<span class="op">&gt;</span> view (<span class="ch">&#39;a&#39;</span>, <span class="dv">5</span>) _1</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a><span class="ch">&#39;a&#39;</span></span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a>ghci<span class="op">&gt;</span> (<span class="ch">&#39;a&#39;</span>, <span class="dv">5</span>) <span class="op">^.</span> _2</span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a><span class="dv">5</span></span></code></pre></div>
<p>We can replace part of a structure with the <code>set</code> function or its operator counterpart, <code>(.~)</code>. We can use the flipped application operator <code>(&amp;) = flip ($)</code> alongside this operator.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a>ghci<span class="op">&gt;</span> set _1 <span class="st">&quot;hello&quot;</span> (<span class="ch">&#39;a&#39;</span>, <span class="dv">5</span>)</span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a>(<span class="st">&quot;hello&quot;</span>, <span class="dv">5</span>)</span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a>ghci<span class="op">&gt;</span> (<span class="ch">&#39;a&#39;</span>, <span class="dv">5</span>) <span class="op">&amp;</span> _2 <span class="op">.~</span> <span class="dt">False</span></span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a>(<span class="ch">&#39;a&#39;</span>, <span class="dt">False</span>)</span></code></pre></div>
<p>And finally, we have <code>over</code> and its operator <code>%~</code> which work much the same way as <code>set</code>, but takes a function to modify the structure with rather than a set value.</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a>ghci<span class="op">&gt;</span> over _1 <span class="fu">succ</span> (<span class="ch">&#39;a&#39;</span>, <span class="dv">5</span>)</span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>(<span class="ch">&#39;b&#39;</span>, <span class="dv">5</span>)</span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a>ghci<span class="op">&gt;</span> (<span class="ch">&#39;a&#39;</span>, <span class="dv">5</span>) <span class="op">&amp;</span> _2 <span class="op">%~</span> <span class="fu">show</span></span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a>(<span class="ch">&#39;a&#39;</span>, <span class="st">&quot;5&quot;</span>)</span></code></pre></div>
<p>Notably, we can compose lenses with the <code>(.)</code> operator from the <code>Prelude</code> to focus on parts of nested structures.</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a>ghci<span class="op">&gt;</span> (<span class="dt">True</span>, (<span class="ch">&#39;a&#39;</span>, <span class="dv">5</span>)) <span class="op">^.</span> _2 <span class="op">.</span> _1</span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a><span class="ch">&#39;a&#39;</span></span></code></pre></div>
<h3 id="generic-lens"><code>generic-lens</code></h3>
<p>The goal of using <code>lens</code> here is to be able to access the fields of the various record types that <code>calamity</code> exposes to us. We could use record accessors and update notation, but many of these records contain fields with the same name, so using them directly will lead to ambiguity errors. <code>generic-lens</code> solves this issue for us by allowing us to create lenses on the fly using the <code>OverloadedLabels</code> extension. For example, the <code>Member</code> type has a field called <code>guildID</code>. If we want to access this field from some member <code>mem</code>, we can simply write <code>mem ^. #guildID</code>.</p>
<p>Note that to use the field names as lenses the type must have an instance of the <code>Generic</code> typeclass. This can be done with the <code>DeriveGeneric</code> extension, which, unsurprisingly, allows the user to write <code>deriving Generic</code>. All, or at least most, of the record types defined in <code>calamity</code> have a <code>Generic</code> instance.</p>
<h2 id="creating-the-skeleton">Creating the Skeleton</h2>
<p>Let’s begin by building the skeleton for our project. Initialize a fresh cabal project by running <code>cabal init</code> in an empty directory. We’ll start by putting the adding the following dependencies in our <code>bot.cabal</code> file under <code>build-depends</code>.</p>
<pre class="plaintext"><code>  -- Use a version of `base` corresponding with GHC 8.10.x
  build-depends:
    , base             ^&gt;=4.14
    , calamity         &gt;=0.2.0 &amp;&amp; &lt;0.2.1
    , data-default
    , data-flags
    , di
    , di-polysemy
    , generic-lens
    , lens
    , polysemy
    , polysemy-plugin
    , text
    , text-show</code></pre>
<p><code>polysemy-plugin</code> is a GHC plugin for <code>polysemy</code> which improves type inference inside the <code>Sem r</code> monad. We have to enable it by adding <code>-fplugin=Polysemy.Plugin</code> to our GHC options.</p>
<pre class="plaintext"><code>  ghc-options:      -fplugin=Polysemy.Plugin</code></pre>
<p>Let’s also start with a couple of language extensions.<code>TypeApplications</code> which lets us instantiate polymorphic values with concrete types, <code>OverloadedStrings</code> to be able to write <code>Text</code> literals, and <code>OverloadedLabels</code> for use with <code>generic-lens</code>. We’ll also need <code>DataKinds</code> later.</p>
<pre class="plaintext"><code>  default-extensions:
    DataKinds
    OverloadedLabels
    OverloadedStrings
    TypeApplications</code></pre>
<p>We’ll build all these dependencies with <code>cabal build --only-dependencies</code>.</p>
<p>Let’s write the skeleton for the <code>main</code> function.</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="kw">module</span> <span class="dt">Main</span> <span class="kw">where</span></span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span>           <span class="dt">Calamity</span></span>
<span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span>           <span class="dt">Calamity.Cache.InMemory</span></span>
<span id="cb13-5"><a href="#cb13-5" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span>           <span class="dt">Calamity.Commands</span></span>
<span id="cb13-6"><a href="#cb13-6" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span>           <span class="dt">Calamity.Commands.Context</span> (useFullContext)</span>
<span id="cb13-7"><a href="#cb13-7" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span>           <span class="dt">Calamity.Metrics.Noop</span></span>
<span id="cb13-8"><a href="#cb13-8" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span>           <span class="dt">Control.Lens</span></span>
<span id="cb13-9"><a href="#cb13-9" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span>           <span class="dt">Control.Monad</span></span>
<span id="cb13-10"><a href="#cb13-10" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span>           <span class="dt">Data.Default</span></span>
<span id="cb13-11"><a href="#cb13-11" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span>           <span class="dt">Data.Generics.Labels</span>      ()</span>
<span id="cb13-12"><a href="#cb13-12" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span>           <span class="dt">Data.Maybe</span></span>
<span id="cb13-13"><a href="#cb13-13" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span>           <span class="dt">Data.Text</span>                 (<span class="dt">Text</span>)</span>
<span id="cb13-14"><a href="#cb13-14" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="kw">qualified</span> <span class="dt">Data.Text</span>                 <span class="kw">as</span> <span class="dt">T</span></span>
<span id="cb13-15"><a href="#cb13-15" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="kw">qualified</span> <span class="dt">Di</span></span>
<span id="cb13-16"><a href="#cb13-16" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span>           <span class="dt">DiPolysemy</span></span>
<span id="cb13-17"><a href="#cb13-17" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="kw">qualified</span> <span class="dt">Polysemy</span>                  <span class="kw">as</span> <span class="dt">P</span></span>
<span id="cb13-18"><a href="#cb13-18" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-19"><a href="#cb13-19" aria-hidden="true" tabindex="-1"></a><span class="ot">main ::</span> <span class="dt">IO</span> ()</span>
<span id="cb13-20"><a href="#cb13-20" aria-hidden="true" tabindex="-1"></a>main <span class="ot">=</span> Di.new <span class="op">$</span> \di <span class="ot">-&gt;</span></span>
<span id="cb13-21"><a href="#cb13-21" aria-hidden="true" tabindex="-1"></a>  void</span>
<span id="cb13-22"><a href="#cb13-22" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> P.runFinal</span>
<span id="cb13-23"><a href="#cb13-23" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> P.embedToFinal <span class="op">@</span><span class="dt">IO</span></span>
<span id="cb13-24"><a href="#cb13-24" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> runDiToIO di</span>
<span id="cb13-25"><a href="#cb13-25" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> runCacheInMemory</span>
<span id="cb13-26"><a href="#cb13-26" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> runMetricsNoop</span>
<span id="cb13-27"><a href="#cb13-27" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> useFullContext</span>
<span id="cb13-28"><a href="#cb13-28" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> useConstantPrefix <span class="st">&quot;!&quot;</span></span>
<span id="cb13-29"><a href="#cb13-29" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> runBotIO (<span class="dt">BotToken</span> <span class="st">&quot;&lt;token&gt;&quot;</span>) defaultIntents</span>
<span id="cb13-30"><a href="#cb13-30" aria-hidden="true" tabindex="-1"></a>  <span class="op">$</span> <span class="kw">do</span></span>
<span id="cb13-31"><a href="#cb13-31" aria-hidden="true" tabindex="-1"></a>    info <span class="op">@</span><span class="dt">Text</span> <span class="st">&quot;Setting up commands and handlers...&quot;</span></span></code></pre></div>
<p>Let’s break this down bit by bit.</p>
<p><code>Di.new</code> has the type</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="ot">new ::</span> (<span class="dt">Di</span> <span class="dt">Level</span> <span class="dt">Path</span> <span class="dt">Message</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> a) <span class="ot">-&gt;</span> <span class="dt">IO</span> a</span></code></pre></div>
<p>It’s a bit more polymorphic than that, but we’re just using it in plain <code>IO</code>. It essentially provides us a <code>Di Level Path Message</code> using a continuation. That value can be thought of as a sort of handle to the logger.</p>
<p>Now for the effect interpreters.</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</span></span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> runBotIO (<span class="dt">BotToken</span> <span class="st">&quot;&lt;token&gt;&quot;</span>) defaultIntents</span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</span></span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb15-5"><a href="#cb15-5" aria-hidden="true" tabindex="-1"></a><span class="co">-- `runBotIO` has the type:</span></span>
<span id="cb15-6"><a href="#cb15-6" aria-hidden="true" tabindex="-1"></a>runBotIO</span>
<span id="cb15-7"><a href="#cb15-7" aria-hidden="true" tabindex="-1"></a><span class="ot">  ::</span> <span class="kw">forall</span> r a<span class="op">.</span> ( <span class="dt">Members</span> &#39;[<span class="dt">Embed</span> <span class="dt">IO</span>, <span class="dt">Final</span> <span class="dt">IO</span>, <span class="dt">CacheEff</span>, <span class="dt">MetricEff</span>, <span class="dt">LogEff</span>] r</span>
<span id="cb15-8"><a href="#cb15-8" aria-hidden="true" tabindex="-1"></a>                 , <span class="dt">Typeable</span> (<span class="dt">SetupEff</span> r))</span>
<span id="cb15-9"><a href="#cb15-9" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=&gt;</span> <span class="dt">Token</span></span>
<span id="cb15-10"><a href="#cb15-10" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">Intents</span></span>
<span id="cb15-11"><a href="#cb15-11" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">Sem</span> (<span class="dt">SetupEff</span> r) a</span>
<span id="cb15-12"><a href="#cb15-12" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">Sem</span> r (<span class="dt">Maybe</span> <span class="dt">StartupError</span>)</span></code></pre></div>
<p><code>runBotIO</code> is the main effect interpreter. It may look daunting, but let’s break it down piece by piece. Firstly, we’ll note it takes a <code>Token</code> and an <code>Intents</code> as inputs. A <code>Token</code>, as you can see in our skeleton, can be constructed using the <code>BotToken</code> constructor. An <code>Intents</code> is just a <code>Word32</code> representing a bunch of binary flags. You can combine these intents and manipulate them with methods from the <code>Flags</code> typeclass from the <code>data-flags</code> package.</p>
<p><code>SetupEff r</code> is a type alias for <code>Reader Client ': (AtomicState EventHandlers ': (Async ': r))</code>. What that means, in particular, is not relevant to us right now, just understand that it’s <code>r</code> with extra effects tacked on.</p>
<p><code>Members '[Embed IO, Final IO, CacheEff, MetricEff, LogEff] r</code> is equivalent to <code>(Member (Embed IO) r, Member (Final IO) r, ...)</code>, it’s just a more convenient way of listing them all.</p>
<p>So, what this whole function does is strip off some of the main effects but requires us to interpret a few other effects afterward. It’s the main interpreter, in a nutshell.</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</span></span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> useConstantPrefix <span class="st">&quot;!&quot;</span></span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</span></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">-- `useConstantPrefix` has the type:</span></span>
<span id="cb16-6"><a href="#cb16-6" aria-hidden="true" tabindex="-1"></a><span class="ot">useConstantPrefix ::</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Sem</span> (<span class="dt">ParsePrefix</span> &#39;<span class="op">:</span> r) a <span class="ot">-&gt;</span> <span class="dt">Sem</span> r a</span></code></pre></div>
<p>Having this interpreter will strip off the <code>ParsePrefix</code> effect, which will be required when we want to register commands later.</p>
<div class="sourceCode" id="cb17"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</span></span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> useFullContext</span>
<span id="cb17-3"><a href="#cb17-3" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</span></span>
<span id="cb17-4"><a href="#cb17-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb17-5"><a href="#cb17-5" aria-hidden="true" tabindex="-1"></a><span class="co">-- `useFullContext` has the type:</span></span>
<span id="cb17-6"><a href="#cb17-6" aria-hidden="true" tabindex="-1"></a><span class="ot">useFullContext ::</span> <span class="dt">Member</span> <span class="dt">CacheEff</span> r <span class="ot">=&gt;</span> <span class="dt">Sem</span> (<span class="dt">ConstructContext</span> <span class="dt">Message</span> <span class="dt">FullContext</span> <span class="dt">IO</span> () &#39;<span class="op">:</span> r) a <span class="ot">-&gt;</span> <span class="dt">Sem</span> r a</span></code></pre></div>
<p><code>useConstantPrefix</code> handles the <code>ConstructContext</code> effect, which determines what information we receive when a command is invoked.</p>
<div class="sourceCode" id="cb18"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</span></span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> runMetricsNoop</span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</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="co">-- `runMetricsNoop` has the type:</span></span>
<span id="cb18-6"><a href="#cb18-6" aria-hidden="true" tabindex="-1"></a><span class="ot">runMetricsNoop ::</span> <span class="dt">Sem</span> (<span class="dt">MetricEff</span> &#39;<span class="op">:</span> r) a <span class="ot">-&gt;</span> <span class="dt">Sem</span> r a</span></code></pre></div>
<p><code>runMetricsNoop</code> will strip off the <code>MetricEff</code> effect by ignoring any metrics that were collected. <code>calamity</code> doesn’t provide any other interpreter for the <code>MetricEff</code> effect, but if we wanted to we could write our own. That’s outside the scope of this post, however.</p>
<div class="sourceCode" id="cb19"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</span></span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> runCacheInMemory</span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</span></span>
<span id="cb19-4"><a href="#cb19-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb19-5"><a href="#cb19-5" aria-hidden="true" tabindex="-1"></a><span class="co">-- `runCacheInMemory` has the type:</span></span>
<span id="cb19-6"><a href="#cb19-6" aria-hidden="true" tabindex="-1"></a><span class="ot">runCacheInMemory ::</span> <span class="dt">Member</span> (<span class="dt">Embed</span> <span class="dt">IO</span>) r <span class="ot">=&gt;</span> <span class="dt">Sem</span> (<span class="dt">CacheEff</span> &#39;<span class="op">:</span> r) a <span class="ot">-&gt;</span> <span class="dt">Sem</span> r a</span></code></pre></div>
<p><code>runCacheInMemory</code> strips the <code>CacheEff</code> for us by storing the cache in memory. If we wanted to we could write an effect interpreter that stores the cache in a file or database.</p>
<div class="sourceCode" id="cb20"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</span></span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a>  <span class="op">.</span> runDiToIO di</span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</span></span>
<span id="cb20-4"><a href="#cb20-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb20-5"><a href="#cb20-5" aria-hidden="true" tabindex="-1"></a><span class="co">-- `runDiToIO` has the type:</span></span>
<span id="cb20-6"><a href="#cb20-6" aria-hidden="true" tabindex="-1"></a>runDiToIO</span>
<span id="cb20-7"><a href="#cb20-7" aria-hidden="true" tabindex="-1"></a><span class="ot">  ::</span> <span class="kw">forall</span> r level msg a<span class="op">.</span></span>
<span id="cb20-8"><a href="#cb20-8" aria-hidden="true" tabindex="-1"></a>     <span class="dt">Member</span> (<span class="dt">Embed</span> <span class="dt">IO</span>) r</span>
<span id="cb20-9"><a href="#cb20-9" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=&gt;</span> <span class="dt">Di</span> level <span class="dt">Path</span> msg</span>
<span id="cb20-10"><a href="#cb20-10" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">Sem</span> (<span class="dt">Di</span> level <span class="dt">Path</span> msg &#39;<span class="op">:</span> r) a</span>
<span id="cb20-11"><a href="#cb20-11" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">Sem</span> r a</span></code></pre></div>
<p><code>runDiToIO</code> will interpret our <code>di</code> logging effect. Note that the <code>LogEff</code> effect mentioned earlier is just a type alias for <code>Di Level Path Message</code>, so this is just an interpreter for the <code>LogEff</code> effect.</p>
<h2 id="our-first-event-handler">Our First Event Handler</h2>
<p>Let’s create an event handler that will do something wholesome, like react with 😄 on any message containing the string “Haskell”.</p>
<div class="sourceCode" id="cb21"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</span></span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a><span class="op">$</span> <span class="kw">do</span></span>
<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a>    info <span class="op">@</span><span class="dt">Text</span> <span class="st">&quot;Setting up commands and handlers...&quot;</span></span>
<span id="cb21-4"><a href="#cb21-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-5"><a href="#cb21-5" aria-hidden="true" tabindex="-1"></a>    react <span class="op">@</span><span class="dt">&#39;MessageCreateEvt</span> <span class="op">$</span> \(msg, _usr, _member) <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>      when (<span class="st">&quot;Haskell&quot;</span> <span class="ot">`T.isInfixOf`</span> (msg <span class="op">^.</span> <span class="op">#</span>content)) <span class="op">$</span></span>
<span id="cb21-7"><a href="#cb21-7" aria-hidden="true" tabindex="-1"></a>        void <span class="op">.</span> invoke <span class="op">$</span> <span class="dt">CreateReaction</span> msg msg (<span class="dt">UnicodeEmoji</span> <span class="st">&quot;😄&quot;</span>)</span></code></pre></div>
<p><code>react</code> is a function that registers an event handler.</p>
<div class="sourceCode" id="cb22"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a>react</span>
<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  ::</span> <span class="kw">forall</span> (<span class="ot">s ::</span> <span class="dt">EventType</span>) r<span class="op">.</span></span>
<span id="cb22-3"><a href="#cb22-3" aria-hidden="true" tabindex="-1"></a>  (<span class="dt">BotC</span> r, <span class="dt">ReactConstraints</span> s)</span>
<span id="cb22-4"><a href="#cb22-4" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=&gt;</span> (<span class="dt">EHType</span> s <span class="ot">-&gt;</span> <span class="dt">Sem</span> r ())</span>
<span id="cb22-5"><a href="#cb22-5" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">Sem</span> r (<span class="dt">Sem</span> r ())</span></code></pre></div>
<p>The type of event we want to handle has to be passed in as a <em>type argument</em> using the <code>TypeApplications</code> extension, which allows us to instantiate type variables to a specific concrete type. <code>calamity</code> provides the <code>EventType</code> datatype which is a simple enumeration, one of the values being <code>MessageCreateEvt</code>. <code>react</code> expects a type variable with the <em>kind</em> <code>EventType</code>, meaning <code>EventType</code> is used as a data-kind. All this means is that the type <code>EventType</code> is promoted from the type level to the kind level.<a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a> Its values, such as <code>MessageCreateEvt</code>, are promoted from the term level to the type level. Just as the type <code>Int</code> has kind <code>Type</code>, the type <code>'MessageCreateEvt</code> has the kind <code>EventType</code>. Notice the tick mark on <code>'MessageCreateEvt</code>. This is to differentiate the value <code>MessageCreateEvt</code> from the type. Usually, GHC can infer this without us explicitly specifying it, and indeed here it’s not required, but we’ll leave it in just to be explicit.</p>
<p>Also, note that the effect row that <code>react</code> uses has a <code>BotC</code> constraint which is just an alias for a few other constraints. We won’t go into the details here, but just know that the <code>runBotIO</code> interpreter handles these constraints for us.</p>
<p><code>react</code> also expects a function as an argument, the handler body. The type of the input to the body depends on the <code>EventType</code> we specified; different types of events have different data associated with them. This is determined by the <code>EHType</code> type family. For those unfamiliar, a type family is essentially a function that operates on <em>types</em> rather than terms. In the case of <code>EHType</code>, it takes a type with kind <code>EventType</code> (remember, <code>DataKinds</code> promotes <code>EventType</code> to the kind level) and gives us a type. So in our case, <code>EHType 'MessageCreateEvt = (Message, Maybe User, Maybe Member)</code>. That means our event handler’s body should have the type <code>(Message, Maybe User, Maybe Member) -&gt; Sem r ()</code>, although we’ll only be using the <code>Message</code> portion of that tuple. You can verify this in a GHCi session (by running <code>cabal repl</code> in the terminal) with the command <code>:kind! EHType 'MessageCreateEvt</code> which will tell you the kind of the argument and will also attempt to evaluate it.</p>
<pre class="plaintext"><code>λ&gt; :kind! EHType MessageCreateEvt 
EHType MessageCreateEvt :: *
= (Message, Maybe User, Maybe Member)</code></pre>
<p>So for the actual body, we want to take the message and perform an action conditional on the message’s content. We use the <code>when</code> function from <code>Control.Monad</code>, which conditionally performs a monadic/applicative action.</p>
<div class="sourceCode" id="cb24"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a><span class="ot">when ::</span> <span class="dt">Applicative</span> f <span class="ot">=&gt;</span> <span class="dt">Bool</span> <span class="ot">-&gt;</span> f () <span class="ot">-&gt;</span> f ()</span></code></pre></div>
<p>To access the message’s content we use <code>generic-lens</code> to <code>view</code> the <code>content</code> field of the message (remember that <code>(^.)</code> is just the infix counterpart to <code>view</code>).</p>
<p>To create the action, we’ll need to create a “create reaction” request, specifically a <code>ChannelRequest</code>.</p>
<div class="sourceCode" id="cb25"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a><span class="dt">CreateReaction</span></span>
<span id="cb25-2"><a href="#cb25-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  ::</span> (<span class="dt">HasID</span> <span class="dt">Channel</span> c, <span class="dt">HasID</span> <span class="dt">Message</span> m)</span>
<span id="cb25-3"><a href="#cb25-3" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=&gt;</span> c</span>
<span id="cb25-4"><a href="#cb25-4" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> m</span>
<span id="cb25-5"><a href="#cb25-5" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">RawEmoji</span></span>
<span id="cb25-6"><a href="#cb25-6" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">ChannelRequest</span> ()</span></code></pre></div>
<p><code>CreateReaction</code> is polymorphic in its first two arguments. Rather than requiring a concrete <code>Snowflake</code> for the channel and message to react to, which, it only requires that it’s possible to extract a <code>Snowflake</code> from the inputs. It does this via a typeclass, <code>HasID</code>, which has two type parameters- the type of the <code>Snowflake</code> we wish to extract and the type of the thing to extract from. It has a single method, <code>HasID b a =&gt; getID :: a -&gt; Snowflake b</code>. If we look at the instances for <code>HasID</code> we see that there are indeed instances <code>HasID Channel Message</code> and <code>HasID Message Message</code>. To illustrate the convenience that this technique gives us, this is what our handler would look like if <code>CreateReaction</code> required concrete <code>Snowflake</code>s.</p>
<div class="sourceCode" id="cb26"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb26-1"><a href="#cb26-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</span></span>
<span id="cb26-2"><a href="#cb26-2" aria-hidden="true" tabindex="-1"></a>void <span class="op">.</span> invoke <span class="op">$</span> <span class="dt">CreateReaction</span> (msg <span class="op">^.</span> <span class="op">#</span>channelID) (msg <span class="op">^.</span> <span class="op">#</span>id) (<span class="dt">UnicodeEmoji</span> <span class="st">&quot;😄&quot;</span>)</span></code></pre></div>
<p>Okay, so now that we have our <code>ChannelRequest</code> we can use the <code>invoke</code> function to run it.</p>
<div class="sourceCode" id="cb27"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb27-1"><a href="#cb27-1" aria-hidden="true" tabindex="-1"></a>invoke</span>
<span id="cb27-2"><a href="#cb27-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  ::</span> (<span class="dt">BotC</span> r, <span class="dt">Request</span> a, <span class="dt">FromJSON</span> (<span class="dt">Result</span> a))</span>
<span id="cb27-3"><a href="#cb27-3" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=&gt;</span> a</span>
<span id="cb27-4"><a href="#cb27-4" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">Sem</span> r (<span class="dt">Either</span> <span class="dt">RestError</span> (<span class="dt">Result</span> a))</span></code></pre></div>
<p>Here, <code>Request</code> is a typeclass for which every <code>ChannelRequest a</code> has an instance, and <code>Result</code> is a type family which extracts the type <code>a</code> from a <code>ChannelRequest a</code>.</p>
<p>In our case, since we don’t need the result of the request, we can discard it using the <code>void</code> function from <code>Control.Monad</code>.</p>
<div class="sourceCode" id="cb28"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb28-1"><a href="#cb28-1" aria-hidden="true" tabindex="-1"></a><span class="ot">void ::</span> <span class="dt">Functor</span> f <span class="ot">=&gt;</span> f a <span class="ot">-&gt;</span> f ()</span></code></pre></div>
<p>One last thing to note about <code>react</code> is that it returns an action that you can use to unregister it, hence the output being <code>Sem r (Sem r ())</code>.</p>
<p>That’s it! That’s our event handler. You can try it out yourself by putting your bot token in the <code>runBotIO</code> interpreter and running the project.</p>
<h2 id="adding-a-command">Adding a command</h2>
<p>Let’s add a command to enable (or disable) slow mode at a given duration, optionally specifying a channel, defaulting to the channel the command was invoked in.</p>
<p>Luckily for us, <code>calamity</code> provides a handy DSL for creating commands.</p>
<div class="sourceCode" id="cb29"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb29-1"><a href="#cb29-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</span></span>
<span id="cb29-2"><a href="#cb29-2" aria-hidden="true" tabindex="-1"></a>        void <span class="op">.</span> invoke <span class="op">$</span> <span class="dt">CreateReaction</span> msg msg (<span class="dt">UnicodeEmoji</span> <span class="st">&quot;😄&quot;</span>)</span>
<span id="cb29-3"><a href="#cb29-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb29-4"><a href="#cb29-4" aria-hidden="true" tabindex="-1"></a>    addCommands <span class="op">$</span> <span class="kw">do</span></span>
<span id="cb29-5"><a href="#cb29-5" aria-hidden="true" tabindex="-1"></a>      helpCommand</span>
<span id="cb29-6"><a href="#cb29-6" aria-hidden="true" tabindex="-1"></a>      command <span class="op">@</span>&#39;[<span class="dt">Int</span>, <span class="dt">Maybe</span> <span class="dt">GuildChannel</span>] <span class="st">&quot;slowmode&quot;</span> <span class="op">$</span> \ctx seconds mchan <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb29-7"><a href="#cb29-7" aria-hidden="true" tabindex="-1"></a>        <span class="kw">let</span> cid <span class="ot">=</span> <span class="fu">maybe</span> (ctx <span class="op">^.</span> <span class="op">#</span>channel <span class="op">.</span> to getID) getID<span class="ot"> mchan ::</span> <span class="dt">Snowflake</span> <span class="dt">Channel</span></span>
<span id="cb29-8"><a href="#cb29-8" aria-hidden="true" tabindex="-1"></a>        void <span class="op">.</span> invoke <span class="op">$</span> <span class="dt">ModifyChannel</span> cid <span class="op">$</span> def</span>
<span id="cb29-9"><a href="#cb29-9" aria-hidden="true" tabindex="-1"></a>          <span class="op">&amp;</span> <span class="op">#</span>rateLimitPerUser <span class="op">?~</span> seconds</span>
<span id="cb29-10"><a href="#cb29-10" aria-hidden="true" tabindex="-1"></a>        void <span class="op">.</span> invoke <span class="op">$</span></span>
<span id="cb29-11"><a href="#cb29-11" aria-hidden="true" tabindex="-1"></a>          <span class="dt">CreateReaction</span> (ctx <span class="op">^.</span> <span class="op">#</span>channel) (ctx <span class="op">^.</span> <span class="op">#</span>message) (<span class="dt">UnicodeEmoji</span> <span class="st">&quot;✅&quot;</span>)</span></code></pre></div>
<p>Registering commands is done with the <code>addCommands</code> function.</p>
<div class="sourceCode" id="cb30"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb30-1"><a href="#cb30-1" aria-hidden="true" tabindex="-1"></a>addCommands</span>
<span id="cb30-2"><a href="#cb30-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  ::</span> (<span class="dt">BotC</span> r, <span class="dt">Member</span> <span class="dt">ParsePrefix</span> r)</span>
<span id="cb30-3"><a href="#cb30-3" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=&gt;</span> <span class="dt">Sem</span> (<span class="dt">DSLState</span> r) a</span>
<span id="cb30-4"><a href="#cb30-4" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">Sem</span> r (<span class="dt">Sem</span> r (), <span class="dt">CommandHandler</span>, a)</span></code></pre></div>
<p>It constructs the commands and registers the proper event handlers to handle them. It requires the <code>ParsePrefix</code> effect to be present in the effect row. It also allows extra effects in the input’s effect row which are used to track the state of the command DSL, using the type alias <code>DSLState</code>. It yields an action to unregister the event handlers, and an object representing the commands that were registered.</p>
<p><code>helpCommand</code> will add a default help command in the DSL.</p>
<p>To create a command, we use the <code>command</code> function</p>
<div class="sourceCode" id="cb31"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb31-1"><a href="#cb31-1" aria-hidden="true" tabindex="-1"></a>command</span>
<span id="cb31-2"><a href="#cb31-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  ::</span> <span class="kw">forall</span> ps r<span class="op">.</span></span>
<span id="cb31-3"><a href="#cb31-3" aria-hidden="true" tabindex="-1"></a>  (<span class="dt">Member</span> (<span class="dt">Final</span> <span class="dt">IO</span>) r, <span class="dt">TypedCommandC</span> ps r)</span>
<span id="cb31-4"><a href="#cb31-4" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=&gt;</span> <span class="dt">Text</span></span>
<span id="cb31-5"><a href="#cb31-5" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> (<span class="dt">Context</span> <span class="ot">-&gt;</span> <span class="dt">CommandForParsers</span> ps r)</span>
<span id="cb31-6"><a href="#cb31-6" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">Sem</span> (<span class="dt">DSLState</span> r) <span class="dt">Command</span></span></code></pre></div>
<p><code>command</code> takes a command name and a command body and adds a command in the DSL. It also takes a type-level list of command arguments, which it uses to parse the inputs and compute the type of the command body.</p>
<p>In our case, we pass the type-level list <code>'[Int, Maybe GuildChannel]</code> (using <code>TypeApplications</code>) which means our command requires an <code>Int</code> and optionally a <code>GuildChannel</code>.</p>
<p>The body of the command will take a <code>Context</code> and any type parameters we pass in will also be the types of arguments to the body (computed by the <code>CommandForParsers</code> type family).</p>
<p>We use the <code>maybe</code> function to get a default channel id- either the id of the channel provided or the id of the channel the message was invoked in, which is extracted from the <code>Context</code>. We need the id specifically even though the <code>ModifyChannel</code> request only requires something which has a <code>HasID Channel</code> instance, since <code>maybe</code> requires the output types to match up.</p>
<p>We invoke the <code>ModifyChannel</code> request.</p>
<div class="sourceCode" id="cb32"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb32-1"><a href="#cb32-1" aria-hidden="true" tabindex="-1"></a><span class="dt">ModifyChannel</span></span>
<span id="cb32-2"><a href="#cb32-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  ::</span> <span class="dt">HasID</span> <span class="dt">Channel</span> c</span>
<span id="cb32-3"><a href="#cb32-3" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=&gt;</span> c</span>
<span id="cb32-4"><a href="#cb32-4" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">ChannelUpdate</span></span>
<span id="cb32-5"><a href="#cb32-5" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">ChannelRequest</span> <span class="dt">Channel</span></span></code></pre></div>
<p>It requires a <code>ChannelUpdate</code> as input.</p>
<div class="sourceCode" id="cb33"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb33-1"><a href="#cb33-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">ChannelUpdate</span> <span class="ot">=</span> <span class="dt">ChannelUpdate</span></span>
<span id="cb33-2"><a href="#cb33-2" aria-hidden="true" tabindex="-1"></a>  {<span class="ot"> name ::</span> <span class="dt">Maybe</span> <span class="dt">Text</span></span>
<span id="cb33-3"><a href="#cb33-3" aria-hidden="true" tabindex="-1"></a>  ,<span class="ot"> position ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span></span>
<span id="cb33-4"><a href="#cb33-4" aria-hidden="true" tabindex="-1"></a>  ,<span class="ot"> topic ::</span> <span class="dt">Maybe</span> <span class="dt">Text</span></span>
<span id="cb33-5"><a href="#cb33-5" aria-hidden="true" tabindex="-1"></a>  ,<span class="ot"> nsfw ::</span> <span class="dt">Maybe</span> <span class="dt">Bool</span></span>
<span id="cb33-6"><a href="#cb33-6" aria-hidden="true" tabindex="-1"></a>  ,<span class="ot"> rateLimitPerUser ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span></span>
<span id="cb33-7"><a href="#cb33-7" aria-hidden="true" tabindex="-1"></a>  ,<span class="ot"> bitrate ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span></span>
<span id="cb33-8"><a href="#cb33-8" aria-hidden="true" tabindex="-1"></a>  ,<span class="ot"> userLimit ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span></span>
<span id="cb33-9"><a href="#cb33-9" aria-hidden="true" tabindex="-1"></a>  ,<span class="ot"> permissionOverwrites ::</span> <span class="dt">Maybe</span> [<span class="dt">Overwrite</span>]</span>
<span id="cb33-10"><a href="#cb33-10" aria-hidden="true" tabindex="-1"></a>  ,<span class="ot"> parentID ::</span> <span class="dt">Maybe</span> (<span class="dt">Snowflake</span> <span class="dt">Channel</span>)</span>
<span id="cb33-11"><a href="#cb33-11" aria-hidden="true" tabindex="-1"></a>  }</span></code></pre></div>
<p>In our case, we just need the <code>rateLimitPerUser</code> field. Luckily, <code>ChannelUpdate</code> implements the <code>Default</code> typeclass, and so it provides a default value <code>def</code> in which all the fields are set to <code>Nothing</code>. We can then use <code>lens</code> to update just the field we need. We can use the <code>(?~)</code> operator, which is a convenience function that <code>set</code>s a field to <code>Just</code> the value on the right-hand side.</p>
<p>We also react to the command invocation, just like we did in our event handler, this time using the <code>Context</code> instead of a <code>Message</code>.</p>
<p>The parser for the command is quite intelligent, so when we come to run the command, we can pass in either a link to the channel (ala <code>#channel-name</code>) or the id of the channel.</p>
<h2 id="creating-messages-with-ease-using-the-tell-function">Creating Messages with Ease Using the <code>tell</code> Function</h2>
<p><code>calamity</code> has a typeclass called <code>Tellable</code>, which has a method <code>getChannel</code>.</p>
<div class="sourceCode" id="cb34"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb34-1"><a href="#cb34-1" aria-hidden="true" tabindex="-1"></a>getChannel </span>
<span id="cb34-2"><a href="#cb34-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  ::</span> (<span class="dt">BotC</span> r, <span class="dt">Member</span> (<span class="dt">Error</span> <span class="dt">RestError</span>) r) </span>
<span id="cb34-3"><a href="#cb34-3" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=&gt;</span> a </span>
<span id="cb34-4"><a href="#cb34-4" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">Sem</span> r (<span class="dt">Snowflake</span> <span class="dt">Channel</span>)</span></code></pre></div>
<p>Any type which has an instance of <code>Tellable</code> can be sent a message with the <code>tell</code> function.</p>
<div class="sourceCode" id="cb35"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb35-1"><a href="#cb35-1" aria-hidden="true" tabindex="-1"></a>tell </span>
<span id="cb35-2"><a href="#cb35-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  ::</span> <span class="kw">forall</span> msg r t<span class="op">.</span> </span>
<span id="cb35-3"><a href="#cb35-3" aria-hidden="true" tabindex="-1"></a>  (<span class="dt">BotC</span> r, <span class="dt">ToMessage</span> msg, <span class="dt">Tellable</span> t) </span>
<span id="cb35-4"><a href="#cb35-4" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=&gt;</span> t </span>
<span id="cb35-5"><a href="#cb35-5" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> msg </span>
<span id="cb35-6"><a href="#cb35-6" aria-hidden="true" tabindex="-1"></a>  <span class="ot">-&gt;</span> <span class="dt">Sem</span> r (<span class="dt">Either</span> <span class="dt">RestError</span> <span class="dt">Message</span>)</span></code></pre></div>
<p>It also requires the item being sent to have a <code>ToMessage</code> instance. Many types have this instance, among them the various string types, files, embeds, and mentions.</p>
<p>Let’s create an event handler that responds to any message edit with “Hey! I saw that!”.</p>
<div class="sourceCode" id="cb36"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb36-1"><a href="#cb36-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</span></span>
<span id="cb36-2"><a href="#cb36-2" aria-hidden="true" tabindex="-1"></a>    react <span class="op">@</span><span class="dt">&#39;MessageUpdateEvt</span> <span class="op">$</span> \(_oldMsg, newMsg, _user, _member) <span class="ot">-&gt;</span> <span class="kw">do</span></span>
<span id="cb36-3"><a href="#cb36-3" aria-hidden="true" tabindex="-1"></a>      void <span class="op">.</span> tell <span class="op">@</span><span class="dt">Text</span> newMsg <span class="op">$</span> <span class="st">&quot;Hey! I saw that!&quot;</span></span>
<span id="cb36-4"><a href="#cb36-4" aria-hidden="true" tabindex="-1"></a><span class="co">-- snip --</span></span></code></pre></div>
<p>Another useful function to check out is <code>reply</code>, which will use Discord’s reply system to reply to a message.</p>
<h2 id="supercharge-your-snowflakes-with-upgrade">Supercharge your <code>Snowflake</code>s with <code>upgrade</code></h2>
<p>It can be a hassle to get a value if you only have access to its id. <code>calamity</code> provides us with the <code>Upgradable</code> typeclass, which provides the <code>upgrade</code> method.</p>
<div class="sourceCode" id="cb37"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb37-1"><a href="#cb37-1" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> <span class="dt">Upgradeable</span> a ids <span class="op">|</span> a <span class="ot">-&gt;</span> ids, ids <span class="ot">-&gt;</span> a <span class="kw">where</span></span>
<span id="cb37-2"><a href="#cb37-2" aria-hidden="true" tabindex="-1"></a><span class="ot">  upgrade ::</span> <span class="dt">BotC</span> r <span class="ot">=&gt;</span> ids <span class="ot">-&gt;</span> <span class="dt">P.Sem</span> r (<span class="dt">Maybe</span> a)</span></code></pre></div>
<p><code>upgrade</code> will take your id(s) and search the cache for the corresponding value, making a request if it’s not in the cache. There are several useful instances defined, all of which take one or a pair of <code>Snowflake</code>s and provide a complete value.</p>
<div class="sourceCode" id="cb38"><pre class="sourceCode hs"><code class="sourceCode haskell"><span id="cb38-1"><a href="#cb38-1" aria-hidden="true" tabindex="-1"></a> <span class="dt">Upgradeable</span> <span class="dt">GuildChannel</span> (<span class="dt">Snowflake</span> <span class="dt">GuildChannel</span>) </span>
<span id="cb38-2"><a href="#cb38-2" aria-hidden="true" tabindex="-1"></a> <span class="dt">Upgradeable</span> <span class="dt">Member</span> (<span class="dt">Snowflake</span> <span class="dt">Guild</span>, <span class="dt">Snowflake</span> <span class="dt">Member</span>)</span></code></pre></div>
<h2 id="utilities">Utilities</h2>
<p><code>Calamity.Utils</code> provides many useful functions: permissions calculations, message formatting, and colors for custom embeds. It’s worthwhile to check it out.</p>
<h2 id="in-summary">In Summary</h2>
<p>There are many things we didn’t get to cover in this post. We only scratched the surface of the commands DSL, we didn’t cover metrics collection, presences, nor the countless datatypes that are defined to model the Discord API. We also didn’t cover most of the effects available in the <code>polysemy</code> library, which could come in handy for storing configuration data, state, etc. But that’s where the documentation comes in. If you’re new to developing real-world Haskell programs, learning how to read the haddocks is invaluable. (A tip: Don’t forget to read the instances!)</p>
<p>If there’s further interest in this I may be inclined to write another post where I write a more fully-featured bot and step through the process, involving other libraries like <code>aeson</code> and database libraries, and defining our own polysemy effects and effect interpreters.</p>
<p>The full source code for the bot is available <a href="https://github.com/MorrowM/calamity-tutorial">here</a>.</p>
<aside id="footnotes" class="footnotes footnotes-end-of-document" role="doc-endnotes">
<hr />
<ol>
<li id="fn1"><p>This is somewhat inaccurate as of <code>TypeInType</code>, in which the kind level and type level have been unified. A more precise way of saying this is that <code>DataKinds</code> gives us the type level entity <code>'MessageCreateEvt</code>, whose kind is <code>EventType</code>, which previously was uninhabited at the type level.<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</aside>
    </section>
</article>]]></description>
    <pubDate>Thu, 29 Apr 2021 00:00:00 UT</pubDate>
    <guid>https://morrowm.github.io//posts/2021-04-29-calamity.html</guid>
    <dc:creator>MorrowM</dc:creator>
</item>

    </channel>
</rss>
