<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>Sebastian Galkin's Blog</title>
    <link href="https://blog.sebastian-galkin.com/atom.xml" rel="self" />
    <link href="https://blog.sebastian-galkin.com" />
    <id>https://blog.sebastian-galkin.com/atom.xml</id>
    <author>
        <name>Sebastian Galkin</name>
        <email>paraseba@gmail.com</email>
    </author>
    <updated>2018-06-02T00:00:00Z</updated>
    <entry>
    <title>An exercise on applicatives</title>
    <link href="https://blog.sebastian-galkin.com/posts/an-exercise-on-applicatives/index.html" />
    <id>https://blog.sebastian-galkin.com/posts/an-exercise-on-applicatives/index.html</id>
    <published>2018-06-02T00:00:00Z</published>
    <updated>2018-06-02T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div itemscope itemtype="http://schema.org/Article">
    <h1 itemprop="headline name">An exercise on applicatives</h1>

    <div class="info">
      <time itemprop="datePublished" datetime="2018-06-02">Posted on June  2, 2018</time>
      <div itemscope itemprop="author publisher" itemtype="http://schema.org/Person">
        
            <meta itemprop="name" content="Sebastian Galkin"/>
        
      </div>

      
        <meta itemprop="description" content="A small exercise in "Applicative programming with effects""/>
      

    </div>
    <div itemprop="articleBody">
      <p>Rereading the great Functional Pearl <a href="http://www.staff.city.ac.uk/~ross/papers/Applicative.pdf">“Applicative programming with effects”</a> I found the following:</p>
<blockquote>
We began this section by observing that <code>Accy o</code> is not a monad. However, given <code>Monoid o</code> it can be defined as the composition of two applicative functors derived from monads—which two, we leave as an exercise
</blockquote>
<p>What they call <code>Accy o</code> is what we would call today <code>Const o</code> from <a href="https://hackage.haskell.org/package/base/docs/Data-Functor-Const.html"><code>Data.Functor.Const</code></a></p>
<div class="sourceCode" id="cb1"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb1-1" data-line-number="1"><span class="kw">newtype</span> <span class="dt">Const</span> o a <span class="fu">=</span> <span class="dt">Const</span> {<span class="ot"> getConst ::</span> o }</a></code></pre></div>
<p>a phantom type that forgets about <code>a</code> and just carries around the <code>o</code>.</p>
<p><code>Const o</code> can be made an instance of <code>Applicative</code> if <code>o</code> has a <code>Monoid</code>:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb2-1" data-line-number="1"><span class="kw">instance</span> <span class="dt">Functor</span> (<span class="dt">Const</span> o) <span class="kw">where</span></a>
<a class="sourceLine" id="cb2-2" data-line-number="2">  fmap _ (<span class="dt">Const</span> o) <span class="fu">=</span> <span class="dt">Const</span> o</a>
<a class="sourceLine" id="cb2-3" data-line-number="3"></a>
<a class="sourceLine" id="cb2-4" data-line-number="4"><span class="kw">instance</span> <span class="dt">Monoid</span> o <span class="ot">=&gt;</span> <span class="dt">Applicative</span> (<span class="dt">Const</span> o) <span class="kw">where</span></a>
<a class="sourceLine" id="cb2-5" data-line-number="5">  pure _ <span class="fu">=</span> <span class="dt">Const</span> mempty</a>
<a class="sourceLine" id="cb2-6" data-line-number="6">  <span class="dt">Const</span> a <span class="fu">&lt;*&gt;</span> <span class="dt">Const</span> b <span class="fu">=</span> <span class="dt">Const</span> (a <span class="fu">&lt;&gt;</span> b)</a></code></pre></div>
<p>Since we are forgetting about the <code>a</code>’s, the only way to combine two <code>Const o</code> is to use the monoid on <code>o</code>.</p>
<p><code>Const o</code> is a pretty unusual applicative. It’s surprising that it satisfies all the laws by discarding so much. Let’s verify it is actually an <code>Applicative</code> by checking the laws:</p>
<p>First the <code>Functor</code> laws:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb3-1" data-line-number="1"><span class="co">-- identity</span></a>
<a class="sourceLine" id="cb3-2" data-line-number="2">fmap id (<span class="dt">Const</span> o) <span class="fu">=</span> <span class="dt">Const</span> o <span class="fu">=</span> id (<span class="dt">Const</span> o)</a>
<a class="sourceLine" id="cb3-3" data-line-number="3"></a>
<a class="sourceLine" id="cb3-4" data-line-number="4"><span class="co">-- composition</span></a>
<a class="sourceLine" id="cb3-5" data-line-number="5">fmap (f<span class="fu">.</span>g) (<span class="dt">Const</span> o) <span class="fu">=</span> <span class="dt">Const</span> o <span class="fu">=</span></a>
<a class="sourceLine" id="cb3-6" data-line-number="6">  <span class="fu">=</span> fmap f (fmap g (<span class="dt">Const</span> o)) <span class="fu">=</span> (fmap f <span class="fu">.</span> fmap g) (<span class="dt">Const</span> o)</a></code></pre></div>
<p>And now the <code>Applicative</code> laws:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb4-1" data-line-number="1"><span class="co">-- identity</span></a>
<a class="sourceLine" id="cb4-2" data-line-number="2">pure id <span class="fu">&lt;*&gt;</span> <span class="dt">Const</span> o <span class="fu">=</span> <span class="dt">Const</span> mempty <span class="fu">&lt;*&gt;</span> <span class="dt">Const</span> o <span class="fu">=</span></a>
<a class="sourceLine" id="cb4-3" data-line-number="3">  <span class="fu">=</span> <span class="dt">Const</span> (mempty <span class="fu">&lt;&gt;</span> o) <span class="fu">=</span> <span class="dt">Const</span> o</a>
<a class="sourceLine" id="cb4-4" data-line-number="4"></a>
<a class="sourceLine" id="cb4-5" data-line-number="5"><span class="co">-- composition</span></a>
<a class="sourceLine" id="cb4-6" data-line-number="6">pure (<span class="fu">.</span>) <span class="fu">&lt;*&gt;</span> <span class="dt">Const</span> u <span class="fu">&lt;*&gt;</span> <span class="dt">Const</span> v <span class="fu">&lt;*&gt;</span> <span class="dt">Const</span> w <span class="fu">=</span></a>
<a class="sourceLine" id="cb4-7" data-line-number="7">  <span class="fu">=</span> <span class="dt">Const</span> (mempty <span class="fu">&lt;&gt;</span> u <span class="fu">&lt;&gt;</span> v <span class="fu">&lt;&gt;</span> w) <span class="fu">=</span> <span class="dt">Const</span> (u <span class="fu">&lt;&gt;</span> v <span class="fu">&lt;&gt;</span> w) <span class="fu">=</span></a>
<a class="sourceLine" id="cb4-8" data-line-number="8">  <span class="fu">=</span> <span class="dt">Const</span> u <span class="fu">&lt;*&gt;</span> (<span class="dt">Const</span> v <span class="fu">&lt;*&gt;</span> <span class="dt">Const</span> w)</a>
<a class="sourceLine" id="cb4-9" data-line-number="9"></a>
<a class="sourceLine" id="cb4-10" data-line-number="10"><span class="co">-- homomorphism</span></a>
<a class="sourceLine" id="cb4-11" data-line-number="11">pure f <span class="fu">&lt;*&gt;</span> pure x <span class="fu">=</span> <span class="dt">Const</span> mempty <span class="fu">&lt;*&gt;</span> <span class="dt">Const</span> mempty <span class="fu">=</span></a>
<a class="sourceLine" id="cb4-12" data-line-number="12">  <span class="fu">=</span> <span class="dt">Const</span> (mempty <span class="fu">&lt;*&gt;</span> mempty) <span class="fu">=</span> <span class="dt">Const</span> mempty <span class="fu">=</span> pure (f x)</a>
<a class="sourceLine" id="cb4-13" data-line-number="13"></a>
<a class="sourceLine" id="cb4-14" data-line-number="14"><span class="co">-- interchange</span></a>
<a class="sourceLine" id="cb4-15" data-line-number="15"><span class="dt">Const</span> f <span class="fu">&lt;*&gt;</span> pure y <span class="fu">=</span> <span class="dt">Const</span> f <span class="fu">&lt;*&gt;</span> <span class="dt">Const</span> mempty <span class="fu">=</span></a>
<a class="sourceLine" id="cb4-16" data-line-number="16">  <span class="fu">=</span> <span class="dt">Const</span> f <span class="fu">=</span> <span class="dt">Const</span> mempty <span class="fu">&lt;*&gt;</span> <span class="dt">Const</span> f <span class="fu">=</span> pure (<span class="fu">$</span> y) <span class="fu">&lt;*&gt;</span> <span class="dt">Const</span> f</a></code></pre></div>
<p>OK, back to the exercise, how can we write <code>Const</code> as the composition of two Monads? If we achieved this, we would get the <code>Applicative</code> instance, and the proof of the laws for free. That’s because there is an instance</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb5-1" data-line-number="1">(<span class="dt">Applicative</span> f, <span class="dt">Applicative</span> g) <span class="ot">=&gt;</span> <span class="dt">Applicative</span> (<span class="dt">Compose</span> f g)</a></code></pre></div>
<p><code>Const</code>’s applicative combines effects using a monoid. The other basic monad we know of with that same behavior is Writer, which also combines its payload using a monoid. So, the <code>Const o</code> applicative looks a lot like the <code>Writer o</code> applicative. We could write:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb6-1" data-line-number="1"><span class="kw">import</span> <span class="dt">Control.Monad.Writer</span></a>
<a class="sourceLine" id="cb6-2" data-line-number="2"></a>
<a class="sourceLine" id="cb6-3" data-line-number="3"><span class="kw">newtype</span> <span class="dt">Const&#39;</span> o a <span class="fu">=</span> <span class="dt">Const&#39;</span> {<span class="ot">getConst&#39; ::</span> (<span class="dt">Writer</span> o a)}</a>
<a class="sourceLine" id="cb6-4" data-line-number="4">  <span class="kw">deriving</span> (<span class="dt">Functor</span>, <span class="dt">Applicative</span>)</a></code></pre></div>
<p>But this doesn’t really ignore the <code>a</code> type. When using this code, some type and value for <code>a</code> must be selected. Even more, the applicative will actually carry out the work of operating on the <code>a</code>’s. What we want is some type that can ignore <code>a</code> completely. Enter <a href="https://hackage.haskell.org/package/base/docs/Data-Proxy.html"><code>Proxy</code></a> in the base library</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb7-1" data-line-number="1"><span class="kw">data</span> <span class="dt">Proxy</span> t <span class="fu">=</span> <span class="dt">Proxy</span></a></code></pre></div>
<p>Again a phantom type monad. There is a single inhabitant in this type, <code>Proxy</code>, so the <code>Applicative</code> doesn’t do any computation at all. The functor, applicative and monad laws for <code>Proxy t</code> are satisfied by construction, because every <code>Proxy t</code> is equal to every “other” <code>Proxy t</code>.</p>
<p>Using <code>Proxy</code> we get a better candidate for the <code>Writer</code> result type:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb8-1" data-line-number="1"><span class="kw">newtype</span> <span class="dt">Const&#39;</span> o a <span class="fu">=</span> <span class="dt">Const&#39;</span> {<span class="ot">getConst&#39; ::</span> (<span class="dt">Writer</span> o (<span class="dt">Proxy</span> a))}</a></code></pre></div>
<p>or, rewriting this in terms of <code>Compose</code><a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a>:</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb10-1" data-line-number="1"><span class="kw">newtype</span> <span class="dt">Const&#39;</span> o a <span class="fu">=</span></a>
<a class="sourceLine" id="cb10-2" data-line-number="2">  <span class="dt">Const&#39;</span> {<span class="ot"> getConst&#39; ::</span> <span class="dt">Compose</span> (<span class="dt">Writer</span> o) <span class="dt">Proxy</span> a }</a>
<a class="sourceLine" id="cb10-3" data-line-number="3">    <span class="kw">deriving</span> (<span class="dt">Functor</span>, <span class="dt">Applicative</span>)</a></code></pre></div>
<p>With this version of <code>Const'</code>, we don’t need to write the instance or prove the applicative laws, and yet, now we can use <code>Const'</code> to traverse combining with the monoid.</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb11-1" data-line-number="1">sum<span class="ot"> ::</span> (<span class="dt">Traversable</span> t, <span class="dt">Num</span> n) <span class="ot">=&gt;</span> t n <span class="ot">-&gt;</span> n</a>
<a class="sourceLine" id="cb11-2" data-line-number="2">sum <span class="fu">=</span>  unwrap <span class="fu">.</span> traverse wrap</a>
<a class="sourceLine" id="cb11-3" data-line-number="3">  <span class="kw">where</span></a>
<a class="sourceLine" id="cb11-4" data-line-number="4">    wrap <span class="fu">=</span> <span class="dt">Const&#39;</span> <span class="fu">.</span> <span class="dt">Compose</span> <span class="fu">.</span> writer <span class="fu">.</span> (<span class="dt">Proxy</span>,) <span class="fu">.</span> <span class="dt">Sum</span></a>
<a class="sourceLine" id="cb11-5" data-line-number="5">    unwrap <span class="fu">=</span> getSum <span class="fu">.</span> execWriter <span class="fu">.</span> getCompose <span class="fu">.</span> getConst&#39;</a></code></pre></div>
<section class="footnotes">
<hr />
<ol>
<li id="fn1"><p><sup>1</sup> As a reminder, functor composition is declared as</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb9-1" data-line-number="1"><span class="kw">newtype</span> <span class="dt">Compose</span> f g a <span class="fu">=</span> <span class="dt">Compose</span> {<span class="ot"> getCompose ::</span> f (g a) }</a></code></pre></div>
<a href="#fnref1" class="footnote-back">↩</a></li>
</ol>
</section>
    </div>
