<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[dave^2 = -1]]></title>
  <link href="http://davesquared.net/atom.xml" rel="self"/>
  <link href="http://davesquared.net/"/>
  <updated>2021-04-26T11:08:54+10:00</updated>
  <id>http://davesquared.net/</id>
  <author>
    <name><![CDATA[David Tchepak]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Using phantom types to associate static values and generic types]]></title>
    <link href="http://davesquared.net/2019/01/phantom-types.html"/>
    <updated>2019-01-17T07:50:00+11:00</updated>
    <id>http://davesquared.net/2019/01/phantom-types</id>
    <content type="html"><![CDATA[<p>Phantom types seem to get used reasonably regularly in a variety of languages for ensuring the safe use of various values (as <a href="https://gekkio.fi/blog/2013-02-07-increased-compile-time-safety-with-phantom-types.html">identifiers</a>, for <a href="http://gabrielsw.blogspot.com/2012/09/phantom-types-in-java.html">state transitions</a> and <a href="http://kean.github.io/post/phantom-types#id-type">others</a>).</p>
<p>A colleague and I recently found a case where they provided a slightly different benefit. They still helped provide some required type safety, but in this case they also helped to statically associate a value with a generic type parameter, avoiding a runtime lookup and keeping the code succinct using type inference.</p>
<p>This post uses Kotlin, but should be applicable to Java or any other language with generics / parameterised types.</p>
<!-- more -->
<h2 id="what-is-a-phantom-type">What is a phantom type?</h2>
<p>A phantom type is a type that has a type parameter in its declaration that is not actually used by the constructors or fields of that type.</p>
<p>For (a fairly contrived) example:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='kotlin'><span></span><span class="k">data</span> <span class="k">class</span> <span class="nc">Measure</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;(</span><span class="k">val</span> <span class="py">value</span><span class="p">:</span> <span class="n">Double</span><span class="p">)</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Here we have a <code>Measure</code> type with a single <code>Double</code> field. It is parameterised by some type <code>T</code>, but we could quite easily remove this parameter and the class would still work (i.e. <code>data class Measure(val value: Double)</code>).</p>
<p>Even though <code>T</code> isn’t used in the class definition, it does let us tag references to this type with additional information. The type parameter does not change how the type itself works, but it does let us restrict how it can be used.</p>
<p>Let’s make a <code>plus</code> operator for <code>Measure</code>, but ensure it only works on values of the same measurement units:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='kotlin'><span></span><span class="k">data</span> <span class="k">class</span> <span class="nc">Measure</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;(</span><span class="k">val</span> <span class="py">value</span><span class="p">:</span> <span class="n">Double</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">operator</span> <span class="k">fun</span> <span class="nf">plus</span><span class="p">(</span><span class="n">other</span><span class="p">:</span> <span class="n">Measure</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;):</span> <span class="n">Measure</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="p">=</span>
            <span class="n">Measure</span><span class="p">(</span><span class="n">value</span> <span class="p">+</span> <span class="n">other</span><span class="p">.</span><span class="n">value</span><span class="p">)</span>
<span class="p">}</span>

<span class="k">object</span> <span class="nc">Metres</span>
<span class="k">object</span> <span class="nc">Kilograms</span>

<span class="n">@Test</span>
<span class="k">fun</span> <span class="nf">testMeasures</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">val</span> <span class="py">first</span> <span class="p">=</span> <span class="n">Measure</span><span class="p">&lt;</span><span class="n">Metres</span><span class="p">&gt;(</span><span class="m">42.0</span><span class="p">)</span>
    <span class="k">val</span> <span class="py">second</span> <span class="p">=</span> <span class="n">Measure</span><span class="p">&lt;</span><span class="n">Metres</span><span class="p">&gt;(</span><span class="m">4200.0</span><span class="p">)</span>
    <span class="k">val</span> <span class="py">third</span> <span class="p">=</span> <span class="n">Measure</span><span class="p">&lt;</span><span class="n">Kilograms</span><span class="p">&gt;(</span><span class="m">1.0</span><span class="p">)</span>

    <span class="c1">// Can add Metres:</span>
    <span class="n">assertEquals</span><span class="p">(</span><span class="n">Measure</span><span class="p">&lt;</span><span class="n">Metres</span><span class="p">&gt;(</span><span class="m">4242.0</span><span class="p">),</span> <span class="n">first</span> <span class="p">+</span> <span class="n">second</span><span class="p">)</span>

    <span class="c1">// Can not add Kilograms to Metres:</span>
    <span class="c1">// assertEquals(Measure&lt;Kilograms&gt;(43.0), first + third)</span>
    <span class="c1">// Type mismatch: inferred type is Measure&lt;Kilograms&gt; but Measure&lt;Metres&gt; was expected</span>
<span class="p">}</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Within <code>Measure&lt;T&gt;</code> we just have a <code>Double</code>; the actual type of <code>T</code> makes no difference at all. But when we need to use <code>Measure&lt;T&gt;</code> values, we can ensure only compatible <code>T</code> values are combined, or define operations only for specific <code>T</code> (such as <code>convert: Measure&lt;Metres&gt; -&gt; Measure&lt;Inches&gt;</code>).</p>
<h2 id="a-problem-associating-a-static-value-with-a-type">A problem associating a static value with a type</h2>
<p>I’ll strip back the actual problem we were facing to something that is convenient to write up, yet still hopefully within the realms of plausibility. Say we have several entity types we want to load from some data store. Values of each type are queried by some schema information.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='kotlin'><span></span><span class="cm">/** Marker interface for persistable entities. */</span>
<span class="k">interface</span> <span class="nc">Entity</span>

<span class="cm">/** Schema information used to query entities in their persisted state. */</span>
<span class="k">data</span> <span class="k">class</span> <span class="nc">Schema</span><span class="p">(</span><span class="k">val</span> <span class="py">name</span><span class="p">:</span> <span class="n">String</span><span class="p">,</span> <span class="k">val</span> <span class="py">version</span><span class="p">:</span> <span class="n">Int</span><span class="p">)</span>

<span class="k">data</span> <span class="k">class</span> <span class="nc">Widget</span><span class="p">(</span><span class="k">val</span> <span class="py">style</span><span class="p">:</span> <span class="n">String</span><span class="p">,</span> <span class="k">val</span> <span class="py">barcode</span><span class="p">:</span> <span class="n">Barcode</span><span class="p">)</span> <span class="p">:</span> <span class="n">Entity</span> <span class="p">{</span>
    <span class="k">companion</span> <span class="k">object</span> <span class="err">{</span>
        <span class="cm">/** Static property of Widget, representing that type&#39;s schema */</span>
        <span class="k">val</span> <span class="py">SCHEMA</span> <span class="p">=</span> <span class="n">Schema</span><span class="p">(</span><span class="s">&quot;acme.Widget&quot;</span><span class="p">,</span> <span class="m">12</span><span class="p">)</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">data</span> <span class="k">class</span> <span class="nc">Sprocket</span><span class="p">(</span><span class="k">val</span> <span class="py">size</span><span class="p">:</span> <span class="n">Int</span><span class="p">)</span> <span class="p">:</span> <span class="n">Entity</span> <span class="p">{</span>
    <span class="k">companion</span> <span class="k">object</span> <span class="err">{</span>
        <span class="cm">/** Schema for Sprockets. */</span>
        <span class="k">val</span> <span class="py">SCHEMA</span> <span class="p">=</span> <span class="n">Schema</span><span class="p">(</span><span class="s">&quot;acme.Sprocket&quot;</span><span class="p">,</span> <span class="m">12</span><span class="p">)</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">class</span> <span class="nc">MagicalBucketOfData</span> <span class="p">{</span>
    <span class="c1">// ... magical persistence code here ...</span>

    <span class="c1">// WILL NOT COMPILE!!!</span>
    <span class="k">fun</span> <span class="err">&lt;</span><span class="nf">T</span> <span class="p">:</span> <span class="n">Entity</span><span class="p">&gt;</span> <span class="n">fetch</span><span class="p">():</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="p">=</span>
            <span class="c1">// Need to get schema for T to query:</span>
            <span class="n">db</span><span class="p">.</span><span class="k">where</span><span class="p">(</span><span class="s">&quot;schema&quot;</span><span class="p">,</span> <span class="n">T</span><span class="p">.</span><span class="n">SCHEMA</span><span class="p">.</span><span class="n">name</span><span class="p">)</span> <span class="c1">// ??? But can&#39;t access T.SCHEMA!</span>
              <span class="p">.</span><span class="n">map</span> <span class="p">{</span> <span class="n">it</span> <span class="k">as</span> <span class="n">T</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>The problem here is that we can’t get the static <code>SCHEMA</code> property from <code>T</code>. There is no way for us to say “all types <code>T</code> where <code>T</code> has a static property <code>SCHEMA: Schema</code>” in Kotlin.</p>
<p>There are a few options here. We can change our <code>fetch</code> method to be <code>fun &lt;T: Entity&gt; fetch(schema: Schema): List&lt;T&gt;</code>, but then we could call <code>fetch&lt;Sprocket&gt;(Widget.SCHEMA)</code> by accident, which will cause all sorts of troubles when we try to cast/convert our data to the wrong type. We could use Kotlin’s <a href="https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters">reified type parameters</a> or pass in a <code>Class&lt;T&gt;</code>, and switch on type to lookup the correct schema for whatever <code>T</code> is passed in, but that gets a little messy and will add a runtime cost when we actually know what we want statically.</p>
<h2 id="phantom-types-to-the-rescue">Phantom types to the rescue</h2>
<p>Instead, let’s make <code>Schema</code> a phantom type and tag it with the information about the specific entity type it represents.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='kotlin'><span></span><span class="k">data</span> <span class="k">class</span> <span class="nc">Schema</span><span class="p">&lt;</span><span class="n">T</span><span class="p">:</span> <span class="n">Entity</span><span class="p">&gt;(</span><span class="k">val</span> <span class="py">name</span><span class="p">:</span> <span class="n">String</span><span class="p">,</span> <span class="k">val</span> <span class="py">version</span><span class="p">:</span> <span class="n">Int</span><span class="p">)</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>This gives a warning that <code>Type parameter "T" is never used</code>, a convincing indication we have a phantom type. Spooky.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='kotlin'><span></span><span class="k">data</span> <span class="k">class</span> <span class="nc">Widget</span><span class="p">(</span><span class="k">val</span> <span class="py">style</span><span class="p">:</span> <span class="n">String</span><span class="p">,</span> <span class="k">val</span> <span class="py">barcode</span><span class="p">:</span> <span class="n">Barcode</span><span class="p">)</span> <span class="p">:</span> <span class="n">Entity</span> <span class="p">{</span>
    <span class="k">companion</span> <span class="k">object</span> <span class="err">{</span>
        <span class="c1">// This isn&#39;t just any schema, it is a schema for a widget!</span>
        <span class="k">val</span> <span class="py">SCHEMA</span> <span class="p">=</span> <span class="n">Schema</span><span class="p">&lt;</span><span class="n">Widget</span><span class="p">&gt;(</span><span class="s">&quot;acme.Widget&quot;</span><span class="p">,</span> <span class="m">12</span><span class="p">)</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">data</span> <span class="k">class</span> <span class="nc">Sprocket</span><span class="p">(</span><span class="k">val</span> <span class="py">size</span><span class="p">:</span> <span class="n">Int</span><span class="p">)</span> <span class="p">:</span> <span class="n">Entity</span> <span class="p">{</span>
    <span class="k">companion</span> <span class="k">object</span> <span class="err">{</span>
        <span class="k">val</span> <span class="py">SCHEMA</span> <span class="p">=</span> <span class="n">Schema</span><span class="p">&lt;</span><span class="n">Sprocket</span><span class="p">&gt;(</span><span class="s">&quot;acme.Sprocket&quot;</span><span class="p">,</span> <span class="m">12</span><span class="p">)</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Now we can pass through a schema value to our instance, and the compiler will infer what <code>T</code> we’re after:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='kotlin'><span></span><span class="k">fun</span> <span class="err">&lt;</span><span class="nf">T</span> <span class="p">:</span> <span class="n">Entity</span><span class="p">&gt;</span> <span class="n">fetch</span><span class="p">(</span><span class="n">schema</span><span class="p">:</span> <span class="n">Schema</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;):</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="p">=</span>
        <span class="n">db</span><span class="p">.</span><span class="k">where</span><span class="p">(</span><span class="s">&quot;schema&quot;</span><span class="p">,</span> <span class="n">schema</span><span class="p">.</span><span class="n">name</span><span class="p">)</span>
          <span class="p">.</span><span class="n">map</span> <span class="p">{</span> <span class="n">it</span> <span class="k">as</span> <span class="n">T</span> <span class="p">}</span>

<span class="c1">// Example uses:</span>

<span class="c1">// Here widgets will be of type `List&lt;Widget&gt;`; the type will get</span>
<span class="c1">// inferred by the schema we pass.</span>
<span class="k">val</span> <span class="py">widgets</span> <span class="p">=</span> <span class="n">fetch</span><span class="p">(</span><span class="n">Widget</span><span class="p">.</span><span class="n">SCHEMA</span><span class="p">)</span>

<span class="c1">// Given a method that works on sprockets:</span>
<span class="k">fun</span> <span class="nf">handleSprockets</span><span class="p">(</span><span class="n">sprockets</span><span class="p">:</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">Sprocket</span><span class="p">&gt;)</span> <span class="p">{</span> <span class="p">...</span> <span class="p">}</span>
<span class="c1">// This will fail as we&#39;re trying to use widgets for sprockets:</span>
<span class="n">handleSprockets</span><span class="p">(</span><span class="n">fetch</span><span class="p">(</span><span class="n">Widget</span><span class="p">.</span><span class="n">SCHEMA</span><span class="p">))</span> <span class="c1">// Type mismatch!</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Now we have schema values that are also associated with specific types, giving us the ability to write generic code that needs these values.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Adding an essentially unused type parameter to <code>Schema</code> here gives us an easy way to associate schema values with a particular type. It avoids runtime lookups on types, and does not compromise code safety by allowing us to pass through a value that is not appropriate for the expected type <code>T</code>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Quick, hacky truth tables in Haskell]]></title>
    <link href="http://davesquared.net/2018/12/haskell-truth-tables.html"/>
    <updated>2018-12-05T16:20:00+11:00</updated>
    <id>http://davesquared.net/2018/12/haskell-truth-tables</id>
    <content type="html"><![CDATA[<p>Today I wanted to test a few boolean expressions, and ended up with some quick truth table generation hackery in Haskell which I thought I’d note down for next time. I’m sure there are many better ways of doing this, but this way was mine.</p>
<!-- more -->
<p>Here’s a list of all booleans in GHCi:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='haskell'><span></span><span class="nf">λ</span><span class="o">&gt;</span> <span class="kr">let</span> <span class="n">bools</span> <span class="ow">=</span> <span class="p">[</span><span class="kt">False</span><span class="p">,</span> <span class="kt">True</span><span class="p">]</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>We can use the default <a href="https://davesquared.net/2015/07/apply-pattern.html">applicative</a> instance for lists to run all combinations of <code>bools</code> through a function. If we use a tuple constructor, we’ll get truth table inputs (shown below for 2 and 3 argument expressions).</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='haskell'><span></span><span class="nf">λ</span><span class="o">&gt;</span> <span class="p">(,)</span> <span class="o">&lt;$&gt;</span> <span class="n">bools</span> <span class="o">&lt;*&gt;</span> <span class="n">bools</span>
<span class="p">[(</span><span class="kt">False</span><span class="p">,</span><span class="kt">False</span><span class="p">),(</span><span class="kt">False</span><span class="p">,</span><span class="kt">True</span><span class="p">),(</span><span class="kt">True</span><span class="p">,</span><span class="kt">False</span><span class="p">),(</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">)]</span>
<span class="nf">λ</span><span class="o">&gt;</span> <span class="p">(,,)</span> <span class="o">&lt;$&gt;</span> <span class="n">bools</span> <span class="o">&lt;*&gt;</span> <span class="n">bools</span> <span class="o">&lt;*&gt;</span> <span class="n">bools</span>
<span class="p">[(</span><span class="kt">False</span><span class="p">,</span><span class="kt">False</span><span class="p">,</span><span class="kt">False</span><span class="p">),(</span><span class="kt">False</span><span class="p">,</span><span class="kt">False</span><span class="p">,</span><span class="kt">True</span><span class="p">),(</span><span class="kt">False</span><span class="p">,</span><span class="kt">True</span><span class="p">,</span><span class="kt">False</span><span class="p">),(</span><span class="kt">False</span><span class="p">,</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">),(</span><span class="kt">True</span><span class="p">,</span><span class="kt">False</span><span class="p">,</span><span class="kt">False</span><span class="p">),(</span><span class="kt">True</span><span class="p">,</span><span class="kt">False</span><span class="p">,</span><span class="kt">True</span><span class="p">),(</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">,</span><span class="kt">False</span><span class="p">),(</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">)]</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Let’s check a basic expression <code>p</code>, and its equivalent using <a href="https://en.wikipedia.org/wiki/De_Morgan%27s_laws">De Morgan’s laws</a>. Writing <code>x &lt;$&gt; bools &lt;*&gt; bools</code> gets repetitive, so we’ll start off by defining <code>tt2</code> to get truth-tableish output values for a 2 input function <code>Bool -&gt; Bool -&gt; Bool</code>.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='haskell'><span></span><span class="nf">λ</span><span class="o">&gt;</span> <span class="kr">let</span> <span class="n">tt2</span> <span class="n">f</span> <span class="ow">=</span> <span class="n">f</span> <span class="o">&lt;$&gt;</span> <span class="n">bools</span> <span class="o">&lt;*&gt;</span> <span class="n">bools</span>
<span class="nf">tt2</span> <span class="ow">::</span> <span class="p">(</span><span class="kt">Bool</span> <span class="ow">-&gt;</span> <span class="kt">Bool</span> <span class="ow">-&gt;</span> <span class="n">b</span><span class="p">)</span> <span class="ow">-&gt;</span> <span class="p">[</span><span class="n">b</span><span class="p">]</span>
<span class="nf">λ</span><span class="o">&gt;</span> <span class="kr">let</span> <span class="n">p</span>  <span class="n">a</span> <span class="n">b</span> <span class="ow">=</span> <span class="n">not</span> <span class="p">(</span><span class="n">a</span> <span class="o">&amp;&amp;</span> <span class="n">not</span> <span class="n">b</span><span class="p">)</span>
<span class="nf">λ</span><span class="o">&gt;</span> <span class="kr">let</span> <span class="n">p&#39;</span> <span class="n">a</span> <span class="n">b</span> <span class="ow">=</span> <span class="n">not</span> <span class="n">a</span> <span class="o">||</span> <span class="n">b</span>
<span class="nf">λ</span><span class="o">&gt;</span> <span class="n">tt2</span> <span class="n">p</span>
<span class="p">[</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">,</span><span class="kt">False</span><span class="p">,</span><span class="kt">True</span><span class="p">]</span>
<span class="nf">λ</span><span class="o">&gt;</span> <span class="n">tt2</span> <span class="n">p&#39;</span>
<span class="p">[</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">,</span><span class="kt">False</span><span class="p">,</span><span class="kt">True</span><span class="p">]</span>
<span class="nf">λ</span><span class="o">&gt;</span> <span class="n">tt2</span> <span class="n">p</span> <span class="o">==</span> <span class="n">tt2</span> <span class="n">p&#39;</span>
<span class="kt">True</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>We can then <code>zipWith</code> to get truth table inputs with the corresponding truth table output (using a bit of <code>uncurry</code> trickery):</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='haskell'><span></span><span class="nf">λ</span><span class="o">&gt;</span> <span class="kt">:</span><span class="n">t</span> <span class="n">uncurry</span> <span class="p">(,,)</span>
<span class="nf">uncurry</span> <span class="p">(,,)</span> <span class="ow">::</span> <span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span> <span class="ow">-&gt;</span> <span class="n">c</span> <span class="ow">-&gt;</span> <span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="n">c</span><span class="p">)</span>
<span class="nf">λ</span><span class="o">&gt;</span> <span class="n">zipWith</span> <span class="p">(</span><span class="n">uncurry</span> <span class="p">(,,))</span> <span class="p">(</span><span class="n">tt2</span> <span class="p">(,))</span> <span class="p">(</span><span class="n">tt2</span> <span class="n">p</span><span class="p">)</span>
<span class="p">[(</span><span class="kt">False</span><span class="p">,</span><span class="kt">False</span><span class="p">,</span><span class="kt">True</span><span class="p">),(</span><span class="kt">False</span><span class="p">,</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">),(</span><span class="kt">True</span><span class="p">,</span><span class="kt">False</span><span class="p">,</span><span class="kt">False</span><span class="p">),(</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">)]</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Or for more arguments:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='haskell'><span></span><span class="nf">λ</span><span class="o">&gt;</span> <span class="kr">let</span> <span class="n">tt3</span> <span class="n">f</span> <span class="ow">=</span> <span class="n">f</span> <span class="o">&lt;$&gt;</span> <span class="n">bools</span> <span class="o">&lt;*&gt;</span> <span class="n">bools</span> <span class="o">&lt;*&gt;</span> <span class="n">bools</span>
<span class="nf">tt3</span> <span class="ow">::</span> <span class="p">(</span><span class="kt">Bool</span> <span class="ow">-&gt;</span> <span class="kt">Bool</span> <span class="ow">-&gt;</span> <span class="kt">Bool</span> <span class="ow">-&gt;</span> <span class="n">b</span><span class="p">)</span> <span class="ow">-&gt;</span> <span class="p">[</span><span class="n">b</span><span class="p">]</span>
<span class="nf">λ</span><span class="o">&gt;</span> <span class="n">zipWith</span> <span class="p">(</span><span class="nf">\</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span><span class="p">)</span> <span class="n">d</span> <span class="ow">-&gt;</span> <span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span><span class="p">,</span><span class="n">d</span><span class="p">))</span> <span class="p">(</span><span class="n">tt3</span> <span class="p">(,,))</span> <span class="p">(</span><span class="n">tt3</span> <span class="p">(</span><span class="nf">\</span><span class="n">a</span> <span class="n">b</span> <span class="n">c</span> <span class="ow">-&gt;</span> <span class="n">a</span> <span class="o">&amp;&amp;</span> <span class="n">b</span> <span class="o">||</span> <span class="n">c</span><span class="p">))</span>
<span class="p">[(</span><span class="kt">False</span><span class="p">,</span><span class="kt">False</span><span class="p">,</span><span class="kt">False</span><span class="p">,</span><span class="kt">False</span><span class="p">),(</span><span class="kt">False</span><span class="p">,</span><span class="kt">False</span><span class="p">,</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">),(</span><span class="kt">False</span><span class="p">,</span><span class="kt">True</span><span class="p">,</span><span class="kt">False</span><span class="p">,</span><span class="kt">False</span><span class="p">),(</span><span class="kt">False</span><span class="p">,</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">),(</span><span class="kt">True</span><span class="p">,</span><span class="kt">False</span><span class="p">,</span><span class="kt">False</span><span class="p">,</span><span class="kt">False</span><span class="p">),(</span><span class="kt">True</span><span class="p">,</span><span class="kt">False</span><span class="p">,</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">),(</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">,</span><span class="kt">False</span><span class="p">,</span><span class="kt">True</span><span class="p">),(</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">,</span><span class="kt">True</span><span class="p">)]</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>We can write something to format these nicely, but this was enough for me to get the information I wanted about a few expressions.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[For sale: Several tonnes of yak hair, going cheap]]></title>
    <link href="http://davesquared.net/2018/10/yaks-galore.html"/>
    <updated>2018-10-20T10:20:00+11:00</updated>
    <id>http://davesquared.net/2018/10/yaks-galore</id>
    <content type="html"><![CDATA[<p>A sordid tale of builds, Gradle, Grunt, node, yarn, Linux, TeamCity, Docker, ssh, and <a href="https://seths.blog/2005/03/dont_shave_that/">shaven yaks</a>.</p>
<figure>
<img src="http://davesquared.net/images/2018/shaving-yak.png" title="Cartoon yak shaving his beard, from the Ren and Stimpy show" alt="Happy yak shaving! (src)" /><figcaption>Happy yak shaving! <a href="https://medium.com/@firehoseproject/a-guide-to-yak-shaving-your-code-d30f98dc759">(src)</a></figcaption>
</figure>
<!-- more -->
<p>Once upon a time there was a project that produced a JAR based on some generated code. I needed to make a repeatable, versioned build for the JAR and plug it into TeamCity so I could reference that build artifact from my current project. Simple!</p>
<figure>
<img src="http://davesquared.net/images/2018/possibli-rong.jpg" title="Helicopter pilot from the Simpsons saying nothing can possib-lie go wrong, shortly before everything goes wrong" alt="What could possibli go rong? (src)" /><figcaption>What could possibli go rong? <a href="https://twitter.com/simpsons_tweets/status/381502181733457920">(src)</a></figcaption>
</figure>
<p>Here is a rough timeline of how this went.</p>
<p><strong>WARNING!</strong> In case it is not painfully obvious, this is all me learning stuff so any specifics mentioned are probably sub-optimal at best to destructive at worst. This is more about the journey than the destination.</p>
<h2 id="local-build">Local build</h2>
<ul>
<li>Do some initial analysis and find I need to invert the current relationship between the JAR project and the generation code (so building the JAR can call out to a specific version of the generator and get freshly generated files).</li>
<li>Learn some Node and <a href="https://gruntjs.com/">Grunt</a> so I can update the generator to accept a parameter to change the output directory, then update the JAR project to have the generator as a git submodule so we can control the version used.</li>
<li>Learn enough Gradle to trigger the generation code on build, then build the JAR and run tests.</li>
<li>Learn a bit more Gradle to call <code>git describe</code> with <a href="http://www.davidchudzicki.com/posts/first-parent/"><code>--first-parent</code></a> and use this information to shove some version info into the manifest.</li>
<li>Test build with clean checkout and various tags, document and push changes.</li>
</ul>
<p>So far so good! Now to wire this up to TeamCity.</p>
<h2 id="add-build-to-teamcity">Add build to TeamCity</h2>
<ul>
<li>Create TeamCity build</li>
<li>Build immediately fails: <code>--first-parent</code> is not supported by <code>git describe</code></li>
<li>Log in to build agent, find it has git 1.8.3, but <code>--first-parent</code> was added to <code>git describe</code> in 1.8.4.</li>
<li>Try to update git on build agents, which needs to be done from source as an updated package is not readily available.</li>
<li>Building from source requires some new packages installed, which fails due to some certificate misconfiguration for one repository.</li>
<li>Type stuff into Google until I find a magic flag to skip that repo and get the packages installed.</li>
<li>Install updated git.</li>
<li>Build gets a step further, but fails at the generation code step. The generator requires specific versions of node and yarn. The agents have different versions.</li>
<li>Start installing updated node and yarn from packages, working around repository problems.</li>
<li>Find out that another project has started sharing these agents and requires a different version of node and yarn. They can’t change their version either.</li>
<li>Roll back node and yarn changes.</li>
</ul>
<h2 id="docker">Docker</h2>
<p>At this point someone suggests trying Docker to isolate the build dependencies. The generator team has an image for the generator I can use as a base. I can then create an image that adds the JDK and the version of Git I need and I should be good to go.</p>
<ul>
<li>Start learning Docker.</li>
<li>Try to work out whether to install Docker locally via brew or via the installer, reading conflicting information on both (I ended up with the installer).</li>
<li>Work through the Docker tutorial.</li>
<li>Learn a bit about images, containers, tags and how to manage the disk space used for these (<code>docker system df -v</code>, different prune options).</li>
<li>Get access to the registry used for storing the base image.</li>
<li>Work out how to create a new Docker image with the required JDK version on top of the base image.</li>
<li>Learn how to run a bash shell in a container based on this image: <code>docker run -it image_name bash</code></li>
<li>The base image already has a modern version of git installed. Hooray!</li>
<li>Learn how to clean up transient containers used for bash shells: <code>docker run -it --rm image_name bash</code></li>
<li>Work out how to map volumes to get host’s SSH working within container. Something like: <code>docker run -it --rm -v ${HOME}/.ssh:/root/.ssh -v $SSH_AUTH_SOCK:/ssh-agent -e SSH_AUTH_SOCK=/ssh-agent image_name bash</code></li>
<li>Work out how to use host’s Gradle properties within container: <code>docker run -it --rm -v ${HOME}/.gradle:/root/.gradle ...</code></li>
<li>Get build working in container! Hooray!</li>
<li>Come up with a versioning and tagging scheme for the <code>Dockerfile</code> and corresponding image so that we always have enough information to build each commit of the project with a compatible Docker image.</li>
<li>Publish new image to registry and test build.</li>
<li>Document all this in the project readme.</li>
</ul>
<h2 id="add-docker-build-to-teamcity">Add Docker build to TeamCity</h2>
<p>Great, home stretch now. TeamCity has some Docker integration so this should be easy.</p>
<ul>
<li>Attempt to install Docker on build agents. Unfortunately due to more package problems this does not work. Have to <code>wget</code> some other packages and manually install them before installing the Docker package.</li>
<li>Read up on TeamCity’s Docker integration.</li>
<li>Work out how to generate a key for TeamCity to talk to the image registry.</li>
<li>Update the TeamCity build to use the required image.</li>
<li>Run the build… JVM crash on the agent!</li>
<li>Log in to agent, find that Docker stores images and containers at a location mounted with no free space.</li>
<li>Work with server team to get more space at that mount point.</li>
<li>Run again, but generation fails. It needs access to checkout its own dependencies via SSH to a separately hosted repo.</li>
<li>Read up on SSH with TeamCity and Docker, and the git hosting being used for the other repo.</li>
<li>Talk to generation team about accessing these dependencies. Get access to generate token with SSH key that can be used for this.</li>
<li>Work out how to assign the token to the required dependency on the git host.</li>
<li>Add key to TeamCity and assign it to the build. Same error.</li>
<li>Find out about TeamCity SSH Agent build feature that needs to be added with the selected key. Same error.</li>
<li>Update TeamCity build’s Docker parameters to pass through SSH info from host. Same error.</li>
<li>Various combinations of the above. Same error.</li>
<li>Work out it is a problem with <code>~/.ssh/known_hosts</code>. Update this on the agents (<code>ssh-keyscan -t rsa the_repo &gt;&gt; ~/.ssh/known_hosts</code>), then make sure <code>.ssh</code> from host gets mapped to container via Docker parameters.</li>
<li>Different error! Well, same error, but for a different dependency.</li>
<li>Assign token to new dependency.</li>
<li>Assign token to the other 4 dependencies as each new error occurs.</li>
<li>Finally get through the main build!</li>
</ul>
<p>Then it failed on deployment due to a different credential issue to another internal system. But after temporarily disabling deployment, the build works! Once I sort out the deployment problem I can start on my actual task of adding this library to my project. But that should be simple to fix, right?</p>
<p>Now if you’ll excuse me I’m going to go and have a bit of a lie down on several mountains of yak hair-stuffed cushions.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[StandaloneDeriving to fix forgetfulness in GHCi]]></title>
    <link href="http://davesquared.net/2018/07/standalone-deriving-in-ghci.html"/>
    <updated>2018-07-03T15:09:00+10:00</updated>
    <id>http://davesquared.net/2018/07/standalone-deriving-in-ghci</id>
    <content type="html"><![CDATA[<p>Quick reminder to Future Dave, as I’m going to assume he’ll keep making the same mistake Past and Present Daves make.</p>
<p>When switching between my editor and GHCi REPL to test stuff out I often forget to add a <code>deriving (Show, Eq)</code> or similar line to my data types. This normally occurs after I’ve just set up a bit of test data in the REPL, so if I just fix the data declaration and <code>:reload</code> GHCi then my setup will be lost. We can use the <a href="https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#stand-alone-deriving-declarations">StandaloneDeriving</a> GHC extension to help here.</p>
<!-- more -->
<p>The following example is me playing around with some parsing stuff and forgetting to make <code>ParseError</code> an instance of <code>Show</code> (so it won’t print in the REPL), then using <code>:set -XStandaloneDeriving</code> to fix this:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='haskell'><span></span><span class="nf">λ</span><span class="o">&gt;</span> <span class="kt">:</span><span class="n">set</span> <span class="o">-</span><span class="kt">XOverloadedStrings</span>
<span class="nf">λ</span><span class="o">&gt;</span> <span class="kr">let</span> <span class="n">kv</span> <span class="ow">=</span> <span class="kt">M</span><span class="o">.</span><span class="n">fromList</span> <span class="p">[</span> <span class="p">(</span><span class="s">&quot;hi&quot;</span> <span class="ow">::</span> <span class="kt">T</span><span class="o">.</span><span class="kt">Text</span><span class="p">,</span> <span class="s">&quot;2011-01-02&quot;</span> <span class="ow">::</span> <span class="kt">T</span><span class="o">.</span><span class="kt">Text</span><span class="p">),</span> <span class="p">(</span><span class="s">&quot;world&quot;</span> <span class="ow">::</span> <span class="kt">T</span><span class="o">.</span><span class="kt">Text</span><span class="p">,</span> <span class="s">&quot;2014-05-07&quot;</span> <span class="ow">::</span> <span class="kt">T</span><span class="o">.</span><span class="kt">Text</span><span class="p">)</span> <span class="p">]</span>
<span class="nf">λ</span><span class="o">&gt;</span> <span class="n">kv</span>
<span class="nf">fromList</span> <span class="p">[(</span><span class="s">&quot;hi&quot;</span><span class="p">,</span><span class="s">&quot;2011-01-02&quot;</span><span class="p">),(</span><span class="s">&quot;world&quot;</span><span class="p">,</span><span class="s">&quot;2014-05-07&quot;</span><span class="p">)]</span>
<span class="nf">λ</span><span class="o">&gt;</span> <span class="kr">let</span> <span class="n">lookup</span> <span class="n">k</span> <span class="ow">=</span> <span class="p">(`</span><span class="n">tag</span><span class="p">`</span> <span class="p">(</span><span class="kt">KeyNotFound</span> <span class="n">k</span><span class="p">))</span> <span class="o">.</span> <span class="kt">M</span><span class="o">.</span><span class="n">lookup</span> <span class="n">k</span>
<span class="nf">λ</span><span class="o">&gt;</span> <span class="n">lookup</span> <span class="s">&quot;hi&quot;</span> <span class="n">kv</span>

<span class="o">&lt;</span><span class="n">interactive</span><span class="o">&gt;:</span><span class="mi">94</span><span class="kt">:</span><span class="mi">1</span><span class="kt">:</span> <span class="ne">error</span><span class="kt">:</span>
    <span class="err">•</span> <span class="kt">No</span> <span class="kr">instance</span> <span class="n">for</span> <span class="p">(</span><span class="kt">Show</span> <span class="kt">ParseError</span><span class="p">)</span> <span class="n">arising</span> <span class="n">from</span> <span class="n">a</span> <span class="n">use</span> <span class="kr">of</span> <span class="err">‘</span><span class="n">print</span><span class="err">’</span>
    <span class="err">•</span> <span class="kt">In</span> <span class="n">a</span> <span class="n">stmt</span> <span class="kr">of</span> <span class="n">an</span> <span class="n">interactive</span> <span class="kt">GHCi</span> <span class="n">command</span><span class="kt">:</span> <span class="n">print</span> <span class="n">it</span>

<span class="nf">λ</span><span class="o">&gt;</span> <span class="kt">:</span><span class="n">set</span> <span class="o">-</span><span class="kt">XStandaloneDeriving</span>
<span class="nf">λ</span><span class="o">&gt;</span> <span class="kr">deriving</span> <span class="kr">instance</span> <span class="kt">Show</span> <span class="kt">ParseError</span>

<span class="o">&lt;</span><span class="n">interactive</span><span class="o">&gt;:</span><span class="mi">1</span><span class="kt">:</span><span class="mi">1</span><span class="kt">:</span> <span class="n">warning</span><span class="kt">:</span> <span class="p">[</span><span class="o">-</span><span class="kt">Worphans</span><span class="p">]</span>
    <span class="kt">Orphan</span> <span class="kr">instance</span><span class="kt">:</span> <span class="kr">instance</span> <span class="kt">Show</span> <span class="kt">ParseError</span> <span class="o">...</span>

<span class="nf">λ</span><span class="o">&gt;</span> <span class="n">lookup</span> <span class="s">&quot;hi&quot;</span> <span class="n">kv</span>
<span class="kt">Right</span> <span class="s">&quot;2011-01-02&quot;</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>I’ve trimmed the orphan instance warning. In this case it should not be a problem as I’m just working around my forgetfulness. :)</p>
<p>We can also use this in real <code>.hs</code> files if necessary via a language pragma (<code>{-# LANGUAGE StandaloneDeriving #-}</code>) as described <a href="https://stackoverflow.com/a/12852367/906">here</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Aggregation]]></title>
    <link href="http://davesquared.net/2017/11/aggregation.html"/>
    <updated>2017-11-04T17:30:00+11:00</updated>
    <id>http://davesquared.net/2017/11/aggregation</id>
    <content type="html"><![CDATA[<p>Today I wanted to look at an approach for producing aggregate data from multiple measurements over a source. I’m learning <a href="https://kotlinlang.org/">Kotlin</a> at the moment so I’ll use that for the examples in this post, but we can apply the same idea to pretty much any language (I’ve used similar approaches in F#, and it would work with C# albeit with a bit more code noise). <!-- more --> Any feedback on the approach in general and on my Kotlin-ing attempts is appreciated.</p>
<h2 id="motivating-example">Motivating example</h2>
<p>For this post we’ll consider the example of a list of <code>Sample</code> values we want aggregate information for. A <code>Sample</code> includes the month and year it was collected, and an integer representing the value sampled. For each set of samples we are required to show the following information:</p>
<ul>
<li>The total value sampled for each month and year</li>
<li>The earliest sample date in this data set</li>
<li>The largest individual sample collected</li>
<li>A count of how many samples where within a specific range.</li>
</ul>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='kotlin'><span></span><span class="k">data</span> <span class="k">class</span> <span class="nc">MonthYear</span><span class="p">(</span><span class="k">val</span> <span class="py">year</span><span class="p">:</span> <span class="n">Int</span><span class="p">,</span> <span class="k">val</span> <span class="py">month</span><span class="p">:</span> <span class="n">Int</span><span class="p">)</span> <span class="p">:</span> <span class="n">Comparable</span><span class="p">&lt;</span><span class="n">MonthYear</span><span class="p">&gt;</span> <span class="p">{</span> <span class="cm">/* ... */</span> <span class="p">}</span>
<span class="k">data</span> <span class="k">class</span> <span class="nc">Sample</span><span class="p">(</span><span class="k">val</span> <span class="py">date</span><span class="p">:</span> <span class="n">MonthYear</span><span class="p">,</span> <span class="k">val</span> <span class="py">value</span><span class="p">:</span> <span class="n">Int</span><span class="p">)</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="initial-attempts">Initial attempts</h2>
<p>We could neatly get each individual bit of information by using multiple queries<a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a>, but requiring multiple iterations seems quite wasteful, especially for larger data sets. Instead we could use multiple variables, or an aggregate type containing those variables, and update each as we loop or fold over the data set:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='kotlin'><span></span><span class="k">data</span> <span class="k">class</span> <span class="nc">CandidateAggregate</span><span class="p">(</span><span class="k">var</span> <span class="py">data</span><span class="p">:</span> <span class="n">Map</span><span class="p">&lt;</span><span class="n">MonthYear</span><span class="p">,</span> <span class="n">Int</span><span class="p">&gt;,</span>
                              <span class="k">var</span> <span class="py">earliestSampleDate</span><span class="p">:</span> <span class="n">MonthYear</span><span class="p">?,</span>
                              <span class="k">var</span> <span class="py">largestSample</span><span class="p">:</span> <span class="n">Int</span><span class="p">,</span>
                              <span class="k">var</span> <span class="py">inRangeCount</span><span class="p">:</span> <span class="n">Int</span><span class="p">)</span>

<span class="k">val</span> <span class="py">result</span> <span class="p">=</span> <span class="n">samples</span><span class="p">.</span><span class="n">fold</span><span class="p">(</span>
        <span class="n">CandidateAggregate</span><span class="p">(</span><span class="n">emptyMap</span><span class="p">(),</span> <span class="k">null</span><span class="p">,</span> <span class="m">0</span><span class="p">,</span> <span class="m">0</span><span class="p">),</span> <span class="c1">// empty case</span>
        <span class="p">{</span> <span class="n">acc</span><span class="p">,</span> <span class="n">s</span> <span class="p">-&gt;</span>
            <span class="n">CandidateAggregate</span><span class="p">(</span>
                <span class="n">acc</span><span class="p">.</span><span class="k">data</span><span class="p">.</span><span class="n">insertOrUpdate</span><span class="p">(</span><span class="n">s</span><span class="p">.</span><span class="n">date</span><span class="p">)</span> <span class="p">{</span> <span class="k">if</span> <span class="p">(</span><span class="n">it</span><span class="p">==</span><span class="k">null</span><span class="p">)</span> <span class="n">s</span><span class="p">.</span><span class="n">value</span> <span class="k">else</span> <span class="n">it</span> <span class="p">+</span> <span class="n">s</span><span class="p">.</span><span class="n">value</span> <span class="p">},</span>
                <span class="n">minOf</span><span class="p">(</span><span class="n">acc</span><span class="p">.</span><span class="n">earliestSampleDate</span> <span class="o">?:</span> <span class="n">s</span><span class="p">.</span><span class="n">date</span><span class="p">,</span> <span class="n">s</span><span class="p">.</span><span class="n">date</span><span class="p">),</span>
                <span class="n">maxOf</span><span class="p">(</span><span class="n">acc</span><span class="p">.</span><span class="n">largestSample</span><span class="p">,</span> <span class="n">s</span><span class="p">.</span><span class="n">value</span><span class="p">),</span>
                <span class="n">acc</span><span class="p">.</span><span class="n">inRangeCount</span> <span class="p">+</span> <span class="k">if</span> <span class="p">((</span><span class="m">100.</span><span class="p">.</span><span class="m">200</span><span class="p">).</span><span class="n">contains</span><span class="p">(</span><span class="n">s</span><span class="p">.</span><span class="n">value</span><span class="p">))</span> <span class="m">1</span> <span class="k">else</span> <span class="m">0</span>
            <span class="p">)</span>
        <span class="p">})</span>

<span class="cm">/** Helper for updating the value for a key in a map, or inserting it if it does not exist. */</span>
<span class="k">private</span> <span class="k">fun</span> <span class="err">&lt;</span><span class="nf">K</span><span class="p">,</span> <span class="n">V</span><span class="p">&gt;</span> <span class="n">Map</span><span class="p">&lt;</span><span class="n">K</span><span class="p">,</span> <span class="n">V</span><span class="p">&gt;.</span><span class="n">insertOrUpdate</span><span class="p">(</span><span class="n">key</span><span class="p">:</span> <span class="n">K</span><span class="p">,</span> <span class="n">transform</span><span class="p">:</span> <span class="p">(</span><span class="n">V</span><span class="p">?)</span> <span class="p">-&gt;</span> <span class="n">V</span><span class="p">):</span> <span class="n">Map</span><span class="p">&lt;</span><span class="n">K</span><span class="p">,</span> <span class="n">V</span><span class="p">&gt;</span> <span class="p">=</span>
        <span class="n">plus</span><span class="p">(</span><span class="n">key</span> <span class="n">to</span> <span class="n">transform</span><span class="p">(</span><span class="k">get</span><span class="p">(</span><span class="n">key</span><span class="p">)))</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>This seems a reasonable approach to me, and we’ll take this and adapt it in an attempt to get a few additional benefits:</p>
<ul>
<li>Include more information about the type of calculation used for each field in the aggregate</li>
<li>Enable reuse of specific calculations in other aggregates</li>
<li>Enable independent testing of each calculation type</li>
<li>Make it fairly simple to change existing aggregates, and to create new ones.</li>
</ul>
<h2 id="representing-aggregate-calculations">Representing aggregate calculations</h2>
<p>First we’ll create a type to represent values that can be combined. We’ll use Kotlin’s <code>plus</code> operator for this purpose.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='kotlin'><span></span><span class="cm">/** A type [T] with an associative binary operation. Must satisfy the associative property:  `a + (b + c) == (a + b) + c` */</span>
<span class="k">interface</span> <span class="nc">Semigroup</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="p">{</span>
    <span class="k">operator</span> <span class="k">fun</span> <span class="nf">plus</span><span class="p">(</span><span class="n">other</span><span class="p">:</span> <span class="n">T</span><span class="p">):</span> <span class="n">T</span>
<span class="p">}</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>We’ll steal the term “<a href="https://en.wikipedia.org/wiki/Semigroup">semigroup</a>” from mathematics as its definition includes the constraints our <code>plus</code> operation needs<a href="#fn2" class="footnote-ref" id="fnref2"><sup>2</sup></a>, although we could also call it <code>Combinable</code> or <code>Addable</code> or something else if we prefer.</p>
<p>If you haven’t used Kotlin before, defining a <code>plus</code> operator function lets us also use the <code>+</code> symbol, so <code>a + b</code> will get translated to <code>a.plus(b)</code>. Whenever you see two semigroups being added using <code>+</code> for the remainder of this post, keep in mind it will be calling the <code>plus</code> function defined by that semigroup instance. (If you don’t like co-opting <code>+</code> in this way feel free to change the interface to declare <code>fun combine(other: T): T)</code> or similar.)</p>
<p>Next, we’ll define instances that represent sum, max, and min aggregation:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='kotlin'><span></span><span class="k">data</span> <span class="k">class</span> <span class="nc">Sum</span><span class="p">(</span><span class="k">val</span> <span class="py">value</span><span class="p">:</span> <span class="n">Int</span><span class="p">)</span> <span class="p">:</span> <span class="n">Semigroup</span><span class="p">&lt;</span><span class="n">Sum</span><span class="p">&gt;</span> <span class="p">{</span>
    <span class="k">override</span> <span class="k">fun</span> <span class="nf">plus</span><span class="p">(</span><span class="n">other</span><span class="p">:</span> <span class="n">Sum</span><span class="p">):</span> <span class="n">Sum</span> <span class="p">=</span> <span class="n">Sum</span><span class="p">(</span><span class="n">value</span> <span class="p">+</span> <span class="n">other</span><span class="p">.</span><span class="n">value</span><span class="p">)</span>
<span class="p">}</span>

<span class="k">data</span> <span class="k">class</span> <span class="nc">Max</span><span class="p">&lt;</span><span class="n">T</span> <span class="p">:</span> <span class="n">Comparable</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;&gt;(</span><span class="k">val</span> <span class="py">value</span><span class="p">:</span> <span class="n">T</span><span class="p">)</span> <span class="p">:</span> <span class="n">Semigroup</span><span class="p">&lt;</span><span class="n">Max</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;&gt;</span> <span class="p">{</span>
    <span class="k">override</span> <span class="k">operator</span> <span class="k">fun</span> <span class="nf">plus</span><span class="p">(</span><span class="n">other</span><span class="p">:</span> <span class="n">Max</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;)</span> <span class="p">=</span> <span class="n">Max</span><span class="p">(</span><span class="n">maxOf</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">other</span><span class="p">.</span><span class="n">value</span><span class="p">))</span>
<span class="p">}</span>

<span class="k">data</span> <span class="k">class</span> <span class="nc">Min</span><span class="p">&lt;</span><span class="n">T</span> <span class="p">:</span> <span class="n">Comparable</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;&gt;(</span><span class="k">val</span> <span class="py">value</span><span class="p">:</span> <span class="n">T</span><span class="p">)</span> <span class="p">:</span> <span class="n">Semigroup</span><span class="p">&lt;</span><span class="n">Min</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;&gt;</span> <span class="p">{</span>
    <span class="k">override</span> <span class="k">operator</span> <span class="k">fun</span> <span class="nf">plus</span><span class="p">(</span><span class="n">other</span><span class="p">:</span> <span class="n">Min</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;)</span> <span class="p">=</span> <span class="n">Min</span><span class="p">(</span><span class="n">minOf</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">other</span><span class="p">.</span><span class="n">value</span><span class="p">))</span>
<span class="p">}</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Looking at our <code>CandidateAggregate</code> from earlier, we also need to handle nullable values (<code>earliestSampleDate: MonthYear?</code>), as well as combining <code>Map&lt;MonthYear, Int&gt;</code> values. Rather than building these specifically for this case, we can express these concepts more generally in terms of other semigroups, so they can be reused for different cases:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='kotlin'><span></span><span class="cm">/**</span>
<span class="cm"> * Combine nullable values. Use the semigroup instance to combine if both have values, or if only</span>
<span class="cm"> * one value is present use that.</span>
<span class="cm"> */</span>
<span class="k">data</span> <span class="k">class</span> <span class="nc">Nullable</span><span class="p">&lt;</span><span class="n">T</span> <span class="p">:</span> <span class="n">Semigroup</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;&gt;(</span><span class="k">val</span> <span class="py">value</span><span class="p">:</span> <span class="n">T</span><span class="p">?)</span> <span class="p">:</span> <span class="n">Semigroup</span><span class="p">&lt;</span><span class="n">Nullable</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;&gt;</span> <span class="p">{</span>
    <span class="k">override</span> <span class="k">fun</span> <span class="nf">plus</span><span class="p">(</span><span class="n">other</span><span class="p">:</span> <span class="n">Nullable</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;):</span> <span class="n">Nullable</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="p">=</span>
            <span class="k">if</span> <span class="p">(</span><span class="n">value</span> <span class="p">!=</span> <span class="k">null</span> <span class="p">&amp;&amp;</span> <span class="n">other</span><span class="p">.</span><span class="n">value</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span> <span class="p">{</span>
                <span class="n">Nullable</span><span class="p">(</span><span class="n">value</span> <span class="p">+</span> <span class="n">other</span><span class="p">.</span><span class="n">value</span><span class="p">)</span> <span class="c1">// Reminder: `+` here will call T.plus defined for the Semigroup&lt;T&gt;.</span>
            <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
                <span class="n">Nullable</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">value</span> <span class="o">?:</span> <span class="n">other</span><span class="p">.</span><span class="n">value</span><span class="p">)</span>
            <span class="p">}</span>
<span class="p">}</span>

<span class="cm">/**</span>
<span class="cm"> * Merge [Map]s where the values have a semigroup instance. If both maps have an entry for the same key, these</span>
<span class="cm"> * will be combined using the semigroup operation.</span>
<span class="cm"> */</span>
<span class="k">data</span> <span class="k">class</span> <span class="nc">Mapped</span><span class="p">&lt;</span><span class="n">K</span><span class="p">,</span> <span class="n">V</span> <span class="p">:</span> <span class="n">Semigroup</span><span class="p">&lt;</span><span class="n">V</span><span class="p">&gt;&gt;(</span><span class="k">val</span> <span class="py">value</span><span class="p">:</span> <span class="n">Map</span><span class="p">&lt;</span><span class="n">K</span><span class="p">,</span> <span class="n">V</span><span class="p">&gt;)</span> <span class="p">:</span> <span class="n">Semigroup</span><span class="p">&lt;</span><span class="n">Mapped</span><span class="p">&lt;</span><span class="n">K</span><span class="p">,</span> <span class="n">V</span><span class="p">&gt;&gt;</span> <span class="p">{</span>
    <span class="k">override</span> <span class="k">fun</span> <span class="nf">plus</span><span class="p">(</span><span class="n">other</span><span class="p">:</span> <span class="n">Mapped</span><span class="p">&lt;</span><span class="n">K</span><span class="p">,</span> <span class="n">V</span><span class="p">&gt;):</span> <span class="n">Mapped</span><span class="p">&lt;</span><span class="n">K</span><span class="p">,</span> <span class="n">V</span><span class="p">&gt;</span> <span class="p">=</span>
            <span class="n">value</span><span class="p">.</span><span class="n">entries</span><span class="p">.</span><span class="n">fold</span><span class="p">(</span><span class="n">other</span><span class="p">.</span><span class="n">value</span><span class="p">)</span> <span class="p">{</span> <span class="n">acc</span><span class="p">,</span> <span class="n">entry</span> <span class="p">-&gt;</span>
                <span class="n">acc</span><span class="p">.</span><span class="n">insertOrUpdate</span><span class="p">(</span><span class="n">entry</span><span class="p">.</span><span class="n">key</span><span class="p">)</span> <span class="p">{</span> <span class="k">if</span> <span class="p">(</span><span class="n">it</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span> <span class="n">it</span> <span class="p">+</span> <span class="n">entry</span><span class="p">.</span><span class="n">value</span> <span class="k">else</span> <span class="n">entry</span><span class="p">.</span><span class="n">value</span> <span class="p">}</span>
            <span class="p">}.</span><span class="n">let</span> <span class="p">{</span> <span class="n">Mapped</span><span class="p">(</span><span class="n">it</span><span class="p">)</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Each of these operations is implemented quite similarly to the code we used for each field in <code>CandidateAggregate</code>, but now we can reuse them for different aggregates, as well as test each in isolation. The cost is we have now spread this code across more types.</p>
<p>We can also write some general functions, <code>concat</code> and <code>concatMap</code>, to combine any list of <code>Semigroup&lt;T&gt;</code> values into a single <code>Semigroup&lt;T&gt;</code> value, effectively combining aggregates<a href="#fn3" class="footnote-ref" id="fnref3"><sup>3</sup></a>. Here is an example of how to define and use these functions (as well as an example of testing <code>Sum</code> and <code>Max</code> in isolation):</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='kotlin'><span></span><span class="cm">/** Reduce a list of `T` to a single `T` using a semigroup operation */</span>
<span class="k">fun</span> <span class="err">&lt;</span><span class="nf">T</span> <span class="p">:</span> <span class="n">Semigroup</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;&gt;</span> <span class="n">concat</span><span class="p">(</span><span class="n">empty</span><span class="p">:</span> <span class="n">T</span><span class="p">,</span> <span class="n">items</span><span class="p">:</span> <span class="n">Iterable</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;)</span> <span class="p">=</span> <span class="n">items</span><span class="p">.</span><span class="n">fold</span><span class="p">(</span><span class="n">empty</span><span class="p">)</span> <span class="p">{</span> <span class="n">acc</span><span class="p">,</span> <span class="n">t</span> <span class="p">-&gt;</span> <span class="n">t</span> <span class="p">+</span> <span class="n">acc</span> <span class="p">}</span>

<span class="cm">/** Reduce a list of [A] by converting each item to a [T] with a semigroup instance, then combining to a single value using [concat]. */</span>
<span class="k">fun</span> <span class="err">&lt;</span><span class="nf">T</span> <span class="p">:</span> <span class="n">Semigroup</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;,</span> <span class="n">A</span><span class="p">&gt;</span> <span class="n">concatMap</span><span class="p">(</span><span class="n">empty</span><span class="p">:</span> <span class="n">T</span><span class="p">,</span> <span class="n">items</span><span class="p">:</span> <span class="n">Iterable</span><span class="p">&lt;</span><span class="n">A</span><span class="p">&gt;,</span> <span class="n">f</span><span class="p">:</span> <span class="p">(</span><span class="n">A</span><span class="p">)</span> <span class="p">-&gt;</span> <span class="n">T</span><span class="p">)</span> <span class="p">=</span>
        <span class="n">items</span><span class="p">.</span><span class="n">fold</span><span class="p">(</span><span class="n">empty</span><span class="p">)</span> <span class="p">{</span> <span class="n">acc</span><span class="p">,</span> <span class="n">t</span> <span class="p">-&gt;</span> <span class="n">f</span><span class="p">(</span><span class="n">t</span><span class="p">)</span> <span class="p">+</span> <span class="n">acc</span> <span class="p">}</span>
        <span class="cm">/* Note: this is logically equivalent to the simpler:</span>
<span class="cm">         *      concat(empty, items.map(f))</span>
<span class="cm">         * But this would do two passes through the list.</span>
<span class="cm">         */</span>

<span class="n">@Test</span>
<span class="k">fun</span> <span class="nf">examples</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">val</span> <span class="py">list</span> <span class="p">=</span> <span class="n">listOf</span><span class="p">(</span><span class="m">42</span><span class="p">,</span> <span class="m">123</span><span class="p">,</span> <span class="m">19</span><span class="p">,</span> <span class="m">73</span><span class="p">)</span>
    <span class="n">assertEquals</span><span class="p">(</span><span class="n">Sum</span><span class="p">(</span><span class="m">257</span><span class="p">),</span> <span class="n">Semigroup</span><span class="p">.</span><span class="n">concatMap</span><span class="p">(</span><span class="n">Sum</span><span class="p">(</span><span class="m">0</span><span class="p">),</span> <span class="n">list</span><span class="p">)</span> <span class="p">{</span> <span class="n">Sum</span><span class="p">(</span><span class="n">it</span><span class="p">)</span> <span class="p">})</span>
    <span class="n">assertEquals</span><span class="p">(</span><span class="n">Max</span><span class="p">(</span><span class="m">123</span><span class="p">),</span> <span class="n">Semigroup</span><span class="p">.</span><span class="n">concatMap</span><span class="p">(</span><span class="n">Max</span><span class="p">(</span><span class="m">0</span><span class="p">),</span> <span class="n">list</span><span class="p">)</span> <span class="p">{</span> <span class="n">Max</span><span class="p">(</span><span class="n">it</span><span class="p">)</span> <span class="p">})</span>
<span class="p">}</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="using-our-aggregation-types">Using our aggregation types</h2>
<p>Now we can rewrite <code>CandidateAggregate</code> using our aggregation types:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='kotlin'><span></span><span class="k">data</span> <span class="k">class</span> <span class="nc">Aggregate</span><span class="p">(</span><span class="k">var</span> <span class="py">data</span><span class="p">:</span> <span class="n">Mapped</span><span class="p">&lt;</span><span class="n">MonthYear</span><span class="p">,</span> <span class="n">Sum</span><span class="p">&gt;,</span>
                     <span class="k">var</span> <span class="py">earliestSampleDate</span><span class="p">:</span> <span class="n">Nullable</span><span class="p">&lt;</span><span class="n">Min</span><span class="p">&lt;</span><span class="n">MonthYear</span><span class="p">&gt;&gt;,</span>
                     <span class="k">var</span> <span class="py">largestSample</span><span class="p">:</span> <span class="n">Max</span><span class="p">&lt;</span><span class="n">Int</span><span class="p">&gt;,</span>
                     <span class="k">var</span> <span class="py">inRange</span><span class="p">:</span> <span class="n">Sum</span><span class="p">)</span> <span class="p">:</span> <span class="n">Semigroup</span><span class="p">&lt;</span><span class="n">Aggregate</span><span class="p">&gt;</span> <span class="p">{</span>
    <span class="k">companion</span> <span class="k">object</span> <span class="err">{</span>
        <span class="k">val</span> <span class="py">empty</span> <span class="p">=</span> <span class="n">Aggregate</span><span class="p">(</span><span class="n">Mapped</span><span class="p">(</span><span class="n">emptyMap</span><span class="p">()),</span> <span class="n">Nullable</span><span class="p">(</span><span class="k">null</span><span class="p">),</span> <span class="n">Max</span><span class="p">(</span><span class="m">0</span><span class="p">),</span> <span class="n">Sum</span><span class="p">(</span><span class="m">0</span><span class="p">))</span>
    <span class="p">}</span>

    <span class="k">override</span> <span class="k">fun</span> <span class="nf">plus</span><span class="p">(</span><span class="n">other</span><span class="p">:</span> <span class="n">Aggregate</span><span class="p">):</span> <span class="n">Aggregate</span> <span class="p">=</span>
            <span class="n">Aggregate</span><span class="p">(</span><span class="k">data</span> <span class="p">+</span> <span class="n">other</span><span class="p">.</span><span class="k">data</span><span class="p">,</span>
                    <span class="n">earliestSampleDate</span> <span class="p">+</span> <span class="n">other</span><span class="p">.</span><span class="n">earliestSampleDate</span><span class="p">,</span>
                    <span class="n">largestSample</span> <span class="p">+</span> <span class="n">other</span><span class="p">.</span><span class="n">largestSample</span><span class="p">,</span>
                    <span class="n">inRange</span> <span class="p">+</span> <span class="n">other</span><span class="p">.</span><span class="n">inRange</span><span class="p">)</span>
<span class="p">}</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>The type of aggregation used appears explicitly for each field in <code>Aggregate</code>. For example <code>largestSample: Max&lt;Int&gt;</code> conveys both the type of the result (<code>Int</code>), as well as the process being used to calculated it (<code>Max</code>). In <code>CandidateAggregate</code> only the former was expressed. We also build some field types by composing semigroups, such as <code>Mapped&lt;MonthYear, Sum&gt;</code>, which specifies we will be adding values using <code>Sum</code> rather than some other approach. This also makes it very simple to update the method of aggregation (as illustrated <a href="#what-have-we-gained-for-the-price">below</a>).</p>
<p>We have made <code>Aggregate</code> itself a semigroup to define how we combine these composite aggregates. We’ve also added an <code>empty</code> property to make it easier to call <code>concat</code> and <code>concatMap</code>.</p>
<p>The last piece we need is to translate a single <code>Sample</code> into an <code>Aggregate</code>, then we can do the entire aggregation using <code>concatMap</code> as shown in the <code>aggregateSamples()</code> test. Each <code>Sample</code> gets transformed into an <code>Aggregate</code> representing that individual sample (an aggregate of 1), then each <code>Aggregate</code> in turn gets combined to calculate the required information across all the samples.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='kotlin'><span></span><span class="k">fun</span> <span class="nf">aggregateSample</span><span class="p">(</span><span class="n">sample</span><span class="p">:</span> <span class="n">Sample</span><span class="p">):</span> <span class="n">Aggregate</span> <span class="p">=</span>
        <span class="n">Aggregate</span><span class="p">(</span><span class="n">Mapped</span><span class="p">(</span><span class="n">mapOf</span><span class="p">(</span><span class="n">sample</span><span class="p">.</span><span class="n">date</span> <span class="n">to</span> <span class="n">Sum</span><span class="p">(</span><span class="n">sample</span><span class="p">.</span><span class="n">value</span><span class="p">))),</span>
                <span class="n">Nullable</span><span class="p">(</span><span class="n">Min</span><span class="p">(</span><span class="n">sample</span><span class="p">.</span><span class="n">date</span><span class="p">)),</span>
                <span class="n">Max</span><span class="p">(</span><span class="n">sample</span><span class="p">.</span><span class="n">value</span><span class="p">),</span>
                <span class="n">sample</span><span class="p">.</span><span class="n">value</span><span class="p">.</span><span class="n">countWithin</span><span class="p">(</span><span class="m">100.</span><span class="p">.</span><span class="m">200</span><span class="p">))</span>

<span class="k">fun</span> <span class="err">&lt;</span><span class="nf">T</span> <span class="p">:</span> <span class="n">Comparable</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;&gt;</span> <span class="n">T</span><span class="p">.</span><span class="n">countWithin</span><span class="p">(</span><span class="n">range</span><span class="p">:</span> <span class="n">ClosedRange</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;)</span> <span class="p">=</span>
        <span class="n">Sum</span><span class="p">(</span><span class="k">if</span> <span class="p">(</span><span class="n">range</span><span class="p">.</span><span class="n">contains</span><span class="p">(</span><span class="k">this</span><span class="p">))</span> <span class="m">1</span> <span class="k">else</span> <span class="m">0</span><span class="p">)</span>

<span class="n">@Test</span>
<span class="k">fun</span> <span class="nf">aggregateSamples</span><span class="p">()</span> <span class="p">{</span>
    <span class="c1">// Aggregation</span>
    <span class="k">val</span> <span class="py">result</span> <span class="p">=</span> <span class="n">Semigroup</span><span class="p">.</span><span class="n">concatMap</span><span class="p">(</span><span class="n">Aggregate</span><span class="p">.</span><span class="n">empty</span><span class="p">,</span> <span class="n">samples</span><span class="p">)</span> <span class="p">{</span> <span class="n">aggregateSample</span><span class="p">(</span><span class="n">it</span><span class="p">)</span> <span class="p">}</span>

    <span class="c1">// Actual results are equivalent to the individual queries on the left:</span>
    <span class="n">assertEquals</span><span class="p">(</span><span class="n">samples</span><span class="p">.</span><span class="n">minBy</span> <span class="p">{</span> <span class="n">it</span><span class="p">.</span><span class="n">date</span> <span class="p">}</span><span class="o">?.</span><span class="n">date</span><span class="p">,</span> <span class="n">result</span><span class="p">.</span><span class="n">earliestSampleDate</span><span class="p">.</span><span class="n">value</span><span class="o">?.</span><span class="n">value</span><span class="p">)</span>
    <span class="n">assertEquals</span><span class="p">(</span><span class="n">samples</span><span class="p">.</span><span class="n">maxBy</span> <span class="p">{</span> <span class="n">it</span><span class="p">.</span><span class="n">value</span> <span class="p">}</span><span class="o">?.</span><span class="n">value</span><span class="p">,</span> <span class="n">result</span><span class="p">.</span><span class="n">largestSample</span><span class="p">.</span><span class="n">value</span><span class="p">)</span>
    <span class="n">assertEquals</span><span class="p">(</span><span class="n">samples</span><span class="p">.</span><span class="n">count</span> <span class="p">{</span> <span class="p">(</span><span class="m">100.</span><span class="p">.</span><span class="m">200</span><span class="p">).</span><span class="n">contains</span><span class="p">(</span><span class="n">it</span><span class="p">.</span><span class="n">value</span><span class="p">)</span> <span class="p">},</span> <span class="n">result</span><span class="p">.</span><span class="n">inRange</span><span class="p">.</span><span class="n">value</span><span class="p">)</span>
    <span class="k">val</span> <span class="py">june2017</span> <span class="p">=</span> <span class="n">MonthYear</span><span class="p">(</span><span class="m">2017</span><span class="p">,</span> <span class="m">6</span><span class="p">)</span>
    <span class="n">assertEquals</span><span class="p">(</span><span class="n">samples</span><span class="p">.</span><span class="n">filter</span> <span class="p">{</span> <span class="n">x</span> <span class="p">-&gt;</span> <span class="n">june2017</span> <span class="p">==</span> <span class="n">x</span><span class="p">.</span><span class="n">date</span> <span class="p">}.</span><span class="n">sumBy</span> <span class="p">{</span> <span class="n">it</span><span class="p">.</span><span class="n">value</span> <span class="p">},</span> <span class="n">result</span><span class="p">.</span><span class="k">data</span><span class="p">.</span><span class="n">value</span><span class="p">[</span><span class="n">june2017</span><span class="p">]</span><span class="o">?.</span><span class="n">value</span><span class="p">)</span>
<span class="p">}</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="what-have-we-gained-for-the-price">What have we gained for the price?</h2>
<p>This definitely has more pieces that the <code>CandidateAggregate</code> version (although the code for each piece has not changed much, it is now spread over multiple types). More pieces suggest a performance impact, but I have not measured this.</p>
<p>We do get a few benefits for this price. Firstly, we now have some small, simple, genuinely reusable aggregation types (<code>Sum</code>, <code>Max</code>, <code>Min</code>, <code>Mapped</code> etc.). These can be combined into other aggregates, and they can be tested in isolation. Secondly, we explicitly define aggregate types in terms of the aggregates of which they are composed. We don’t have an aggregate that contains an <code>Int</code>, we have a <code>Sum</code> or a <code>Max&lt;Int&gt;</code> which conveys more information as to the aggregation process, as well as preventing errors (summing two <code>Int</code> values that should have been combined using <code>maxOf</code> for example).</p>
<p>We also make it simpler to change our aggregation. For example, if we wanted to change from reporting the total value to the maximum value for each month, we can change <code>Mapped&lt;MonthYear, Sum&gt;</code> to <code>Mapped&lt;MonthYear, Max&lt;Int&gt;&gt;</code> and the aggregation process will adjust accordingly.</p>
<h2 id="conclusion">Conclusion</h2>
<p>We introduced a <code>Semigroup&lt;T&gt;</code> interface which represents values that can be combined with an associative, binary operation. We also introduced <code>concat</code> and <code>concatMap</code> operations that work for any instance of this interface. We created <code>Sum</code>, <code>Max</code>, <code>Min</code>, <code>Nullable</code> and <code>Mapped</code> instances of this interface to represent common methods of aggregation, then built a custom <code>Aggregate</code> semigroup composed of some of these instances.</p>
<p>This is a bit more complex compared than manually aggregating a set of values over a loop or fold, but in return gives us reusable and testable aggregate types, more communicative types for our aggregate model, less opportunities for bugs in the aggregation process, as well as making the creation of new aggregates and modifications to existing aggregates simpler.</p>
<h2 id="suggested-reading">Suggested reading</h2>
<ul>
<li><a href="https://fsharpforfunandprofit.com/series/understanding-monoids.html">Understanding monoids</a>, a three part series on monoids (a special case of semigroup) by Scott Wlaschin at the excellent <a href="https://fsharpforfunandprofit.com/">F# for fun and profit</a> site.</li>
</ul>
<section class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Example of multiple queries:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode kotlin"><code class="sourceCode kotlin"><a class="sourceLine" id="cb1-1" title="1"><span class="kw">val</span> <span class="va">minDate</span> = samples.map { it.date }.min()</a>
<a class="sourceLine" id="cb1-2" title="2"><span class="kw">val</span> <span class="va">maxSample</span> = samples.map { it.value }.max()</a>
<a class="sourceLine" id="cb1-3" title="3"><span class="kw">val</span> <span class="va">inRangeCount</span> = samples.count { (<span class="dv">100</span>..<span class="dv">200</span>).contains(it.value) }</a></code></pre></div>
<a href="#fnref1" class="footnote-back">↩</a></li>
<li id="fn2"><p>A semigroup for a type <code>T</code> consists of a closed binary operation <code>T -&gt; T -&gt; T</code> that is also <a href="https://davesquared.net/2012/04/associativity.html">associative</a> (i.e. <code>a + (b + c) == (a + b) + c</code>). This associativity constraint means we can combine and compose these values fairly flexibly. For example, we can do <code>a + b + c</code>, without having to worry about wether <code>b</code> is itself a composite of <code>x + y</code>, as associativity guarantees <code>a + (x + y) + c</code> is the same as <code>((a + x) + y) + c</code>. We can’t do the same thing with non-associative operations like subtraction:</p>
<pre><code>100 - (30 - 10) - 5 /= ((100 - 30) - 10) - 5
75 /= 55</code></pre>
<p>The end result is we can use associativity to combine values without having to also take evaluation order into account.<a href="#fnref2" class="footnote-back">↩</a></p></li>
<li id="fn3"><p>Both <code>concat</code> and <code>concatMap</code> take an <code>empty: T</code> value for cases where the <code>items</code> lists are empty. We could use a <code>Monoid</code> constraint instead of <code>Semigroup</code>, which adds the concept of an empty identity element, but I found this messy to implement in Kotlin.<a href="#fnref3" class="footnote-back">↩</a></p></li>
</ol>
</section>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Specifying FAKE targets]]></title>
    <link href="http://davesquared.net/2017/02/fake-targets.html"/>
    <updated>2017-02-05T08:45:00+11:00</updated>
    <id>http://davesquared.net/2017/02/fake-targets</id>
    <content type="html"><![CDATA[<!-- more -->
<p><a href="http://fsharp.github.io/FAKE/">FAKE</a> is an F#-based build tool along similar lines to Make, Rake, etc. The <a href="http://fsharp.github.io/FAKE/gettingstarted.html">FAKE documentation</a> describes one way of setting up dependencies between targets using the <code>==&gt;</code> operator. For example:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="s">&quot;Clean&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;Version&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;Build&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;Test&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;Package&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;Full&quot;</span><span class="o">`</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>This declaration means that to run the <code>Test</code> target, <code>Build</code> must be run beforehand, which in turn requires <code>Version</code>, which in turn requires <code>Clean</code> to be run.</p>
<p>This approach limits us to a linear build order. I’d prefer to specify these dependencies less prescriptively, and have FAKE calculate the ordering based on whatever target or targets I need.</p>
<p>Continuing the above example, I’d like to quickly build and run the tests during development, but for that case I don’t really need to version the assemblies. I’d also like to avoid running <code>Clean</code> in this case to take advantage of incremental compilation. But if I’m running the <code>Package</code> task to package everything for NuGet then it is essential to run <code>Version</code> before <code>Build</code> to make sure the packaged assemblies have the right version numbers. And I want to make sure I <code>Clean</code> before a full build to avoid any old artefacts making it into a package.</p>
<p>I fairly recently found out that FAKE does support this flexibility, using <a href="http://fsharp.github.io/FAKE/soft-dependencies.html">soft dependencies</a> and the ability to specify multiple dependencies using the <a href="http://fsharp.github.io/FAKE/apidocs/fake-targethelper.html"><code>&lt;==</code></a> operator.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="c1">// ... target definitions elided ... </span>
<span class="n">Target</span> <span class="s">&quot;Full&quot;</span> <span class="n">DoNothing</span>

<span class="c1">// Dependencies</span>
<span class="s">&quot;Clean&quot;</span>   <span class="o">?=&gt;</span> <span class="s">&quot;Build&quot;</span>
<span class="s">&quot;Version&quot;</span> <span class="o">?=&gt;</span> <span class="s">&quot;Build&quot;</span>
<span class="s">&quot;Test&quot;</span>    <span class="o">&lt;==</span> <span class="o">[</span> <span class="s">&quot;Build&quot;</span> <span class="o">]</span>
<span class="s">&quot;Package&quot;</span> <span class="o">&lt;==</span> <span class="o">[</span> <span class="s">&quot;Build&quot;</span><span class="o">;</span> <span class="s">&quot;Version&quot;</span> <span class="o">]</span>
<span class="s">&quot;Full&quot;</span>    <span class="o">&lt;==</span> <span class="o">[</span> <span class="s">&quot;Clean&quot;</span><span class="o">;</span> <span class="s">&quot;Version&quot;</span><span class="o">;</span> <span class="s">&quot;Build&quot;</span><span class="o">;</span> <span class="s">&quot;Test&quot;</span><span class="o">;</span> <span class="s">&quot;Package&quot;</span> <span class="o">]</span>

<span class="n">RunTargetOrDefault</span> <span class="s">&quot;Full&quot;</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>The <code>"Clean" ?=&gt; "Build"</code> line tells FAKE “if <code>Clean</code> needs to run, it must run before <code>Build</code>”. We also tell FAKE that if we are <code>Version</code>ing, that has to be done before build as well. Unlike the linear definition we are not saying we <em>have</em> to run <code>Clean</code> or <code>Version</code>, just that <em>if</em> they need to run, they must go before <code>Build</code>.</p>
<p>The <code>&lt;==</code> operator lets us make a target depend on multiple other targets. So <code>"Package" &lt;== [ "Build"; "Version" ]</code> tells FAKE that to run <code>Package</code>, we have to run <code>Build</code> and <code>Version</code>. When we <a href="http://fsharp.github.io/FAKE/commandline.html">run</a> <code>fake Package</code> FAKE knows it has to run both tasks, and it also knows that if it runs <code>Version</code> it must do so before <code>Build</code>. So the final build order for that case is: <code>Version</code>, then <code>Build</code>, then <code>Package</code>.<a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a></p>
<p>This gives me exactly the behaviour I was after. I can run the <code>Test</code> target which will force a build, but won’t run a clean or version the assemblies. I can generate a NuGet package with versioned assemblies (I should probably make that depend on <code>Test</code> as well). Or I can run a <code>Full</code> build which will clean, version, build, test and create the package.</p>
<section class="footnotes">
<hr />
<ol>
<li id="fn1"><p>I’d normally specify the task in the expected final order where possible, so <code>"Package" &lt;== [ "Verison"; "Build" ]</code>, but I just wanted to illustrate that FAKE is working out the required order, it isn’t a side-effect of the order dependencies are specified.<a href="#fnref1" class="footnote-back">↩</a></p></li>
</ol>
</section>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Pondering a prescription for pattern matching prevalance]]></title>
    <link href="http://davesquared.net/2016/02/pattern-matching.html"/>
    <updated>2016-02-16T20:45:00+11:00</updated>
    <id>http://davesquared.net/2016/02/pattern-matching</id>
    <content type="html"><![CDATA[<p>In which I ramble on about how my thoughts on pattern matching have changed over the years.</p>
<!-- more -->
<h2 id="glorified-conditional">Glorified conditional?</h2>
<p>At its most basic, pattern matching can be use to represent standard conditionals and <code>switch</code> statements. For example (in F#):</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="c1">// Pattern matching syntax:</span>
<span class="k">let</span> <span class="nv">menu</span> <span class="n">s</span> <span class="o">=</span>
    <span class="k">match</span> <span class="n">s</span> <span class="k">with</span>
    <span class="o">|</span> <span class="s">&quot;X&quot;</span> <span class="o">=</span> <span class="n">exitCommand</span>
    <span class="o">|</span> <span class="s">&quot;U&quot;</span> <span class="o">=</span> <span class="n">moveUpCommand</span>
    <span class="o">|</span> <span class="s">&quot;D&quot;</span> <span class="o">=</span> <span class="n">moveDownCommand</span>
    <span class="o">|</span>  <span class="o">_</span>  <span class="o">=</span> <span class="o">...</span>

<span class="c1">// Conditionals:</span>
<span class="k">let</span> <span class="nv">menu2</span> <span class="n">s</span> <span class="o">=</span>
    <span class="k">if</span> <span class="n">s</span> <span class="o">=</span> <span class="s">&quot;X&quot;</span> <span class="k">then</span> <span class="n">exitCommand</span>
    <span class="k">else</span> <span class="k">if</span> <span class="n">s</span> <span class="o">=</span> <span class="s">&quot;U&quot;</span> <span class="k">then</span> <span class="n">moveUpCommand</span>
    <span class="k">else</span> <span class="k">if</span> <span class="n">s</span> <span class="o">=</span> <span class="s">&quot;D&quot;</span> <span class="k">then</span> <span class="n">moveDownCommand</span>
    <span class="k">else</span> <span class="o">...</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>This did not initially seem very exciting to me. There has to be more to it than this, right? (Spoiler: yes :) )</p>
<h2 id="pattern-match-all-teh-things">Pattern match all teh things!</h2>
<p>Things get more interesting when we are dealing with types whose values can have different shapes. For example, <code>Option&lt;T&gt;</code> (similar to <code>Nullable&lt;T&gt;</code> in C#). In F# <code>Option&lt;T&gt;</code> has an <code>IsSome</code> property (like <code>HasValue</code> for <code>Nullable&lt;T&gt;</code>). If this is <code>true</code> then it is safe to access that value’s <code>Value</code> property. If <code>IsSome</code> is <code>false</code>, then accessing <code>Value</code> will throw a <code>NullReferenceException</code>. So we could (but please don’t) use option types like this:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="c1">// Don&#39;t do this!</span>
<span class="k">let</span> <span class="nv">getKeyAndValue</span> <span class="o">(</span><span class="n">key</span> <span class="o">:</span> <span class="kt">string</span><span class="o">)</span> <span class="o">(</span><span class="n">dict</span> <span class="o">:</span> <span class="n">Map</span><span class="o">&lt;</span><span class="kt">string</span><span class="o">,</span><span class="kt">string</span><span class="o">&gt;)</span> <span class="o">=</span>
    <span class="k">let</span> <span class="nv">result</span> <span class="o">=</span> <span class="n">dict</span><span class="o">.</span><span class="n">TryFind</span><span class="o">(</span><span class="n">key</span><span class="o">)</span>
    <span class="k">if</span> <span class="n">result</span><span class="o">.</span><span class="n">IsSome</span> <span class="k">then</span>
        <span class="n">Some</span> <span class="o">(</span><span class="n">key</span><span class="o">,</span> <span class="n">result</span><span class="o">.</span><span class="n">Value</span><span class="o">)</span>  <span class="c1">// please don&#39;t do this</span>
    <span class="k">else</span>
        <span class="n">None</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>I don’t like this. I’m not fond of null reference exceptions, and I don’t like checking <code>IsSome</code> before accessing values because I do silly things like messing up the conditional, or forgetting to check and crashing with a <code>NullReferenceException</code> (or if not forgetting, there are always those cases that “will never be null” which end up being just that due to a misunderstanding or a change somewhere along a call stack). And what about more complicated types, where we may have to check several different preconditions before accessing a number of different values?</p>
<p>Instead, we can use pattern matching to match all the possible shapes of our type:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="c1">// Better (but can still be improved)</span>
<span class="k">let</span> <span class="nv">getKeyAndValue</span> <span class="o">(</span><span class="n">key</span> <span class="o">:</span> <span class="kt">string</span><span class="o">)</span> <span class="o">(</span><span class="n">dict</span> <span class="o">:</span> <span class="n">Map</span><span class="o">&lt;</span><span class="kt">string</span><span class="o">,</span><span class="kt">string</span><span class="o">&gt;)</span> <span class="o">=</span>
    <span class="k">match</span> <span class="n">dict</span><span class="o">.</span><span class="n">TryFind</span><span class="o">(</span><span class="n">key</span><span class="o">)</span> <span class="k">with</span>
    <span class="o">|</span> <span class="n">Some</span> <span class="n">value</span> <span class="o">-&gt;</span> <span class="n">Some</span> <span class="o">(</span><span class="n">key</span><span class="o">,</span> <span class="n">value</span><span class="o">)</span>
    <span class="o">|</span> <span class="n">None</span>       <span class="o">-&gt;</span> <span class="n">None</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>This is great because we don’t need to access the null reference-throwing <code>.Value</code> property. Instead the value is assigned as part of the pattern: <code>Some value</code>. For the <code>None</code> case there is no value we can access within the pattern. If we tried to add one, the compiler will stop and tell use we have the wrong pattern. What is extra great is that if we don’t cover all the possible allowable values of the type we are matching against the compiler will warn us.</p>
<p>So we’ve ruled out a whole bunch of errors, and have very explicit, compiler-checked documentation about valid ways to use values of each type.</p>
<p>This is awesome! Pattern match all teh things!</p>
<h2 id="the-meh-of-matching">The “meh” of matching</h2>
<p>Say we have a collection of key value pairs, where both keys and values are strings. Maybe we got this from a POST request, or a flattened JSON object or something. We want to get the value for a particular key, and convert it to an integer (or <code>0</code> if we can not do the conversion).</p>
<p>So we have two cases that can be <code>None</code>, looking up a value for a key that may not be in the JSON, and trying to convert the value to a valid integer.</p>
<p>Let’s start out with the conditional version:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">let</span> <span class="nv">getRows</span> <span class="o">(</span><span class="n">dict</span> <span class="o">:</span> <span class="n">Map</span><span class="o">&lt;</span><span class="kt">string</span><span class="o">,</span> <span class="kt">string</span><span class="o">&gt;)</span> <span class="o">:</span> <span class="n">int</span> <span class="o">=</span>
    <span class="k">let</span> <span class="nv">rows</span> <span class="o">=</span> <span class="n">dict</span><span class="o">.</span><span class="n">TryFind</span><span class="o">(</span><span class="s">&quot;numberOfRows&quot;</span><span class="o">)</span>
    <span class="k">if</span> <span class="n">rows</span><span class="o">.</span><span class="n">IsSome</span> <span class="k">then</span>
        <span class="k">let</span> <span class="nv">result</span> <span class="o">=</span> <span class="n">tryParseInt</span><span class="o">(</span><span class="n">rows</span><span class="o">.</span><span class="n">Value</span><span class="o">)</span>
        <span class="k">if</span> <span class="n">result</span><span class="o">.</span><span class="n">IsSome</span> <span class="k">then</span> <span class="n">result</span><span class="o">.</span><span class="n">Value</span>
        <span class="k">else</span> <span class="mi">0</span>
    <span class="k">else</span> <span class="mi">0</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Yuck, look at all those potentially catastrophic <code>.Value</code> calls! Let’s rewrite it with our new-found hammer:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">let</span> <span class="nv">getRows2</span> <span class="o">(</span><span class="n">dict</span> <span class="o">:</span> <span class="n">Map</span><span class="o">&lt;</span><span class="kt">string</span><span class="o">,</span> <span class="kt">string</span><span class="o">&gt;)</span> <span class="o">:</span> <span class="n">int</span> <span class="o">=</span>
    <span class="k">match</span> <span class="n">dict</span><span class="o">.</span><span class="n">TryFind</span><span class="o">(</span><span class="s">&quot;numberOfRows&quot;</span><span class="o">)</span> <span class="k">with</span>
    <span class="o">|</span> <span class="n">None</span> <span class="o">-&gt;</span> <span class="mi">0</span>
    <span class="o">|</span> <span class="n">Some</span> <span class="n">rows</span> <span class="o">-&gt;</span>
        <span class="k">match</span> <span class="n">tryParseInt</span> <span class="n">rows</span> <span class="k">with</span>
        <span class="o">|</span> <span class="n">None</span> <span class="o">-&gt;</span> <span class="mi">0</span>
        <span class="o">|</span> <span class="n">Some</span> <span class="n">result</span> <span class="o">-&gt;</span> <span class="n">result</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>What isn’t so great is that we are still writing very similar code, just with safer pattern-matching instead of free-form conditionals. But we’re still going through the same code branches.</p>
<p>What I also found alarming when first starting out with this is a side-effect of the compiler warning us about unmatched values – we’re now forced to be explicit everywhere about how to handle all the values. Isn’t this going to get horribly verbose? We already have a good idea about when things are going to be null, so why trade concise code for a little safety?</p>
<p>Well, the good thing is we can have our safety and eat… er… code… concisely too!</p>
<h2 id="combinator-all-teh-things">Combinator all teh things!</h2>
<p>Rather than digging into the details of a type by pattern matching all the time, we can define operations for using and combining values of these types. I often see these referred to as “combinators” (although <a href="https://wiki.haskell.org/Combinator">that term seems overloaded</a>). For example, we can rewrite our <code>getRows</code> function using <code>Option.bind</code> and <code>Option.getOrElse</code><a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a> without ever digging in to grab a value from an <code>Option&lt;T&gt;</code> type.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">let</span> <span class="nv">getRows3</span> <span class="o">(</span><span class="n">dict</span> <span class="o">:</span> <span class="n">Map</span><span class="o">&lt;</span><span class="kt">string</span><span class="o">,</span> <span class="kt">string</span><span class="o">&gt;)</span> <span class="o">:</span> <span class="n">int</span> <span class="o">=</span>
    <span class="n">dict</span><span class="o">.</span><span class="n">TryFind</span><span class="o">(</span><span class="s">&quot;numberOfRows&quot;</span><span class="o">)</span>
    <span class="o">|&gt;</span> <span class="nn">Option</span><span class="p">.</span><span class="n">bind</span> <span class="n">tryParseInt</span>
    <span class="o">|&gt;</span> <span class="nn">Option</span><span class="p">.</span><span class="n">getOrElse</span> <span class="mi">0</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Under the hood this code is still doing exactly the same thing, but we are now expressing the operation in terms of other distinct operations, instead of via the details of deconstructing values<a href="#fn2" class="footnote-ref" id="fnref2"><sup>2</sup></a>. This allows us to start thinking at a higher level of abstraction. Rather than thinking about things like “if this is <code>Some value</code> return that, or if it is <code>None</code> then return the second option”, we start thinking in terms of the higher-level operations like <code>or</code> and <code>map</code>. These operations allow us to more easily and precisely express more complex ideas.</p>
<p>This was a huge turning point for me. Previously I was worried about things like <code>Option&lt;T&gt;</code> values propagating all over the code, and having to pattern match at each call site. Now we still get propagation (which is completely valid! If we are dealing with a call that can return an empty value, chances are the caller will also need to return an empty value), but there is no cost for this. Combinators make using these values almost as convenient as using the wrapped type<a href="#fn3" class="footnote-ref" id="fnref3"><sup>3</sup></a>, with the benefit that we are now safely handling empty values instead of relying on us to remember which calls sometimes return <code>null</code> instead of a <code>T</code>.</p>
<h2 id="an-aside-for-pattern-matching-less-languages">An aside for pattern matching-less languages</h2>
<p>If we mainly use combinators for combining types of values, this makes pattern matching a less essential part of a language. It is still a very nice feature to have, as it is pretty natural to implement combinators using pattern matching, and pattern matching seems to go hand-in-hand with <a href="http://fsharpforfunandprofit.com/posts/discriminated-unions/">sum types</a> which I regard as an essential language feature. But for those who still do a lot of work in C# and similar languages this means that we can implement these combinators in others ways (sometimes messy ways, without as much compiler/type system help) and get a lot out of useful, oft-pattern-matched types like <code>Option</code> and <code>Either</code>.</p>
<h2 id="conclusion">Conclusion</h2>
<p>My experience with pattern matching has gone from not understanding why it was useful, then to wanting to use it everywhere, now to favouring combinators and avoiding having to dig in to the details of a type as much as possible. Using these operations defined over types gives me a nice, high-level way of thinking about building up these values.</p>
<p>Pattern-matching is still really useful, particularly for defining operations over a type, but in general I try to use those defined operations instead, only falling back to pattern matching in the cases where it is much simpler (for example: cases like <code>let (a,b) = foo</code> instead of <code>let a = fst foo; let b = snd foo</code>).</p>
<p>If you currently use pattern matching all the time, maybe try to pull out the repeated operations the pattern matches represent and see if you prefer that style. Operations like <code>map</code>, <code>flatMap</code>, <code>apply</code>, <code>reduce</code>/<code>fold</code>, and other combining functions along the lines of <code>+</code>, <code>and</code>, and <code>or</code> are good places to start.</p>
<section class="footnotes">
<hr />
<ol>
<li id="fn1"><p><code>getOrElse</code> is not part of the <code>Option</code> module in F#3, but thankfully we can add members to modules.<a href="#fnref1" class="footnote-back">↩</a></p></li>
<li id="fn2"><p>To me using combinators like this is similar to how we tend to use classes. The internal details of the class are stored in private fields, and we define methods to interact with instances of that class without having to know the details of those fields. Combinators give us the same level of abstraction – we can access operations over a type without knowing the patterns / specific constructors of that type.<a href="#fnref2" class="footnote-back">↩</a></p></li>
<li id="fn3"><p>…and every bit as easy as using an object with methods hanging off it, which is one valid way of implementing these combinator functions<a href="#fnref3" class="footnote-back">↩</a></p></li>
</ol>
</section>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Currying vs. partial application]]></title>
    <link href="http://davesquared.net/2016/02/currying-vs-partialapp.html"/>
    <updated>2016-02-10T21:30:00+11:00</updated>
    <id>http://davesquared.net/2016/02/currying-vs-partialapp</id>
    <content type="html"><![CDATA[<p>When I first came across the terms “currying” and “partial application” I was a bit confused about the difference. Here is my attempt at an explanation<a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a>. I’m not 100% confident of my understanding, so please point out any inconsistencies – I’m happy to be corrected :).</p>
<!-- more -->
<p>Consider a call that takes 2 arguments and returns some value<a href="#fn2" class="footnote-ref" id="fnref2"><sup>2</sup></a>:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="n">f</span> <span class="o">:</span> <span class="o">(</span><span class="n">String</span><span class="o">,</span> <span class="n">Int</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">Widget</span>
<span class="c1">// Example call:</span>
<span class="n">f</span><span class="o">(</span><span class="s">&quot;a&quot;</span><span class="o">,</span> <span class="mi">1</span><span class="o">)</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Currying is the process of converting this to a function that takes a single argument, and returns another function that takes a single argument.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="n">f&#39;</span> <span class="o">:</span> <span class="n">String</span> <span class="o">-&gt;</span> <span class="o">(</span><span class="n">Int</span> <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">)</span>
<span class="c1">// or just:</span>
<span class="n">f&#39;</span> <span class="o">:</span> <span class="n">String</span> <span class="o">-&gt;</span> <span class="n">Int</span> <span class="o">-&gt;</span> <span class="n">Widget</span>

<span class="c1">// Example call:</span>
<span class="n">f&#39;</span><span class="o">(</span><span class="s">&quot;a&quot;</span><span class="o">)(</span><span class="mi">1</span><span class="o">)</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>For functions with more than 2 arguments, we can use currying to convert it to a series of functions that each take a single argument:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="n">g</span> <span class="o">:</span> <span class="o">(</span><span class="n">a</span><span class="o">,</span><span class="n">b</span><span class="o">,</span><span class="n">c</span><span class="o">,</span><span class="n">d</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">e</span>
<span class="n">g&#39;</span> <span class="o">:</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="o">(</span><span class="n">b</span> <span class="o">-&gt;</span> <span class="o">(</span><span class="n">c</span> <span class="o">-&gt;</span> <span class="o">(</span><span class="n">d</span> <span class="o">-&gt;</span> <span class="n">e</span><span class="o">)))</span>
<span class="c1">// or just:</span>
<span class="n">g&#39;</span> <span class="o">:</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="n">b</span> <span class="o">-&gt;</span> <span class="n">c</span> <span class="o">-&gt;</span> <span class="n">d</span> <span class="o">-&gt;</span> <span class="n">e</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Partial application is when we can have a function that takes multiple arguments, give it a subset of those arguments, and get back a function that will take the remaining arguments. With curried functions we get this ability for free, but you could imagine a language feature that implements this for uncurried functions:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="c1">// With curried function:</span>
<span class="n">g&#39;</span> <span class="o">:</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="n">b</span> <span class="o">-&gt;</span> <span class="n">c</span> <span class="o">-&gt;</span> <span class="n">d</span> <span class="o">-&gt;</span> <span class="n">e</span>
<span class="k">let</span> <span class="nv">partialApplyG</span><span class="k">&#39;</span> <span class="o">=</span> <span class="n">g&#39;</span><span class="o">(</span><span class="mi">1</span><span class="o">)(</span><span class="mi">2</span><span class="o">)</span>
<span class="c1">// partialApplyG&#39; : c -&gt; d -&gt; e</span>
<span class="n">partialApplyG&#39;</span><span class="o">(</span><span class="mi">3</span><span class="o">)(</span><span class="mi">4</span><span class="o">)</span> <span class="c1">// &lt;- providing the rest of the arguments</span>

<span class="c1">// With uncurried function (via our imagined language feature):</span>
<span class="n">g</span> <span class="o">:</span> <span class="o">(</span><span class="n">a</span><span class="o">,</span><span class="n">b</span><span class="o">,</span><span class="n">c</span><span class="o">,</span><span class="n">d</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">e</span>
<span class="k">let</span> <span class="nv">partialApplyG</span> <span class="o">=</span> <span class="n">g</span> <span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">)</span>
<span class="c1">// partialApplyG : (c, d) -&gt; e</span>
<span class="n">partialApplyG</span> <span class="o">(</span><span class="mi">3</span><span class="o">,</span> <span class="mi">4</span><span class="o">)</span> <span class="c1">// &lt;- providing the rest of the arguments</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>I think it is correct to say that all curried functions support partial application, but not all partial application implementations require currying.</p>
<section class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Also left as a comment to <a href="http://blog.thecodewhisperer.com/2016/01/21/how-a-smell-in-the-tests-points-to-a-risk-in-the-design/">this post</a>, modified slightly here<a href="#fnref1" class="footnote-back">↩</a></p></li>
<li id="fn2"><p>See <a href="http://davesquared.net/2016/02/reading-type-annotations.html">Reading type annotations</a> if this style of writing out types is unfamiliar.<a href="#fnref2" class="footnote-back">↩</a></p></li>
</ol>
</section>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Reading type annotations]]></title>
    <link href="http://davesquared.net/2016/02/reading-type-annotations.html"/>
    <updated>2016-02-09T22:30:00+11:00</updated>
    <id>http://davesquared.net/2016/02/reading-type-annotations</id>
    <content type="html"><![CDATA[<p>C and C-style languages like C++, Java, and C# tend to have method types written like this:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<div class="highlight">
<pre><code class=''>returnType methodName(argType0 arg0, argType1 arg1);</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Other typed languages and programming papers use a notation more like this:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<div class="highlight">
<pre><code class=''>methodName : (argType0, argType1) -&gt; returnType</code></pre>
</div>
</figure>
</notextile>
</div>
<p>I found it took a bit of getting used to, but I now much prefer to read and write this style. I think it is worth becoming familiar with, as it is used in quite a few languages<a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a> and in all the programming papers I’ve seen. So here’s a quick guide on how to read this style of type annotation.</p>
<!-- more -->
<h2 id="structure">Structure</h2>
<p>From the <code>methodName</code> example above, we can see the structure has changed from “return type - name - arguments” to “name - arguments - return type”. So the main change is moving the return type from the beginning to the end.</p>
<p>A <code>:</code> separates the name from the type signature. <code>:</code> can be read as “has type”. Haskell unfortunately uses <code>::</code> for this, instead of the <code>:</code> character which seems to be used pretty much everywhere else.</p>
<p>A <code>-&gt;</code> arrow separates function input from function output. So <code>a -&gt; b</code> reads as “I take values of type <code>a</code> and produce values of type <code>b</code>”.</p>
<p>Arguments are shown as a tuple of one or more types. In some languages (like ML, OCaml, and F#) tuple types are shown denoted by types separated by <code>*</code> characters, so the signature would look like <code>methodName : argType0 * argType1 -&gt; returnType</code>.</p>
<h2 id="generics">Generics</h2>
<p>There are a few different ways of representing generic parameters. Let’s take a function that, given a single element of some type, returns a singleton list of that type.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<div class="highlight">
<pre><code class=''>// C#
List&lt;T&gt; Singleton&lt;T&gt;(T value);

// Haskell
singleton :: t -&gt; List t

// F#
singleton : 't -&gt; List&lt;'t&gt;
// or F# can use postfix syntax where the type variable
// is followed by the type constructor
singleton : 't -&gt; 't list</code></pre>
</div>
</figure>
</notextile>
</div>
<p>In Haskell, any type starting with a lowercase character is a type variable rather than a concrete type. In F# type parameters begin with a quote character <code>'</code>. Not requiring an additional step to list generic parameters is handy.</p>
<h2 id="higher-order-functions">Higher order functions</h2>
<p>Where this notation starts to show some advantages is with higher order functions. For example, say we want a generic <code>map</code> function:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<div class="highlight">
<pre><code class=''>// C#-style
List&lt;A&gt; Select&lt;T,A&gt;(Func&lt;T,A&gt; f, List&lt;T&gt; list);

// Haskell-style
map :: (t -&gt; a) -&gt; List t -&gt; List a

// or a more exact, less idiomatic translation:
map :: ((t -&gt; a), List t) -&gt; List a</code></pre>
</div>
</figure>
</notextile>
</div>
<p>These functions take a function that translates Ts to As, and a list of Ts, to produce a list of As. The parentheses around the <code>(t -&gt; a)</code> in the Haskell-style signature show that this is a single argument (that happens to itself be another function). This is a bit cleaner than the equivalent <code>Func&lt;T, A&gt;</code> in the C# version, particularly when the explicit type parameter declarations are taken into account. The difference becomes more noticeable as we increase the number of functions and type parameters:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<div class="highlight">
<pre><code class=''>// Example: function composition, (f ∘ g)(x) = f(g(x))

// Haskell style:
compose :: (b -&gt; c) -&gt; (a -&gt; b) -&gt; (a -&gt; c)

// C#-style:
Func&lt;A,C&gt; Compose&lt;A,B,C&gt;(Func&lt;B,C&gt; f, Func&lt;A,B&gt; g);</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="curried-functions">Curried functions</h2>
<p>In the <code>map</code> example above a “more exact, less idiomatic translation” was shown:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<div class="highlight">
<pre><code class=''>map1 :: (t -&gt; a) -&gt; List t -&gt; List a
map2 :: ((t -&gt; a), List t) -&gt; List a</code></pre>
</div>
</figure>
</notextile>
</div>
<p><code>map1</code> takes a function <code>(t -&gt; a)</code> and returns a function <code>List t -&gt; List a</code>. It would also be correct to write it as <code>map1 :: (t -&gt; a) -&gt; (List t -&gt; List a)</code>. In constrast, <code>map2</code> takes a single argument that happens to be a tuple of <code>((t -&gt; a), List t)</code>. If we are supplying both arguments at once there is not much difference, but the <code>map1</code> version also lets us supply just the <code>(t -&gt; a)</code> argument to create a new function.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<div class="highlight">
<pre><code class=''>&gt; map1 (+1) [1..3]
[2,3,4]
&gt; map2 ((+1), [1..3])
[2,3,4]

&gt; let addOne = map1 (+1)
addOne :: [List Int] -&gt; [List Int]
&gt; addOne [1..3]
[2,3,4]</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Being able to supply less than the full contingent of arguments to a function, and get back a function that takes the remainder of the arguments, is called partial application.</p>
<p>The <code>map1</code> form of signature, where a function is built out of functions that each take a single argument, is called a curried function (<code>map2</code> is “uncurried”). We get partial application, the ability to provide one argument at a time, for free with curried functions.</p>
<p>Curried function signatures in C# get unpleasant fairly quickly:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<div class="highlight">
<pre><code class=''>// Haskell-style
curriedEg :: a -&gt; b -&gt; c -&gt; d -&gt; e
uncurriedEg :: (a, b, c, d) -&gt; e

// C#
Func&lt;B, Func&lt;C, Func&lt;D, E&gt;&gt;&gt; CurriedEg&lt;A,B,C,D,E&gt;(A a);
E UncurriedEg&lt;A,B,C,D,E&gt;(A a, B b, C c, D d);

// cluck cluck, bgark!</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="unit-values">Unit values</h2>
<p>Some methods take no input and return a value (either a constant, or due to some side-effect). The “no input” value is normally represented by empty parenthesis <code>()</code>, and is called “unit” (because there is only a single legal value of this type, <code>()</code>).</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<div class="highlight">
<pre><code class=''>DateTime GetDate();

getDate : () -&gt; DateTime</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Similarly for things that take an argument but produce no direct output value (i.e. performs a side-effect)<a href="#fn2" class="footnote-ref" id="fnref2"><sup>2</sup></a>. Again, this is represented by unit:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<div class="highlight">
<pre><code class=''>void Save(Widget w);
save : Widget -&gt; ()</code></pre>
</div>
</figure>
</notextile>
</div>
<p>This starts to look a bit funny when methods take other calls with no input and no direct output:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<div class="highlight">
<pre><code class=''>void Subscribe(Action callback);
subscribe : (() -&gt; ()) -&gt; ()</code></pre>
</div>
</figure>
</notextile>
</div>
<p>It does give some immediate clues as to where side-effects are in a type signature thought.</p>
<h2 id="types-inside-implementations">Types inside implementations</h2>
<p>We’ve looked at different forms of type signatures, but this style also tends to work its way into method definitions, again using the form <code>name : type</code>.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<div class="highlight">
<pre><code class=''>// C#
List&lt;T&gt; Singleton&lt;T&gt;(T t) {
    return new List&lt;T&gt; { t };
}

// Haskell
singleton :: t -&gt; [T]
singleton t = [t]

// F#
let singleton (t : 'T) : List&lt;'T&gt; = [t]

// Swift
func singleton&lt;T&gt;(t : T) -&gt; [T] {
    return [t]
}</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Haskell tends to split the type signature from definition. F# specifies the arguments as <code>argName : argType</code>, and then gives the type of the resulting value (in this case <code>List&lt;'T&gt;</code>. Generic type parameters are indicated with a <code>'</code> prefix. Swift uses a similar style, but an arrow is used for the return type. Swift needs explicit declaration of generic type parameters.</p>
<p>In both the Haskell and F# cases the type information can actually be omitted – the type system will infer the correct type signature.</p>
<h2 id="conclusion">Conclusion</h2>
<p>This has been a quick tour through the things that first tripped me up when reading type signatures from non-C-style languages.</p>
<p>The main habit I needed to break was expecting to see a type then a name. Instead, names are first, then their type shown. So method types change like this:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<div class="highlight">
<pre><code class=''>returnType blah()
// becomes something like:
blah : () -&gt; returnType</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Similarly arguments go from <code>ArgType name</code> to <code>name : ArgType</code>.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<div class="highlight">
<pre><code class=''>void Load(int id)
// becomes something like:
load(id : int) : ()</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Hope this helps!</p>
<section class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Such as Haskell, F#, Swift, Scala, OCaml, ML, Idris, Elm, PureScript, and TypeScript.<a href="#fnref1" class="footnote-back">↩</a></p></li>
<li id="fn2"><p>Note that <code>void</code> in C-style languages is different to the terms “unit” and “Void” in non-C-style languages. In C-style languages <code>void</code> means “has no return value”, where a return type of <code>()</code> means “returns the value ()”. In contrast, the type <code>Void</code> is one with no legal instance. We can never return a value of type <code>Void</code>, so my understanding is a function <code>a -&gt; Void</code> can never return.<a href="#fnref2" class="footnote-back">↩</a></p></li>
</ol>
</section>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Apply pattern]]></title>
    <link href="http://davesquared.net/2015/07/apply-pattern.html"/>
    <updated>2015-07-27T21:45:00+10:00</updated>
    <id>http://davesquared.net/2015/07/apply-pattern</id>
    <content type="html"><![CDATA[<p>I really enjoy trying to understand how and why things like work, but for this post I’m going to try to skip all that wonderful stuff and instead give a practical outline of how to use a very useful pattern arising from <a href="http://www.davesquared.net/2012/05/fp-newbie-learns-applicatives.html">applicative functors</a>.</p>
<p>I’ve found this pattern incredibly useful in F#, Swift and Haskell. The examples here are in F#, but as far as I can tell we can use it anywhere that has generic types and higher-order functions.</p>
<!-- more -->
<h2 id="aim">Aim</h2>
<p>Say we have some generic type, let’s call it <code>Widget&lt;T&gt;</code> (we’ll use the term “widget” as a placeholder for a generic type we are working with - feel free to substitute in <code>Option&lt;T&gt;</code>, <code>Either&lt;E,A&gt;</code>, <code>Future&lt;T&gt;</code>, <code>List&lt;T&gt;</code> etc.). There are lots of useful functions that work with non-widget types, and we would like them to work with <code>Widget</code> values without having to re-write them.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="c1">// Some useful, non-widget functions:</span>
<span class="o">(+)</span> <span class="o">:</span> <span class="n">Int</span> <span class="o">-&gt;</span> <span class="n">Int</span> <span class="o">-&gt;</span> <span class="n">Int</span>
<span class="o">(::)</span> <span class="o">:</span> <span class="k">&#39;</span><span class="n">a</span> <span class="o">-&gt;</span> <span class="o">[</span><span class="k">&#39;</span><span class="n">a</span><span class="o">]</span> <span class="o">-&gt;</span> <span class="o">[</span><span class="k">&#39;</span><span class="n">a</span><span class="o">]</span>
<span class="n">createThingoe</span> <span class="o">::</span> <span class="n">Pop</span> <span class="o">-&gt;</span> <span class="n">Blah</span> <span class="o">-&gt;</span> <span class="n">Zap</span> <span class="o">-&gt;</span> <span class="n">Thingoe</span>

<span class="c1">// Widget compatible versions:</span>
<span class="n">widgetPlus</span> <span class="o">:</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="n">Int</span><span class="o">&gt;</span> <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="n">Int</span><span class="o">&gt;</span> <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="n">Int</span><span class="o">&gt;</span>
<span class="n">widgetCons</span> <span class="o">:</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">a</span><span class="o">&gt;</span>  <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">a</span><span class="o">&gt;</span>  <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">a</span><span class="o">&gt;</span>
<span class="n">widgetThingoe</span> <span class="o">:</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="n">Pop</span><span class="o">&gt;</span>  <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="n">Blah</span><span class="o">&gt;</span>  <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="n">Zap</span><span class="o">&gt;</span> <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="n">Thingoe</span><span class="o">&gt;</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="prerequisites">Prerequisites</h2>
<p>We can achieve this aim if the generic type has a <code>map</code> (or <code>Select</code> in C# terminology) and an <code>apply</code> function. Continuing our <code>Widget</code> example:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">module</span> <span class="nn">Widget</span> <span class="o">=</span>
    <span class="k">let</span> <span class="nv">map</span>   <span class="o">:</span>    <span class="o">(</span><span class="k">&#39;</span><span class="n">a</span><span class="o">-&gt;</span><span class="k">&#39;</span><span class="n">b</span><span class="o">)</span>    <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">a</span><span class="o">&gt;</span> <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">b</span><span class="o">&gt;</span> <span class="o">=</span> <span class="o">...</span>
    <span class="k">let</span> <span class="nv">apply</span> <span class="o">:</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">a</span><span class="o">-&gt;</span><span class="k">&#39;</span><span class="n">b</span><span class="o">&gt;</span> <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">a</span><span class="o">&gt;</span> <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">b</span><span class="o">&gt;</span> <span class="o">=</span> <span class="o">...</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>If the type does not have these functions provided we may still be able to write them. We’ll look at this <a href="#when-a-generic-type-does-not-meet-the-prequisites">later</a>.</p>
<h2 id="apply-pattern">Apply pattern</h2>
<p>We can use any non-widget function with widget values using <code>map</code> for the first argument, and <code>apply</code> for subsequent arguments.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">let</span> <span class="o">(&lt;^&gt;)</span> <span class="o">=</span> <span class="nn">Widget</span><span class="p">.</span><span class="n">map</span>
<span class="k">let</span> <span class="o">(&lt;*&gt;)</span> <span class="o">=</span> <span class="nn">Widget</span><span class="p">.</span><span class="n">apply</span>

<span class="c1">// Use non-widget function with non-widgets:</span>
<span class="k">let</span> <span class="nv">normalResult</span> <span class="o">=</span>
  <span class="n">nonWidgetFn</span> <span class="n">firstArg</span> <span class="n">secondArg</span> <span class="n">thirdArg</span> <span class="o">...</span> <span class="n">finalArg</span>

<span class="c1">// Use non-widget function with widgets. It&#39;s just like non-widget function</span>
<span class="c1">// application, only with more punctuation. :)</span>
<span class="k">let</span> <span class="nv">widgetResult</span> <span class="o">=</span>
  <span class="n">nonWidgetFn</span> <span class="o">&lt;^&gt;</span> <span class="n">firstWidget</span> <span class="o">&lt;*&gt;</span> <span class="n">secondWidget</span> <span class="o">&lt;*&gt;</span> <span class="n">thirdWidget</span> <span class="o">&lt;*&gt;</span> <span class="o">...</span> <span class="o">&lt;*&gt;</span> <span class="n">finalWidget</span>

<span class="c1">// Convert any 2 argument function, (a -&gt; b -&gt; c) -&gt; (Widget a -&gt; Widget b -&gt; Widget c)</span>
<span class="k">let</span> <span class="nv">lift2</span> <span class="n">f</span> <span class="n">a</span> <span class="n">b</span>     <span class="o">=</span> <span class="n">f</span> <span class="o">&lt;^&gt;</span> <span class="n">a</span> <span class="o">&lt;*&gt;</span> <span class="n">b</span>

<span class="c1">// Convert any 3 argument function:</span>
<span class="k">let</span> <span class="nv">lift3</span> <span class="n">f</span> <span class="n">a</span> <span class="n">b</span> <span class="n">c</span>   <span class="o">=</span> <span class="n">f</span> <span class="o">&lt;^&gt;</span> <span class="n">a</span> <span class="o">&lt;*&gt;</span> <span class="n">b</span> <span class="o">&lt;*&gt;</span> <span class="n">c</span>

<span class="c1">// Convert any 4 argument function:</span>
<span class="k">let</span> <span class="nv">lift4</span> <span class="n">f</span> <span class="n">a</span> <span class="n">b</span> <span class="n">c</span> <span class="n">d</span> <span class="o">=</span> <span class="n">f</span> <span class="o">&lt;^&gt;</span> <span class="n">a</span> <span class="o">&lt;*&gt;</span> <span class="n">b</span> <span class="o">&lt;*&gt;</span> <span class="n">c</span> <span class="o">&lt;*&gt;</span> <span class="n">d</span>

<span class="c1">// Widget-compatible plus and cons:</span>
<span class="n">widgetPlus</span> <span class="n">a</span> <span class="n">b</span> <span class="o">=</span> <span class="o">(+)</span> <span class="o">&lt;^&gt;</span> <span class="n">a</span> <span class="o">&lt;*&gt;</span> <span class="n">b</span>
<span class="n">widgetCons</span> <span class="n">a</span> <span class="n">b</span> <span class="o">=</span>
    <span class="k">let</span> <span class="nv">cons</span> <span class="n">a</span> <span class="n">b</span> <span class="o">=</span> <span class="n">a</span> <span class="o">::</span> <span class="n">b</span>
    <span class="n">cons</span> <span class="o">&lt;^&gt;</span> <span class="n">a</span> <span class="o">&lt;*&gt;</span> <span class="n">b</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="example">Example</h2>
<p>Say we are using a library with a <code>Result&lt;'Error, 'T&gt;</code> type that represents operations that can fail with a value of type <code>'Error</code>, or succeed with a value of type <code>'T</code>. The library also supplies <code>map</code> and <code>apply</code> functions for this type. We want to use this type to try to parse a <code>Person</code> value from a UI form with <code>name</code>, <code>email</code> and <code>age</code> text fields:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">let</span> <span class="nv">nonEmpty</span>   <span class="o">(</span><span class="n">s</span> <span class="o">:</span> <span class="kt">string</span><span class="o">)</span> <span class="o">:</span> <span class="n">Result</span><span class="o">&lt;</span><span class="n">AppError</span><span class="o">,</span> <span class="kt">string</span><span class="o">&gt;</span> <span class="o">=</span> <span class="o">...</span>
<span class="k">let</span> <span class="nv">validEmail</span> <span class="o">(</span><span class="n">s</span> <span class="o">:</span> <span class="kt">string</span><span class="o">)</span> <span class="o">:</span> <span class="n">Result</span><span class="o">&lt;</span><span class="n">AppError</span><span class="o">,</span> <span class="kt">string</span><span class="o">&gt;</span> <span class="o">=</span> <span class="o">...</span>
<span class="k">let</span> <span class="nv">parseInt</span>   <span class="o">(</span><span class="n">s</span> <span class="o">:</span> <span class="kt">string</span><span class="o">)</span> <span class="o">:</span> <span class="n">Result</span><span class="o">&lt;</span><span class="n">AppError</span><span class="o">,</span> <span class="n">int</span><span class="o">&gt;</span> <span class="o">=</span> <span class="o">...</span>

<span class="k">type</span> <span class="nc">Person</span> <span class="o">=</span> <span class="o">{</span> <span class="n">name</span> <span class="o">:</span> <span class="kt">string</span><span class="o">;</span> <span class="n">email</span> <span class="o">:</span> <span class="kt">string</span><span class="o">;</span> <span class="n">age</span> <span class="o">:</span> <span class="n">int</span> <span class="o">}</span>
    <span class="k">with</span>
    <span class="k">static</span> <span class="k">member</span> <span class="n">create</span> <span class="n">a</span> <span class="n">b</span> <span class="n">c</span> <span class="o">=</span> <span class="o">{</span> <span class="n">name</span><span class="o">=</span><span class="n">a</span><span class="o">;</span> <span class="n">email</span><span class="o">=</span><span class="n">b</span><span class="o">;</span> <span class="n">age</span><span class="o">=</span><span class="n">c</span> <span class="o">}</span>

<span class="c1">// We want to use Person.create which takes strings and ints, but we need to try to</span>
<span class="c1">// parse values from text fields which will give us Result&lt;AppError, string&gt;</span>
<span class="c1">// and Result&lt;AppError, int&gt; values.</span>
<span class="k">let</span> <span class="o">(&lt;^&gt;)</span> <span class="o">=</span> <span class="nn">Result</span><span class="p">.</span><span class="n">map</span>
<span class="k">let</span> <span class="o">(&lt;*&gt;)</span> <span class="o">=</span> <span class="nn">Result</span><span class="p">.</span><span class="n">apply</span>

<span class="nn">Person</span><span class="p">.</span><span class="n">create</span> <span class="o">&lt;^&gt;</span> <span class="n">nonEmpty</span> <span class="o">(</span><span class="n">name</span><span class="o">.</span><span class="n">text</span><span class="o">)</span> <span class="o">&lt;*&gt;</span> <span class="n">validEmail</span> <span class="o">(</span><span class="n">email</span><span class="o">.</span><span class="n">text</span><span class="o">)</span> <span class="o">&lt;*&gt;</span> <span class="n">parseInt</span> <span class="o">(</span><span class="n">age</span><span class="o">.</span><span class="n">text</span><span class="o">)</span>
    <span class="o">|&gt;</span> <span class="n">printfn</span> <span class="s">&quot;%A&quot;</span>
<span class="c">(*</span>
<span class="c">When all fields are valid:</span>
<span class="c">&gt; Success {name = </span><span class="s">&quot;Abc&quot;</span><span class="c">; email = </span><span class="s">&quot;abc@example.com&quot;</span><span class="c">; age = 42;}</span>

<span class="c">When firstName.text is empty:</span>
<span class="c">&gt; Failed UnexpectedEmptyString</span>

<span class="c">When age.text is invalid:</span>
<span class="c">&gt; Failed (CouldNotParseInt </span><span class="s">&quot;12jf&quot;</span><span class="c">)</span>
<span class="c">*)</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="when-a-generic-type-does-not-meet-the-prequisites">When a generic type does not meet the prequisites</h2>
<p>Sometimes a type will not have an <code>apply</code> function provided, but will have <code>map</code>, and also a <code>flatMap</code>/<code>bind</code> function provided with the following type:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="c1">// Also called &quot;bind&quot;</span>
<span class="k">let</span> <span class="nv">flatMap</span> <span class="o">:</span> <span class="o">(</span><span class="k">&#39;</span><span class="n">a</span><span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">b</span><span class="o">&gt;)</span> <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">a</span><span class="o">&gt;</span> <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">b</span><span class="o">&gt;</span> <span class="o">=</span> <span class="o">...</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>This is the case with the <a href="https://msdn.microsoft.com/en-us/library/ee370544.aspx">F# Option module</a>, which provides <code>map</code> and <code>bind</code> with the required signatures. In these cases we can implement <code>apply</code> in terms of the these other functions:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">module</span> <span class="nn">Option</span> <span class="o">=</span>
    <span class="k">let</span> <span class="nv">apply</span> <span class="n">ff</span> <span class="n">a</span> <span class="o">=</span> <span class="nn">Option</span><span class="p">.</span><span class="n">bind</span> <span class="o">(</span><span class="k">fun</span> <span class="n">f</span> <span class="o">-&gt;</span> <span class="nn">Option</span><span class="p">.</span><span class="n">map</span> <span class="n">f</span> <span class="n">a</span><span class="o">)</span> <span class="n">ff</span>

<span class="c1">// General case:</span>
<span class="k">module</span> <span class="nn">SomeOtherType</span> <span class="o">=</span>
    <span class="k">let</span> <span class="nv">apply</span> <span class="n">ff</span> <span class="n">a</span> <span class="o">=</span> <span class="nn">SomeOtherType</span><span class="p">.</span><span class="n">bind</span> <span class="o">(</span><span class="k">fun</span> <span class="n">f</span> <span class="o">-&gt;</span> <span class="nn">SomeOtherType</span><span class="p">.</span><span class="n">map</span> <span class="n">f</span> <span class="n">a</span><span class="o">)</span> <span class="n">ff</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>We can now use the pattern with optionals (and any type with <code>map</code> and <code>flatMap</code>/<code>bind</code>):</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">let</span> <span class="o">(&lt;^&gt;)</span> <span class="o">=</span> <span class="nn">Option</span><span class="p">.</span><span class="n">map</span>
<span class="k">let</span> <span class="o">(&lt;*&gt;)</span> <span class="o">=</span> <span class="nn">Option</span><span class="p">.</span><span class="n">apply</span>

<span class="k">let</span> <span class="nv">result</span> <span class="o">:</span> <span class="n">Option</span><span class="o">&lt;</span><span class="n">int</span><span class="o">&gt;</span> <span class="o">=</span> <span class="o">(+)</span> <span class="o">&lt;^&gt;</span> <span class="n">tryParseInt</span> <span class="o">(</span><span class="n">first</span><span class="o">.</span><span class="n">text</span><span class="o">)</span> <span class="o">&lt;*&gt;</span> <span class="n">tryParseInt</span> <span class="o">(</span><span class="n">second</span><span class="o">.</span><span class="n">text</span><span class="o">)</span>
<span class="c1">//&gt; val result : Option&lt;int&gt; = Some 42</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="mixing-widget-and-non-widget-arguments">Mixing widget and non-widget arguments</h2>
<p>In cases where we have a mix of arguments, some using our generic type and others not, we can still apply<a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a> the pattern by converting the values to our generic type. For our <code>Person.create</code> example, we could already have the person’s email as a valid <code>string</code> value from earlier in the sign-up process:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">let</span> <span class="nv">email</span> <span class="o">:</span> <span class="kt">string</span> <span class="o">=</span> <span class="s">&quot;abc@example.com&quot;</span>
<span class="nn">Person</span><span class="p">.</span><span class="n">create</span> <span class="o">&lt;^&gt;</span> <span class="n">nonEmpty</span> <span class="o">(</span><span class="n">name</span><span class="o">.</span><span class="n">text</span><span class="o">)</span> <span class="o">&lt;*&gt;</span> <span class="n">Success</span> <span class="n">email</span> <span class="o">&lt;*&gt;</span> <span class="n">parseInt</span> <span class="o">(</span><span class="n">age</span><span class="o">.</span><span class="n">text</span><span class="o">)</span>
    <span class="o">|&gt;</span> <span class="o">...</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Here we convert <code>email</code> from a <code>string</code> to a <code>Result&lt;AppError,string&gt;</code> value first using the <code>Success</code> constructor. Then we have our three <code>Result&lt;AppError,'T&gt;</code> values to use with the apply pattern.</p>
<h2 id="summary">Summary</h2>
<p>This pattern is useful for being able reuse all our existing functions in the context of another type, like <code>Future&lt;T&gt;</code>, <code>Option&lt;T&gt;</code>, <code>Result&lt;E,A&gt;</code> and lots, lots more. To do this for some generic type <code>Widget&lt;T&gt;</code> we need:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">let</span> <span class="nv">map</span> <span class="o">:</span> <span class="o">(</span><span class="k">&#39;</span><span class="n">a</span> <span class="o">-&gt;</span> <span class="k">&#39;</span><span class="n">b</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">a</span><span class="o">&gt;</span> <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">b</span><span class="o">&gt;</span>
<span class="k">let</span> <span class="nv">apply</span> <span class="o">:</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">a</span> <span class="o">-&gt;</span> <span class="k">&#39;</span><span class="n">b</span><span class="o">&gt;</span> <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">a</span><span class="o">&gt;</span> <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">b</span><span class="o">&gt;</span>

<span class="c1">// Alternatively, can also use bind/flatMap to get an apply function</span>
<span class="k">let</span> <span class="nv">flatMap</span> <span class="o">:</span> <span class="o">(</span><span class="k">&#39;</span><span class="n">a</span> <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">b</span><span class="o">&gt;)</span> <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">a</span><span class="o">&gt;</span> <span class="o">-&gt;</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">b</span><span class="o">&gt;</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>We then apply the non-widget function to the first argument using <code>map</code>, and use <code>apply</code> for subsequent applications.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">let</span> <span class="o">(&lt;^&gt;)</span> <span class="o">=</span> <span class="nn">Widget</span><span class="p">.</span><span class="n">map</span>
<span class="k">let</span> <span class="o">(&lt;*&gt;)</span> <span class="o">=</span> <span class="nn">Widget</span><span class="p">.</span><span class="n">apply</span>
<span class="k">let</span> <span class="nv">result</span> <span class="o">:</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="n">A</span><span class="o">&gt;</span> <span class="o">=</span>
    <span class="n">nonWidgetFn</span> <span class="o">&lt;^&gt;</span> <span class="n">firstWidgetArg</span> <span class="o">&lt;*&gt;</span> <span class="n">secondWidgetArg</span> <span class="o">&lt;*&gt;</span> <span class="o">...</span> <span class="o">&lt;*&gt;</span> <span class="n">lastWidgetArg</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Calls look similar to regular function application, with the additional operators taking care of conversion into our <code>Widget&lt;T&gt;</code> context.</p>
<p>We can mix widget and non-widget arguments by converting non-widgets:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">let</span> <span class="nv">result</span> <span class="o">:</span> <span class="n">Widget</span><span class="o">&lt;</span><span class="n">A</span><span class="o">&gt;</span> <span class="o">=</span>
    <span class="n">nonWidgetFn</span> <span class="o">&lt;^&gt;</span> <span class="n">firstWidgetArg</span> <span class="o">&lt;*&gt;</span> <span class="n">toWidget</span> <span class="n">secondArg</span> <span class="o">&lt;*&gt;</span> <span class="o">...</span> <span class="o">&lt;*&gt;</span> <span class="n">lastWidgetArg</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>I wrote a bit more about <a href="http://davesquared.net/2012/05/fp-newbie-learns-applicatives.html">how this works</a> a while back, or search around for “applicative functor” if you are interested in the theory behind the practice. We can effectively use this pattern without delving into the details though - so we can apply now and ask questions later. :)</p>
<section class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Sorry.<a href="#fnref1" class="footnote-back">↩</a></p></li>
</ol>
</section>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Git tidbit: Comparing different paths across branches or commits]]></title>
    <link href="http://davesquared.net/2015/04/git-compare-different-paths-across-branches.html"/>
    <updated>2015-04-22T11:25:00+10:00</updated>
    <id>http://davesquared.net/2015/04/git-compare-different-paths-across-branches</id>
    <content type="html"><![CDATA[<p>Today I updated a library version in a project, which changed the path from <code>packages/FSharp.Formatting.CommandTool-2.8.0</code> to <code>packages/FSharpFormatting.CommandTool-2.9.1</code>. We’d also taken our own copies of some templates in the package, and I wanted to check if there were any differences between <code>-2.8.0\templates</code> and <code>-2.9.1\templates</code> that I should port across.</p>
<p>Rather than my usual fumbling about (check out both, copy, diff) I thought I’d try to learn the necessary Git incantation to compare the paths. And then blog it, so that when I forget I’ll have a quick reference handy for next time. :)</p>
<!-- more -->
<p>I ended up <a href="http://stackoverflow.com/a/8131164/906">using <code>git diff</code> with the <code>COMMIT:PATH</code> format</a>, using <code>HEAD</code> and <code>HEAD~1</code> as the commit references (shown split over multiple lines):</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<div class="highlight">
<pre><code class=''>git diff --ignore-space-change \
    HEAD:source/packages/FSharp.Formatting.CommandTool.2.9.1/templates \
    HEAD~1:source/packages/FSharp.Formatting.CommandTool.2.8.0/templates/</code></pre>
</div>
</figure>
</notextile>
</div>
<p>To get a summary of the files changes instead (in this case, to confirm nothing changed), use the <code>--stat</code> option:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<div class="highlight">
<pre><code class=''>% git diff --stat --ignore-space-change HEAD:source/packages/FSharp.Formatting.CommandTool.2.9.1/templates HEAD~1:source/packages/FSharp.Formatting.CommandTool.2.8.0/templates
 docpage.cshtml                | 0
 reference/module.cshtml       | 0
 reference/namespaces.cshtml   | 0
 reference/part-members.cshtml | 0
 reference/part-nested.cshtml  | 0
 reference/type.cshtml         | 0
 template.cshtml               | 0
 7 files changed, 0 insertions(+), 0 deletions(-)</code></pre>
</div>
</figure>
</notextile>
</div>
<p>I was pretty impressed that Git’s Bash prompt on Windows gave me autocompletion on the <code>HEAD~1:/...2.8.0/</code> path despite the path no longer being in the working directory.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[F# type signature gotchas]]></title>
    <link href="http://davesquared.net/2015/01/fsharp-type-signature-gotchas.html"/>
    <updated>2015-01-22T23:30:00+11:00</updated>
    <id>http://davesquared.net/2015/01/fsharp-type-signature-gotchas</id>
    <content type="html"><![CDATA[<p>Today I was speaking with a colleague about some F#, and he pointed out a few gotchas with F# type signatures, especially if you’ve spent some time with Haskell (and not OCaml or other ML-ish language).</p>
<!-- more -->
<div class="note">
<em>Aside</em>: This post just runs through some gotchas, but if you would like more general information on reading <code>-&gt;</code> style function signatures please let me know.
</div>
<p>The example we were looking at is <a href="https://msdn.microsoft.com/en-us/library/ee340363.aspx"><code>Seq.unfold</code></a>, whose signature looks like this:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="nn">Seq</span><span class="p">.</span><span class="n">unfold</span> <span class="o">:</span> <span class="o">(</span><span class="k">&#39;</span><span class="n">State</span> <span class="o">-&gt;</span> <span class="o">(</span><span class="k">&#39;</span><span class="n">T</span> <span class="o">*</span> <span class="k">&#39;</span><span class="n">State</span><span class="o">)</span> <span class="n">option</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="k">&#39;</span><span class="n">State</span> <span class="o">-&gt;</span> <span class="n">seq</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">T</span><span class="o">&gt;</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="apostrophes-for-type-parameters">Apostrophes for type parameters</h2>
<p>Any type prefixed with a <code>'</code> character represents a type parameter (or generic type in C# parlance). For <code>unfold</code> this means <code>'State</code> and <code>'T</code> can be any type. We can also write this in potentially more familiar .NET syntax:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="nn">Seq</span><span class="p">.</span><span class="n">unfold</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">State</span><span class="o">,</span> <span class="k">&#39;</span><span class="n">T</span><span class="o">&gt;</span> <span class="o">:</span> <span class="o">(</span><span class="k">&#39;</span><span class="n">State</span> <span class="o">-&gt;</span> <span class="o">(</span><span class="k">&#39;</span><span class="n">T</span> <span class="o">*</span> <span class="k">&#39;</span><span class="n">State</span><span class="o">)</span> <span class="n">option</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="k">&#39;</span><span class="n">State</span> <span class="o">-&gt;</span> <span class="n">seq</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">T</span><span class="o">&gt;</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>A lot of the F# code I see follows a more Haskellish (?) convention of using lowercase type variable names, more like:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="nn">Seq</span><span class="p">.</span><span class="n">unfold</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">s</span><span class="o">,</span> <span class="k">&#39;</span><span class="n">t</span><span class="o">&gt;</span> <span class="o">:</span> <span class="o">(</span><span class="k">&#39;</span><span class="n">s</span> <span class="o">-&gt;</span> <span class="o">(</span><span class="k">&#39;</span><span class="n">t</span> <span class="o">*</span> <span class="k">&#39;</span><span class="n">s</span><span class="o">)</span> <span class="n">option</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="k">&#39;</span><span class="n">s</span> <span class="o">-&gt;</span> <span class="n">seq</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">t</span><span class="o">&gt;</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="asterisk-for-tuples">Asterisk for tuples</h2>
<p>Types separated by a <code>*</code> are tupled (or <a href="http://en.wikipedia.org/wiki/Product_type">product types</a>, which explains the <code>*</code> symbol). For example, <code>(1, "abc", Foo())</code> is of type <code>int * string * Foo</code>.</p>
<p>So in <code>unfold</code>, <code>'T * 'State</code> represents a tuple of <code>'T</code> and <code>'State</code>.</p>
<h2 id="postfix-generic-syntax">Postfix generic syntax</h2>
<p>F# supports <a href="http://stackoverflow.com/questions/10167359/any-difference-between-ta-and-a-t-in-f">both .NET-style prefix generic syntax and ML-style postfix syntax</a>. So instead of writing <code>int option</code>, we can also write <code>Option&lt;int&gt;</code> (<a href="http://stackoverflow.com/a/10167770/906">both forms are equivalent</a>). Which means we can re-write <code>unfold</code> as:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="nn">Seq</span><span class="p">.</span><span class="n">unfold</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">s</span><span class="o">,</span> <span class="k">&#39;</span><span class="n">t</span><span class="o">&gt;</span> <span class="o">:</span> <span class="o">(</span><span class="k">&#39;</span><span class="n">s</span> <span class="o">-&gt;</span> <span class="n">Option</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">t</span> <span class="o">*</span> <span class="k">&#39;</span><span class="n">s</span><span class="o">&gt;)</span> <span class="o">-&gt;</span> <span class="k">&#39;</span><span class="n">s</span> <span class="o">-&gt;</span> <span class="n">seq</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">t</span><span class="o">&gt;</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="using-unfold">Using <code>unfold</code></h2>
<p>With those things in mind, let’s use the <code>unfold</code> signature to work out what it does.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="n">unfold</span> <span class="o">:</span>
  <span class="o">(</span><span class="k">&#39;</span><span class="n">s</span> <span class="o">-&gt;</span> <span class="n">Option</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">t</span> <span class="o">*</span> <span class="k">&#39;</span><span class="n">s</span><span class="o">&gt;)</span> <span class="o">--</span> <span class="n">A</span> <span class="k">function</span> <span class="n">that</span> <span class="n">takes</span> <span class="n">an</span> <span class="k">&#39;</span><span class="n">s</span> <span class="ow">and</span> <span class="n">gives</span> <span class="n">an</span> <span class="n">optional</span> <span class="n">tuple</span> <span class="k">of</span> <span class="k">&#39;</span><span class="n">t</span> <span class="ow">and</span> <span class="k">&#39;</span><span class="n">s</span><span class="o">.</span>
  <span class="o">-&gt;</span> <span class="k">&#39;</span><span class="n">s</span>                   <span class="o">--</span> <span class="n">A</span> <span class="n">value</span> <span class="k">of</span> <span class="k">type</span> <span class="k">&#39;</span><span class="n">s</span>
  <span class="o">-&gt;</span> <span class="n">seq</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">t</span><span class="o">&gt;</span>              <span class="o">--</span> <span class="n">A</span> <span class="n">sequence</span> <span class="k">of</span> <span class="k">&#39;</span><span class="n">t</span> <span class="n">values</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Given a function that can take <code>'s</code> values and return a tuple of an element and next <code>'s</code> value or nothing, and a starting <code>'s</code>, <code>unfold</code> will generate a sequence of <code>'t</code> values until the generator function returns <code>None</code> (i.e. potentially infinite).</p>
<p>We could use this to generate a sequence of all the days since a starting date (infinite, at least until <code>DateTime</code> hits <code>DateTime.MaxValue</code>):</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">let</span> <span class="nv">daysAfterThisPost</span> <span class="o">=</span>
    <span class="n">DateTime</span><span class="o">(</span><span class="mi">2015</span><span class="o">,</span> <span class="mi">1</span><span class="o">,</span> <span class="mi">22</span><span class="o">)</span>
    <span class="o">|&gt;</span> <span class="nn">Seq</span><span class="p">.</span><span class="n">unfold</span> <span class="o">(</span><span class="k">fun</span> <span class="n">d</span> <span class="o">-&gt;</span> <span class="k">let</span> <span class="nv">d</span><span class="k">&#39;</span> <span class="o">=</span> <span class="n">d</span><span class="o">.</span><span class="n">AddDays</span><span class="o">(</span><span class="mi">1</span><span class="o">)</span> <span class="k">in</span> <span class="n">Some</span> <span class="o">(</span><span class="n">d&#39;</span><span class="o">,</span> <span class="n">d&#39;</span><span class="o">))</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="translating-to-other-languages">Translating to other languages</h2>
<p>Finally, if you’re more familiar with C# or Haskell, here are my attempted translations:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="c1">// F#</span>
<span class="nn">Seq</span><span class="p">.</span><span class="n">unfold</span> <span class="o">:</span> <span class="o">(</span><span class="k">&#39;</span><span class="n">State</span> <span class="o">-&gt;</span> <span class="o">(</span><span class="k">&#39;</span><span class="n">T</span> <span class="o">*</span> <span class="k">&#39;</span><span class="n">State</span><span class="o">)</span> <span class="n">option</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="k">&#39;</span><span class="n">State</span> <span class="o">-&gt;</span> <span class="n">seq</span><span class="o">&lt;</span><span class="k">&#39;</span><span class="n">T</span><span class="o">&gt;</span>

<span class="o">--</span> <span class="n">Haskell</span>
<span class="n">unfold</span> <span class="o">::</span> <span class="o">(</span><span class="n">s</span> <span class="o">-&gt;</span> <span class="n">Maybe</span> <span class="o">(</span><span class="n">t</span><span class="o">,</span><span class="n">s</span><span class="o">))</span> <span class="o">-&gt;</span> <span class="n">s</span> <span class="o">-&gt;</span> <span class="o">[</span><span class="n">t</span><span class="o">]</span>

<span class="c1">// C# (uncurried. seq = IEnumerable)</span>
<span class="n">IEnumerable</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span> <span class="n">Unfold</span><span class="o">&lt;</span><span class="n">S</span><span class="o">,</span><span class="n">T</span><span class="o">&gt;(</span><span class="n">Func</span><span class="o">&lt;</span><span class="n">S</span><span class="o">,</span> <span class="n">Option</span><span class="o">&lt;</span><span class="n">Tuple</span><span class="o">&lt;</span><span class="n">T</span><span class="o">,</span><span class="n">S</span><span class="o">&gt;&gt;&gt;</span> <span class="n">generator</span><span class="o">,</span> <span class="n">S</span> <span class="n">initial</span><span class="o">);</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Haskell uses lowercase type names for generics (instead of <code>'</code> characters), while concrete types have uppercase names. It also uses the same syntax for tuple types as values, so <code>(1,2) :: (Int, Int)</code>. For some odd reason, Haskell uses <code>::</code> for “type of” instead of a single <code>:</code>.</p>
<p>The C# version is a bit messier due to having to use <code>Func</code> instead of a shorthand for function types, and similarly for declaring tuple types. (I’ve also uncurried the C# version otherwise we end up with nested <code>Func</code> types everywhere, and it is the more typical form for C# functions.)</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[F#: Pattern matching on field literals]]></title>
    <link href="http://davesquared.net/2015/01/fsharp-pattern-match-on-field-literals.html"/>
    <updated>2015-01-14T08:30:00+11:00</updated>
    <id>http://davesquared.net/2015/01/fsharp-pattern-match-on-field-literals</id>
    <content type="html"><![CDATA[<p>F# gave me the following error when working with some C# code:</p>
<pre><code>error FS0729: This field is not a literal and cannot be used in a pattern </code></pre>
<p>I’m not entirely sure it’s a good idea, but I managed to work around this using a <a href="http://msdn.microsoft.com/en-us/library/dd233248.aspx">partial active pattern</a>.</p>
<!-- more -->
<p>Here’s the gist of the C# code I was working with:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='csharp'><span></span><span class="k">namespace</span> <span class="nn">Workshop.SomeCSharpLib</span> <span class="p">{</span>
    <span class="k">public</span> <span class="k">class</span> <span class="nc">Thingamabobs</span> <span class="p">{</span>
        <span class="k">private</span> <span class="nf">Thingamabobs</span><span class="p">(</span><span class="kt">string</span> <span class="n">s</span><span class="p">)</span> <span class="p">{</span> <span class="p">}</span>
        <span class="c1">// ... </span>
        <span class="k">public</span> <span class="k">static</span> <span class="k">readonly</span> <span class="n">Thingamabobs</span> <span class="n">Foo</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Thingamabobs</span><span class="p">(</span><span class="s">&quot;foo&quot;</span><span class="p">);</span>
        <span class="k">public</span> <span class="k">static</span> <span class="k">readonly</span> <span class="n">Thingamabobs</span> <span class="n">Bar</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Thingamabobs</span><span class="p">(</span><span class="s">&quot;bar&quot;</span><span class="p">);</span>
        <span class="k">public</span> <span class="k">static</span> <span class="k">readonly</span> <span class="n">Thingamabobs</span> <span class="n">Clunk</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Thingamabobs</span><span class="p">(</span><span class="s">&quot;clunk&quot;</span><span class="p">);</span>
        <span class="k">public</span> <span class="k">static</span> <span class="k">readonly</span> <span class="n">Thingamabobs</span> <span class="n">Zap</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Thingamabobs</span><span class="p">(</span><span class="s">&quot;zap&quot;</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p><code>Thingamabobs</code> represent a sort of enum with an associated value - the kind of thing we’d typically use a <a href="http://fsharpforfunandprofit.com/posts/discriminated-unions/">discriminated union</a> for in F#.</p>
<p>Trying to convert this to my own type using pattern matching resulted in the FS0729 error:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">type</span> <span class="nc">Things</span> <span class="o">=</span> <span class="n">Foo</span> <span class="o">|</span> <span class="n">Bar</span> <span class="o">|</span> <span class="n">Clunk</span> <span class="o">|</span> <span class="n">Zap</span>

<span class="k">let</span> <span class="nv">convertThingamabob</span> <span class="o">=</span>
    <span class="k">function</span>
    <span class="o">|</span> <span class="nn">Thingamabobs</span><span class="p">.</span><span class="n">Foo</span>   <span class="o">-&gt;</span> <span class="n">Some</span> <span class="n">Foo</span> <span class="c1">// *</span>
    <span class="o">|</span> <span class="nn">Thingamabobs</span><span class="p">.</span><span class="n">Bar</span>   <span class="o">-&gt;</span> <span class="n">Some</span> <span class="n">Bar</span>
    <span class="o">|</span> <span class="nn">Thingamabobs</span><span class="p">.</span><span class="n">Clunk</span> <span class="o">-&gt;</span> <span class="n">Some</span> <span class="n">Clunk</span>
    <span class="o">|</span> <span class="nn">Thingamabobs</span><span class="p">.</span><span class="n">Zap</span>   <span class="o">-&gt;</span> <span class="n">Some</span> <span class="n">Zap</span>
    <span class="o">|</span> <span class="o">_</span>                  <span class="o">-&gt;</span> <span class="n">None</span>

    <span class="c1">// * error FS0729: This field is not a literal and cannot be used in a pattern </span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>I couldn’t find much information on this error, but I gather I need to explicitly compare the argument to the field value using <code>if ... else if ... else</code>, something like:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span>   <span class="k">fun</span> <span class="n">x</span> <span class="o">-&gt;</span> <span class="k">if</span> <span class="n">x</span> <span class="o">=</span> <span class="nn">Thingamabobs</span><span class="p">.</span><span class="n">Foo</span> <span class="k">then</span> <span class="n">Some</span> <span class="n">Foo</span>
            <span class="k">else</span> <span class="k">if</span> <span class="n">x</span> <span class="o">=</span> <span class="o">...</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>I think it looks neater as a pattern match, so worked around this using a partial active pattern to do the comparison:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="c1">// Partial active pattern. Match if field equals value.</span>
<span class="k">let</span> <span class="o">(|</span><span class="n">Field</span><span class="o">|_|)</span> <span class="n">field</span> <span class="n">x</span> <span class="o">=</span> <span class="k">if</span> <span class="n">field</span> <span class="o">=</span> <span class="n">x</span> <span class="k">then</span> <span class="n">Some</span> <span class="bp">()</span> <span class="k">else</span> <span class="n">None</span>

<span class="k">type</span> <span class="nc">Things</span> <span class="o">=</span> <span class="n">Foo</span> <span class="o">|</span> <span class="n">Bar</span> <span class="o">|</span> <span class="n">Clunk</span> <span class="o">|</span> <span class="n">Zap</span>

<span class="k">let</span> <span class="nv">convertThingamabob</span> <span class="o">=</span>
    <span class="k">function</span>
    <span class="o">|</span> <span class="n">Field</span> <span class="nn">Thingamabobs</span><span class="p">.</span><span class="n">Foo</span>   <span class="o">-&gt;</span> <span class="n">Some</span> <span class="n">Foo</span>
    <span class="o">|</span> <span class="n">Field</span> <span class="nn">Thingamabobs</span><span class="p">.</span><span class="n">Bar</span>   <span class="o">-&gt;</span> <span class="n">Some</span> <span class="n">Bar</span>
    <span class="o">|</span> <span class="n">Field</span> <span class="nn">Thingamabobs</span><span class="p">.</span><span class="n">Clunk</span> <span class="o">-&gt;</span> <span class="n">Some</span> <span class="n">Clunk</span>
    <span class="o">|</span> <span class="n">Field</span> <span class="nn">Thingamabobs</span><span class="p">.</span><span class="n">Zap</span>   <span class="o">-&gt;</span> <span class="n">Some</span> <span class="n">Zap</span>
    <span class="o">|</span> <span class="o">_</span>                        <span class="o">-&gt;</span> <span class="n">None</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>I’m not sure if there are any drawbacks to this approach, so if you can think of any please let me know.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[D3 newbie updates a bar chart]]></title>
    <link href="http://davesquared.net/2014/09/d3-update-a-bar-chart.html"/>
    <updated>2014-09-01T00:01:00+10:00</updated>
    <id>http://davesquared.net/2014/09/d3-update-a-bar-chart</id>
    <content type="html"><![CDATA[<p>I’ve been trying to learn <a href="http://d3js.org/">D3.js</a> via Mike Bostock’s excellent <a href="http://bost.ocks.org/mike/bar/">“Let’s make a bar chart”</a> tutorial series. This post is my attempt to extend that example to handle data updates.</p>
<!-- more -->
<h2 id="starting-point">Starting point</h2>
<p><a href="http://bost.ocks.org/mike/bar/3/">Part 3</a> of the tutorial ends with a bar chart that shows the relative frequency of letters used in the English language.</p>
<p>The creation of each bar per datum is handled by this code:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='javascript'><span></span><span class="nx">chart</span><span class="p">.</span><span class="nx">selectAll</span><span class="p">(</span><span class="s2">&quot;.bar&quot;</span><span class="p">)</span>
      <span class="p">.</span><span class="nx">data</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span>
  <span class="p">.</span><span class="nx">enter</span><span class="p">().</span><span class="nx">append</span><span class="p">(</span><span class="s2">&quot;rect&quot;</span><span class="p">)</span>
    <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;class&quot;</span><span class="p">,</span> <span class="s2">&quot;bar&quot;</span><span class="p">)</span>
    <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;x&quot;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">d</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">x</span><span class="p">(</span><span class="nx">d</span><span class="p">.</span><span class="nx">name</span><span class="p">);</span> <span class="p">})</span>
    <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;y&quot;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">d</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">y</span><span class="p">(</span><span class="nx">d</span><span class="p">.</span><span class="nx">value</span><span class="p">);</span> <span class="p">})</span>
    <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;height&quot;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">d</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">height</span> <span class="o">-</span> <span class="nx">y</span><span class="p">(</span><span class="nx">d</span><span class="p">.</span><span class="nx">value</span><span class="p">);</span> <span class="p">})</span>
    <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;width&quot;</span><span class="p">,</span> <span class="nx">x</span><span class="p">.</span><span class="nx">rangeBand</span><span class="p">());</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>This says we’re dealing with chart elements of the CSS class <code>.bar</code> for each datum. The <code>.enter()</code> call tells D3 we want to perform the operations that follow for any new data (<a href="http://bost.ocks.org/mike/join/">data that has entered source</a>). We can also use <code>.exit()</code> for data that is no longer in the source. If we want to handle updated data we can add properties directly (outside of <code>enter()</code> / <code>exit()</code>).</p>
<h2 id="adjusting-the-bars-for-new-data">Adjusting the bars for new data</h2>
<p>To specify updates I had to change the data join so D3 knows how to differentiate added, removed and updated data. In this case we will use the <code>name</code> property, which is a letter from <code>A</code> to <code>Z</code>.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='javascript'><span></span><span class="kd">var</span> <span class="nx">bar</span> <span class="o">=</span> <span class="nx">chart</span><span class="p">.</span><span class="nx">selectAll</span><span class="p">(</span><span class="s2">&quot;.bar&quot;</span><span class="p">)</span>
        <span class="p">.</span><span class="nx">data</span><span class="p">(</span><span class="nx">data</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">d</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">d</span><span class="p">.</span><span class="nx">name</span><span class="p">;</span> <span class="p">});</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Next we’ll modify the code to specify how to handle updated and removed data, instead of just what to do on <code>enter()</code> for new data.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='javascript'><span></span><span class="c1">// new data:</span>
<span class="nx">bar</span><span class="p">.</span><span class="nx">enter</span><span class="p">().</span><span class="nx">append</span><span class="p">(</span><span class="s2">&quot;rect&quot;</span><span class="p">)</span>
   <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;class&quot;</span><span class="p">,</span> <span class="s2">&quot;bar&quot;</span><span class="p">)</span>
   <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;x&quot;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">d</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">x</span><span class="p">(</span><span class="nx">d</span><span class="p">.</span><span class="nx">name</span><span class="p">);</span> <span class="p">})</span>
   <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;y&quot;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">d</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">y</span><span class="p">(</span><span class="nx">d</span><span class="p">.</span><span class="nx">value</span><span class="p">);</span> <span class="p">})</span>
   <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;height&quot;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">d</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">height</span> <span class="o">-</span> <span class="nx">y</span><span class="p">(</span><span class="nx">d</span><span class="p">.</span><span class="nx">value</span><span class="p">);</span> <span class="p">})</span>
   <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;width&quot;</span><span class="p">,</span> <span class="nx">x</span><span class="p">.</span><span class="nx">rangeBand</span><span class="p">());</span>
<span class="c1">// removed data:</span>
<span class="nx">bar</span><span class="p">.</span><span class="nx">exit</span><span class="p">().</span><span class="nx">remove</span><span class="p">();</span>
<span class="c1">// updated data:</span>
<span class="nx">bar</span>
   <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;y&quot;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">d</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">y</span><span class="p">(</span><span class="nx">d</span><span class="p">.</span><span class="nx">value</span><span class="p">);</span> <span class="p">})</span>
   <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;height&quot;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">d</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">height</span> <span class="o">-</span> <span class="nx">y</span><span class="p">(</span><span class="nx">d</span><span class="p">.</span><span class="nx">value</span><span class="p">);</span> <span class="p">});</span>
   <span class="c1">// &quot;x&quot; and &quot;width&quot; will already be set from when the data was</span>
   <span class="c1">// first added from &quot;enter()&quot;.</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="updating-the-axes">Updating the axes</h2>
<p>This was enough to update the chart, but the y-axis would draw the new axis over the top of the previous axis, so both values would show. This <a href="http://stackoverflow.com/a/13550144/906">answer on StackOverflow</a> suggested removing the axis and redrawing it each time, which worked well.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='javascript'><span></span><span class="c1">// Remove previous y-axis:</span>
<span class="nx">chart</span><span class="p">.</span><span class="nx">select</span><span class="p">(</span><span class="s2">&quot;.y.axis&quot;</span><span class="p">).</span><span class="nx">remove</span><span class="p">();</span> <span class="c1">// &lt;&lt; this line added</span>
<span class="c1">// Existing code to draw y-axis:</span>
<span class="nx">chart</span><span class="p">.</span><span class="nx">append</span><span class="p">(</span><span class="s2">&quot;g&quot;</span><span class="p">)</span>
      <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;class&quot;</span><span class="p">,</span> <span class="s2">&quot;y axis&quot;</span><span class="p">)</span>
      <span class="p">.</span><span class="nx">call</span><span class="p">(</span><span class="nx">yAxis</span><span class="p">)</span>
  <span class="p">.</span><span class="nx">append</span><span class="p">(</span><span class="s2">&quot;text&quot;</span><span class="p">)</span>
    <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;transform&quot;</span><span class="p">,</span> <span class="s2">&quot;rotate(-90)&quot;</span><span class="p">)</span>
    <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;y&quot;</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span>
    <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;dy&quot;</span><span class="p">,</span> <span class="s2">&quot;.71em&quot;</span><span class="p">)</span>
    <span class="p">.</span><span class="nx">style</span><span class="p">(</span><span class="s2">&quot;text-anchor&quot;</span><span class="p">,</span> <span class="s2">&quot;end&quot;</span><span class="p">)</span>
    <span class="p">.</span><span class="nx">text</span><span class="p">(</span><span class="s2">&quot;Frequency&quot;</span><span class="p">);</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="basic-transition">Basic transition</h2>
<p>The next thing I wanted to try was animating changes to existing data. This turned out to be trivial thanks to D3’s <code>transition()</code> method, which I just dumped prior to the code we used to update each bar.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='javascript'><span></span><span class="nx">bar</span>
  <span class="p">.</span><span class="nx">transition</span><span class="p">().</span><span class="nx">duration</span><span class="p">(</span><span class="mi">750</span><span class="p">)</span>  <span class="c1">// &lt;&lt;&lt; added this</span>
    <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;y&quot;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">d</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">y</span><span class="p">(</span><span class="nx">d</span><span class="p">.</span><span class="nx">value</span><span class="p">);</span> <span class="p">})</span>
    <span class="p">.</span><span class="nx">attr</span><span class="p">(</span><span class="s2">&quot;height&quot;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">d</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">height</span> <span class="o">-</span> <span class="nx">y</span><span class="p">(</span><span class="nx">d</span><span class="p">.</span><span class="nx">value</span><span class="p">);</span> <span class="p">});</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>And that’s it!</p>
<h2 id="end-result">End result</h2>
<p>Here’s an example of the update in action. Use the radio buttons to alternate between the chart showing frequencies of letters in English and the frequencies of letters used in the source for this post.</p>
<form>
<input type="radio" name="inputsrc" id="defaultInput" value="default" checked/><label for="defaultInput">English</label> <input type="radio" name="inputsrc" id="thisPostInput" value="post"/><label for="thisPostInput">This post</label>
</form>
<svg id="d3newbie-chart">
</svg>
<style>
.bar {
  fill: steelblue;
}
.bar:hover {
    fill: brown;
}
.axis text {
  font: 10px sans-serif;
}
.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}
</style>
<script src="http://davesquared.net/javascripts/d3.min.js" charset="utf8=-8"></script>
<script>
var outerWidth = 600, outerHeight = 400;
var margin = { top: 20, right: 30, bottom: 30, left: 40 },
    width  = outerWidth - margin.left - margin.right,
    height = outerHeight - margin.top - margin.bottom;

var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split('');

var x = d3.scale.ordinal()
          .rangeRoundBands([0, width], .1)
          .domain(chars);
var y = d3.scale.linear()
          .range([height, 0]);

var xAxis = d3.svg.axis()
              .scale(x)
              .orient("bottom");
var yAxis = d3.svg.axis()
              .scale(y)
              .orient("left")
              .ticks(10, "%");
var chart = d3.select("#d3newbie-chart")
              .attr("width", outerWidth)
              .attr("height", outerHeight)
            .append("g")
              .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

// x-axis
chart
    .append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")") 
      .call(xAxis);

function type(d) {
    d.value = +d.value;
    return d;
}
function updateDefault() {
    d3.tsv("/downloads/data-chars.tsv", type, update);
}
function updateThisPost() {
    d3.text(".", function(err, data) { update(err, freqs(data)); });
}
function update(err, data) {
    y.domain([0, d3.max(data, function(d) { return d.value; })]);
    // y-axis
    chart.select(".y.axis").remove();
    chart.append("g")
          .attr("class", "y axis")
          .call(yAxis)
      .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Frequency");

    var bar = chart.selectAll(".bar")
            .data(data, function(d) { return d.name; });

    // new data:
    bar.enter().append("rect")
       .attr("class", "bar")
       .attr("x", function(d) { return x(d.name); })
       .attr("y", function(d) { return y(d.value); })
       .attr("height", function(d) { return height - y(d.value); })
       .attr("width", x.rangeBand());
    // removed data:
    bar.exit().remove();
    // updated data:
    bar
       .transition()
       .duration(750)
           .attr("y", function(d) { return y(d.value); })
           .attr("height", function(d) { return height - y(d.value); });
};

document.getElementById("defaultInput")
        .onclick = updateDefault;
document.getElementById("thisPostInput")
        .onclick = updateThisPost;
updateDefault();

function freqs(str) {
    var s = str.toUpperCase()
    var n = s.length
    var x = {}
    for (var i = 0; i<chars.length; i++) {
        x[chars[i]] = 0;
    }
    for (var i=0; i<s.length; i++) {
        if (/[A-Z]/.test(s[i])) {
            x[s[i]]++;
        }
    }
    var f = []
    for (var c in x) {
        f.push( { name: c, value: x[c]/=n });
    }
    return f;
}
</script>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A simple circuit, an Arduino, and Haskell]]></title>
    <link href="http://davesquared.net/2014/08/simple-nodebot-haskell.html"/>
    <updated>2014-08-12T23:45:00+10:00</updated>
    <id>http://davesquared.net/2014/08/simple-nodebot-haskell</id>
    <content type="html"><![CDATA[<p>I recently had loads of fun attending a <a href="http://nodebots.io/">Nodebots AU</a> event in Sydney. (Thanks a lot to <a href="https://twitter.com/DamonOehlman">Damon</a> and <a href="https://twitter.com/ajfisher">Andrew</a> for organising, and <a href="https://www.nicta.com.au/">NICTA</a> for the venue!) I got to muck around with some simple circuits and drive them with Javascript. Towards the end of the day I was running out of time and creativity to do anything fancy, so I decided to see if I could get one of the circuits working with Haskell.</p>
<!-- more -->
<h2 id="nodebot-prerequisites">Nodebot prerequisites</h2>
<p>I got a <a href="http://node-ardx.org/">Node ARDX kit</a> at the event, and followed the <a href="https://github.com/nodebotsau/nbdau/blob/master/setup.md">Nodebots AU setup guide</a> to get all the software bits and pieces.</p>
<p>For Haskelling, I used my <a href="http://www.davesquared.net/2014/05/platformless-haskell.html">existing Haskell installation</a>, then created a new <code>cabal sandbox</code> and installed the <a href="http://hackage.haskell.org/package/hArduino">hArduino</a> package (v0.9) into it.</p>
<h2 id="a-simple-circuit">A simple circuit</h2>
<p>Here’s a simple circuit that includes a potentiometer and a bunch of LEDs. The idea is that as someone turns up the potentiometer, the number of LEDs switched on increases accordingly. (Yes, this may seem somewhat unimpressive, but as a complete newbie who managed to do this without blowing anything up, I’m calling it a win! :))</p>
<div class="note">
<strong>DISCLAIMER:</strong> While I somehow managed to avoid blowing anything up while attempting this, I don’t know what I’m doing and so can’t guarantee that this won’t destroy anything you value. Use at your own risk! :)
</div>
<figure>
<img src="http://davesquared.net/images/2014/potlights.png" alt="Arduino Uno with potentiometer connected to A5, and six LEDs (with 330Ω resistors) connected to pins 2-7. Image created with the open-source Fritzing app. [View full size]" /><figcaption>Arduino Uno with potentiometer connected to A5, and six LEDs (with 330Ω resistors) connected to pins 2-7. Image created with the open-source <a href="http://fritzing.org/">Fritzing</a> app. <a href="http://davesquared.net/images/2014/potlights-orig.png">[View full size]</a></figcaption>
</figure>
<h2 id="haskellbot">Haskellbot</h2>
<p>So now I’m in my cabal sandbox and it’s time to write some Haskell. Here’s the main outline of the program (with some explanatory comments added).</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='haskell'><span></span><span class="kr">import</span> <span class="nn">Control.Applicative</span>
<span class="kr">import</span> <span class="nn">Control.Monad</span> <span class="p">(</span><span class="nf">when</span><span class="p">)</span>
<span class="kr">import</span> <span class="nn">Data.Foldable</span> <span class="p">(</span><span class="nf">for_</span><span class="p">)</span>
<span class="kr">import</span> <span class="nn">System.Hardware.Arduino</span>

<span class="nf">leds</span> <span class="ow">=</span> <span class="n">digital</span> <span class="o">&lt;$&gt;</span> <span class="p">[</span><span class="mi">2</span><span class="o">..</span><span class="mi">7</span><span class="p">]</span>             <span class="c1">-- leds on digital pins 2 to 7</span>
<span class="nf">pot</span> <span class="ow">=</span> <span class="n">analog</span> <span class="mi">5</span>                        <span class="c1">-- potentiometer on A5 </span>
<span class="nf">setPin</span> <span class="ow">=</span> <span class="n">flip</span> <span class="n">setPinMode</span>

<span class="nf">main</span> <span class="ow">::</span> <span class="kt">IO</span><span class="nb">()</span>
<span class="nf">main</span> <span class="ow">=</span>
  <span class="n">withArduino</span> <span class="kt">False</span> <span class="s">&quot;/dev/cu.usbmodemfa131&quot;</span> <span class="o">$</span> <span class="kr">do</span>
      <span class="n">for_</span> <span class="n">leds</span> <span class="p">(</span><span class="n">setPin</span> <span class="kt">OUTPUT</span><span class="p">)</span>       <span class="c1">-- set each led pin as an output</span>
      <span class="n">setPin</span> <span class="kt">ANALOG</span> <span class="n">pot</span>               <span class="c1">-- set potentiometer&#39;s pin as analog</span>
      <span class="n">run</span> <span class="mi">0</span>                           <span class="c1">-- run with initial pot. value of 0</span>
  <span class="kr">where</span>
    <span class="n">run</span> <span class="n">cur</span> <span class="ow">=</span> <span class="kr">do</span>
      <span class="n">new</span> <span class="ow">&lt;-</span> <span class="n">analogRead</span> <span class="n">pot</span>           <span class="c1">-- read potentiometer&#39;s value</span>
      <span class="n">when</span> <span class="p">(</span><span class="n">new</span> <span class="o">/=</span> <span class="n">cur</span><span class="p">)</span> <span class="o">$</span> <span class="n">updateLeds</span> <span class="n">new</span>  <span class="c1">-- if it has changed from current,</span>
                                          <span class="c1">-- update the LEDs based on the new value</span>
      <span class="n">delay</span> <span class="mi">250</span>                       <span class="c1">-- wait for a bit</span>
      <span class="n">run</span> <span class="n">new</span>                         <span class="c1">-- continue main run loop</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>After the initialisation stuff, the main bit of the program is the run loop, which polls the potentiometer and updates the LEDs whenever the value changes.</p>
<p>The <code>updateLeds</code> and related code looks like this:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='haskell'><span></span><span class="nf">updateLeds</span> <span class="ow">::</span> <span class="kt">Int</span> <span class="ow">-&gt;</span> <span class="kt">Arduino</span> <span class="nb">()</span>
<span class="nf">updateLeds</span> <span class="n">potVal</span> <span class="ow">=</span>
    <span class="n">for_</span> <span class="p">(</span><span class="n">zip</span> <span class="n">leds</span> <span class="p">[</span><span class="mi">1</span><span class="o">..</span><span class="p">])</span> <span class="o">$</span>
        <span class="nf">\</span><span class="p">(</span><span class="n">led</span><span class="p">,</span> <span class="n">ledNum</span><span class="p">)</span> <span class="ow">-&gt;</span> <span class="n">digitalWrite</span> <span class="n">led</span> <span class="p">(</span><span class="n">ledNum</span> <span class="o">&lt;=</span> <span class="n">maxLedNum</span><span class="p">)</span>
    <span class="kr">where</span>
        <span class="n">maxLedNum</span> <span class="ow">=</span> <span class="n">numLedsOn</span> <span class="n">potVal</span>

<span class="nf">numLedsOn</span> <span class="ow">::</span> <span class="kt">Int</span> <span class="ow">-&gt;</span> <span class="kt">Int</span>
<span class="nf">numLedsOn</span> <span class="n">potVal</span> <span class="ow">=</span> <span class="n">numLeds</span> <span class="o">*</span> <span class="n">potVal</span> <span class="p">`</span><span class="n">div</span><span class="p">`</span> <span class="n">maxPotVal</span>
    <span class="kr">where</span>
        <span class="n">maxPotVal</span> <span class="ow">=</span> <span class="mi">1023</span>
        <span class="n">numLeds</span>   <span class="ow">=</span> <span class="n">length</span> <span class="n">leds</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>The <code>updateLeds</code> function takes the potentiometer value and works out how many LEDs it needs to turn on based on the <code>numLedsOn</code> function. It then loops through each numbered LED and turns it on or off based on whether the <code>ledNum &lt;= maxLedNum</code> we need to switch on.<a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a></p>
<p><code>numLedsOn</code> doesn’t need to be a separate function like this, but I found it helped to be able to test my arithmetic independently of hardware. :) (We could also get away without specifying any types, but I find doing so makes it easier for me to read.)</p>
<h2 id="running-this-er-masterpiece">Running this… er… ‘masterpiece’</h2>
<p>Rather than setup a build, I just ran <code>cabal repl</code> from my sandbox to get a GHCi with the <code>hArduino</code> package accessible, then loaded and ran the code:</p>
<pre><code>ghci&gt; :load lights.hs
ghci&gt; main</code></pre>
<p>Now I could finally fulfill my life-long dream of adjusting LEDs using a twirly dial! Hooray! :)</p>
<section class="footnotes">
<hr />
<ol>
<li id="fn1"><p>The <code>updateLeds</code> loop is a bit neater in applicative form, but assumes familiarity with the operators: <code>for_ (zip leds [1..]) $ digitalWrite &lt;$&gt; fst &lt;*&gt; ((&lt;= maxLedNum) . snd)</code><a href="#fnref1" class="footnote-back">↩</a></p></li>
</ol>
</section>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Reasoning with more than evaluation]]></title>
    <link href="http://davesquared.net/2014/07/reasoning-with-more-than-evaluation.html"/>
    <updated>2014-07-24T22:30:00+10:00</updated>
    <id>http://davesquared.net/2014/07/reasoning-with-more-than-evaluation</id>
    <content type="html"><![CDATA[<!-- more -->
<p><a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-12.html#%_thm_1.41">Exercise 1.41 of SICP</a> asks us to work out what the following expression will evaluate to, given the definition of <code>double</code>:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='scheme'><span></span><span class="p">(</span><span class="k">define </span><span class="p">(</span><span class="nf">double</span> <span class="nv">f</span><span class="p">)</span>
  <span class="p">(</span><span class="k">lambda </span><span class="p">(</span><span class="nf">x</span><span class="p">)</span> <span class="p">(</span><span class="nf">f</span> <span class="p">(</span><span class="nf">f</span> <span class="nv">x</span><span class="p">))))</span>

<span class="p">(((</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="nv">double</span><span class="p">))</span> <span class="nv">inc</span><span class="p">)</span> <span class="mi">5</span><span class="p">)</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="direct-substitution">Direct substitution</h2>
<p>If this expression had side-effects, we’d need to <a href="http://www.davesquared.net/2013/03/reasoning-and-mutability.html">understand the evaluation order and keep track of state changes with each evaluation step</a>. Because this is a pure function, we can <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-10.html#%_sec_1.1.5">substitute the definitions</a> of each sub-expression, and in any order we like. I found these substitutions quite tricky though, because with each evaluation of <code>double</code> I had to take into account its argument. I ended up with something like this:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='scheme'><span></span><span class="nv">Aim:</span> <span class="nv">evaluate</span> <span class="p">(((</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="nv">double</span><span class="p">))</span> <span class="nv">inc</span><span class="p">)</span> <span class="mi">5</span><span class="p">)</span>

<span class="p">(</span><span class="nf">double</span> <span class="nv">f</span><span class="p">)</span>
<span class="nv">=</span> <span class="k">lambda </span><span class="p">(</span><span class="nf">x</span><span class="p">)</span> <span class="p">(</span><span class="nf">f</span> <span class="p">(</span><span class="nf">f</span> <span class="nv">x</span><span class="p">))</span>

<span class="p">(</span><span class="nf">double</span> <span class="nv">double</span><span class="p">)</span>
<span class="nv">=</span> <span class="k">lambda </span><span class="p">(</span><span class="nf">x</span><span class="p">)</span> <span class="p">(</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="nv">x</span><span class="p">))</span>

<span class="p">(</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="nv">double</span><span class="p">))</span>
<span class="nv">=</span> <span class="k">lambda </span><span class="p">(</span><span class="nf">x</span><span class="p">)</span> <span class="p">(</span> <span class="p">(</span><span class="nf">double</span> <span class="nv">double</span><span class="p">)</span> <span class="p">((</span><span class="nf">double</span> <span class="nv">double</span><span class="p">)</span> <span class="nv">x</span><span class="p">))</span>
<span class="nv">=</span> <span class="k">lambda </span><span class="p">(</span><span class="nf">x</span><span class="p">)</span> <span class="p">(</span> <span class="p">(</span><span class="k">lambda </span><span class="p">(</span><span class="nf">x</span><span class="o">&#39;</span><span class="p">)</span> <span class="p">(</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="nv">x</span><span class="o">&#39;</span><span class="p">)))</span>
                 <span class="p">((</span><span class="k">lambda </span><span class="p">(</span><span class="nf">x</span><span class="o">&#39;</span><span class="p">)</span> <span class="p">(</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="nv">x</span><span class="o">&#39;</span><span class="p">)))</span> <span class="nv">x</span><span class="p">)</span> <span class="p">)</span>
<span class="nv">=</span> <span class="k">lambda </span><span class="p">(</span><span class="nf">x</span><span class="p">)</span> <span class="p">(</span> <span class="p">(</span><span class="k">lambda </span><span class="p">(</span><span class="nf">x</span><span class="o">&#39;</span><span class="p">)</span> <span class="p">(</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="nv">x</span><span class="o">&#39;</span><span class="p">)))</span>
                 <span class="p">((</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="nv">x</span><span class="p">)))</span> <span class="p">)</span>
<span class="nv">=</span> <span class="k">lambda </span><span class="p">(</span><span class="nf">x</span><span class="p">)</span> <span class="p">(</span> <span class="nv">double</span> <span class="p">(</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="nv">x</span><span class="p">)))</span> <span class="p">)</span>

<span class="p">((</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="nv">double</span><span class="p">))</span> <span class="nv">inc</span><span class="p">)</span>
<span class="nv">=</span> <span class="p">(</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="nv">inc</span><span class="p">))))</span>
<span class="nv">=</span> <span class="p">(</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="p">(</span><span class="k">lambda </span><span class="p">(</span><span class="nf">x</span><span class="p">)</span> <span class="p">(</span><span class="nf">inc</span> <span class="p">(</span><span class="nf">inc</span> <span class="nv">x</span><span class="p">))))))</span>
<span class="nv">=</span> <span class="p">(</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="p">(</span><span class="k">lambda </span><span class="p">(</span><span class="nf">x</span><span class="p">)</span> <span class="p">(</span><span class="nf">inc</span> <span class="p">(</span><span class="nf">inc</span> <span class="p">(</span><span class="nf">inc</span> <span class="p">(</span><span class="nf">inc</span> <span class="nv">x</span><span class="p">)))))))</span>
<span class="nv">=</span> <span class="p">(</span><span class="nf">double</span> <span class="p">(</span><span class="k">lambda </span><span class="p">(</span><span class="nf">x</span><span class="p">)</span> <span class="p">(</span><span class="nf">inc</span> <span class="p">(</span><span class="nf">inc</span> <span class="p">(</span><span class="nf">inc</span> <span class="p">(</span><span class="nf">inc</span> <span class="p">(</span><span class="nf">inc</span> <span class="p">(</span><span class="nf">inc</span> <span class="p">(</span><span class="nf">inc</span> <span class="p">(</span><span class="nf">inc</span> <span class="nv">x</span><span class="p">))))))))))</span>
<span class="nv">=</span> <span class="p">(</span><span class="k">lambda </span><span class="p">(</span><span class="nf">x</span><span class="p">)</span> <span class="p">(</span> <span class="o">...</span> <span class="mi">16</span> <span class="nv">incs</span> <span class="o">...</span> <span class="nv">x</span><span class="p">))</span>

<span class="p">(((</span><span class="nf">double</span> <span class="p">(</span><span class="nf">double</span> <span class="nv">double</span><span class="p">))</span> <span class="nv">inc</span><span class="p">)</span> <span class="mi">5</span><span class="p">)</span>
<span class="nv">=</span> <span class="p">(</span><span class="o">...</span> <span class="mi">16</span> <span class="nv">incs</span> <span class="o">...</span> <span class="mi">5</span><span class="p">)</span>
<span class="nv">=</span> <span class="mi">16</span><span class="nv">+5</span>
<span class="nv">=</span> <span class="mi">21</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>I found this quite hard to follow. I had to use additional intermediary steps (not shown above) to evaluate expressions like <code>(double (lambda (x) (inc (inc x))))</code>.</p>
<h2 id="using-other-equalities">Using other equalities</h2>
<p>Instead of direct substitution we can transform the expression into equivalent terms we find easier to reason about, such as those with mathematical properties we can apply to simplify the expression. We still use substitution, but with other equalities instead of replacing a term’s name with its definition.</p>
<p>For this example, I found it easier to think of <code>double</code> in terms of function composition.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='haskell'><span></span><span class="nf">f</span> <span class="o">.</span> <span class="n">g</span>    <span class="ow">=</span> <span class="nf">\</span><span class="n">x</span> <span class="ow">-&gt;</span> <span class="n">f</span> <span class="p">(</span><span class="n">g</span> <span class="n">x</span><span class="p">)</span>

<span class="nf">double</span> <span class="n">f</span> <span class="ow">=</span> <span class="nf">\</span><span class="n">x</span> <span class="ow">-&gt;</span> <span class="n">f</span> <span class="p">(</span><span class="n">f</span> <span class="n">x</span><span class="p">)</span>
         <span class="ow">=</span> <span class="n">f</span> <span class="o">.</span> <span class="n">f</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Function composition is associative (which we can convince ourselves of using equalities<a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a>). I find this made it easier to reduce the nested <code>double</code> calls.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='haskell'><span></span><span class="nf">double</span> <span class="n">double</span>
  <span class="ow">=</span> <span class="n">double</span> <span class="o">.</span> <span class="n">double</span>
<span class="nf">double</span> <span class="p">(</span><span class="n">double</span> <span class="n">double</span><span class="p">)</span>
  <span class="ow">=</span> <span class="p">(</span><span class="n">double</span> <span class="o">.</span> <span class="n">double</span><span class="p">)</span> <span class="o">.</span> <span class="p">(</span><span class="n">double</span> <span class="o">.</span> <span class="n">double</span><span class="p">)</span>
  <span class="ow">=</span> <span class="n">double</span> <span class="o">.</span> <span class="n">double</span> <span class="o">.</span> <span class="n">double</span> <span class="o">.</span> <span class="n">double</span>           <span class="c1">-- by associativity of composition</span>
<span class="p">(</span><span class="n">double</span> <span class="p">(</span><span class="n">double</span> <span class="n">double</span><span class="p">))</span> <span class="n">inc</span>
  <span class="ow">=</span> <span class="p">(</span><span class="n">double</span> <span class="o">.</span> <span class="n">double</span> <span class="o">.</span> <span class="n">double</span> <span class="o">.</span> <span class="n">double</span><span class="p">)</span> <span class="n">inc</span>
  <span class="ow">=</span> <span class="p">(</span><span class="n">double</span> <span class="o">.</span> <span class="n">double</span> <span class="o">.</span> <span class="n">double</span><span class="p">)</span> <span class="p">(</span><span class="n">double</span> <span class="n">inc</span><span class="p">)</span>     <span class="c1">-- by defn of f . g</span>
  <span class="ow">=</span> <span class="p">(</span><span class="n">double</span> <span class="o">.</span> <span class="n">double</span> <span class="o">.</span> <span class="n">double</span><span class="p">)</span> <span class="p">(</span><span class="n">inc</span> <span class="o">.</span> <span class="n">inc</span><span class="p">)</span>      <span class="c1">-- by: double f = f . f</span>
  <span class="ow">=</span> <span class="p">(</span><span class="n">double</span> <span class="o">.</span> <span class="n">double</span><span class="p">)</span> <span class="p">(</span><span class="n">double</span> <span class="p">(</span><span class="n">inc</span> <span class="o">.</span> <span class="n">inc</span><span class="p">))</span>
  <span class="ow">=</span> <span class="p">(</span><span class="n">double</span> <span class="o">.</span> <span class="n">double</span><span class="p">)</span> <span class="p">(</span><span class="n">inc</span> <span class="o">.</span> <span class="n">inc</span> <span class="o">.</span> <span class="n">inc</span> <span class="o">.</span> <span class="n">inc</span><span class="p">)</span>
  <span class="ow">=</span> <span class="n">double</span> <span class="p">(</span><span class="n">inc</span> <span class="o">.</span> <span class="n">inc</span> <span class="o">.</span> <span class="n">inc</span> <span class="o">.</span> <span class="n">inc</span> <span class="o">.</span> <span class="n">inc</span> <span class="o">.</span> <span class="n">inc</span> <span class="o">.</span> <span class="n">inc</span> <span class="o">.</span> <span class="n">inc</span><span class="p">)</span>
  <span class="ow">=</span> <span class="p">(</span> <span class="o">...</span> <span class="mi">16</span> <span class="n">incs</span> <span class="o">...</span><span class="p">)</span>
  <span class="ow">=</span> <span class="p">(</span><span class="mi">16</span><span class="o">+</span><span class="p">)</span>                                       <span class="c1">-- \x -&gt; inc (inc x) = (2+)</span>

<span class="kt">So</span> <span class="p">(((</span><span class="n">double</span> <span class="p">(</span><span class="n">double</span> <span class="n">double</span><span class="p">))</span> <span class="n">inc</span><span class="p">)</span> <span class="mi">5</span><span class="p">)</span> <span class="ow">=</span> <span class="p">(</span><span class="mi">16</span><span class="o">+</span><span class="p">)</span> <span class="mi">5</span> <span class="ow">=</span> <span class="mi">21</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Composition lets us deal with functions as values without having to substitute in for their arguments at each step. The fact composition is associative hides unimportant details, such as not having to worry about the order of composition in expressions like <code>(double . double) . (double . double)</code>. I found each step made more sense to me, and I had more confidence in my answer.</p>
<p>I imagine different people will find different forms easier than others, but the point is we can choose whichever transformations we like to get the expression into an equivalent form we can work with more easily.</p>
<h2 id="conclusion">Conclusion</h2>
<p>For a while now I’ve appreciated that pure functions mean we can <a href="http://www.davesquared.net/2013/03/reasoning-and-mutability.html">more easily use substitution to understand code</a>, but it wasn’t until this exercise that I’ve finally started to get a vague idea of what <a href="http://www.haskellforall.com/2013/12/equational-reasoning.html">equational reasoning</a> means. It is more than just substitution – it is being able to use all sorts of transformations and properties to understand our code. I don’t think this example really showcases this idea, but I did feel like it was my first glimpse into a different, powerful way of understanding code.</p>
<section class="footnotes">
<hr />
<ol>
<li id="fn1"><p>My attempt at showing function composition is associative:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb1-1" title="1"><span class="co">-- Associativity of composition</span></a>
<a class="sourceLine" id="cb1-2" title="2">f <span class="fu">.</span> g <span class="fu">=</span> \x <span class="ot">-&gt;</span> f (g x)</a>
<a class="sourceLine" id="cb1-3" title="3"></a>
<a class="sourceLine" id="cb1-4" title="4">a <span class="fu">.</span> (b <span class="fu">.</span> c) <span class="fu">=</span> \x <span class="ot">-&gt;</span> a ( (b<span class="fu">.</span>c) x)</a>
<a class="sourceLine" id="cb1-5" title="5">            <span class="fu">=</span> \x <span class="ot">-&gt;</span> a ( (\x&#39; <span class="ot">-&gt;</span> b (c x&#39;)) x)</a>
<a class="sourceLine" id="cb1-6" title="6">            <span class="fu">=</span> \x <span class="ot">-&gt;</span> a ( b (c x) )</a>
<a class="sourceLine" id="cb1-7" title="7">            <span class="fu">=</span> \x <span class="ot">-&gt;</span> (a <span class="fu">.</span> b) (c x)</a>
<a class="sourceLine" id="cb1-8" title="8">            <span class="fu">=</span> \x <span class="ot">-&gt;</span> ((a <span class="fu">.</span> b) <span class="fu">.</span> c) x</a>
<a class="sourceLine" id="cb1-9" title="9">            <span class="fu">=</span> (a <span class="fu">.</span> b) <span class="fu">.</span> c</a></code></pre></div>
<a href="#fnref1" class="footnote-back">↩</a></li>
</ol>
</section>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[F# assertion libraries]]></title>
    <link href="http://davesquared.net/2014/07/fsharp-assertion-libraries.html"/>
    <updated>2014-07-22T21:30:00+10:00</updated>
    <id>http://davesquared.net/2014/07/fsharp-assertion-libraries</id>
    <content type="html"><![CDATA[<p>There are a few different libraries that provide test assertions for F#. I went through a couple today and tried a trivial example in each.</p>
<!-- more -->
<p>I’m using xUnit for these examples, but all of this should apply to NUnit (and other test runners) too. I’ve put all the code in a <a href="https://gist.github.com/dtchepak/62fe3c689700180777c2">Sample.fs gist</a> if you want to see it all in one place.</p>
<h2 id="xunit-assertions">xUnit assertions</h2>
<p>I’ve written about <a href="http://www.davesquared.net/2013/03/hello-world-testing-in-fsharp.html">getting started with NUnit in F#</a> before. We can also use <a href="https://github.com/xunit/xunit">xUnit</a> and its built in assertions.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">open</span> <span class="nn">Xunit</span>

<span class="o">[&lt;</span><span class="n">Fact</span><span class="o">&gt;]</span>
<span class="k">let</span> <span class="n">``map (+1) over list using Xunit``</span> <span class="bp">()</span> <span class="o">=</span>
    <span class="k">let</span> <span class="nv">result</span> <span class="o">=</span> <span class="nn">List</span><span class="p">.</span><span class="n">map</span> <span class="n">incr</span> <span class="o">[</span><span class="mi">1</span><span class="o">;</span><span class="mi">2</span><span class="o">;</span><span class="mi">3</span><span class="o">]</span>
    <span class="nn">Assert</span><span class="p">.</span><span class="n">Equal</span><span class="o">&lt;</span><span class="n">int</span> <span class="kt">list</span><span class="o">&gt;([</span><span class="mi">2</span><span class="o">;</span><span class="mi">3</span><span class="o">;</span><span class="mi">4</span><span class="o">],</span> <span class="n">result</span><span class="o">)</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>I needed to specify the <code>int list</code> type explicitly to get F# to resolve the correct overload.</p>
<p>Here’s an example of an assertion failure (when I change the expected value to <code>[2;3;5]</code>):</p>
<pre><code>Position: First difference is at position 2
Expected: FSharpList&lt;Int32&gt; { 2, 3, 5 }
Actual:   FSharpList&lt;Int32&gt; { 2, 3, 4 }</code></pre>
<h2 id="fsunit">FsUnit</h2>
<p><a href="https://github.com/fsharp/FsUnit">FsUnit</a> provides helpers for NUnit, xUnit, MbUnit, and MSTest assertions to make them play nicely with F# syntax and type inference. I installed the <code>FsUnit.Xunit</code> package.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">open</span> <span class="nn">FsUnit.Xunit</span>

<span class="o">[&lt;</span><span class="n">Fact</span><span class="o">&gt;]</span>
<span class="k">let</span> <span class="n">``map (+1) over list using FsUnit.Xunit``</span> <span class="bp">()</span> <span class="o">=</span>
    <span class="k">let</span> <span class="nv">result</span> <span class="o">=</span> <span class="nn">List</span><span class="p">.</span><span class="n">map</span> <span class="n">incr</span> <span class="o">[</span><span class="mi">1</span><span class="o">;</span><span class="mi">2</span><span class="o">;</span><span class="mi">3</span><span class="o">]</span>
    <span class="n">result</span> <span class="o">|&gt;</span> <span class="n">should</span> <span class="n">equal</span> <span class="o">[</span><span class="mi">2</span><span class="o">;</span><span class="mi">3</span><span class="o">;</span><span class="mi">4</span><span class="o">]</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>Sample failure:</p>
<pre><code>Position: First difference is at position 0
Expected: Equals [2; 3; 5]
Actual:   was [2; 3; 4]</code></pre>
<p>(I’m not sure why first difference is at position 0 here?)</p>
<h2 id="unquote">Unquote</h2>
<p><a href="https://code.google.com/p/unquote/">Unquote</a> lets us use quoted expressions for assertions.</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">open</span> <span class="nn">Swensen.Unquote</span>

<span class="o">[&lt;</span><span class="n">Fact</span><span class="o">&gt;]</span>
<span class="k">let</span> <span class="n">``map (+1) over list using Unquote``</span> <span class="bp">()</span> <span class="o">=</span>
    <span class="n">test</span> <span class="o">&lt;@</span> <span class="nn">List</span><span class="p">.</span><span class="n">map</span> <span class="n">incr</span> <span class="o">[</span><span class="mi">1</span><span class="o">;</span><span class="mi">2</span><span class="o">;</span><span class="mi">3</span><span class="o">]</span> <span class="o">=</span> <span class="o">[</span><span class="mi">2</span><span class="o">;</span><span class="mi">3</span><span class="o">;</span><span class="mi">4</span><span class="o">]</span> <span class="o">@&gt;</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>If the test fails, Unquote shows each step in reducing the expression so you can see where they start to differ:</p>
<pre><code>List.map Sample.incr [1; 2; 3] = [2; 3; 5]
[2; 3; 4] = [2; 3; 5]
false</code></pre>
<p>This case only shows 3 steps, but more complex expressions will show more.</p>
<h2 id="fscheck">FsCheck</h2>
<p><a href="https://fsharp.github.io/FsCheck/">FsCheck</a> is influenced by Haskell’s QuickCheck and Scala’s scalacheck. Rather than asserting a specific input and output, we define a property that should hold for all values of a type (optionally requiring they meet certain criteria, such as being a positive integer).</p>
<p>The FsCheck.Xunit package has specific support for xUnit through a <code>PropertyAttribute</code> that let us run properties directly as an xUnit test (otherwise a little more boilerplate is required, see <a href="https://fsharp.github.io/FsCheck/QuickStart.html">“Using FsCheck with other testing frameworks” in the Quick Start guide</a>).</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">open</span> <span class="nn">FsCheck</span>
<span class="k">open</span> <span class="nn">FsCheck.Xunit</span>

<span class="o">[&lt;</span><span class="n">Property</span><span class="o">&gt;]</span>
<span class="k">let</span> <span class="n">``map f . map g = map (f . g)``</span> <span class="o">(</span><span class="n">xs</span><span class="o">:</span><span class="n">int</span> <span class="kt">list</span><span class="o">)</span> <span class="o">=</span>
    <span class="k">let</span> <span class="nv">f</span> <span class="n">x</span> <span class="o">=</span> <span class="n">x</span><span class="o">*</span><span class="mi">10</span>
    <span class="k">let</span> <span class="nv">g</span> <span class="n">x</span> <span class="o">=</span> <span class="n">x</span><span class="o">+</span><span class="mi">1</span>
    <span class="o">(</span><span class="nn">List</span><span class="p">.</span><span class="n">map</span> <span class="n">f</span> <span class="o">&lt;&lt;</span> <span class="nn">List</span><span class="p">.</span><span class="n">map</span> <span class="n">g</span><span class="o">)</span> <span class="n">xs</span> <span class="o">=</span> <span class="nn">List</span><span class="p">.</span><span class="n">map</span> <span class="o">(</span><span class="n">f</span> <span class="o">&lt;&lt;</span> <span class="n">g</span><span class="o">)</span> <span class="n">xs</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>If we modify the property to ensure it fails (for example, <code>(List.map f &lt;&lt; List.map g) xs = List.map (f &lt;&lt; g) (List.filter even xs)</code>), we get this output:</p>
<pre><code>FsCheck.Xunit.PropertyFailedException
Falsifiable, after 3 tests (2 shrinks) (StdGen (267259328,295888818)):
[1]</code></pre>
<p>This shows that given an input of <code>[1]</code> the property does not hold.</p>
<h2 id="fuchu">Fuchu</h2>
<p><a href="https://github.com/mausch/Fuchu">Fuchu</a> is more focussed on test organisation than assertions, and can be used with any of the assertion-providing libraries above. If you’d like to try something different to the usual (N|x|Mb)Unit approaches for defining test cases then <a href="http://bugsquash.blogspot.com.au/2012/06/fuchu-functional-test-library-for-net.html">give it a look</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Digitising hand drawn sketches]]></title>
    <link href="http://davesquared.net/2014/05/sketches-to-png.html"/>
    <updated>2014-05-21T22:30:00+10:00</updated>
    <id>http://davesquared.net/2014/05/sketches-to-png</id>
    <content type="html"><![CDATA[<p>Every so often I want to quickly sketch out what should be a simple diagram. Irrespective of what drawing program I use, I always seem to take much more time than I intend for a result that does not even remotely resemble what I want.</p>
<p>So I decided to give up and find a way to use hand-drawn sketches instead. Here’s the method I ended up with, based almost entirely on Marc Liberatore’s <a href="http://people.cs.umass.edu/~liberato/blog/2013/01/21/whiteboard-diagrams-as-pdfs/">“Whiteboard Diagrams as PDFs”</a> post and the wonderful <a href="http://www.imagemagick.org/">ImageMagick</a> and <a href="http://potrace.sourceforge.net/">Potrace</a> utilities.</p>
<p>My drawings still look fairly terrible, but at least they convey what I want them to and are quick to produce! :)</p>
<!-- more -->
<h2 id="ingredients">Ingredients</h2>
<ul>
<li>Paper / whiteboard</li>
<li>Marker</li>
<li>Phone with camera</li>
<li><a href="http://www.imagemagick.org/">ImageMagick</a>: <code>brew install imagemagick</code></li>
<li><a href="http://potrace.sourceforge.net/">Potrace</a>. I used the binary distribution, although it’s also on Homebrew.</li>
</ul>
<h2 id="method">Method</h2>
<h3 id="commit-sin-against-art">Commit sin against art</h3>
<p>Here’s a sample result of me unleashing my inner <a href="http://en.wikipedia.org/wiki/Leonardo_da_Vinci#Drawings">da Vinci</a> on a poor, defenceless bit of paper.</p>
<figure>
<img src="http://davesquared.net/images/2014/sketch_photo.jpg" alt="I don’t know much about art, but I repeat myself" /><figcaption>I don’t know much about art, but I repeat myself</figcaption>
</figure>
<p>I’ve found a <a href="http://en.wikipedia.org/wiki/Marker_pen">thick texta/marker</a> works well, but standard ball-point pens can come out alright too.</p>
<h3 id="photo-cameras-not-just-for-tweeting-lunch">Photo cameras: not just for tweeting lunch</h3>
<p>Next, take a photo with ye olde phone camera. I avoid using the flash - even light (no shadows) is best. (Try holding the paper up vertically so your phone does not cast a shadow over the paper.)</p>
<p>My phone auto-uploads photos to an online thingoe from which I can quickly crop the image and download to my Mac.</p>
<h3 id="post-processing">Post-processing</h3>
<p>Next up I want to convert the photo to a grayscale bitmap and turn up the brightness and contrast to wash out the background and bring out the marker lines. I’m using ImageMagick’s <code>convert</code> to quickly do this from the console.</p>
<p>We’ll then run the bitmap through <code>potrace</code> as described in <a href="http://people.cs.umass.edu/~liberato/blog/2013/01/21/whiteboard-diagrams-as-pdfs/">Marc’s post</a> to create a nice SVG. We can stop there, or use ImageMagick again to get a PNG out.</p>
<p>Here’s the original photo, which I’ve cropped and saved as <code>sketch.jpg</code>:</p>
<figure>
<img src="http://davesquared.net/images/2014/sketch_cropped_photo.jpg" alt="Taken with no flash. Cropped and downloaded with no processing." /><figcaption>Taken with no flash. Cropped and downloaded with no processing.</figcaption>
</figure>
<p>Then the adjustments:</p>
<pre><code># Convert to grayscale BMP. Dial up brightness (20) and contrast (10)
% convert sketch.jpg -colorspace Gray -brightness-contrast 20x10 sketch.bmp

# Convert to SVG (-s), set a reasonable height, smooth speckles (-t 10)
% potrace -s -H 400pt -t 10 sketch.bmp

# Convert SVG to PNG (using 256 colours)
% convert sketch.svg PNG8:sketch.png</code></pre>
<p>And here’s the output:</p>
<figure>
<img src="http://davesquared.net/images/2014/sketch_processed.png" alt="The end result" /><figcaption>The end result</figcaption>
</figure>
<p>You may need to tweak settings like brightness, contrast, dimensions, PNG quality/size<a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a> and so on.</p>
<section class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Might be worth also running <a href="http://pmt.sourceforge.net/pngcrush/">Pngcrush</a> or <a href="http://www.hanselman.com/blog/BloggersKnowWhenToUseAJPGAndWhenToUseAPNGAndAlwaysSquishThemBoth.aspx">similar optimiser</a> over the resulting PNG: <code>brew install pngcrush; png crush sketch.png sketch2.png</code>. A GUI option for Mac is <a href="https://imageoptim.com/">ImageOptim</a>.<a href="#fnref1" class="footnote-back">↩</a></p></li>
</ol>
</section>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Haskell without the Haskell Platform]]></title>
    <link href="http://davesquared.net/2014/05/platformless-haskell.html"/>
    <updated>2014-05-10T20:00:00+10:00</updated>
    <id>http://davesquared.net/2014/05/platformless-haskell</id>
    <content type="html"><![CDATA[<p>Apparently it can be <a href="http://www.reddit.com/r/haskell/comments/23tj8y/haskellplatform_vs_ghccabal/ch0l784">a bit tricky to get some Haskell libraries working on Windows</a>, in which case the <a href="http://www.haskell.org/platform/">Haskell Platform</a> is a great way to get going with Haskell. For Mac and Linux the platform works too, but we can also just grab the latest GHC and Cabal (ooh, shiny!) and go from there.</p>
<p><em><strong>UPDATE 2019-02:</strong> I tend to use <a href="https://github.com/haskell/ghcup">ghcup</a> on Mac and Linux these days. Am leaving these steps here as building GHC and Cabal is still a valid way of getting Haskell up and running.</em></p>
<!-- more -->
<p>This is how I got it working on my Mac, with loads of help from <a href="https://twitter.com/dom_dere">ddere</a> and <a href="https://twitter.com/bitemyapp">bitemyapp</a> on the <a href="https://twitter.com/bitemyapp/status/463119899640868865">#haskell-beginners channel on Freenode IRC</a>. It is reasonable to assume all mistakes in this write up are mine, while they deserve the credit for any useful bits.</p>
<p>I’ve got XCode 5.1.1 installed, which I believe is a prerequisite (or at least the dev tools?). Other than that, grab a terminal and a browser, and we’re set to go.</p>
<h2 id="tldr">tl;dr</h2>
<p><em><strong>UPDATE 2019-02:</strong> Check out <a href="https://github.com/haskell/ghcup">ghcup</a> for an easier way to get a platformless Haskell running on Mac or Linux. I’ve switched to using that to manage Haskell installations.</em></p>
<p>Here’s the summary if you want the steps without explanation:</p>
<ul>
<li>Grab the binary <a href="http://www.haskell.org/ghc/download">GHC distribution</a>, extract, <code>configure --prefix=&lt;my-dir&gt;</code>, <code>make install</code>, and add to PATH</li>
<li>Grab the <a href="https://www.haskell.org/cabal/download.html">Cabal binary</a> and add it to the GHC <code>bin</code> directory</li>
<li><code>cabal update; cabal install cabal cabal-install alex happy</code></li>
<li>Add <code>~/.cabal/bin/</code> to PATH</li>
<li>Build projects in a sandbox (<code>cabal sandbox init</code>)</li>
<li>Build binaries in a sandbox and symlink or copy to <code>~/.cabal/bin</code>; or install directly into <code>~/.cabal</code> and <code>rm -rf ~/.ghc</code> if we ever get build conflicts. I’m doing the former.</li>
</ul>
<p>The rest of the post will go through the specific commands used, and explain some of the decisions you might need to make.</p>
<h2 id="installing-ghc">Installing GHC</h2>
<ul>
<li>Grab the latest <a href="http://www.haskell.org/ghc/download">binary distribution of GHC</a> and extract it somewhere (I used <code>~/dev/ghc-7.8.2</code>)</li>
<li>Open a terminal and run <code>./configure --prefix=&lt;my-dir&gt;</code> from the extract directory. I used <code>./configure --prefix=/Users/dave/dev/ghc</code>.</li>
<li><code>make install</code></li>
<li>Next I added the GHC binaries to my PATH. That’s <code>~/dev/ghc/bin</code> for me.</li>
</ul>
<p>We should now be able to run <code>ghc</code>, <code>ghci</code> and co. Success!</p>
<h2 id="bootstrap-cabal-install-binary">Bootstrap cabal-install binary</h2>
<ul>
<li>Grab the latest <a href="https://www.haskell.org/cabal/download.html">cabal-install binary</a>.</li>
<li>Extract it and copy the <code>cabal</code> binary somewhere. I put mine in alongside my GHC binaries in <code>~/dev/ghc/bin</code> so it is on my PATH and I can quickly fallback to it if I nuke everything else but GHC.</li>
<li>Run <code>cabal update</code> to initialise the package database.</li>
</ul>
<p>This will just be used to kick off our cabal-ing. Afterwards we’ll be managing cabal with cabal (for that nice recursive touch).</p>
<h2 id="final-bits-and-pieces">Final bits and pieces</h2>
<p>We’re now going to build and install some final bits and pieces into Cabal’s user-db (stored in <code>~/.cabal/</code>).</p>
<pre><code>% cabal install cabal cabal-install alex happy</code></pre>
<p>Next up I adjusted my PATH to make sure binaries are loaded from <code>~/.cabal/bin</code> first<a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a>. My PATH now looks like this:</p>
<pre><code>export PATH=~/.cabal/bin:~/dev/ghc/bin:(non-haskell stuff)</code></pre>
<h2 id="new-projects">New projects</h2>
<p>We should now have everything we need to build Haskell projects. For projects we’ll run all our <code>cabal install</code> commands within a sandbox.</p>
<pre><code>% mkdir myNewProj
% cd myNewProj
% cabal sandbox init
% cabal init
-- insert joyous haskelling here --</code></pre>
<h2 id="moar-binaries">Moar binaries!</h2>
<p>Sometimes we’d like to use <code>cabal</code> to install some binaries like <code>hlint</code>, <code>hoogle</code> or <code>pointfree</code>. I’ve heard a few schools of thought on this.</p>
<h3 id="sandboxed-builds">Sandboxed builds</h3>
<p>Here is what I’ve found works reasonably well for me. I’ve created a directory <code>~/dev/hs/</code> to build these utilities in. From there:</p>
<pre><code>~/dev/hs/ % mkdir hlint
~/dev/hs/ % cd hlint
~/dev/hs/hlint % cabal sandbox init
~/dev/hs/hlint % cabal install hlint
~/dev/hs/hlint % ln -s &quot;$(pwd)/.cabal-sandbox/bin/hlint&quot; ~/.cabal/bin/</code></pre>
<p>This builds gives us a fresh <code>hlint</code> binary and creates a symbolic link to it in the <code>.cabal/bin</code> directory (i.e. somewhere on my PATH). Sometimes I’ll copy instead of symlink.</p>
<p>The good thing about this is if I need to use specific versions of a particular dependent library for a build I can <code>cabal install</code> it without worrying about it affecting other builds outside the sandbox.</p>
<p>The catch is some libraries also link against static assets that get put in <code>$(pwd)/.cabal-sandbox/share</code>, which means if we move or delete this sandbox that binary will stop working.</p>
<h3 id="in-user-db">In user-db</h3>
<p>The other approach is to <code>cabal install</code> the utility outside of a sandbox. This means all docs and static assets go into a safe location (<code>~/.cabal</code>), but on the downside we’ll sometimes get build failures due to library version conflicts.</p>
<p>In these cases we need to delete everything in <code>~/.ghc</code> and try again. I have it on good authority from several sources that this is no problem. All our binaries in <code>~/.cabal</code> should still work, it just means next <code>cabal install</code> won’t rely on cached library builds.</p>
<p>Still, I feel more comfortable with the <a href="#sandboxed-builds">sandboxed build</a> approach (almost definitely because I don’t fully understand what’s going on behind the scenes).</p>
<h3 id="pandoc-example">Pandoc example</h3>
<p>At the time of writing I had some trouble building the wonderful <a href="http://johnmacfarlane.net/pandoc/">Pandoc</a> library due to a change in a dependent library. Pandoc is a library that relies on statically linked assets by default which was <a href="#sandboxed-builds">mentioned in the sandboxed builds</a> section as a possible problem. Thankfully it provides a build option to embed these assets.</p>
<pre><code>% cd ~/dev/hs
% mkdir pandoc
% cd pandoc
% cabal sandbox init
% cabal install exceptions-0.4
% cabal install hsb2hs
% cabal install pandoc -fembed_data_files
% cp &quot;$(pwd)/.cabal-sandbox/bin/&quot; ~/.cabal/bin/</code></pre>
<p>Installing a specific version of <code>exceptions-0.4</code> fixed the build problem, while passing the <code>-fembed_data_files</code> option to the Pandoc build embeds the static assets so we can move the binary and delete the sandbox without breaking Pandoc.</p>
<p>Thanks to <a href="https://twitter.com/cartazio">Carter</a> for telling me which version of <code>exceptions</code> I needed, and about <code>-fembed_data_files</code> for Pandoc.</p>
<h2 id="request-for-corrections">Request for corrections</h2>
<p>This seems to be working ok for me, but if you can see any problems with this approach or can suggest any improvements please let me know and I’ll update the post.</p>
<section class="footnotes">
<hr />
<ol>
<li id="fn1"><p>We’ve now installed a verion of the <code>cabal</code> binary into <code>~/.cabal/bin</code>. By putting that into our PATH first we’ll always use the latest version for our builds. If we lose our <code>~/.cabal</code> for some reason then we can fall back to the one we put into the <code>ghc</code> folder earlier.<a href="#fnref1" class="footnote-back">↩</a></p></li>
</ol>
</section>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Some regex help from the F# compiler]]></title>
    <link href="http://davesquared.net/2014/04/fsharp-regex-provider.html"/>
    <updated>2014-04-19T21:45:00+10:00</updated>
    <id>http://davesquared.net/2014/04/fsharp-regex-provider</id>
    <content type="html"><![CDATA[<p><em>tl;dr: Make invalid regular expression strings and attempts to access non-existent capture groups a compile-time error, thanks to the <a href="http://fsprojects.github.io/RegexProvider/">Regex type provider</a>.</em></p>
<!-- more -->
<h2 id="standard-.net-regex">Standard .NET regex</h2>
<p>Say we want to parse out some information from basic <a href="https://github.com/Shopify/liquid">Liquid</a> tags, like this:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='csharp'><span></span><span class="na">[Test]</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">GetInformationFromAllSampleTags</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">const</span> <span class="kt">string</span> <span class="n">input</span> <span class="p">=</span>
        <span class="s">@&quot;This is a test. {% sample %}ABC{% endsample %}. Some {% other %} 123 {% endother %} tag.</span>
<span class="s">          {% sample %} DEF {% endsample %}&quot;</span><span class="p">;</span>
    <span class="n">GetSamples</span><span class="p">(</span><span class="n">input</span><span class="p">).</span><span class="n">ShouldBe</span><span class="p">(</span><span class="k">new</span> <span class="p">[]</span> <span class="p">{</span> <span class="s">&quot;ABC&quot;</span><span class="p">,</span> <span class="s">&quot;DEF&quot;</span> <span class="p">});</span>
<span class="p">}</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>We can give ourselves <a href="http://regex.info/blog/2006-09-15/247">two problems</a> and implement this using <code>System.Text.RegularExpressions</code> (it looks almost identical in C#, see <a href="https://gist.github.com/dtchepak/11083161">this gist</a> or footnote<a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a>):</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="c1">// F#</span>
<span class="k">let</span> <span class="nv">getSamples</span> <span class="n">s</span> <span class="o">:</span> <span class="kt">string</span> <span class="n">seq</span> <span class="o">=</span>
    <span class="k">let</span> <span class="nv">re</span> <span class="o">=</span> <span class="s">@&quot;\{%\s*(?&lt;tag&gt;\w+)\s*\%\}(?&lt;contents&gt;(?s:.*?))\{%\s*end\1\s*%\}&quot;</span>
    <span class="nn">Regex</span><span class="p">.</span><span class="n">Matches</span><span class="o">(</span><span class="n">s</span><span class="o">,</span> <span class="n">re</span><span class="o">)</span>
        <span class="o">|&gt;</span> <span class="nn">Seq</span><span class="p">.</span><span class="n">cast</span><span class="o">&lt;</span><span class="n">Match</span><span class="o">&gt;</span>
        <span class="o">|&gt;</span> <span class="nn">Seq</span><span class="p">.</span><span class="n">filter</span> <span class="o">(</span><span class="k">fun</span> <span class="n">m</span> <span class="o">-&gt;</span> <span class="n">m</span><span class="o">.</span><span class="n">Groups</span><span class="o">.[</span><span class="s">&quot;tag&quot;</span><span class="o">].</span><span class="n">Value</span> <span class="o">=</span> <span class="s">&quot;sample&quot;</span><span class="o">)</span>
        <span class="o">|&gt;</span> <span class="nn">Seq</span><span class="p">.</span><span class="n">map</span> <span class="o">(</span><span class="k">fun</span> <span class="n">m</span> <span class="o">-&gt;</span> <span class="n">m</span><span class="o">.</span><span class="n">Groups</span><span class="o">.[</span><span class="s">&quot;contents&quot;</span><span class="o">].</span><span class="n">Value</span><span class="o">.</span><span class="n">Trim</span><span class="bp">()</span><span class="o">)</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<h2 id="f-type-provider-version">F# type provider version</h2>
<p>First up we need to add the <a href="http://fsprojects.github.io/RegexProvider/">RegexProvider</a> to our project via nuget: <code>PM&gt; Install-Package RegexProvider</code>.</p>
<p>Now we can rewrite our previous implementation like this:</p>
<div class="bogus-wrapper">
<notextile>
<figure class="code">
<figcaption>
<span></span>
</figcaption>
<div class="highlight">
<pre><code class='fsharp'><span></span><span class="k">open</span> <span class="nn">FSharp.RegexProvider</span>
<span class="k">type</span> <span class="nc">LiquidTagRegex</span> <span class="o">=</span> <span class="n">Regex</span><span class="o">&lt;</span> <span class="s">@&quot;\{%\s*(?&lt;tag&gt;\w+)\s*\%\}(?&lt;contents&gt;(?s:.*?))\{%\s*end\1\s*%\}&quot;</span> <span class="o">&gt;</span>

<span class="k">let</span> <span class="nv">getSamples</span> <span class="n">s</span> <span class="o">:</span> <span class="kt">string</span> <span class="n">seq</span> <span class="o">=</span>
    <span class="n">LiquidTagRegex</span><span class="bp">()</span><span class="o">.</span><span class="n">Matches</span><span class="o">(</span><span class="n">s</span><span class="o">)</span>
        <span class="o">|&gt;</span> <span class="nn">Seq</span><span class="p">.</span><span class="n">filter</span> <span class="o">(</span><span class="k">fun</span> <span class="n">m</span> <span class="o">-&gt;</span> <span class="n">m</span><span class="o">.</span><span class="n">tag</span><span class="o">.</span><span class="n">Value</span> <span class="o">=</span> <span class="s">&quot;sample&quot;</span><span class="o">)</span>
        <span class="o">|&gt;</span> <span class="nn">Seq</span><span class="p">.</span><span class="n">map</span> <span class="o">(</span><span class="k">fun</span> <span class="n">m</span> <span class="o">-&gt;</span> <span class="n">m</span><span class="o">.</span><span class="n">contents</span><span class="o">.</span><span class="n">Value</span><span class="o">.</span><span class="n">Trim</span><span class="bp">()</span><span class="o">)</span>
</code></pre>
</div>
</figure>
</notextile>
</div>
<p>This will compile equivalently to our previous implementation<a href="#fn2" class="footnote-ref" id="fnref2"><sup>2</sup></a>, but we’ve gained some nice static checks.</p>
<p>We can access the <code>tag</code> and <code>contents</code> capture groups of our match as properties. This isn’t a <code>method_missing</code>-style dynamic lookup – if we rename the group in the regex to <code>(?&lt;notTag&gt;\w+)</code> then we get a compile-time error:</p>
<pre><code>error FS0039: The field, constructor or member &#39;tag&#39; is not defined</code></pre>
<p>Also neat, if we completely muck up our regex, the compiler will let us know:</p>
<pre><code>error FS3033: The type provider ... reported an error: parsing &quot;[asd&quot; -
Unterminated [] set.</code></pre>
<p>Tests would catch both these errors, but feedback doesn’t get much faster than “as we’re typing the code”, plus we get precise line numbers for the errors as well. It also reduces code noise, dealing directly with the capture group names rather than having to specify particular collection lookups.</p>
<section class="footnotes">
<hr />
<ol>
<li id="fn1">An equivalent implementation in C#:
<div class="highlight">
<div class="sourceCode" id="cb1"><pre class="sourceCode csharp"><code class="sourceCode cs"><a class="sourceLine" id="cb1-1" title="1"><span class="co">// C#</span></a>
<a class="sourceLine" id="cb1-2" title="2"><span class="kw">public</span> IEnumerable&lt;<span class="dt">string</span>&gt; <span class="fu">GetSamples</span>(<span class="dt">string</span> s) {</a>
<a class="sourceLine" id="cb1-3" title="3">    <span class="dt">var</span> re = @<span class="st">&quot;\{%\s*(?&lt;tag&gt;\w+)\s*\%\}(?&lt;contents&gt;(?s:.*?))\{%\s*end\1\s*%\}&quot;</span>;</a>
<a class="sourceLine" id="cb1-4" title="4">    <span class="kw">return</span> Regex.<span class="fu">Matches</span>(s, re)</a>
<a class="sourceLine" id="cb1-5" title="5">                .<span class="fu">Cast</span>&lt;Match&gt;()</a>
<a class="sourceLine" id="cb1-6" title="6">                .<span class="fu">Where</span>(m =&gt; m.<span class="fu">Groups</span>[<span class="st">&quot;tag&quot;</span>].<span class="fu">Value</span> == <span class="st">&quot;sample&quot;</span>)</a>
<a class="sourceLine" id="cb1-7" title="7">                .<span class="fu">Select</span>(m =&gt; m.<span class="fu">Groups</span>[<span class="st">&quot;contents&quot;</span>].<span class="fu">Value</span>.<span class="fu">Trim</span>());</a>
<a class="sourceLine" id="cb1-8" title="8">}</a></code></pre></div>
</div>
<a href="#fnref1" class="footnote-back">↩</a></li>
<li id="fn2"><p>The type provider creates a type with the <code>tag</code> and <code>contents</code> properties, but this type gets erased in the final compiled output, replaced with the <code>Groups</code> accessor code from our original implementation.<a href="#fnref2" class="footnote-back">↩</a></p></li>
</ol>
</section>
]]></content>
  </entry>
  
</feed>
