<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>Axman6.com</title>
    <link href="https://axman6.com/atom.xml" rel="self" />
    <link href="https://axman6.com" />
    <id>https://axman6.com/atom.xml</id>
    <author>
        <name>Alex Mason</name>
        <email>axman6@gmail.com</email>
    </author>
    <updated>2019-06-08T00:00:00Z</updated>
    <entry>
    <title>What I Wish I Had Remembered a Year Later When I Needed it</title>
    <link href="https://axman6.com/posts/2019-06-08-What-I-Wish-I-Remembered.html" />
    <id>https://axman6.com/posts/2019-06-08-What-I-Wish-I-Remembered.html</id>
    <published>2019-06-08T00:00:00Z</published>
    <updated>2019-06-08T00:00:00Z</updated>
    <summary type="html"><![CDATA[
<figure>
  <img src="/images/fulls/Haskell-Logo.svg" alt="Haskell logo - public domain (https://commons.wikimedia.org/wiki/File:Haskell-Logo.svg)" style="width: 18em; border-radius: 0px 120px 120px 120px;"/>
</figure>

<div class="info">
    Posted on June  8, 2019
    
        by Alex Mason
    
    <a href="#disqus_thread"
       data-disqus-identifier="b9caff7c-cb14-44fa-95ab-4d3b3ee7f6b0"
       class="icon fa-comments disqus-comment-count"
    >
      &nbsp;<span class="label">Comments</span>
    </a>
    
</div>

<p>Over the years I’ve come across more awesome Haskell tools, libraries and ideas than I can remember. I have put together <a href="/Haskell-notes.html">Haskell notes</a>, a place for me to keep notes about cool things I’ve found so in a year from now, when I run intop the problem solved by opne of those things, I’ll remeber it… I hope.</p>


<div id="disqus_thread"></div>
<script>
    /**
     *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
     *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables
     */

    var disqus_config = function () {
        this.page.url = "http://axman6.com/posts/2019-06-08-What-I-Wish-I-Remembered.html";  // Replace PAGE_URL with your page's canonical URL variable
        this.page.identifier = "b9caff7c-cb14-44fa-95ab-4d3b3ee7f6b0"; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
    };

    (function() {  // DON'T EDIT BELOW THIS LINE
        var d = document, s = d.createElement('script');

        s.src = '//axman6.disqus.com/embed.js';

        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);
    })();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript>
]]></summary>
</entry>
<entry>
    <title>Thoughts on the design of Digital Elections</title>
    <link href="https://axman6.com/posts/2017-12-18-Thoughts-on-the-design-of-Digital-Elections.html" />
    <id>https://axman6.com/posts/2017-12-18-Thoughts-on-the-design-of-Digital-Elections.html</id>
    <published>2017-12-18T00:00:00Z</published>
    <updated>2017-12-18T00:00:00Z</updated>
    <summary type="html"><![CDATA[
<div class="info">
    Posted on December 18, 2017
    
        by Alex Mason
    
    <a href="#disqus_thread"
       data-disqus-identifier="07a19e56-54c0-4c77-b824-36e68cf600be"
       class="icon fa-comments disqus-comment-count"
    >
      &nbsp;<span class="label">Comments</span>
    </a>
    
      <h2 class="draft">DRAFT</h2>
    
</div>

<p>I have been thinking for quite some time about how a digital election system should work and the properties that one should hold. Now seemed like as good a time as any to write down these ideas and to see if others can fill in the gaps. A lot of the design I’ve been considering revolves around cryptography, for building both the identification infrastructure and for the ability to independently verify the results. If the properties below can be built with high confidence, then we could come to expect the same level of integrity in our elections that we expect from our <del>banks</del> …</p>
<p>I have been working on the assumption that the properties we expect from modern cryptography are similar to those we’d expect from a voting system, though there are further properties we’d also need to insure:</p>
<ol style="list-style-type: decimal">
<li>The design must be open to all and open to scrutiny</li>
<li>privacy should be guaranteed, only in the event that someone’s private key is compromised should it be possible to tell how someone voted (I can’t think of any way around this one, but it might be possible to provide electors with private keys they have no access to)</li>
<li>it should be possible for any elector to verify that their vote was submitted as they intended</li>
<li>it should be possible for any elector to verify that their vote was counted, and was counted how they expected</li>
<li>it should be possible for any elector to verify that the number of votes is equal to the number of votes submitted</li>
</ol>
<p>I’m a fan of the idea of <a href="https://en.wikipedia.org/wiki/Delegative_democracy">Liquid Democracy</a>, so some other properties I would like to see may also be built on top of this base, but that’s probably for another post. The short version of what it means (at least to me) is all citizens can vote on all subjects, but may delegate this power at any time to another person for a particular subject, and may revoke that delegation at any time, creating a large incentive for people who choose to be representitives to vote the way they have promised to.</p>
<h2 id="open-protocols">Open Protocols</h2>
<p>Any advocate of cryptography will tell you that you shouldn’t trust any crypto which is protected by the fact its implementation is secret. Good crypto must stand up to the harsh light of public disclosure and scrutiny by experts. The same should be true for electronic voting; the protocol must be robust enough that any person can build their own client for casting a vote, and even be able to submit a valid vote created using their own implementation, without any fear that the particular implementation is up to no good. The same is true of the implementation of the server, anyone should be able to take the publicly released information for the authority running the election, and be able to reproduce the the result exactly.</p>
<ul>
<li>the implementation should not actually matter, anyone with sufficient skill should be able to build a client or server alternative and come to the same exact result as the official result</li>
</ul>


<div id="disqus_thread"></div>
<script>
    /**
     *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
     *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables
     */

    var disqus_config = function () {
        this.page.url = "http://axman6.com/posts/2017-12-18-Thoughts-on-the-design-of-Digital-Elections.html";  // Replace PAGE_URL with your page's canonical URL variable
        this.page.identifier = "07a19e56-54c0-4c77-b824-36e68cf600be"; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
    };

    (function() {  // DON'T EDIT BELOW THIS LINE
        var d = document, s = d.createElement('script');

        s.src = '//axman6.disqus.com/embed.js';

        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);
    })();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript>
]]></summary>
</entry>
<entry>
    <title>Announcing amazonka-s3-streaming-0.1</title>
    <link href="https://axman6.com/posts/2016-12-24-Announcing-amazonka-s3-streaming-0.1.html" />
    <id>https://axman6.com/posts/2016-12-24-Announcing-amazonka-s3-streaming-0.1.html</id>
    <published>2016-12-24T00:00:00Z</published>
    <updated>2016-12-24T00:00:00Z</updated>
    <summary type="html"><![CDATA[
<figure>
  <img src="/images/fulls/Storage-Content-Delivery_AmazonS3.svg" alt="Amazon" style="width: 18em; border-radius: 0px 120px 120px 120px;"/>
</figure>

<div class="info">
    Posted on December 24, 2016
    
        by Alex Mason
    
    <a href="#disqus_thread"
       data-disqus-identifier="c525c6fe-96ec-4c2e-b038-105a3638c9ea"
       class="icon fa-comments disqus-comment-count"
    >
      &nbsp;<span class="label">Comments</span>
    </a>
    
</div>

<p>I’ve spent some time over the last week writing <a href="https://hackage.haskell.org/package/amazonka-s3-streaming">amazonka-s3-streaming</a> (<a href="https://github.com/Axman6/amazonka-s3-streaming"><i class="fa fa-github" aria-hidden="true"></i></a>) which provides a conduit based streaming interface for uploading files/data to Amazon’a S3 service. There’s also a way to upload files or strict ByteStrings to S3 concurrently using the async package. The package is based on Brendan Hay’s amazing <a href="https://hackage.haskell.org/package/amazonka">Amazonka</a> (<a href="https://github.com/brendanhay/amazonka"><i class="fa fa-github" aria-hidden="true"></i></a>) suite of libraries.</p>
<p>I’ve tried to make things as efficient as possible, and to avoid excess memory usage if I can. A few of the ways I’ve attempted to do this are:</p>
<h2 id="mmaping-file-segments"><code>mmap</code>ing file segments</h2>
<p>when concurrently uploading a file, each file part (currently 6MiB) is read in using <code>mmap</code>. The ensures that the mappings can be garbage collected as soon as they’re sent, usually resulting in much lower memory usage that mapping the whole file might.</p>
<p>The one big caveat here, which is unlikely to affect many people, but worth keeping in mind is that mmapping ByteStrings can break referential transparancy - if another process modifies the file, the contents of these parks might change.</p>
<h2 id="avoiding-bytestring.builder">Avoiding <code>ByteString.Builder</code></h2>
<p>Initially I was accumulating data in the conduit streaming interface using a ByteString <code>Builder</code>, and then converting this to a Lazy ByteString for upload. It occured to me that</p>
<ol style="list-style-type: lower-alpha">
<li>the bytestrings are already in memory</li>
<li>by converting them to Builders, buffers would be allocated to produce the Lazy ByteString</li>
<li>these buffers would be immediately written to the socket</li>
<li>so why not just use the already allocated ByteStrings and send them to the socket.</li>
</ol>
<p>so I changed the implementation to store a (D)List of ByteStrings until more than 6MiB have been accumulated, and this list is then turned into a conduit <code>Source</code> to be sent by the <code>UploadPart</code> request to S3. I also keep track of the length and the SHA256 hash and total length, which are needed by <code>amazonka</code>.</p>
<p>The Builder based implementation was my initial experiment, and didn’t survive long enough compare the performance with the list based implementation, so I don’t have benchmarks to prove this was a sensible move or not.</p>
<p>My experiments so far have shown that the concurrent upload is capable of saturating a 1Gbps connection quite easily, while using ~70MB RAM uploading a multi-hundred-megabyte file. The streaming interface has managed up to 40MB/s in my testing in GHCi. I’ll update this post once I’m back at work in the new year with some numbers.</p>
<p>I was inspired by <a href="https://github.com/brendanhay/amazonka/issues/343">a question</a> by Alex Babkin about how to stream data into S3. His usecase is pretty cool, wanting to use his <a href="https://github.com/ababkin/qmuli">Qmuli <i class="fa fa-github" aria-hidden="true"></i></a> package to stream data through AWS Lambdas written in Haskell without needing to download the entire file. Hopefully this package will allow this, while using no more than a few tens of MB more RAM than you would expect if you were able to stream the data directly over the network.</p>
<p>I’d love any feedback you’ve got, either here or on <a href="https://www.reddit.com/r/haskell/comments/5k34gg/announcing_amazonkas3streaming01_efficient/">Reddit <i class="fa fa-reddit" aria-hidden="true"></i></a>.</p>


<div id="disqus_thread"></div>
<script>
    /**
     *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
     *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables
     */

    var disqus_config = function () {
        this.page.url = "http://axman6.com/posts/2016-12-24-Announcing-amazonka-s3-streaming-0.1.html";  // Replace PAGE_URL with your page's canonical URL variable
        this.page.identifier = "c525c6fe-96ec-4c2e-b038-105a3638c9ea"; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
    };

    (function() {  // DON'T EDIT BELOW THIS LINE
        var d = document, s = d.createElement('script');

        s.src = '//axman6.disqus.com/embed.js';

        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);
    })();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript>
]]></summary>
</entry>
<entry>
    <title>Linear resources in Haskell</title>
    <link href="https://axman6.com/posts/2016-07-10-Linear-resources-in-haskell.html" />
    <id>https://axman6.com/posts/2016-07-10-Linear-resources-in-haskell.html</id>
    <published>2016-07-10T00:00:00Z</published>
    <updated>2016-07-10T00:00:00Z</updated>
    <summary type="html"><![CDATA[
<figure>
  <img src="/images/fulls/fractal_golden_ratio.jpg" alt="fracme / stockarch.com (http://stockarch.com/images/abstract/patterns/green-shell-lines-2119)" style="width: 18em; border-radius: 0px 120px 120px 120px;"/>
</figure>

<div class="info">
    Posted on July 10, 2016
    
        by Alex Mason
    
    <a href="#disqus_thread"
       data-disqus-identifier="24b218cf-c395-4a06-92f8-99d7a17655ab"
       class="icon fa-comments disqus-comment-count"
    >
      &nbsp;<span class="label">Comments</span>
    </a>
    
</div>

<p>A few months ago, I was reading through <a href="http://benl.ouroborus.net/papers/2016-polarized/dpdf-FHPC2016-sub.pdf">Polarised Data Parallel Data Flow</a>, and noticed there were some invariants which needed to be kept in mind when using the library, mainly that streams must only be consumed once. It seemed to me that with all the power of Haskell’s type system, we could do something about this.</p>
<p>I’d recently seen Gabriele Keller’s <a href="https://www.youtube.com/watch?v=DSOOZyukILI&amp;list=PLIpl4GKFQR6dFB0W9IzF_gcIt1VMRnuco&amp;index=5">Bringing Down the Cost of Verification</a> talk at LambdaJam ’16, and thought that maybe we could use the type system to ensure that</p>
<ul>
<li>Resources are only consumed once</li>
<li>all resources are consumed</li>
</ul>
<p>It turns out you can, but making it nice to work with it harder than I’d hoped. Let’s start with some imports, there’s a lot because we’re using some mildly advanced features in GHC.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">{-# LANGUAGE KindSignatures #-}</span>
<span class="ot">{-# LANGUAGE DataKinds #-}</span>
<span class="ot">{-# LANGUAGE TypeOperators #-}</span>
<span class="ot">{-# LANGUAGE TypeFamilies #-}</span>
<span class="ot">{-# LANGUAGE EmptyDataDecls #-}</span>
<span class="ot">{-# LANGUAGE MagicHash #-}</span>
<span class="ot">{-# LANGUAGE TupleSections #-}</span>
<span class="ot">{-# LANGUAGE ScopedTypeVariables #-}</span>

<span class="kw">module</span> <span class="dt">Main</span> <span class="kw">where</span></code></pre></div>
<p>and some imports</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">import </span><span class="dt">GHC.TypeLits</span>
<span class="kw">import </span><span class="dt">GHC.Prim</span>
<span class="kw">import </span><span class="dt">Data.Type.List</span>
<span class="kw">import </span><span class="dt">Data.Proxy</span>
<span class="kw">import </span><span class="dt">Control.Monad.Indexed</span></code></pre></div>
<p>The most interesting import is <code>Control.Monad.Indexed</code> from the <a href="https://hackage.haskell.org/package/indexed">indexed</a> package, which implements notion of indexed monads (and functors and comonads), which has been much more clearly explained <a href="http://stackoverflow.com/a/28696299/19872">elsewhere</a> than I could have - thanks Conor!</p>
<p>The primary idea I wanted express in the type system was that of a counter which is incremented each time a resource is allocated, and a list of resources which are yet to be consumed. To achieve this, we’ll start with the <code>L</code> type, basically a type level tuple of a <code>Nat</code> (read type level <code>Natural</code>) and a list of <code>Nat</code>s</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">L</span> (<span class="ot">n ::</span> <span class="dt">Nat</span>) (<span class="ot">is ::</span> [<span class="dt">Nat</span>])</code></pre></div>
<p>The <code>L</code> type forms the input and output of our indexed monad. The input <code>Nat</code> tells you how many says how many resources have been allocated before a particular action was invoked, and the output <code>Nat</code> minus the input tells you how many resources were allocated within an action. Similarly, the input and output <code>[Nat]</code>’s tell you which resources haven’t been consumed before and after a particular action. This will make more sense once we’ve introduced the <code>Linear</code> monad.</p>
<p><code>Linear</code> is essentially a monad transformer defined by a newtype wrapping a monad <code>p</code>, with some extra type parameters</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">newtype</span> <span class="dt">Linear</span> p i o a <span class="fu">=</span> <span class="dt">Linear</span> (p a)</code></pre></div>
<p>Now for the indexed monad classes we’ll need:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- ireturn is similar to return or pure, but guarantees</span>
<span class="co">-- through its type that no effects which could change</span>
<span class="co">-- the indices occur.</span>
<span class="kw">class</span> <span class="dt">IxFunctor</span> m <span class="ot">=&gt;</span> <span class="dt">IxPointed</span> m <span class="kw">where</span>
<span class="ot">  ireturn ::</span> a <span class="ot">-&gt;</span> m i i a

<span class="co">-- imap can only change the last type parameter, just like our</span>
<span class="co">-- old friend fmap. Anything that changed in the indexed</span>
<span class="co">-- parameters will still change after being imapped</span>
<span class="kw">class</span> <span class="dt">IxFunctor</span> f <span class="kw">where</span>
<span class="ot">	imap ::</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> f j k a <span class="ot">-&gt;</span> f j k b

<span class="co">-- iap is where things get more interesting - it works</span>
<span class="co">-- just like ap or &lt;*&gt;, but also composes the effects</span>
<span class="co">-- expressed in the indices.</span>
<span class="co">--</span>
<span class="co">-- Notice that the final indices are i and k, and the</span>
<span class="co">-- two actions share j.</span>
<span class="kw">class</span> <span class="dt">IxPointed</span> m <span class="ot">=&gt;</span> <span class="dt">IxApplicative</span> m <span class="kw">where</span>
<span class="ot">	iap ::</span> m i j (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> m j k a <span class="ot">-&gt;</span> m i k b

<span class="co">-- ibind is just like &gt;&gt;= but again composing the indices</span>
<span class="co">-- as above.</span>
<span class="kw">class</span> <span class="dt">IxApplicative</span> m <span class="ot">=&gt;</span> <span class="dt">IxMonad</span> m <span class="kw">where</span>
<span class="ot">	ibind ::</span> (a <span class="ot">-&gt;</span> m j k b) <span class="ot">-&gt;</span> m i j a <span class="ot">-&gt;</span> m i k b</code></pre></div>
<p>The implementations for <code>Linear</code> are trivial, just using non-indexed functions we’re used to in everyday Haskell, with the necessary changes in <code>IxMonad</code> to work with the <code>newtype</code>.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">instance</span> <span class="dt">Functor</span> p <span class="ot">=&gt;</span> <span class="dt">IxFunctor</span> (<span class="dt">Linear</span> p) <span class="kw">where</span>
  imap f (<span class="dt">Linear</span> x) <span class="fu">=</span> <span class="dt">Linear</span> (fmap f x)

<span class="kw">instance</span> <span class="dt">Applicative</span> p <span class="ot">=&gt;</span> <span class="dt">IxPointed</span> (<span class="dt">Linear</span> p) <span class="kw">where</span>
  ireturn x <span class="fu">=</span> <span class="dt">Linear</span> (pure x)

<span class="kw">instance</span> <span class="dt">Applicative</span> p <span class="ot">=&gt;</span> <span class="dt">IxApplicative</span> (<span class="dt">Linear</span> p) <span class="kw">where</span>
  iap (<span class="dt">Linear</span> pf) (<span class="dt">Linear</span> px) <span class="fu">=</span> <span class="dt">Linear</span> (pf <span class="fu">&lt;*&gt;</span> px)

<span class="kw">instance</span> <span class="dt">Monad</span> p <span class="ot">=&gt;</span> <span class="dt">IxMonad</span> (<span class="dt">Linear</span> p) <span class="kw">where</span>
  ibind f (<span class="dt">Linear</span> a) <span class="fu">=</span> <span class="dt">Linear</span> (a <span class="fu">&gt;&gt;=</span> \x <span class="ot">-&gt;</span> <span class="kw">let</span> (<span class="dt">Linear</span> y) <span class="fu">=</span> f x <span class="kw">in</span> y)</code></pre></div>
<p>With this sorted, we can get into the details of managing resources. First, we’ll define a <code>newtype</code> which wraps a Resource, and whose type includes the index it was assigned when it was allocated.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">newtype</span> <span class="dt">Resource</span> (<span class="ot">n ::</span> <span class="dt">Nat</span>) a <span class="fu">=</span> <span class="dt">Res</span> a</code></pre></div>
<p>So how do we allocate a Resource? with <code>allocate</code></p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">allocate ::</span> (m <span class="fu">~</span> (n <span class="fu">+</span> <span class="dv">1</span>)          <span class="co">-- (3)</span>
            , os <span class="fu">~</span> (<span class="dt">Insert</span> n is)  <span class="co">-- (4)</span>
            , <span class="dt">Functor</span> p)
         <span class="ot">=&gt;</span> p a                   <span class="co">-- (1)</span>
         <span class="ot">-&gt;</span> <span class="dt">Linear</span> p
                  (<span class="dt">L</span> n is)        <span class="co">-- (2)</span>
                  (<span class="dt">L</span> m os)        <span class="co">-- (5)</span>
                  (<span class="dt">Resource</span> n a)  <span class="co">-- (6)</span>
allocate x <span class="fu">=</span> <span class="dt">Linear</span> <span class="fu">$</span> fmap <span class="dt">Res</span> x</code></pre></div>
<p>There’s a lot going on in this type, so let’s walk through it.</p>
<ol style="list-style-type: decimal">
<li>The action from the underlying monad is is used to allocate the resoure is passed in. this could be, for example <code>openFile</code> which allocate a file <code>Handle</code></li>
<li>the <code>Linear</code> type is passed <code>n</code>, the current resource allocation count and <code>is</code>, the in scope resources.</li>
<li>Since we’re allocating a new resource, we need to increment the outgoing count</li>
<li>the output has the current index <code>n</code> inserted into the inout - we’ve consumed nothing which was previously in scope, and now we’ve got one more, <code>n</code></li>
<li>the previous two values are used in the output, to be passed to any following actions.</li>
<li>the wrapped resource is returned, marhed with its index.</li>
</ol>
<p>The other side of this is resource consumption. To consume a resource, we need to ensure that the given resource hasn’t been consumed elsewhere, and that once it is consumed, we remove its index from the list of in scope resources.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">consume ::</span> (<span class="dt">Find</span> i is <span class="fu">~</span> <span class="ch">&#39;True, os ~ Remove i is)</span>
        <span class="ot">=&gt;</span> <span class="dt">Resource</span> i a
        <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> p b)
        <span class="ot">-&gt;</span> <span class="dt">Linear</span> p (<span class="dt">L</span> n is) (<span class="dt">L</span> n os) b
consume (<span class="dt">Res</span> x) f <span class="fu">=</span> <span class="dt">Linear</span> (f x)</code></pre></div>
<p>Here we first check that index <code>i</code> is present in the input list of resources <code>is</code>. We also remove set the output list <code>os</code> to the input list with <code>i</code> <code>Remove</code>d. Then we pass in the wrapped resource and the function in the underlying monad which will deallocate the resource.</p>
<p>Along similar lines, we could implement a function for using the resource while it’s in scope but which doesn’t deallocate it - if you wanted to ensure that resources were only ever used once, as in the original problem, then we would omit this function.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">utilise ::</span> (<span class="dt">Find</span> i is <span class="fu">~</span> <span class="ch">&#39;True)</span>
        <span class="ot">=&gt;</span> <span class="dt">Resource</span> i a
        <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> p b)
        <span class="ot">-&gt;</span> <span class="dt">Linear</span> p (<span class="dt">L</span> n is) (<span class="dt">L</span> n is) b
utilise (<span class="dt">Res</span> x) f <span class="fu">=</span> <span class="dt">Linear</span> (f x)</code></pre></div>
<p>Note that the only change is that <code>i</code> is not removed from the output, and everything else is identical to <code>consume</code>.</p>
<p>Finally we can provide a function to run a computation, which ensures that the resource index starts at zero, and ensures that all resources are consumed.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">runLinear ::</span> <span class="dt">KnownNat</span> m <span class="ot">=&gt;</span> <span class="dt">Linear</span> p (<span class="dt">L</span> <span class="dv">0</span> <span class="ch">&#39;[]) (L m &#39;</span>[]) a <span class="ot">-&gt;</span> p a
runLinear (<span class="dt">Linear</span> x) <span class="fu">=</span> x</code></pre></div>
<p>which can be used like so</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">main ::</span> <span class="dt">IO</span> ()
main <span class="fu">=</span> runLinear <span class="fu">$</span>
  allocate openFile <span class="fu">&gt;&gt;&gt;=</span> \f0 <span class="ot">-&gt;</span>
  allocate openFile <span class="fu">&gt;&gt;&gt;=</span> \f1 <span class="ot">-&gt;</span>
  consume f0 closeFile <span class="fu">&gt;&gt;&gt;=</span> \_ <span class="ot">-&gt;</span>
  allocate openFile <span class="fu">&gt;&gt;&gt;=</span> \f2 <span class="ot">-&gt;</span>
  consume f2 closeFile <span class="fu">&gt;&gt;&gt;=</span> \_ <span class="ot">-&gt;</span>
  consume f1 closeFile</code></pre></div>
<p>Notice that the resources are consumed in a different order from the order they were allocated. This is something that differentiates this technique from something like Golang’s <code>defer</code>.</p>
<p>Now for the problem. Using the library works well when used like this, but it doesn’t allow you to define composable actions. The problem is that GHC isn’t s enough to smart enough when composing actions to realise that <code>Find i (Insert i is)</code> is always true when it doesn’t know what <code>is</code> is. I had tried just cons’ing <code>i</code> onto <code>is</code> but this only helps in the situation where a resource being consumed is the most recently allocated one. For example, I can define <code>test1</code> with the type shown, but I can’t define it with either of the other two, which are the types GHC tried to infer</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- test1 :: Linear IO (L n &#39;[]) (L (n+3) &#39;[]) ()</span>
<span class="co">-- test1 :: Linear IO (L n &#39;[]) (L (((n+1)+1)+1) &#39;[]) ()</span>
<span class="ot">test1 ::</span> <span class="dt">Linear</span> <span class="dt">IO</span> (<span class="dt">L</span> <span class="dv">0</span> <span class="ch">&#39;[]) (L 3 &#39;</span>[]) ()
test1 <span class="fu">=</span>
  allocate openFile <span class="fu">&gt;&gt;&gt;=</span> \f0 <span class="ot">-&gt;</span>
  allocate openFile <span class="fu">&gt;&gt;&gt;=</span> \f1 <span class="ot">-&gt;</span>
  consume f0 closeFile <span class="fu">&gt;&gt;&gt;=</span> \_ <span class="ot">-&gt;</span>
  allocate openFile <span class="fu">&gt;&gt;&gt;=</span> \f2 <span class="ot">-&gt;</span>
  consume f2 closeFile <span class="fu">&gt;&gt;&gt;=</span> \_ <span class="ot">-&gt;</span>
  consume f1 closeFile</code></pre></div>
<p>To solve this, I’d love to see type level Sets which allow for tests like <code>Find i (Add i s)</code> to be true for all <code>s</code>.</p>
<p>I’d love to hear what others have to say about this idea, and alternative methods which can be used to implement similar ideas.</p>


<div id="disqus_thread"></div>
<script>
    /**
     *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
     *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables
     */

    var disqus_config = function () {
        this.page.url = "http://axman6.com/posts/2016-07-10-Linear-resources-in-haskell.html";  // Replace PAGE_URL with your page's canonical URL variable
        this.page.identifier = "24b218cf-c395-4a06-92f8-99d7a17655ab"; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
    };

    (function() {  // DON'T EDIT BELOW THIS LINE
        var d = document, s = d.createElement('script');

        s.src = '//axman6.disqus.com/embed.js';

        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);
    })();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript>
]]></summary>
</entry>

</feed>