</div>
]]></summary>
</entry>
<entry>
    <title>Monoids talk</title>
    <link href="https://blog.sebastian-galkin.com/posts/monoids-talk-at-scaladores/index.html" />
    <id>https://blog.sebastian-galkin.com/posts/monoids-talk-at-scaladores/index.html</id>
    <published>2018-06-01T00:00:00Z</published>
    <updated>2018-06-01T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div itemscope itemtype="http://schema.org/Article">
    <h1 itemprop="headline name">Monoids talk</h1>

    <div class="info">
      <time itemprop="datePublished" datetime="2018-06-01">Posted on June  1, 2018</time>
      <div itemscope itemprop="author publisher" itemtype="http://schema.org/Person">
        
            <meta itemprop="name" content="Sebastian Galkin"/>
        
      </div>

      
        <meta itemprop="description" content="A talk I gave at the São Paulo Scala group."/>
      

    </div>
    <div itemprop="articleBody">
      <p>On May 29th 2018 I gave a talk about Monoids at <a href="https://www.meetup.com/scaladores/events/250823565/">Scaladores</a>, the Scala meetup group in São Paulo.</p>
<p>Here are the <a href="https://paraseba.gitlab.io/scaladores-may-2018-talk/slides.pdf">slides</a>. If you want to see the code and tests, go to the <a href="https://github.com/paraseba/scaladores-may-2018-talk">GitHub project</a>.</p>
<p>Scaladores should make the video recording available soon.</p>
    </div>
</div>
]]></summary>
</entry>
<entry>
    <title>Our own mutable variables</title>
    <link href="https://blog.sebastian-galkin.com/posts/our-own-mutable-variables/index.html" />
    <id>https://blog.sebastian-galkin.com/posts/our-own-mutable-variables/index.html</id>
    <published>2017-10-08T00:00:00Z</published>
    <updated>2017-10-08T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div itemscope itemtype="http://schema.org/Article">
    <h1 itemprop="headline name">Our own mutable variables</h1>

    <div class="info">
      <time itemprop="datePublished" datetime="2017-10-08">Posted on October  8, 2017</time>
      <div itemscope itemprop="author publisher" itemtype="http://schema.org/Person">
        
            <meta itemprop="name" content="Sebastian Galkin"/>
        
      </div>

      
        <meta itemprop="description" content="Defining mutable variables in different monads"/>
      

    </div>
    <div itemprop="articleBody">
      <p>Talking with a friend earlier today we decided to make an experiment in declaring generic mutable variables that can be used in <code>IO</code>, <code>ST</code> or <code>State</code> monads. I don’t think this is useful, but it was fun to write. Here is result.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb1-1" data-line-number="1"><span class="ot">{-# LANGUAGE MultiParamTypeClasses #-}</span></a>
<a class="sourceLine" id="cb1-2" data-line-number="2"><span class="ot">{-# LANGUAGE FlexibleInstances #-}</span></a>
<a class="sourceLine" id="cb1-3" data-line-number="3"><span class="ot">{-# LANGUAGE FlexibleContexts  #-}</span></a>
<a class="sourceLine" id="cb1-4" data-line-number="4"><span class="ot">{-# LANGUAGE FunctionalDependencies  #-}</span></a>
<a class="sourceLine" id="cb1-5" data-line-number="5"></a>
<a class="sourceLine" id="cb1-6" data-line-number="6"><span class="kw">import</span> <span class="dt">Data.Array.MArray</span></a>
<a class="sourceLine" id="cb1-7" data-line-number="7"><span class="kw">import</span> <span class="dt">Data.Array.IO</span></a>
<a class="sourceLine" id="cb1-8" data-line-number="8"><span class="kw">import</span> <span class="dt">Control.Monad.ST</span></a>
<a class="sourceLine" id="cb1-9" data-line-number="9"><span class="kw">import</span> <span class="dt">Data.STRef</span></a>
<a class="sourceLine" id="cb1-10" data-line-number="10"><span class="kw">import</span> <span class="kw">qualified</span> <span class="dt">Data.List.NonEmpty</span> <span class="kw">as</span> <span class="dt">NE</span></a>
<a class="sourceLine" id="cb1-11" data-line-number="11"><span class="kw">import</span> <span class="dt">Data.List.NonEmpty</span> (<span class="dt">NonEmpty</span>)</a>
<a class="sourceLine" id="cb1-12" data-line-number="12"><span class="kw">import</span> <span class="kw">qualified</span> <span class="dt">Control.Monad.State.Strict</span> <span class="kw">as</span> <span class="dt">State</span></a>
<a class="sourceLine" id="cb1-13" data-line-number="13"><span class="kw">import</span> <span class="dt">Data.Foldable</span> (forM_)</a>
<a class="sourceLine" id="cb1-14" data-line-number="14"><span class="kw">import</span> <span class="dt">Control.Monad</span> (when)</a>
<a class="sourceLine" id="cb1-15" data-line-number="15"></a>
<a class="sourceLine" id="cb1-16" data-line-number="16"><span class="kw">import</span> <span class="dt">Test.QuickCheck</span></a>
<a class="sourceLine" id="cb1-17" data-line-number="17"><span class="kw">import</span> <span class="dt">Test.QuickCheck.Monadic</span></a></code></pre></div>
<p>Let’s define the abstract interface. <code>v</code> will be the type of variables that can operate on the monad <code>m</code>, holding values of type <code>a</code>. We need three operation: create a variable, read, and write to it.</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb2-1" data-line-number="1"><span class="kw">class</span> <span class="dt">Var</span> v m a <span class="fu">|</span> m <span class="ot">-&gt;</span> v <span class="kw">where</span></a>
<a class="sourceLine" id="cb2-2" data-line-number="2"><span class="ot">  new ::</span> a <span class="ot">-&gt;</span> m (v a)</a>
<a class="sourceLine" id="cb2-3" data-line-number="3"><span class="ot">  get ::</span> v a <span class="ot">-&gt;</span> m a</a>
<a class="sourceLine" id="cb2-4" data-line-number="4"><span class="ot">  set ::</span> v a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> m ()</a></code></pre></div>
<p>Notice we had to use <code>FunctionalDependencies</code> to ease type inference. I don’t like this, there is probably a better way.</p>
<p>A utility function to do both read and write passing through a function:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb3-1" data-line-number="1"><span class="ot">modify ::</span> (<span class="dt">Monad</span> m, <span class="dt">Var</span> v m a) <span class="ot">=&gt;</span> (a <span class="ot">-&gt;</span> a) <span class="ot">-&gt;</span> v a <span class="ot">-&gt;</span> m ()</a>
<a class="sourceLine" id="cb3-2" data-line-number="2">modify f v <span class="fu">=</span> get v <span class="fu">&gt;&gt;=</span> set v <span class="fu">.</span> f</a></code></pre></div>
<p>Now we can provide different implementations for variables. First one in <code>IO</code></p>
<div class="sourceCode" id="cb4"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb4-1" data-line-number="1"><span class="kw">newtype</span> <span class="dt">IOVar</span> a <span class="fu">=</span> <span class="dt">IOVar</span> (<span class="dt">IOArray</span> () a)</a></code></pre></div>
<p>We represent the value as an array of a single element. This is obviously overkill, but the goal was also to experiment with the low level array API</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb5-1" data-line-number="1"><span class="kw">instance</span> <span class="dt">Var</span> <span class="dt">IOVar</span> <span class="dt">IO</span> a <span class="kw">where</span></a>
<a class="sourceLine" id="cb5-2" data-line-number="2">  new <span class="fu">=</span> fmap <span class="dt">IOVar</span> <span class="fu">.</span> newArray ((), ())</a>
<a class="sourceLine" id="cb5-3" data-line-number="3">  get (<span class="dt">IOVar</span> ar) <span class="fu">=</span> readArray ar ()</a>
<a class="sourceLine" id="cb5-4" data-line-number="4">  set (<span class="dt">IOVar</span> ar) a <span class="fu">=</span> writeArray ar () a</a></code></pre></div>
<p>The implementation is straightforward, reading and writing from/to the the array. Creation needs to take care of wrapping the array in the <code>IOVar</code> constructor. Notice that <code>()</code> is a valid index type for arrays, and it makes obvious in the type the fact that the array has a single element.</p>
<p>Providing an implementation in the <code>ST</code> monad is not much harder. Here, we could also use an <code>STArray</code>, but we go directly to <code>STRef</code> for simplicity</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb6-1" data-line-number="1"><span class="kw">newtype</span> <span class="dt">STVar</span> s a <span class="fu">=</span> <span class="dt">STVar</span> (<span class="dt">STRef</span> s a)</a>
<a class="sourceLine" id="cb6-2" data-line-number="2"></a>
<a class="sourceLine" id="cb6-3" data-line-number="3"><span class="kw">instance</span> <span class="dt">Var</span> (<span class="dt">STVar</span> s) (<span class="dt">ST</span> s) a <span class="kw">where</span></a>
<a class="sourceLine" id="cb6-4" data-line-number="4">  new <span class="fu">=</span> fmap <span class="dt">STVar</span> <span class="fu">.</span> newSTRef</a>
<a class="sourceLine" id="cb6-5" data-line-number="5">  get (<span class="dt">STVar</span> ref) <span class="fu">=</span> readSTRef ref</a>
<a class="sourceLine" id="cb6-6" data-line-number="6">  set (<span class="dt">STVar</span> ref) a <span class="fu">=</span> writeSTRef ref a</a></code></pre></div>
<p>The code looks very similar to the <code>IO</code> case.</p>
<p>Finally, let’s try to implement a variable in the <code>State</code> monad. For a variable holding values of type <code>a</code>, it is enough to maintain state <code>a</code>. So we can define</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb7-1" data-line-number="1"><span class="kw">newtype</span> <span class="dt">StateVar</span> a <span class="fu">=</span> <span class="dt">StateVar</span> a</a></code></pre></div>
<p>And now to create an instance of <code>Var</code> we can do</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb8-1" data-line-number="1"><span class="kw">instance</span> <span class="dt">Var</span> <span class="dt">StateVar</span> (<span class="dt">State.State</span> a) a <span class="kw">where</span></a>
<a class="sourceLine" id="cb8-2" data-line-number="2">  new x <span class="fu">=</span> <span class="dt">State.StateT</span> <span class="fu">$</span> \_ <span class="ot">-&gt;</span> return (<span class="dt">StateVar</span> x, x)</a>
<a class="sourceLine" id="cb8-3" data-line-number="3">  get _ <span class="fu">=</span> State.get</a>
<a class="sourceLine" id="cb8-4" data-line-number="4">  set _ <span class="fu">=</span> State.put</a></code></pre></div>
<p><code>get</code> and <code>set</code> are simple. <code>new</code> requires some care. Initializing the variable means setting the state to a given value, so it can then be read by <code>get</code>. So in <code>new</code> we need it ignore the current state, and set it to <code>x</code>. The types are not enough to ensure correctness, there is a wrong implementation that also compiles:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb9-1" data-line-number="1">wrongNew x <span class="fu">=</span> return <span class="fu">.</span> <span class="dt">StateVar</span></a></code></pre></div>
<p>And that’s it, we have the three types of variables we wanted. Now we can write a stateful looking algorithm, computing the maximum of a list is a good example. The way people do this in non functional languages usually is:</p>
<ul>
<li>initialize a variable <code>max</code> with the first element of the list</li>
<li>go through all other elements:
<ul>
<li>if the current element is larger than <code>max</code>, update <code>max</code> with the new value</li>
</ul></li>
<li>when done iterating the list return <code>max</code></li>
</ul>
<p>We can express exactly this algorithm with our variables, even more, we can do it in a way that is generic for every type of <code>Var</code> and every supported <code>Monad</code></p>
<div class="sourceCode" id="cb10"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb10-1" data-line-number="1"><span class="ot">myMaximum ::</span> (<span class="dt">Monad</span> m, <span class="dt">Var</span> v m a, <span class="dt">Ord</span> a) <span class="ot">=&gt;</span> <span class="dt">NonEmpty</span> a <span class="ot">-&gt;</span> m a</a></code></pre></div>
<p>Take a look at the signature: given a non empty list (<code>NonEmpty a</code>), we return its maximum in some monad (<code>Monad m</code>). We can do this as long as <code>a</code> can be ordered (<code>Ord a</code>), and there is some type of variable <code>v</code> which works for the monad <code>m</code> and the type <code>a</code> (<code>Var v m a</code>). The type signature expresses all this pretty well.</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb11-1" data-line-number="1">myMaximum xs <span class="fu">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb11-2" data-line-number="2">  max <span class="ot">&lt;-</span> new (NE.head xs) <span class="co">-- initialize a new var</span></a>
<a class="sourceLine" id="cb11-3" data-line-number="3">  forM_ (NE.tail xs) <span class="fu">$</span> \a <span class="ot">-&gt;</span> <span class="kw">do</span>  <span class="co">-- for each el after the head</span></a>
<a class="sourceLine" id="cb11-4" data-line-number="4">    maxSoFar <span class="ot">&lt;-</span> get max  <span class="co">-- get the current maximum</span></a>
<a class="sourceLine" id="cb11-5" data-line-number="5">    when (a <span class="fu">&gt;</span> maxSoFar) <span class="fu">$</span>  <span class="co">-- compare with current element</span></a>
<a class="sourceLine" id="cb11-6" data-line-number="6">      set max a  <span class="co">-- update if needed</span></a>
<a class="sourceLine" id="cb11-7" data-line-number="7">  get max</a></code></pre></div>
<p>Just like in the description of the algorithm, we create a variable and update it for every element that is larger than the initial value. When done iterating we return the last value hold by the variable.</p>
<p>Now we need to write some tests:</p>
<p>In <code>IO</code></p>
<div class="sourceCode" id="cb12"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb12-1" data-line-number="1"><span class="ot">testIO ::</span> (<span class="dt">NonEmptyList</span> <span class="dt">Int</span>) <span class="ot">-&gt;</span> <span class="dt">Property</span></a>
<a class="sourceLine" id="cb12-2" data-line-number="2">testIO (<span class="dt">NonEmpty</span> xs) <span class="fu">=</span> monadicIO <span class="fu">$</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb12-3" data-line-number="3">  mine <span class="ot">&lt;-</span> run <span class="fu">.</span> myMaximum <span class="fu">.</span> NE.fromList <span class="fu">$</span> xs</a>
<a class="sourceLine" id="cb12-4" data-line-number="4">  assert <span class="fu">$</span> mine <span class="fu">==</span> maximum xs</a></code></pre></div>
<p>In <code>ST</code></p>
<div class="sourceCode" id="cb13"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb13-1" data-line-number="1"><span class="ot">testST ::</span> (<span class="dt">NonEmptyList</span> <span class="dt">Int</span>) <span class="ot">-&gt;</span> <span class="dt">Property</span></a>
<a class="sourceLine" id="cb13-2" data-line-number="2">testST (<span class="dt">NonEmpty</span> xs) <span class="fu">=</span> monadicST <span class="fu">$</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb13-3" data-line-number="3">  mine <span class="ot">&lt;-</span> run <span class="fu">.</span> myMaximum <span class="fu">.</span> NE.fromList <span class="fu">$</span> xs</a>
<a class="sourceLine" id="cb13-4" data-line-number="4">  assert <span class="fu">$</span> mine <span class="fu">==</span> maximum xs</a></code></pre></div>
<p>And in <code>State</code></p>
<div class="sourceCode" id="cb14"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb14-1" data-line-number="1"><span class="ot">testState ::</span> (<span class="dt">NonEmptyList</span> <span class="dt">Int</span>) <span class="ot">-&gt;</span> <span class="dt">Bool</span></a>
<a class="sourceLine" id="cb14-2" data-line-number="2">testState (<span class="dt">NonEmpty</span> xs) <span class="fu">=</span></a>
<a class="sourceLine" id="cb14-3" data-line-number="3">  State.execState (mine xs) whoCares <span class="fu">==</span> maximum xs</a>
<a class="sourceLine" id="cb14-4" data-line-number="4">  <span class="kw">where</span></a>
<a class="sourceLine" id="cb14-5" data-line-number="5">    mine <span class="fu">=</span> myMaximum <span class="fu">.</span> NE.fromList</a>
<a class="sourceLine" id="cb14-6" data-line-number="6">    whoCares <span class="fu">=</span> <span class="dv">42</span></a></code></pre></div>
<p>Running the QuickCheck tests</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode literate haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb15-1" data-line-number="1">main <span class="fu">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb15-2" data-line-number="2">  quickCheckWith opts testIO</a>
<a class="sourceLine" id="cb15-3" data-line-number="3">  quickCheckWith opts testST</a>
<a class="sourceLine" id="cb15-4" data-line-number="4">  quickCheckWith opts testState</a>
<a class="sourceLine" id="cb15-5" data-line-number="5">  <span class="kw">where</span> opts <span class="fu">=</span> stdArgs {maxSuccess <span class="fu">=</span> <span class="dv">5000</span>}</a></code></pre></div>
<p>Success!</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode bash"><code class="sourceCode bash"><a class="sourceLine" id="cb16-1" data-line-number="1"><span class="ex">+++</span> OK, passed 5000 tests.</a>
<a class="sourceLine" id="cb16-2" data-line-number="2"><span class="ex">+++</span> OK, passed 5000 tests.</a>
<a class="sourceLine" id="cb16-3" data-line-number="3"><span class="ex">+++</span> OK, passed 5000 tests.</a></code></pre></div>
    </div>
</div>
]]></summary>
</entry>
<entry>
    <title>Shape and contents with traversables</title>
    <link href="https://blog.sebastian-galkin.com/posts/traversable-shape-contents/index.html" />
    <id>https://blog.sebastian-galkin.com/posts/traversable-shape-contents/index.html</id>
    <published>2017-01-21T00:00:00Z</published>
    <updated>2017-01-21T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div itemscope itemtype="http://schema.org/Article">
    <h1 itemprop="headline name">Shape and contents with traversables</h1>

    <div class="info">
      <time itemprop="datePublished" datetime="2017-01-21">Posted on January 21, 2017</time>
      <div itemscope itemprop="author publisher" itemtype="http://schema.org/Person">
        
            <meta itemprop="name" content="Sebastian Galkin"/>
        
      </div>

      
        <meta itemprop="description" content="An interesting idea found in a paper, splitting a collection in its elements and shape"/>
      

    </div>
    <div itemprop="articleBody">
      <p>One of the first papers I could find that seriously studies the properties of Traversals is <strong>“The essence of the iterator pattern”</strong>, by <em>Jeremy Gibbons</em> and <em>Bruno C. d. S. Oliveira</em> <a href="https://www.cs.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf">(PDF)</a></p>
<p>In there, they show the idea of splitting a traversable collection in its contents and its shape, attributing this idea to Moggi <em>et al.</em> in <em>“Monads, Shapely Functors and Traversals”</em>. The idea is to traverse the collection extracting shape and elements in a way that would allow to reconstruct the original structure.</p>
<p>To represent the contents of a traversable collections <code>Traversable t =&gt; t a</code> we can use simply <code>[a]</code>. For the shape, we need to conserve the traversable structure, discarding the elements: <code>Traversable t =&gt; t ()</code>.</p>
<h2 id="extracting-contents">Extracting contents</h2>
<p>Let’s start with the contents. We want a function of type</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb1-1" data-line-number="1"><span class="dt">Traversable</span> t <span class="ot">=&gt;</span> t a <span class="ot">-&gt;</span> [a]</a></code></pre></div>
<p>The type class function <code>traverse</code> can do the job of iterating over all the elements giving us access to each of them, we just need to provide the right <code>Applicative f</code>:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb2-1" data-line-number="1">traverse</a>
<a class="sourceLine" id="cb2-2" data-line-number="2"><span class="ot">  ::</span> (<span class="dt">Traversable</span> t, <span class="dt">Applicative</span> f)</a>
<a class="sourceLine" id="cb2-3" data-line-number="3">  <span class="ot">=&gt;</span> (a <span class="ot">-&gt;</span> f b) <span class="ot">-&gt;</span> t a <span class="ot">-&gt;</span> f (t b)</a></code></pre></div>
<p>What we want is to accumulate each element on a list, monoid style. Fortunately, every monoid, and lists in particular, can generate an applicative that uses the monoid operation to combine effects in <code>&lt;*&gt;</code>, and <code>mempty</code> for <code>pure</code>. Haskell calls this monoid <code>Const</code> apparently, because it looks like the <code>const</code> function, it just ignores the second argument:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb3-1" data-line-number="1"><span class="kw">newtype</span> <span class="dt">Const</span> a b <span class="fu">=</span> <span class="dt">Const</span> {<span class="ot"> getConst ::</span> a }</a>
<a class="sourceLine" id="cb3-2" data-line-number="2"></a>
<a class="sourceLine" id="cb3-3" data-line-number="3"><span class="kw">instance</span> <span class="dt">Functor</span> (<span class="dt">Const</span> m) <span class="kw">where</span></a>
<a class="sourceLine" id="cb3-4" data-line-number="4">    fmap _ (<span class="dt">Const</span> v) <span class="fu">=</span> <span class="dt">Const</span> v</a>
<a class="sourceLine" id="cb3-5" data-line-number="5"></a>
<a class="sourceLine" id="cb3-6" data-line-number="6"><span class="kw">instance</span> <span class="dt">Monoid</span> m <span class="ot">=&gt;</span> <span class="dt">Applicative</span> (<span class="dt">Const</span> m) <span class="kw">where</span></a>
<a class="sourceLine" id="cb3-7" data-line-number="7">    pure _ <span class="fu">=</span> <span class="dt">Const</span> mempty</a>
<a class="sourceLine" id="cb3-8" data-line-number="8">    <span class="dt">Const</span> f <span class="fu">&lt;*&gt;</span> <span class="dt">Const</span> v <span class="fu">=</span> <span class="dt">Const</span> (f <span class="ot">`mappend`</span> v)</a></code></pre></div>
<p>So this <code>Const</code> applicative behaves like the monoid in its first argument</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb4-1" data-line-number="1"><span class="fu">$&gt;</span> <span class="dt">Const</span> [<span class="dv">5</span>] <span class="fu">&lt;*&gt;</span> <span class="dt">Const</span> [<span class="dv">1</span>]</a>
<a class="sourceLine" id="cb4-2" data-line-number="2"><span class="dt">Const</span> [<span class="dv">5</span>,<span class="dv">1</span>]</a></code></pre></div>
<p>and it’s exactly what we need to implement our <code>contents</code> function:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb5-1" data-line-number="1"><span class="ot">contentsBody ::</span> a <span class="ot">-&gt;</span> <span class="dt">Const</span> [a] b</a>
<a class="sourceLine" id="cb5-2" data-line-number="2">contentsBody <span class="fu">=</span> <span class="dt">Const</span> <span class="fu">.</span> (<span class="fu">:</span> [])</a>
<a class="sourceLine" id="cb5-3" data-line-number="3"></a>
<a class="sourceLine" id="cb5-4" data-line-number="4">contents</a>
<a class="sourceLine" id="cb5-5" data-line-number="5"><span class="ot">  ::</span> <span class="dt">Traversable</span> t</a>
<a class="sourceLine" id="cb5-6" data-line-number="6">  <span class="ot">=&gt;</span> t a <span class="ot">-&gt;</span> [a]</a>
<a class="sourceLine" id="cb5-7" data-line-number="7">contents <span class="fu">=</span> getConst <span class="fu">.</span> traverse contentsBody</a>
<a class="sourceLine" id="cb5-8" data-line-number="8"></a>
<a class="sourceLine" id="cb5-9" data-line-number="9"><span class="fu">$&gt;</span> contents (<span class="dt">Just</span> <span class="dv">42</span>)</a>
<a class="sourceLine" id="cb5-10" data-line-number="10">[<span class="dv">42</span>]</a>
<a class="sourceLine" id="cb5-11" data-line-number="11"></a>
<a class="sourceLine" id="cb5-12" data-line-number="12"><span class="fu">$&gt;</span> contents <span class="dt">Nothing</span></a>
<a class="sourceLine" id="cb5-13" data-line-number="13">[]</a></code></pre></div>
<p>To make the examples more interesting, let’s define a <code>Tree</code> type</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb6-1" data-line-number="1"><span class="kw">data</span> <span class="dt">Tree</span> a</a>
<a class="sourceLine" id="cb6-2" data-line-number="2">  <span class="fu">=</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb6-3" data-line-number="3">  <span class="fu">|</span> <span class="dt">Leaf</span> a</a>
<a class="sourceLine" id="cb6-4" data-line-number="4">  <span class="fu">|</span> <span class="dt">Node</span> (<span class="dt">Tree</span> a)</a>
<a class="sourceLine" id="cb6-5" data-line-number="5">         a</a>
<a class="sourceLine" id="cb6-6" data-line-number="6">         (<span class="dt">Tree</span> a)</a>
<a class="sourceLine" id="cb6-7" data-line-number="7">  <span class="kw">deriving</span> (<span class="dt">Show</span>)</a>
<a class="sourceLine" id="cb6-8" data-line-number="8"></a>
<a class="sourceLine" id="cb6-9" data-line-number="9"><span class="kw">instance</span> <span class="dt">Functor</span> <span class="dt">Tree</span> <span class="kw">where</span></a>
<a class="sourceLine" id="cb6-10" data-line-number="10">  fmap <span class="fu">=</span> fmapDefault</a>
<a class="sourceLine" id="cb6-11" data-line-number="11"></a>
<a class="sourceLine" id="cb6-12" data-line-number="12"><span class="kw">instance</span> <span class="dt">Foldable</span> <span class="dt">Tree</span> <span class="kw">where</span></a>
<a class="sourceLine" id="cb6-13" data-line-number="13">  foldMap <span class="fu">=</span> foldMapDefault</a>
<a class="sourceLine" id="cb6-14" data-line-number="14"></a>
<a class="sourceLine" id="cb6-15" data-line-number="15"><span class="kw">instance</span> <span class="dt">Traversable</span> <span class="dt">Tree</span> <span class="kw">where</span></a>
<a class="sourceLine" id="cb6-16" data-line-number="16">  traverse f <span class="dt">Empty</span> <span class="fu">=</span> pure <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb6-17" data-line-number="17">  traverse f (<span class="dt">Leaf</span> x) <span class="fu">=</span> <span class="dt">Leaf</span> <span class="fu">&lt;$&gt;</span> f x</a>
<a class="sourceLine" id="cb6-18" data-line-number="18">  traverse f (<span class="dt">Node</span> l k r) <span class="fu">=</span></a>
<a class="sourceLine" id="cb6-19" data-line-number="19">    <span class="dt">Node</span> <span class="fu">&lt;$&gt;</span> traverse f l <span class="fu">&lt;*&gt;</span> f k <span class="fu">&lt;*&gt;</span> traverse f r</a></code></pre></div>
<p>and try <code>contents</code> on it</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb7-1" data-line-number="1"><span class="fu">$&gt;</span> t <span class="fu">=</span> <span class="dt">Node</span> left <span class="dv">3</span> right</a>
<a class="sourceLine" id="cb7-2" data-line-number="2">     <span class="kw">where</span> left <span class="fu">=</span> <span class="dt">Node</span> (<span class="dt">Leaf</span> <span class="dv">1</span>) <span class="dv">2</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb7-3" data-line-number="3">           right <span class="fu">=</span> <span class="dt">Node</span> (<span class="dt">Leaf</span> <span class="dv">4</span>) <span class="dv">5</span> (<span class="dt">Leaf</span> <span class="dv">6</span>)</a>
<a class="sourceLine" id="cb7-4" data-line-number="4"></a>
<a class="sourceLine" id="cb7-5" data-line-number="5"><span class="fu">$&gt;</span> elems <span class="fu">=</span> contents t</a>
<a class="sourceLine" id="cb7-6" data-line-number="6">[<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>,<span class="dv">4</span>,<span class="dv">5</span>,<span class="dv">6</span>]</a></code></pre></div>
<p>We will continue to use this tree <code>t</code> in future examples.</p>
<h2 id="extracting-shape">Extracting shape</h2>
<p>To extract the shape of the collection we want to <code>traverse</code> it ignoring all elements. The right applicative to do that is <code>Identity</code> found in <code>Data.Functor</code> in the <a href="https://hackage.haskell.org/package/transformers">transformers</a> package, or in a modern enough ghc base (&gt;= 4.8.0.0)</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb8-1" data-line-number="1"><span class="kw">newtype</span> <span class="dt">Identity</span> a <span class="fu">=</span> <span class="dt">Identity</span> {<span class="ot"> runIdentity ::</span> a }</a>
<a class="sourceLine" id="cb8-2" data-line-number="2"></a>
<a class="sourceLine" id="cb8-3" data-line-number="3"><span class="kw">instance</span> <span class="dt">Applicative</span> <span class="dt">Identity</span> <span class="kw">where</span></a>
<a class="sourceLine" id="cb8-4" data-line-number="4">    pure  <span class="fu">=</span> <span class="dt">Identity</span></a>
<a class="sourceLine" id="cb8-5" data-line-number="5">    <span class="dt">Identity</span> f (<span class="fu">&lt;*&gt;</span>) <span class="dt">Identity</span> a <span class="fu">=</span> <span class="dt">Identity</span> (f a)</a></code></pre></div>
<p>This applicative basically “does nothing”, which is what we want to extract the shape, no effects. Using this applicative and <code>traverse</code> we can write</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb9-1" data-line-number="1"><span class="ot">shapeBody ::</span> a <span class="ot">-&gt;</span> <span class="dt">Identity</span> ()</a>
<a class="sourceLine" id="cb9-2" data-line-number="2">shapeBody _ <span class="fu">=</span> <span class="dt">Identity</span> ()</a>
<a class="sourceLine" id="cb9-3" data-line-number="3"></a>
<a class="sourceLine" id="cb9-4" data-line-number="4">shape</a>
<a class="sourceLine" id="cb9-5" data-line-number="5"><span class="ot">  ::</span> <span class="dt">Traversable</span> t</a>
<a class="sourceLine" id="cb9-6" data-line-number="6">  <span class="ot">=&gt;</span> t a <span class="ot">-&gt;</span> t ()</a>
<a class="sourceLine" id="cb9-7" data-line-number="7">shape <span class="fu">=</span> runIdentity <span class="fu">.</span> traverse shapeBody</a>
<a class="sourceLine" id="cb9-8" data-line-number="8"></a>
<a class="sourceLine" id="cb9-9" data-line-number="9"><span class="fu">$&gt;</span> shape t</a>
<a class="sourceLine" id="cb9-10" data-line-number="10"><span class="dt">Node</span> (<span class="dt">Node</span> (<span class="dt">Leaf</span> ()) () <span class="dt">Empty</span>) () (<span class="dt">Node</span> (<span class="dt">Leaf</span> ()) () (<span class="dt">Leaf</span> ()))</a></code></pre></div>
<h2 id="contents-and-shape-in-one-pass">Contents and shape in one pass</h2>
<p>If we want to compute both the contents <em>and</em> the shape, we can call <code>traverse</code> twice, but there is a better way. The product of two applicatives is guaranteed to be an applicative, unlike for instance the product of two monads. That means that we can write in a generic way the applicative instance for an arbitrary pair of applicatives. The <code>base</code> package already has this <code>Product</code> type in <code>Data.Functor.Product</code></p>
<div class="sourceCode" id="cb10"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb10-1" data-line-number="1"><span class="kw">data</span> <span class="dt">Product</span> f g a <span class="fu">=</span> <span class="dt">Pair</span> (f a) (g a)</a>
<a class="sourceLine" id="cb10-2" data-line-number="2"></a>
<a class="sourceLine" id="cb10-3" data-line-number="3"><span class="kw">instance</span> (<span class="dt">Applicative</span> f, <span class="dt">Applicative</span> g) <span class="ot">=&gt;</span></a>
<a class="sourceLine" id="cb10-4" data-line-number="4">         <span class="dt">Applicative</span> (<span class="dt">Product</span> f g) <span class="kw">where</span></a>
<a class="sourceLine" id="cb10-5" data-line-number="5">  pure x <span class="fu">=</span> <span class="dt">Pair</span> (pure x) (pure x)</a>
<a class="sourceLine" id="cb10-6" data-line-number="6">  <span class="dt">Pair</span> f g <span class="fu">&lt;*&gt;</span> <span class="dt">Pair</span> x y <span class="fu">=</span> <span class="dt">Pair</span> (f <span class="fu">&lt;*&gt;</span> x) (g <span class="fu">&lt;*&gt;</span> y)</a></code></pre></div>
<p>As we can see, this applicative tracks the effects of <code>f</code> and <code>g</code> in parallel, using a tuple-like <code>Pair</code> constructor.</p>
<p>With this, and in a single traversal we can compute both the contents and the shape:</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb11-1" data-line-number="1"><span class="ot">prod ::</span> (a <span class="ot">-&gt;</span> m b) <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> n b) <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> <span class="dt">Product</span> m n b)</a>
<a class="sourceLine" id="cb11-2" data-line-number="2">prod f g a <span class="fu">=</span> <span class="dt">Pair</span> (f a) (g a)</a>
<a class="sourceLine" id="cb11-3" data-line-number="3"></a>
<a class="sourceLine" id="cb11-4" data-line-number="4">decompose</a>
<a class="sourceLine" id="cb11-5" data-line-number="5"><span class="ot">  ::</span> <span class="dt">Traversable</span> t</a>
<a class="sourceLine" id="cb11-6" data-line-number="6">  <span class="ot">=&gt;</span> t a <span class="ot">-&gt;</span> <span class="dt">Product</span> (<span class="dt">Const</span> [a]) <span class="dt">Identity</span> (t ())</a>
<a class="sourceLine" id="cb11-7" data-line-number="7">decompose <span class="fu">=</span> traverse (prod contentsBody shapeBody)</a>
<a class="sourceLine" id="cb11-8" data-line-number="8"></a>
<a class="sourceLine" id="cb11-9" data-line-number="9"><span class="fu">$&gt;</span> decompose t</a>
<a class="sourceLine" id="cb11-10" data-line-number="10"><span class="dt">Pair</span></a>
<a class="sourceLine" id="cb11-11" data-line-number="11">  (<span class="dt">Const</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>])</a>
<a class="sourceLine" id="cb11-12" data-line-number="12">  (<span class="dt">Identity</span> (<span class="dt">Node</span> (<span class="dt">Node</span> (<span class="dt">Leaf</span> ()) () <span class="dt">Empty</span>)</a>
<a class="sourceLine" id="cb11-13" data-line-number="13">                  ()</a>
<a class="sourceLine" id="cb11-14" data-line-number="14">                  (<span class="dt">Node</span> (<span class="dt">Leaf</span> ()) () (<span class="dt">Leaf</span> ()))))</a></code></pre></div>
<h2 id="reconstructing">Reconstructing</h2>
<p>Now the paper proposes to reconstruct the original traversable from it’s shape and contents as extracted in the previous sections. This sounds like a fold, but we can also think about it as a stateful computation. The state being tracked is the list of elements, the contents. For each element of the desired shape, we extract the first element from the state and leave the rest in the new state. Since every monad is an applicative we know we’ll be able to use the <code>State</code> monad in a call to <code>traverse</code>.</p>
<p>But there is a one extra detail to take into account. If the number of elements provided as content are not enough to fill the shape, we won’t be able to recreate the datastructure. For this reason the end result has to be optional. So we have a combination of a State applicative with a <code>Maybe</code>, in a composition of both effects.</p>
<p>Just like in the case of <code>Product</code> the composition of two applicatives is also an applicative</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb12-1" data-line-number="1"><span class="kw">newtype</span> <span class="dt">Compose</span> f g a <span class="fu">=</span> <span class="dt">Compose</span> {<span class="ot"> getCompose ::</span> f (g a) }</a>
<a class="sourceLine" id="cb12-2" data-line-number="2"></a>
<a class="sourceLine" id="cb12-3" data-line-number="3"><span class="kw">instance</span> (<span class="dt">Applicative</span> f, <span class="dt">Applicative</span> g) <span class="ot">=&gt;</span></a>
<a class="sourceLine" id="cb12-4" data-line-number="4">         <span class="dt">Applicative</span> (<span class="dt">Compose</span> f g) <span class="kw">where</span></a>
<a class="sourceLine" id="cb12-5" data-line-number="5">  pure x <span class="fu">=</span> <span class="dt">Compose</span> (pure (pure x))</a>
<a class="sourceLine" id="cb12-6" data-line-number="6">  <span class="dt">Compose</span> f <span class="fu">&lt;*&gt;</span> <span class="dt">Compose</span> x <span class="fu">=</span> <span class="dt">Compose</span> ((<span class="fu">&lt;*&gt;</span>) <span class="fu">&lt;$&gt;</span> f <span class="fu">&lt;*&gt;</span> x)</a></code></pre></div>
<p>In this form, <code>Compose (State [a]) Maybe</code> gives us the exact combination of effects we want. We can write the function to reassemble now</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb13-1" data-line-number="1">reassemble</a>
<a class="sourceLine" id="cb13-2" data-line-number="2"><span class="ot">  ::</span> <span class="dt">Traversable</span> t</a>
<a class="sourceLine" id="cb13-3" data-line-number="3">  <span class="ot">=&gt;</span> t () <span class="ot">-&gt;</span> <span class="dt">Compose</span> (<span class="dt">State</span> [a]) <span class="dt">Maybe</span> (t a)</a>
<a class="sourceLine" id="cb13-4" data-line-number="4">reassemble <span class="fu">=</span> traverse reassembleBody</a></code></pre></div>
<p>This <code>reassembleBody</code> function must take a <code>()</code> and return the composed stateful/optional computation</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb14-1" data-line-number="1"><span class="ot">reassembleBody ::</span> () <span class="ot">-&gt;</span> <span class="dt">Compose</span> (<span class="dt">State</span> [a]) <span class="dt">Maybe</span> a</a>
<a class="sourceLine" id="cb14-2" data-line-number="2">reassembleBody _ <span class="fu">=</span> <span class="dt">Compose</span> (state takeHead)</a>
<a class="sourceLine" id="cb14-3" data-line-number="3">  <span class="kw">where</span></a>
<a class="sourceLine" id="cb14-4" data-line-number="4">    takeHead (a<span class="fu">:</span>as) <span class="fu">=</span> (<span class="dt">Just</span> a, as)</a>
<a class="sourceLine" id="cb14-5" data-line-number="5">    takeHead [] <span class="fu">=</span> (<span class="dt">Nothing</span>, [])</a></code></pre></div>
<p>Now to reconstruct the datastructure we just need to feed the shape to <code>reassemble</code> and then run the stateful computation resulting</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb15-1" data-line-number="1">reconstruct</a>
<a class="sourceLine" id="cb15-2" data-line-number="2"><span class="ot">  ::</span> <span class="dt">Traversable</span> t</a>
<a class="sourceLine" id="cb15-3" data-line-number="3">  <span class="ot">=&gt;</span> t () <span class="ot">-&gt;</span> [a] <span class="ot">-&gt;</span> <span class="dt">Maybe</span> (t a)</a>
<a class="sourceLine" id="cb15-4" data-line-number="4">reconstruct <span class="fu">=</span> evalState <span class="fu">.</span> getCompose <span class="fu">.</span> reassemble</a></code></pre></div>
<p>Here, we are discarding any extra elements provided.</p>
<h2 id="swapping-data">Swapping data</h2>
<p>With this machinery we can, for instance, write a generic way to <em>swap</em> the contents of two datastructures of differente shapes.</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb16-1" data-line-number="1">swap</a>
<a class="sourceLine" id="cb16-2" data-line-number="2"><span class="ot">  ::</span> (<span class="dt">Traversable</span> s, <span class="dt">Traversable</span> t)</a>
<a class="sourceLine" id="cb16-3" data-line-number="3">  <span class="ot">=&gt;</span> t a <span class="ot">-&gt;</span> s b <span class="ot">-&gt;</span> (<span class="dt">Maybe</span> (t b), <span class="dt">Maybe</span> (s a))</a>
<a class="sourceLine" id="cb16-4" data-line-number="4">swap x y <span class="fu">=</span> (reconstruct xShape yData, reconstruct yShape xData)</a>
<a class="sourceLine" id="cb16-5" data-line-number="5">  <span class="kw">where</span></a>
<a class="sourceLine" id="cb16-6" data-line-number="6">    <span class="dt">Pair</span> (<span class="dt">Const</span> xData) (<span class="dt">Identity</span> xShape) <span class="fu">=</span> decompose x</a>
<a class="sourceLine" id="cb16-7" data-line-number="7">    <span class="dt">Pair</span> (<span class="dt">Const</span> yData) (<span class="dt">Identity</span> yShape) <span class="fu">=</span> decompose y</a>
<a class="sourceLine" id="cb16-8" data-line-number="8">    </a>
<a class="sourceLine" id="cb16-9" data-line-number="9"></a>
<a class="sourceLine" id="cb16-10" data-line-number="10"><span class="fu">$&gt;</span> swap t [<span class="ch">&#39;a&#39;</span><span class="fu">..</span><span class="ch">&#39;f&#39;</span>]</a>
<a class="sourceLine" id="cb16-11" data-line-number="11">( <span class="dt">Just</span> (<span class="dt">Node</span> (<span class="dt">Node</span> (<span class="dt">Leaf</span> <span class="ch">&#39;a&#39;</span>) <span class="ch">&#39;b&#39;</span> <span class="dt">Empty</span>)</a>
<a class="sourceLine" id="cb16-12" data-line-number="12">             <span class="ch">&#39;c&#39;</span></a>
<a class="sourceLine" id="cb16-13" data-line-number="13">             (<span class="dt">Node</span> (<span class="dt">Leaf</span> <span class="ch">&#39;d&#39;</span>) <span class="ch">&#39;e&#39;</span> (<span class="dt">Leaf</span> <span class="ch">&#39;f&#39;</span>)))</a>
<a class="sourceLine" id="cb16-14" data-line-number="14">, <span class="dt">Just</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>])</a>
<a class="sourceLine" id="cb16-15" data-line-number="15"></a>
<a class="sourceLine" id="cb16-16" data-line-number="16"><span class="fu">$&gt;</span> swap t [<span class="ch">&#39;a&#39;</span><span class="fu">..</span><span class="ch">&#39;z&#39;</span>]</a>
<a class="sourceLine" id="cb16-17" data-line-number="17">( <span class="dt">Just</span> (<span class="dt">Node</span> (<span class="dt">Node</span> (<span class="dt">Leaf</span> <span class="ch">&#39;a&#39;</span>) <span class="ch">&#39;b&#39;</span> <span class="dt">Empty</span>)</a>
<a class="sourceLine" id="cb16-18" data-line-number="18">             <span class="ch">&#39;c&#39;</span></a>
<a class="sourceLine" id="cb16-19" data-line-number="19">             (<span class="dt">Node</span> (<span class="dt">Leaf</span> <span class="ch">&#39;d&#39;</span>) <span class="ch">&#39;e&#39;</span> (<span class="dt">Leaf</span> <span class="ch">&#39;f&#39;</span>)))</a>
<a class="sourceLine" id="cb16-20" data-line-number="20">, <span class="dt">Nothing</span>)</a></code></pre></div>
<h2 id="final-notes">Final notes</h2>
<p>It’s a great <a href="https://www.cs.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf">paper</a>, I highly recommend to read it. This shape/contents thing is only a short section in the paper, it goes in several other directions with many other interesting ideas.</p>
<p>If you are an intermediate level Haskell programmer, reading classic papers is great, particularly old ones (this on is from 2009, so not that old). Lots of ideas, plainly explained.</p>
    </div>
</div>
]]></summary>
</entry>
<entry>
    <title>Misunderstanding Conway's law</title>
    <link href="https://blog.sebastian-galkin.com/posts/misunderstanding-conways-law/index.html" />
    <id>https://blog.sebastian-galkin.com/posts/misunderstanding-conways-law/index.html</id>
    <published>2016-01-09T00:00:00Z</published>
    <updated>2016-01-09T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div itemscope itemtype="http://schema.org/Article">
    <h1 itemprop="headline name">Misunderstanding Conway's law</h1>

    <div class="info">
      <time itemprop="datePublished" datetime="2016-01-09">Posted on January  9, 2016</time>
      <div itemscope itemprop="author publisher" itemtype="http://schema.org/Person">
        
            <meta itemprop="name" content="Sebastian Galkin"/>
        
      </div>

      
        <meta itemprop="description" content="Some common mistakes engineering teams make applying Conway's law"/>
      

    </div>
    <div itemprop="articleBody">
      <blockquote>
<p>Any organization that designs a system (defined broadly) will produce a design whose structure is a copy of the organization’s communication structure.</p>
</blockquote>
<p>That statement is what people in the software industry call the <a href="https://en.wikipedia.org/wiki/Conway%27s_law">Conway’s law</a>:</p>
<p>I like the less precise but funnier rendering by Eric S. Raymond:</p>
<blockquote>
<p>If you have four groups working on a compiler, you’ll get a 4-pass compiler.</p>
</blockquote>
<p>I don’t want to discuss the validity of this “law”, the Wikipedia article seems to point to some supporting evidence. My point in this post is not about the validity but about the interpretation of Conway’s law.</p>
<h2 id="what-conways-law-says">What Conway’s law says</h2>
<p>Conway’s law is an impossibility result. It tell us <em>there is no way</em> to have an architecture that doesn’t reflect the organization’s structure.</p>
<p>In particular, Conway’s law doesn’t provide any kind of strategy to find a good architecture. If anything, if Conway’s law is a true statement, it can help avoid time wasted trying to maintain a disagreement between organization structure and architecture.</p>
<h2 id="what-conways-law-doesnt-say">What Conway’s law doesn’t say</h2>
<p>Many software companies, particularly after they reach certain size, tacitly use a different statement, calling it Conway’s law:</p>
<blockquote>
<p>The proper architecture is the one that better reflects the organization’s communication structure</p>
</blockquote>
<ol type="1">
<li>This new statement is <em>absolutely</em> not the Conway’s law. It has little relation to it.</li>
<li>This new statement is neither proven nor obviously true, and in fact it’s pretty arguable.</li>
<li>This new statement is a (poor) strategy to define an architecture.</li>
</ol>
<p>Companies sometimes use their existing communication structure to <em>justify</em> architectural decision. This could be right or wrong, depending on the circumstances, but Conway’s law provides <em>no support</em> for this justification.</p>
<h2 id="common-patterns-and-mistakes">Common patterns and mistakes</h2>
<ul>
<li>Decisions made invoking Conway’s law usually ignore the problem being solved completely. “We should use architecture <code>A</code> because we have organization structure <code>S</code>” is not a statement about software.</li>
<li>Making organizational decisions without taking into account the architecture is always a mistake. And a pretty common one.</li>
<li>Companies solving vastly different problems are usually better served by different architectures. This means they should probably have different communication structures. And yet, copying organizational models is very common in the industry.</li>
<li>When the problem being solved or the solution implemented change significantly, a change in organizational structure should be expected.</li>
</ul>
    </div>
</div>
]]></summary>
</entry>
<entry>
    <title>An exercise using Monoids</title>
    <link href="https://blog.sebastian-galkin.com/posts/an-exercise-on-monoids/index.html" />
    <id>https://blog.sebastian-galkin.com/posts/an-exercise-on-monoids/index.html</id>
    <published>2015-12-28T00:00:00Z</published>
    <updated>2015-12-28T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div itemscope itemtype="http://schema.org/Article">
    <h1 itemprop="headline name">An exercise using Monoids</h1>

    <div class="info">
      <time itemprop="datePublished" datetime="2015-12-28">Posted on December 28, 2015</time>
      <div itemscope itemprop="author publisher" itemtype="http://schema.org/Person">
        
            <meta itemprop="name" content="Sebastian Galkin"/>
        
      </div>

      
        <meta itemprop="description" content="A simple but interesting Haskell problem using Monoids and Foldable"/>
      

    </div>
    <div itemprop="articleBody">
      <p>I found a fun exercise in <em><a href="https://www.manning.com/books/functional-programming-in-scala">“Functional Programming in Scala”</a></em>, a book I’m <a href="/posts/diverse-readings">reading</a> these days. This is the exercise description, slightly generalized and translated to Haskell types:</p>
<blockquote>
<p>Use a <code>Monoid</code> and <code>foldMap</code> to detect if a given <code>Foldable</code> is ordered.</p>
</blockquote>
<p>Let’s start by thinking what the type of the requested function is. The argument is a <code>Foldable</code>, so we will need <code>(Foldable t) =&gt;</code>. Since we want to check for ordering, we will need to compare elements in the datastructure, so we will also need <code>(Ord a) =&gt;</code>. The result will of course be a <code>Bool</code> indicating if the data is sorted. Putting it all together, this is the type of the function we want:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb1-1" data-line-number="1"><span class="ot">isSorted ::</span> (<span class="dt">Foldable</span> t, <span class="dt">Ord</span> a) <span class="ot">=&gt;</span> t a <span class="ot">-&gt;</span> <span class="dt">Bool</span></a></code></pre></div>
<h2 id="specifying-the-function-with-quickcheck">Specifying the function with <code>QuickCheck</code></h2>
<p>Let’s now write down a couple of <a href="https://www.stackage.org/package/QuickCheck">QuickCheck</a> properties for the <code>isSorted</code> function:</p>
<ul>
<li><p><code>isSorted</code> should be true for sorted lists <code>haskell   prop_isSortedForSortedLists :: [Int] -&gt; Bool   prop_isSortedForSortedLists = isSorted . sort</code> if we first sort the list, then <code>isSorted</code> must return <code>True</code>.</p></li>
<li><p>How about unsorted lists? A simple strategy we can use is to compare the output of <code>isSorted</code> to the output of a much simple implementation of the same function. The simplest way I kind think of to know if a list is sorted, is to actually sort it and verify that the result is equal to the original. <code>haskell    prop_isSortedIfSorted :: [Int] -&gt; Bool    prop_isSortedIfSorted as = isSorted as == isSorted'      where isSorted' = sort as == as</code></p></li>
</ul>
<p>The first property is redundant given the second one, but we keep it to make sure we test <code>isSorted</code> with enough sorted lists. Finally, <code>sort as == as</code> is not necessarily equivalent to <code>isSorted</code> unless <code>sort</code> is stable, but Haskell’s list’s <code>sort</code> is in fact stable, and we are good to go.</p>
<h2 id="developing-intuition">Developing intuition</h2>
<p>The exercise asks us to use <a href="http://haddock.stackage.org/nightly-2015-12-29/base-4.8.2.0/Prelude.html#v:foldMap"><code>foldMap</code></a></p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb2-1" data-line-number="1">foldMap<span class="ot"> ::</span> (<span class="dt">Foldable</span> t, <span class="dt">Monoid</span> m) <span class="ot">=&gt;</span> (a <span class="ot">-&gt;</span> m) <span class="ot">-&gt;</span> t a <span class="ot">-&gt;</span> m</a></code></pre></div>
<p>Using <code>foldMap</code> we have the opportunity to transform every element in the data structure by turning it into some <code>Monoid</code> and then use <code>mappend</code> between pairs, starting with <code>mempty</code>. For a list, the end result looks something like:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb3-1" data-line-number="1">foldMap f [a,b,c] <span class="fu">=</span> f a <span class="fu">&lt;&gt;</span> f b <span class="fu">&lt;&gt;</span> f c <span class="fu">&lt;&gt;</span> mempty</a></code></pre></div>
<p><code>&lt;&gt;</code> is simply an infix synonym for <code>mappend</code>, and we don’t need parentheses because <code>mappend</code> is associative.</p>
<p>The key is to find a <code>Monoid</code> that can keep track of the elements it has seen, and make sure the next one is in the right order.</p>
<p>My first intuition was to use some kind of wrapper over <code>Maybe a</code>. <code>Nothing</code> would represent an unsorted element detected, and <code>Just</code> would wrap the right argument to <code>mappend</code>. Something like:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb4-1" data-line-number="1"><span class="kw">newtype</span> <span class="dt">Sorted</span> a <span class="fu">=</span> <span class="dt">S</span> (<span class="dt">Maybe</span> a)</a>
<a class="sourceLine" id="cb4-2" data-line-number="2"></a>
<a class="sourceLine" id="cb4-3" data-line-number="3"><span class="kw">instance</span> (<span class="dt">Ord</span> a) <span class="ot">=&gt;</span> <span class="dt">Monoid</span> (<span class="dt">Sorted</span> a) <span class="kw">where</span></a>
<a class="sourceLine" id="cb4-4" data-line-number="4">  mempty <span class="fu">=</span> <span class="dt">S</span> <span class="dt">Nothing</span></a>
<a class="sourceLine" id="cb4-5" data-line-number="5"></a>
<a class="sourceLine" id="cb4-6" data-line-number="6">  <span class="dt">S</span> <span class="dt">Nothing</span> <span class="ot">`mappend`</span> _ <span class="fu">=</span> <span class="dt">S</span> <span class="dt">Nothing</span></a>
<a class="sourceLine" id="cb4-7" data-line-number="7"></a>
<a class="sourceLine" id="cb4-8" data-line-number="8">  _ <span class="ot">`mappend`</span> <span class="dt">S</span> <span class="dt">Nothing</span> <span class="fu">=</span> <span class="dt">S</span> <span class="dt">Nothing</span></a>
<a class="sourceLine" id="cb4-9" data-line-number="9"></a>
<a class="sourceLine" id="cb4-10" data-line-number="10">  <span class="dt">S</span> (<span class="dt">Just</span> a) <span class="ot">`mappend`</span> <span class="dt">S</span> (<span class="dt">Just</span> b)</a>
<a class="sourceLine" id="cb4-11" data-line-number="11">    <span class="fu">|</span> b <span class="fu">&gt;=</span> a <span class="fu">=</span> <span class="dt">S</span> (<span class="dt">Just</span> b)</a>
<a class="sourceLine" id="cb4-12" data-line-number="12">    <span class="fu">|</span> otherwise <span class="fu">=</span> <span class="dt">S</span> <span class="dt">Nothing</span></a></code></pre></div>
<p>It turns out this simple approach has, at least, two problems:</p>
<ol type="1">
<li><p><code>mempty</code> has the same representation as an unsorted element detection. This means, for instance, that an empty list would be marked as not sorted.</p></li>
<li><p>A more significant problem is that this version of <code>Sorted</code> is not even a <code>Monoid</code> because it doesn’t satisfy the <a href="https://en.wikipedia.org/wiki/Associative_property">associativity law</a>. Let’s see a counterexample: <code>haskell  (S (Just 1) &lt;&gt; S (Just 0)) &lt;&gt; S (Just 1)  = S Nothing &lt;&gt; S (Just 1)  = S Nothing</code> but associating to the right we get: <code>haskell  S (Just 1) &lt;&gt; (S (Just 0)) &lt;&gt; S (Just 1)  = S (Just 1) &lt;&gt; S (Just 1)  = S (Just 1)</code> Those two results should be equal to have a valid <code>Monoid</code></p></li>
</ol>
<p>To fix those problems we need to track more state. Problem 1 requires us to track more state, in particular a way to differentiate <code>mempty</code> from ordering failure. To solve problem 2, maintaining the largest/smallest element is not enough, it introduces associativity problems.</p>
<h2 id="a-solution">A solution</h2>
<p>We will need a type that can distinguish the “nothing is known” case from “ordering failed”. Let’s start with that:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb5-1" data-line-number="1"><span class="kw">data</span> <span class="dt">Sorted</span> a <span class="fu">=</span> <span class="dt">Init</span> <span class="fu">|</span> <span class="dt">Failed</span></a></code></pre></div>
<p><code>Init</code> is the initial, know-nothing state<a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a>. As we mentioned in the previous section, tracking failure and max element is not associative. What we can do instead is to track the full interval as known so far. In this case <code>mappend</code> can expand the interval with each new sorted element, or fail if the new element lies within the previous interval.</p>
<p>Expanding our type to this we get:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb6-1" data-line-number="1"><span class="kw">data</span> <span class="dt">Sorted</span> a <span class="fu">=</span> <span class="dt">Init</span> <span class="fu">|</span> <span class="dt">Failed</span> <span class="fu">|</span> <span class="dt">Range</span> a a</a></code></pre></div>
<p>We will need a way to initialize a <code>Sorted</code> with a single element, but that’s easy, we can create the <code>Range</code> with the element as both start and end of the interval.</p>
<h3 id="the-monoid-instance">The <code>Monoid</code> instance</h3>
<p>Let’s write the <a href="http://haddock.stackage.org/nightly-2015-12-29/base-4.8.2.0/Prelude.html#t:Monoid"><code>Monoid</code></a> for this type</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode numberSource haskell numberLines"><code class="sourceCode haskell"><a class="sourceLine" id="cb7-1" data-line-number="1"><span class="kw">instance</span> (<span class="dt">Ord</span> a) <span class="ot">=&gt;</span> <span class="dt">Monoid</span> (<span class="dt">Sorted</span> a) <span class="kw">where</span></a>
<a class="sourceLine" id="cb7-2" data-line-number="2"></a>
<a class="sourceLine" id="cb7-3" data-line-number="3">  <span class="co">-- we start knowing nothing</span></a>
<a class="sourceLine" id="cb7-4" data-line-number="4">  mempty <span class="fu">=</span> <span class="dt">Init</span></a>
<a class="sourceLine" id="cb7-5" data-line-number="5"></a>
<a class="sourceLine" id="cb7-6" data-line-number="6">  <span class="co">-- failure propagates contagiously</span></a>
<a class="sourceLine" id="cb7-7" data-line-number="7">  <span class="dt">Failed</span>      <span class="ot">`mappend`</span> _           <span class="fu">=</span> <span class="dt">Failed</span></a>
<a class="sourceLine" id="cb7-8" data-line-number="8">  _           <span class="ot">`mappend`</span> <span class="dt">Failed</span>      <span class="fu">=</span> <span class="dt">Failed</span></a>
<a class="sourceLine" id="cb7-9" data-line-number="9"></a>
<a class="sourceLine" id="cb7-10" data-line-number="10">  <span class="co">-- we maintain any information we gain</span></a>
<a class="sourceLine" id="cb7-11" data-line-number="11">  <span class="dt">Init</span>        <span class="ot">`mappend`</span> s           <span class="fu">=</span> s</a>
<a class="sourceLine" id="cb7-12" data-line-number="12">  s           <span class="ot">`mappend`</span> <span class="dt">Init</span>        <span class="fu">=</span> s</a>
<a class="sourceLine" id="cb7-13" data-line-number="13"></a>
<a class="sourceLine" id="cb7-14" data-line-number="14">  <span class="co">-- this is where the detection happens</span></a>
<a class="sourceLine" id="cb7-15" data-line-number="15">  <span class="dt">Range</span> a1 b1 <span class="ot">`mappend`</span> <span class="dt">Range</span> a2 b2</a>
<a class="sourceLine" id="cb7-16" data-line-number="16">    <span class="fu">|</span> a2 <span class="fu">&gt;=</span> b1                      <span class="fu">=</span> <span class="dt">Range</span> a1 b2</a>
<a class="sourceLine" id="cb7-17" data-line-number="17">    <span class="fu">|</span> otherwise                     <span class="fu">=</span> <span class="dt">Failed</span></a></code></pre></div>
<p>If we are <em>mappending</em> over a failure, there is nothing to do, we return the failure. Mappending with <code>Init</code>, returns the new element. In the interesting case, mappending <code>Ranges</code>, we verify if the new range is outside of the interval, and return the new expanded interval, or, if the new element intersects the interval, we fail.</p>
<p>Is this a <code>Monoid</code> now? Let’s see</p>
<ul>
<li><code>mempty &lt;&gt; s = s &lt;&gt; mempty = s</code> is trivially true given the code on lines 11 and 12.</li>
<li><code>Failed</code> on both sides of <code>&lt;&gt;</code> returns <code>Failed</code>, that guarantees associativity when there is a <code>Failed</code> in the equation.</li>
<li>When there is <code>Init &lt;&gt; s</code> or <code>s &lt;&gt; Init</code> we can replace it for <code>s</code>, so we turn the three terms into 2 and associativity holds.</li>
<li>When we have three <code>Ranges</code>
<ul>
<li>If ranges are properly ordered, each <code>&lt;&gt;</code> will expand the range</li>
</ul>
<div class="sourceCode" id="cb8"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb8-1" data-line-number="1">(<span class="dt">Range</span> a1 b1 <span class="fu">&lt;&gt;</span> <span class="dt">Range</span> a2 b2) <span class="fu">&lt;&gt;</span> <span class="dt">Range</span> a3 b3</a>
<a class="sourceLine" id="cb8-2" data-line-number="2"><span class="fu">=</span> <span class="dt">Range</span> a1 b2 <span class="fu">&lt;&gt;</span> <span class="dt">Range</span> a3 b3</a>
<a class="sourceLine" id="cb8-3" data-line-number="3"><span class="fu">=</span> <span class="dt">Range</span> a1 b3</a>
<a class="sourceLine" id="cb8-4" data-line-number="4">and</a>
<a class="sourceLine" id="cb8-5" data-line-number="5"><span class="dt">Range</span> a1 b1 <span class="fu">&lt;&gt;</span> (<span class="dt">Range</span> a2 b2) <span class="fu">&lt;&gt;</span> <span class="dt">Range</span> a3 b3)</a>
<a class="sourceLine" id="cb8-6" data-line-number="6"><span class="fu">=</span> <span class="dt">Range</span> a1 b1 <span class="fu">&lt;&gt;</span> <span class="dt">Range</span> a2 b3</a>
<a class="sourceLine" id="cb8-7" data-line-number="7"><span class="fu">=</span> <span class="dt">Range</span> a1 b3</a></code></pre></div>
<ul>
<li>The case with one or two failing pairs can also be proved easily, left as an exercise.</li>
</ul></li>
</ul>
<h3 id="the-issorted-function">The <code>isSorted</code> function</h3>
<p>Now that we have our <code>Monoid</code> writing <code>isSorted</code> is easy. We need to map over the <code>Foldable</code> creating <code>Sorted</code> values with empty ranges. Then reduce with <code>mappend</code>, and finally verify that we don’t end up with a <code>Failed</code>:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb9-1" data-line-number="1"><span class="ot">isSorted ::</span> (<span class="dt">Foldable</span> t, <span class="dt">Ord</span> a) <span class="ot">=&gt;</span> t a <span class="ot">-&gt;</span> <span class="dt">Bool</span></a>
<a class="sourceLine" id="cb9-2" data-line-number="2">isSorted <span class="fu">=</span> not <span class="fu">.</span> isFailed <span class="fu">.</span> foldMap mkSorted</a>
<a class="sourceLine" id="cb9-3" data-line-number="3"></a>
<a class="sourceLine" id="cb9-4" data-line-number="4"><span class="ot">isFailed ::</span> <span class="dt">Sorted</span> a <span class="ot">-&gt;</span> <span class="dt">Bool</span></a>
<a class="sourceLine" id="cb9-5" data-line-number="5">isFailed <span class="dt">Failed</span> <span class="fu">=</span> <span class="dt">True</span></a>
<a class="sourceLine" id="cb9-6" data-line-number="6">isFailed _ <span class="fu">=</span> <span class="dt">False</span></a>
<a class="sourceLine" id="cb9-7" data-line-number="7"></a>
<a class="sourceLine" id="cb9-8" data-line-number="8"><span class="ot">mkSorted ::</span> a <span class="ot">-&gt;</span> <span class="dt">Sorted</span> a</a>
<a class="sourceLine" id="cb9-9" data-line-number="9">mkSorted a <span class="fu">=</span> <span class="dt">Range</span> a a</a></code></pre></div>
<p>This code passes our specification, we are done.</p>
<h2 id="a-sidenote-on-lazyness">A sidenote on lazyness</h2>
<p>Our code has an interesting property, it can detect non-ordering in partial datastructures. That is, datastructures where <em>bottom</em> is present as an element. Let’s use the <code>Foldable</code> for lists to show this:</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb10-1" data-line-number="1">isSorted [<span class="dv">1</span>, undefined, <span class="dv">2</span>, <span class="dv">1</span>, <span class="dv">3</span>] <span class="fu">=</span> <span class="dt">False</span></a></code></pre></div>
<p>This is nice, and we got it for free. <code>isSorted</code> only inspects the insides of the datastructure as much as it needs to make a decision. Since for lists <code>foldMap</code> is implemented in terms of <code>foldr</code>, we need to “provide evidence” that the list is unsorted to the right of the <code>undefined</code> element.</p>
<p>Let’s see how the evaluation proceeds</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb11-1" data-line-number="1">isSorted [<span class="dv">0</span>, undefined, <span class="dv">2</span>, <span class="dv">1</span>]</a>
<a class="sourceLine" id="cb11-2" data-line-number="2"></a>
<a class="sourceLine" id="cb11-3" data-line-number="3"><span class="co">-- substituting isSorted definition</span></a>
<a class="sourceLine" id="cb11-4" data-line-number="4"><span class="fu">=</span> not <span class="fu">.</span> isFailed <span class="fu">.</span> foldMap mkSorted) <span class="fu">$</span> [<span class="dv">0</span>, undefined, <span class="dv">2</span>, <span class="dv">1</span>]</a>
<a class="sourceLine" id="cb11-5" data-line-number="5"></a>
<a class="sourceLine" id="cb11-6" data-line-number="6"><span class="co">-- substituting foldMap definition</span></a>
<a class="sourceLine" id="cb11-7" data-line-number="7"><span class="fu">=</span> not <span class="fu">.</span> isFailed <span class="fu">.</span> foldr (mappend <span class="fu">.</span> mkSorted) mempty <span class="fu">$</span> [<span class="fu">...</span>]</a>
<a class="sourceLine" id="cb11-8" data-line-number="8"></a>
<a class="sourceLine" id="cb11-9" data-line-number="9"><span class="co">-- substituting foldr definition and defining</span></a>
<a class="sourceLine" id="cb11-10" data-line-number="10"><span class="co">-- ru = Range undefined undefined;</span></a>
<a class="sourceLine" id="cb11-11" data-line-number="11"><span class="co">-- r1 = Range 1 1; r2 = Range 2 2</span></a>
<a class="sourceLine" id="cb11-12" data-line-number="12"><span class="fu">=</span> not <span class="fu">.</span> isFailed <span class="fu">$</span> r1 <span class="fu">&lt;&gt;</span> ru <span class="fu">&lt;&gt;</span> r2 <span class="fu">&lt;&gt;</span> r1 <span class="fu">&lt;&gt;</span> <span class="dt">Init</span></a>
<a class="sourceLine" id="cb11-13" data-line-number="13"><span class="fu">=</span> not <span class="fu">.</span> isFailed <span class="fu">$</span> r1 <span class="fu">&lt;&gt;</span> ru <span class="fu">&lt;&gt;</span> r2 <span class="fu">&lt;&gt;</span> r1</a>
<a class="sourceLine" id="cb11-14" data-line-number="14"><span class="fu">=</span> not <span class="fu">.</span> isFailed <span class="fu">$</span> r1 <span class="fu">&lt;&gt;</span> ru <span class="fu">&lt;&gt;</span> <span class="dt">Failed</span></a></code></pre></div>
<p>At this point we notice that our <code>&lt;&gt;</code> implementation doesn’t evaluate its left <code>Range</code> argument <a href="#fn2" class="footnote-ref" id="fnref2"><sup>2</sup></a> when the right argument is <code>Failed</code>. So, even in the presence of a <code>Range undefined undefined</code>, evaluation can continue as:</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb13-1" data-line-number="1"><span class="fu">=</span> not <span class="fu">.</span> isFailed <span class="fu">$</span> r1 <span class="fu">&lt;&gt;</span> ru <span class="fu">&lt;&gt;</span> <span class="dt">Failed</span></a>
<a class="sourceLine" id="cb13-2" data-line-number="2"><span class="fu">=</span> not <span class="fu">.</span> isFailed <span class="fu">$</span> r1 <span class="fu">&lt;&gt;</span> <span class="dt">Failed</span></a>
<a class="sourceLine" id="cb13-3" data-line-number="3"><span class="fu">=</span> not <span class="fu">.</span> isFailed <span class="fu">$</span> <span class="dt">Failed</span></a>
<a class="sourceLine" id="cb13-4" data-line-number="4"><span class="fu">=</span> not <span class="dt">True</span></a>
<a class="sourceLine" id="cb13-5" data-line-number="5"><span class="fu">=</span> <span class="dt">False</span></a></code></pre></div>
<h2 id="code">Code</h2>
<p>The complete code for the exercise and tests is on <a href="https://github.com/paraseba/blog/blob/master/posts/2015-12-28-an-exercise-on-monoids/code/sorted.hs">GitHub</a></p>
<section class="footnotes">
<hr />
<ol>
<li id="fn1"><p><sup>1</sup> <code>Init</code> is not essential to the problem, it’s an artifact of having to use a <code>Monoid</code>, which requires <code>mempty</code>. An alternative way would be to replace the <code>Monoid</code> with a <code>Semigroup</code> and use <code>foldr1</code> instead of <code>foldMap</code>.<a href="#fnref1" class="footnote-back">↩</a></p></li>
<li id="fn2"><p><sup>2</sup> The first pattern match in our <code>mappend</code> implementation is</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb12-1" data-line-number="1"><span class="dt">Failed</span> <span class="ot">`mappend`</span> _ <span class="fu">=</span> <span class="dt">Failed</span></a></code></pre></div>
<p>So, in fact, <code>&lt;&gt;</code> will evaluate the left argument, but only to <a href="https://wiki.haskell.org/Weak_head_normal_form">Weak Head Normal Form</a>, that is, only enough to know it’s not a <code>Failed</code>, it won’t touch the <code>undefined</code>.<a href="#fnref2" class="footnote-back">↩</a></p></li>
</ol>
</section>
    </div>
</div>
]]></summary>
</entry>
<entry>
    <title>Diverse readings</title>
    <link href="https://blog.sebastian-galkin.com/posts/diverse-readings/index.html" />
    <id>https://blog.sebastian-galkin.com/posts/diverse-readings/index.html</id>
    <published>2015-12-27T00:00:00Z</published>
    <updated>2015-12-27T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div itemscope itemtype="http://schema.org/Article">
    <h1 itemprop="headline name">Diverse readings</h1>

    <div class="info">
      <time itemprop="datePublished" datetime="2015-12-27">Posted on December 27, 2015</time>
      <div itemscope itemprop="author publisher" itemtype="http://schema.org/Person">
        
            <meta itemprop="name" content="Sebastian Galkin"/>
        
      </div>

      
        <meta itemprop="description" content="Some good books I'm currently reading"/>
      

    </div>
    <div itemprop="articleBody">
      <p>I usually read from two, three or more books during the same week. Unless there is one book that I’m so passionate about that I can’t put it down, I prefer different books for different times of the day. I try to read on different topics at the same time too.</p>
<p>Currently these are the books I’m working on:</p>
<h2 id="functional-programming-in-scala">Functional Programming in Scala</h2>
<blockquote>
<p>by <em>Paul Chiusano and Rúnar Bjarnason</em></p>
</blockquote>
<p>It has an excellent approach to introducing functor, applicative and monad. It constructs them out of pattern repetition, by showing that we are writing the same code in many different domains.</p>
<p>Good exercises, and very good real world examples of functional code.</p>
<p><a href="https://www.manning.com/books/functional-programming-in-scala"><img alt="functional programming in scala cover" src="/images/fp-in-scala.jpg" width="70%"/></a></p>
<h2 id="basic-category-theory-for-computer-scientists">Basic Category Theory for Computer Scientists</h2>
<blockquote>
<p>by <em>Benjamin C. Pierce</em></p>
</blockquote>
<p>I’m group reading this with friends. Very short book, seems to be nice and to the point, but too soon to say.</p>
<p><a href="https://mitpress.mit.edu/books/basic-category-theory-computer-scientists"><img alt="basic category theory for computer scientists cover" src="/images/basic-cat-the.jpg" width="70%"/></a></p>
<h2 id="anarchism">Anarchism</h2>
<h3 id="a-collection-of-revolutionary-writings">A Collection of Revolutionary Writings</h3>
<blockquote>
<p>by <em>Peter Kropotkin</em></p>
</blockquote>
<p>This is currently my commute book. A collection of short essays, published originally mostly as pamphlets in Europe, during Kropotkin exile. Kropotkin is quite a character, a former aristocrat, a scientist and mostly a profoundly humane person.</p>
<p>This one gets me plenty of weird looks on the Muni.</p>
<p><a href="https://books.google.com/books?id=eUK8AQAAQBAJ&amp;source=gbs_book_other_versions"><img alt="Anarchis. a collection of revolutionary writings cover" src="/images/anarchism-krop.jpg" width="70%"/></a></p>
    </div>
</div>
]]></summary>
</entry>
<entry>
    <title>Beautiful Power Series</title>
    <link href="https://blog.sebastian-galkin.com/posts/beautiful-power-series/index.html" />
    <id>https://blog.sebastian-galkin.com/posts/beautiful-power-series/index.html</id>
    <published>2015-12-26T00:00:00Z</published>
    <updated>2015-12-26T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div itemscope itemtype="http://schema.org/Article">
    <h1 itemprop="headline name">Beautiful Power Series</h1>

    <div class="info">
      <time itemprop="datePublished" datetime="2015-12-26">Posted on December 26, 2015</time>
      <div itemscope itemprop="author publisher" itemtype="http://schema.org/Person">
        
            <meta itemprop="name" content="Sebastian Galkin"/>
        
      </div>

      
        <meta itemprop="description" content="A tiny Haskell formulation for power series"/>
      

    </div>
    <div itemprop="articleBody">
      <p>I’m getting better at Haskell, or at least that’s what I choose to believe. Anyway, I recently joined Haskell-cafe, one of the e-mail distribution lists, and I found this great <a href="https://mail.haskell.org/pipermail/haskell-cafe/2015-December/122521.html">thread</a> where Kim-Ee Yeoh links to a <strong>gorgeous</strong> article <em><a href="http://www.cs.dartmouth.edu/~doug/powser.html">Power serious: power series in ten one-liners</a></em>.</p>
<p>In the article Doug McIlroy, in a few one-liners, defines infinite power series for trigonometric functions exploiting the power of Haskell’s lazy evaluation.</p>
<p>As a teaser, this is the code for the <code>sin</code> and <code>cos</code> series<a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a>,</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb1-1" data-line-number="1">sins <span class="fu">=</span> int coss</a>
<a class="sourceLine" id="cb1-2" data-line-number="2">coss <span class="fu">=</span> <span class="dv">1</span> <span class="fu">-</span> int sins</a></code></pre></div>
<p>How awesome is that!</p>
<p>I have to find some time to play with the code. It makes me happy that this can be written so simply and beautifully, we must be doing something right.</p>
<section class="footnotes">
<hr />
<ol>
<li id="fn1"><p><sup>1</sup> <code>int</code> is integration and it can also be trivially defined.<a href="#fnref1" class="footnote-back">↩</a></p></li>
</ol>
</section>
    </div>
</div>
]]></summary>
</entry>
<entry>
    <title>Why is Applicative More Efficient Than Monad</title>
    <link href="https://blog.sebastian-galkin.com/posts/why-is-applicative-more-efficient-than-monad/index.html" />
    <id>https://blog.sebastian-galkin.com/posts/why-is-applicative-more-efficient-than-monad/index.html</id>
    <published>2015-12-21T00:00:00Z</published>
    <updated>2015-12-21T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div itemscope itemtype="http://schema.org/Article">
    <h1 itemprop="headline name">Why is Applicative More Efficient Than Monad</h1>

    <div class="info">
      <time itemprop="datePublished" datetime="2015-12-21">Posted on December 21, 2015</time>
      <div itemscope itemprop="author publisher" itemtype="http://schema.org/Person">
        
            <meta itemprop="name" content="Sebastian Galkin"/>
        
      </div>

      
        <meta itemprop="description" content="One reason to use Applicative instead of Monad"/>
      

    </div>
    <div itemprop="articleBody">
      <p>It is well known that <code>Monad</code> is more powerful than <code>Applicative</code> Functor. Using the Monad methods you can implement the Applicative ones, to the point that in recent GHC versions we have</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb1-1" data-line-number="1"><span class="kw">class</span> <span class="dt">Applicative</span> m <span class="ot">=&gt;</span> <span class="dt">Monad</span> m</a></code></pre></div>
<p>with equivalence laws</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb2-1" data-line-number="1">pure <span class="fu">=</span> return</a>
<a class="sourceLine" id="cb2-2" data-line-number="2"></a>
<a class="sourceLine" id="cb2-3" data-line-number="3">(<span class="fu">&lt;*&gt;</span>) <span class="fu">=</span> ap</a></code></pre></div>
<p>and default implementation</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb3-1" data-line-number="1"><span class="ot">ap ::</span> (<span class="dt">Monad</span> m) <span class="ot">=&gt;</span> m (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> m a <span class="ot">-&gt;</span> m b</a>
<a class="sourceLine" id="cb3-2" data-line-number="2">ap m1 m2 <span class="fu">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb3-3" data-line-number="3">  x1 <span class="ot">&lt;-</span> m1</a>
<a class="sourceLine" id="cb3-4" data-line-number="4">  x2 <span class="ot">&lt;-</span> m2</a>
<a class="sourceLine" id="cb3-5" data-line-number="5">  return (x1 x2)</a></code></pre></div>
<p>There are many good examples of Applicatives that are not, and can not be, <code>Monads</code>, like <a href="http://haddock.stackage.org/lts-3.19/either-4.4.1/Data-Either-Validation.html">Validation</a> and <a href="http://haddock.stackage.org/lts-3.19/base-4.8.1.0/Control-Applicative.html#v:ZipList">ZipList</a></p>
<p>But the question I was asking myself these days:</p>
<blockquote>
<p>If we have an Applicative that is also a Monad, is there any reason to prefer <code>&lt;*&gt;</code> over <code>ap</code></p>
</blockquote>
<h2 id="developing-some-intuition">Developing some intuition</h2>
<p>From the Monad laws above we know that in fact they produce the same result, but could important performance differences exist?</p>
<p>Comparing the <code>Monad</code> and <code>Applicative</code> minimal implementations, we can expect some kind of performance difference. After all, with <code>&gt;&gt;=</code> the continuation function has to create the monadic context dynamically:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb4-1" data-line-number="1"><span class="ot">(&gt;&gt;=) ::</span> <span class="dt">Monad</span> m <span class="ot">=&gt;</span> m a <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> m b) <span class="ot">-&gt;</span> m b</a></code></pre></div>
<p>The right argument to <code>&gt;&gt;=</code> has type <code>Monad m =&gt; a -&gt; m b</code>, so it has to create the monadic context during execution. On the other hand, for <code>Applicative</code>, the output context is fully defined by the “program” not by the evaluation of the function:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb5-1" data-line-number="1"><span class="ot">(&lt;*&gt;) ::</span> <span class="dt">Applicative</span> f <span class="ot">=&gt;</span> f (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> f a <span class="ot">-&gt;</span> f b</a></code></pre></div>
<p>When we do <code>ma &gt;&gt;= f</code>, <code>f</code> is in charge of creating the final monadic context. But <code>f :: a -&gt; m b</code> doesn’t have access to the original context it is being chained to. So the new context gets created with no knowledge of the original one.</p>
<p>On the other hand, when we do <code>f k &lt;*&gt; f a</code> the <code>&lt;*&gt;</code> operator itself is in charge of creating the output applicative context, and it does so with access to the initial one. In that way, there is opportunity for optimizing the creation of the output context.</p>
<p>Based on this intuition, let’s try to find an example in a monad where creating the output context could be optimized with the extra knowledge.</p>
<h2 id="an-array-monad">An array Monad</h2>
<p>Regular Haskell Arrays, in <code>Data.Array</code> are not monads or applicatives. They are too powerful, allowing for arbitrary index values. For example, let’s take the right identity law for monads</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb6-1" data-line-number="1">  as <span class="fu">&gt;&gt;=</span> return <span class="fu">=</span> as</a></code></pre></div>
<p><code>as</code> will have certain index values, but we have no way to make <code>return</code> create an array with the same index values <code>as</code> has, for all <code>as</code>. There is no way to satisfy the law.</p>
<p>But we can create our own, much simplified, 1D array that can in fact be turned into a Monad. Let’s write the most basic array, in fact using Haskell’s <code>Data.Array</code> as a backend:</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb7-1" data-line-number="1"><span class="kw">data</span> <span class="dt">Arr</span> a <span class="fu">=</span> <span class="dt">Arr</span> {<span class="ot">toArray ::</span> <span class="fu">!</span>(<span class="dt">Array</span> <span class="dt">Integer</span> a)}</a>
<a class="sourceLine" id="cb7-2" data-line-number="2"></a>
<a class="sourceLine" id="cb7-3" data-line-number="3"><span class="ot">fromList ::</span> [a] <span class="ot">-&gt;</span> <span class="dt">Arr</span> a</a>
<a class="sourceLine" id="cb7-4" data-line-number="4">fromList [] <span class="fu">=</span> error <span class="st">&quot;No empty arrays&quot;</span></a>
<a class="sourceLine" id="cb7-5" data-line-number="5">fromList as <span class="fu">=</span> <span class="dt">Arr</span> <span class="fu">$</span> listArray (<span class="dv">0</span>, genericLength as <span class="fu">-</span> <span class="dv">1</span>) as</a></code></pre></div>
<p>We can only create these arrays from a list. These are terrible arrays, performance is going to be awful, but that’s not the point.</p>
<p>Now we provide instances for <code>Functor</code>, <code>Applicative</code> and <code>Monad</code>.</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb8-1" data-line-number="1"><span class="kw">instance</span> <span class="dt">Functor</span> <span class="dt">Arr</span> <span class="kw">where</span></a>
<a class="sourceLine" id="cb8-2" data-line-number="2">  fmap f <span class="fu">=</span> <span class="dt">Arr</span> <span class="fu">.</span> fmap f <span class="fu">.</span> toArray</a></code></pre></div>
<p>Nothing fancy there, the usual unwrapping and wrapping and delegating to <code>Data.Array</code>’s implementation.</p>
<p>For the <code>&lt;*&gt;</code> to behave similarly to lists, we want to apply every function on the left to every value in the right argument array. We can use list comprehension and the fact that <code>Data.Arrays</code> are <code>Foldable</code> so they provide <code>toList</code>. Since we are at it, we make our <code>Arr</code> also <code>Foldable</code></p>
<div class="sourceCode" id="cb9"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb9-1" data-line-number="1"><span class="kw">instance</span> <span class="dt">Foldable</span> <span class="dt">Arr</span> <span class="kw">where</span></a>
<a class="sourceLine" id="cb9-2" data-line-number="2">  foldMap f <span class="fu">=</span> foldMap f <span class="fu">.</span> toArray</a>
<a class="sourceLine" id="cb9-3" data-line-number="3"></a>
<a class="sourceLine" id="cb9-4" data-line-number="4"><span class="kw">instance</span> <span class="dt">Applicative</span> <span class="dt">Arr</span> <span class="kw">where</span></a>
<a class="sourceLine" id="cb9-5" data-line-number="5">  pure <span class="fu">=</span>  fromList <span class="fu">.</span> pure</a>
<a class="sourceLine" id="cb9-6" data-line-number="6">  fs <span class="fu">&lt;*&gt;</span> as <span class="fu">=</span> fromList [f a <span class="fu">|</span> f <span class="ot">&lt;-</span> toList fs, a <span class="ot">&lt;-</span> toList as]</a></code></pre></div>
<p>Again, this is going to be horrible performance, we turn the arrays into lists, then use the lists for the cartesian product, and finally turn the resulting back into an <code>Arr</code>. The key here is that we only create a single <code>Arr</code>, since we know the applicative contexts on the left and right, we know exactly what the size of the resulting array will be, and we can just construct it.</p>
<p>On the other hand, when we make <code>Arr</code> a <code>Monad</code></p>
<div class="sourceCode" id="cb10"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb10-1" data-line-number="1"><span class="kw">instance</span> <span class="dt">Monad</span> <span class="dt">Arr</span> <span class="kw">where</span></a>
<a class="sourceLine" id="cb10-2" data-line-number="2">  return <span class="fu">=</span> fromList <span class="fu">.</span> return</a>
<a class="sourceLine" id="cb10-3" data-line-number="3">  as <span class="fu">&gt;&gt;=</span> f <span class="fu">=</span> fromList <span class="fu">$</span> concatMap (toList <span class="fu">.</span> f) as</a></code></pre></div>
<p>There is no way around it, each call to <code>f</code> creates a new <code>Arr</code>, and finally we need to create yet another big array. <code>Data.Array</code> is strict on the indexes, this is more work that for the <code>Applicative</code> case.</p>
<h3 id="benchmark">Benchmark</h3>
<p>Let’s run the same operation using both the <code>Applicative</code> and the <code>Monad</code>. The fantastic <a href="http://haddock.stackage.org/lts-3.19/criterion-1.1.0.0/index.html">criterion</a> library can be used to get some numbers.</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb11-1" data-line-number="1"><span class="ot">applicativeWork ::</span> (<span class="dt">Applicative</span> f, <span class="dt">Foldable</span> f, <span class="dt">Num</span> a) <span class="ot">=&gt;</span></a>
<a class="sourceLine" id="cb11-2" data-line-number="2">  f a <span class="ot">-&gt;</span> a</a>
<a class="sourceLine" id="cb11-3" data-line-number="3">applicativeWork as <span class="fu">=</span> sum <span class="fu">$</span> (<span class="fu">+</span>) <span class="fu">&lt;$&gt;</span> as <span class="fu">&lt;*&gt;</span> as</a>
<a class="sourceLine" id="cb11-4" data-line-number="4"></a>
<a class="sourceLine" id="cb11-5" data-line-number="5"><span class="ot">monadWork ::</span> (<span class="dt">Monad</span> f, <span class="dt">Foldable</span> f, <span class="dt">Num</span> a) <span class="ot">=&gt;</span></a>
<a class="sourceLine" id="cb11-6" data-line-number="6">  f a <span class="ot">-&gt;</span> a</a>
<a class="sourceLine" id="cb11-7" data-line-number="7">monadWork as <span class="fu">=</span> sum <span class="fu">$</span> ((<span class="fu">+</span>) <span class="fu">&lt;$&gt;</span> as) <span class="ot">`ap`</span> as</a></code></pre></div>
<p>We sum the results of a cartesian product, both on the applicative context, using <code>&lt;*&gt;</code>, and on the monadic context using <code>ap</code>. And now we drive it with criterion’s <code>defaultMain</code> and a reasonable size. As a control case, we do the same for lists.</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb12-1" data-line-number="1">main <span class="fu">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb12-2" data-line-number="2">  <span class="kw">let</span> n  <span class="fu">=</span> <span class="dv">500</span><span class="ot"> ::</span> <span class="dt">Int</span></a>
<a class="sourceLine" id="cb12-3" data-line-number="3">      l  <span class="fu">=</span> [<span class="dv">0</span><span class="fu">..</span>n]</a>
<a class="sourceLine" id="cb12-4" data-line-number="4">      as <span class="fu">=</span> fromList l</a>
<a class="sourceLine" id="cb12-5" data-line-number="5"></a>
<a class="sourceLine" id="cb12-6" data-line-number="6">  defaultMain [</a>
<a class="sourceLine" id="cb12-7" data-line-number="7">    bgroup <span class="st">&quot;array&quot;</span> [</a>
<a class="sourceLine" id="cb12-8" data-line-number="8">       bench <span class="st">&quot;applicative&quot;</span> <span class="fu">$</span> nf applicativeWork as</a>
<a class="sourceLine" id="cb12-9" data-line-number="9">     , bench <span class="st">&quot;monad&quot;</span>       <span class="fu">$</span> nf monadWork as]</a>
<a class="sourceLine" id="cb12-10" data-line-number="10"></a>
<a class="sourceLine" id="cb12-11" data-line-number="11">   ,bgroup <span class="st">&quot;list&quot;</span> [</a>
<a class="sourceLine" id="cb12-12" data-line-number="12">       bench <span class="st">&quot;applicative&quot;</span> <span class="fu">$</span> nf applicativeWork l</a>
<a class="sourceLine" id="cb12-13" data-line-number="13">     , bench <span class="st">&quot;monad&quot;</span>       <span class="fu">$</span> nf monadWork l]</a>
<a class="sourceLine" id="cb12-14" data-line-number="14">    ]</a></code></pre></div>
<p><img width="100%" src="/images/array-criterion.png" alt="Criterion Array Result"/></p>
<p>We see for <code>Arr</code> the <code>Applicative</code> is around three times faster than the <code>Monad</code>, while for lists, times are exactly the same.</p>
<p>So, that’s one reason to prefer <code>&lt;*&gt;</code> over <code>ap</code>, for some monads the former can be vastly more efficient.</p>
<h2 id="code">Code</h2>
<p>You can find all the source for this post on <a href="https://github.com/paraseba/blog/tree/master/posts/2015-12-21-why-is-applicative-more-efficient-than-monad/code">GitHub</a></p>
    </div>
</div>
]]></summary>
</entry>

</feed>
