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

  <title><![CDATA[Brandon.Si(mmons)]]></title>
  <link href="http://brandon.si/atom.xml" rel="self"/>
  <link href="http://brandon.si/"/>
  <updated>2012-05-15T15:20:00-04:00</updated>
  <id>http://brandon.si/</id>
  <author>
    <name><![CDATA[Brandon Simmons]]></name>
    <email><![CDATA[brandon.m.simmons@gmail.com]]></email>
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[A Simulation of a Biological MIS Algorithm]]></title>
    <link href="http://brandon.si/code/a-simulation-of-a-biological-mis-algorithm/"/>
    <updated>2012-05-14T19:25:00-04:00</updated>
    <id>http://brandon.si/code/a-simulation-of-a-biological-mis-algorithm</id>
    <content type="html"><![CDATA[<p>I&#8217;ve finished a simulation-visualization of the very cool algorithm for
generating a
<a href="http://en.wikipedia.org/wiki/Maximal_independent_set">Maximal Independant Set</a>
from &#8220;A Biological Solution to a Fundamental Distributed Computing Problem&#8221; by
Afek et al. (sorry I don&#8217;t have a link to the PDF, and respect you too much to
link you to a paywall).</p>

<p>You can <a href="http://jberryman.github.com/fly-mis/">play with it</a>
or <a href="https://github.com/jberryman/fly-mis">check out the code</a> on GitHub;
in particular, see
<a href="https://github.com/jberryman/fly-mis/blob/master/algorithm.js">&#8220;algorithm.js&#8221;</a>
for the didactic implementation of the algorithm.</p>

<p>It uses jQuery and <a href="http://raphaeljs.com">Raphael.js</a> for the visuals and
events.</p>

<h2>Goals for the project</h2>

<ol>
<li><p>create a fun visual simulation that can give a nice intuition for the
algorithm</p></li>
<li><p>remain true to the algorithm as described in the paper, and to avoid anything
novel or clever at this point</p></li>
<li><p>attempt to organize my code in such a way as to be a readable explanation of
the algorithm as described in the paper, hiding or isolating implementation
details</p></li>
<li><p>attempt to model the behavior of a real-world network of nodes using the OO
abstraction, and (synchronous) events.</p></li>
</ol>


<p>Trying to meet these demands was revealing. For one thing I was forced to break
up the two message exchange steps into four discrete steps which must be
performed synchronously across the network for things to work without race
conditions.</p>

<h2>Later</h2>

<p>The pseudocode description is hiding some of the complexity and brittleness of
the algorithm IMHO. I&#8217;d like to take it apart and try to rip out as many of the
synchronous-network dependencies as I can, or explore how an identical but
asynchronous system behaves: give all the nodes jittery clocks and without a
coordinated start.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Trenton]]></title>
    <link href="http://brandon.si/art/trenton/"/>
    <updated>2012-05-02T15:44:00-04:00</updated>
    <id>http://brandon.si/art/trenton</id>
    <content type="html"><![CDATA[<p><img src="http://brandon.si/art/prints/trenton/landscape1.jpg" title="this roll has bad emulsion damage" alt="landscape #1" />
<img src="http://brandon.si/art/prints/trenton/landscape2.jpg" title="...and went through too many airport x-rays" alt="landscape #2" />
<img src="http://brandon.si/art/prints/trenton/for_sale.jpg" title="..." alt="For Sale" />
<img src="http://brandon.si/art/prints/trenton/refuse.jpg" alt="Refuse" /></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Converting HTML5 canvas elements to images]]></title>
    <link href="http://brandon.si/code/converting-html5-canvas-elements-to-images/"/>
    <updated>2012-04-30T14:47:00-04:00</updated>
    <id>http://brandon.si/code/converting-html5-canvas-elements-to-images</id>
    <content type="html"><![CDATA[<p>I recently needed to do some conversions/processing to a bunch of HTML files,
which contained html <a href="http://en.wikipedia.org/wiki/Canvas_element">canvas</a>
images, so I needed a way of converting all the canvas elements on the page to
PNGs.</p>

<p>After a bit of research and tweaking, the following worked well enough for me:</p>

<div><script src='https://gist.github.com/2561736.js?file='></script>
<noscript><pre><code>$('canvas').each(function(i,e){ var img = e.toDataURL(&quot;image/png&quot;); $(e).replaceWith(  $('&lt;img src=&quot;'+img+'&quot;/&gt;').attr({width: $(e).attr(&quot;width&quot;), height: $(e).attr(&quot;height&quot;), style: $(e).attr(&quot;style&quot;) }) ) });
</code></pre></noscript></div>


<p>Run it in your browser&#8217;s JS console on the page you want to process (we assume
jQuery is already loaded on the page).</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[reserved for vans]]></title>
    <link href="http://brandon.si/art/reserved-for-vans/"/>
    <updated>2012-04-05T22:32:00-04:00</updated>
    <id>http://brandon.si/art/reserved-for-vans</id>
    <content type="html"><![CDATA[<p><img src="http://brandon.si/art/prints/reserved_for_vans.jpg" title="i am endlessly obsessed with signage, its almost human-like awkwardness" alt="Reserved For Vans" /></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Announcing yet another lens library]]></title>
    <link href="http://brandon.si/code/yall/"/>
    <updated>2012-04-04T21:50:00-04:00</updated>
    <id>http://brandon.si/code/yall</id>
    <content type="html"><![CDATA[<p>I just uploaded the first version of a lens library I&#8217;ve been working on, called
<a href="http://hackage.haskell.org/package/yall">yall</a>. You can get it with a</p>

<pre><code>cabal install yall
</code></pre>

<p>or check it out <a href="https://github.com/jberryman/yall">on github</a>. There will be a
Template Haskell library for automatically deriving lenses at some point in the
future.</p>

<p>I was motivated primarily by the desire for a lens that is acceptable for
<a href="http://hackage.haskell.org/package/pez">pez</a> (existing libs  such as the
excellent <a href="http://hackage.haskell.org/package/fclabels">fclabels</a>
or <a href="http://hackage.haskell.org/package/data-lens">data-lens</a>
didn&#8217;t fit the bill for assorted reasons), and
to explore some abstractions and generalizations re lenses more deeply.</p>

<p>The result is fairly rough at this point, but I&#8217;m interested in feedback.</p>

<h2>Distinguishing features</h2>

<p>This is a bit of copy/paste from the docs I just wrote.</p>

<ul>
<li><p>Lenses are parameterized over two Monads (by convention m and w), and look
like <code>a -&gt; m (b -&gt; w a, b)</code>. this lets us define lenses for sum types, that
perform validation, that do IO (e.g. persist data to disk), etc., etc.</p></li>
<li><p>a module Data.Yall.Iso that complements Lens powerfully</p></li>
<li><p>a rich set of category-level class instances (for now from
<a href="http://hackage.haskell.org/package/categories">categories</a>) for
Lens and Iso. These along with the pre-defined primitive lenses and
combinators give an interface comparable to Arrow</p></li>
</ul>


<h2>Examples</h2>

<p>And here is a little showcase of functionality. First, an illustration of
partial lenses, appropriate for multi-constructor types.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
</pre></td><td class='code'><pre><code class='haskell'><span class='line'><span class="c1">-- First, lenses for a sum type. This is something like what we&#39;ll generate</span>
</span><span class='line'><span class="c1">-- with template haskell.</span>
</span><span class='line'><span class="kr">data</span> <span class="kt">Test</span> <span class="n">a</span> <span class="ow">=</span> <span class="kt">C1</span> <span class="p">{</span> <span class="n">_testString</span> <span class="ow">::</span> <span class="kt">String</span><span class="p">,</span> <span class="n">_testA</span> <span class="ow">::</span> <span class="n">a</span> <span class="p">}</span>
</span><span class='line'>            <span class="o">|</span> <span class="kt">C2</span> <span class="p">{</span> <span class="n">_testString</span> <span class="ow">::</span> <span class="kt">String</span><span class="p">,</span> <span class="n">_testRec</span> <span class="ow">::</span> <span class="kt">Test</span> <span class="n">a</span> <span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="c1">-- pure lens, polymorphic in Monad for composability:</span>
</span><span class='line'><span class="nf">testString</span> <span class="ow">::</span> <span class="p">(</span><span class="kt">Monad</span> <span class="n">w</span><span class="p">,</span> <span class="kt">Monad</span> <span class="n">m</span><span class="p">)</span><span class="ow">=&gt;</span> <span class="kt">Lens</span> <span class="n">w</span> <span class="n">m</span> <span class="p">(</span><span class="kt">Test</span> <span class="n">a</span><span class="p">)</span> <span class="kt">String</span>
</span><span class='line'><span class="nf">testString</span> <span class="ow">=</span> <span class="kt">Lens</span> <span class="o">$</span> <span class="nf">\</span><span class="n">t</span><span class="ow">-&gt;</span> <span class="n">return</span> <span class="p">(</span><span class="nf">\</span><span class="n">s</span><span class="ow">-&gt;</span> <span class="n">return</span> <span class="n">t</span><span class="p">{</span> <span class="n">_testString</span> <span class="ow">=</span> <span class="n">s</span> <span class="p">},</span> <span class="n">_testString</span> <span class="n">t</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="c1">-- lenses that can fail. For now, use Maybe. In the TH library, I&#39;ll probably</span>
</span><span class='line'><span class="c1">-- generate lenses polymorphic in &lt;http://hackage.haskell.org/package/failure&gt;</span>
</span><span class='line'><span class="nf">testA</span> <span class="ow">::</span> <span class="kt">LensM</span> <span class="kt">Maybe</span> <span class="p">(</span><span class="kt">Test</span> <span class="n">a</span><span class="p">)</span> <span class="n">a</span>
</span><span class='line'><span class="nf">testA</span> <span class="ow">=</span> <span class="kt">Lens</span> <span class="n">f</span> <span class="kr">where</span>
</span><span class='line'>    <span class="n">f</span> <span class="p">(</span><span class="kt">C1</span> <span class="n">s</span> <span class="n">a</span><span class="p">)</span> <span class="ow">=</span> <span class="n">return</span> <span class="p">(</span><span class="n">return</span> <span class="o">.</span> <span class="kt">C1</span> <span class="n">s</span><span class="p">,</span> <span class="n">a</span><span class="p">)</span>
</span><span class='line'>    <span class="n">f</span> <span class="kr">_</span> <span class="ow">=</span> <span class="kt">Nothing</span>
</span><span class='line'>
</span><span class='line'><span class="nf">testRec</span> <span class="ow">::</span> <span class="kt">LensM</span> <span class="kt">Maybe</span> <span class="p">(</span><span class="kt">Test</span> <span class="n">a</span><span class="p">)</span> <span class="p">(</span><span class="kt">Test</span> <span class="n">a</span><span class="p">)</span>
</span><span class='line'><span class="nf">testRec</span> <span class="ow">=</span> <span class="kt">Lens</span> <span class="n">f</span> <span class="kr">where</span>
</span><span class='line'>    <span class="n">f</span> <span class="p">(</span><span class="kt">C2</span> <span class="n">s</span> <span class="n">i</span><span class="p">)</span> <span class="ow">=</span> <span class="n">return</span> <span class="p">(</span><span class="n">return</span> <span class="o">.</span> <span class="kt">C2</span> <span class="n">s</span><span class="p">,</span> <span class="n">i</span><span class="p">)</span>
</span><span class='line'>    <span class="n">f</span> <span class="kr">_</span>        <span class="ow">=</span> <span class="kt">Nothing</span>
</span><span class='line'>
</span><span class='line'><span class="c1">-- conposing a pure and partial lens:</span>
</span><span class='line'><span class="nf">demo0</span> <span class="ow">::</span> <span class="kt">Maybe</span> <span class="kt">String</span>
</span><span class='line'><span class="nf">demo0</span> <span class="ow">=</span> <span class="n">getM</span> <span class="p">(</span><span class="n">testString</span> <span class="o">.</span> <span class="n">testRec</span> <span class="o">.</span> <span class="n">testRec</span><span class="p">)</span> <span class="p">(</span><span class="kt">C2</span> <span class="s">&quot;top&quot;</span> <span class="p">(</span><span class="kt">C1</span> <span class="s">&quot;lens will fail&quot;</span> <span class="kt">True</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now an example of a more creative use of monadic getter, allowing us to define
a lens on the &#8220;Nth&#8221; element in a list, returning our results in the <code>[]</code> monad
environment.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='haskell'><span class='line'><span class="c1">-- Here we have a lens with a getter in the list monad, defining a mutable view</span>
</span><span class='line'><span class="c1">-- on the Nth element of the list:</span>
</span><span class='line'><span class="nf">nth</span> <span class="ow">::</span> <span class="kt">LensM</span> <span class="kt">[]</span> <span class="p">[</span><span class="n">a</span><span class="p">]</span> <span class="n">a</span>
</span><span class='line'><span class="nf">nth</span> <span class="ow">=</span> <span class="kt">Lens</span> <span class="o">$</span> <span class="n">foldr</span> <span class="n">nthGS</span> <span class="kt">[]</span>
</span><span class='line'>    <span class="kr">where</span> <span class="n">nthGS</span> <span class="n">n</span> <span class="n">l</span> <span class="ow">=</span> <span class="p">(</span><span class="n">return</span> <span class="o">.</span> <span class="p">(</span><span class="kt">:</span> <span class="n">map</span> <span class="n">snd</span> <span class="n">l</span><span class="p">),</span> <span class="n">n</span><span class="p">)</span> <span class="kt">:</span> <span class="n">map</span> <span class="p">(</span><span class="n">prepend</span> <span class="n">n</span><span class="p">)</span> <span class="n">l</span>
</span><span class='line'>          <span class="n">prepend</span> <span class="ow">=</span> <span class="n">first</span> <span class="o">.</span> <span class="n">fmap</span> <span class="o">.</span> <span class="n">liftM</span> <span class="o">.</span> <span class="p">(</span><span class="kt">:</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="c1">-- This composes nicely. Set the Nth element of our list to 0:</span>
</span><span class='line'><span class="nf">demo1</span> <span class="ow">::</span> <span class="p">[</span> <span class="p">[(</span><span class="kt">Char</span><span class="p">,</span><span class="kt">Int</span><span class="p">)]</span> <span class="p">]</span>
</span><span class='line'><span class="nf">demo1</span> <span class="ow">=</span> <span class="n">setM</span> <span class="p">(</span><span class="n">sndL</span> <span class="o">.</span> <span class="n">nth</span><span class="p">)</span> <span class="mi">0</span> <span class="p">[(</span><span class="sc">&#39;a&#39;</span><span class="p">,</span><span class="mi">1</span><span class="p">),(</span><span class="sc">&#39;b&#39;</span><span class="p">,</span><span class="mi">2</span><span class="p">),(</span><span class="sc">&#39;c&#39;</span><span class="p">,</span><span class="mi">3</span><span class="p">)]</span>
</span></code></pre></td></tr></table></div></figure>


<p>Finally here&#8217;s a bit of a silly example illustrating a lens with Monadic setter
(<code>w</code>) that does IO, in this case persisting a serialized version of the data
we&#8217;re operating on to a text file.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
</pre></td><td class='code'><pre><code class='haskell'><span class='line'><span class="c1">-- persist modifications to a type to a given file. An effect-ful identity lens.</span>
</span><span class='line'><span class="nf">persistL</span> <span class="ow">::</span> <span class="p">(</span><span class="kt">Monad</span> <span class="n">m</span><span class="p">)</span> <span class="ow">=&gt;</span> <span class="kt">FilePath</span> <span class="ow">-&gt;</span> <span class="kt">Lens</span> <span class="kt">IO</span> <span class="n">m</span> <span class="kt">String</span> <span class="kt">String</span>
</span><span class='line'><span class="nf">persistL</span> <span class="n">nm</span> <span class="ow">=</span> <span class="kt">Lens</span> <span class="o">$</span> <span class="nf">\</span><span class="n">s</span><span class="ow">-&gt;</span> <span class="n">return</span> <span class="p">(</span><span class="nf">\</span><span class="n">s&#39;</span><span class="ow">-&gt;</span> <span class="n">writeFile</span> <span class="n">nm</span> <span class="n">s&#39;</span> <span class="o">&gt;&gt;</span> <span class="n">return</span> <span class="n">s&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="c1">-- we&#39;ll use this one:</span>
</span><span class='line'><span class="nf">tmpFile</span> <span class="ow">=</span> <span class="s">&quot;/tmp/yall-test&quot;</span>
</span><span class='line'><span class="nf">printFileContents</span> <span class="ow">=</span> <span class="n">putStrLn</span> <span class="o">.</span> <span class="p">(</span><span class="s">&quot;file contents: &quot;</span> <span class="o">++</span><span class="p">)</span> <span class="o">=&lt;&lt;</span> <span class="n">readFile</span> <span class="n">tmpFile</span>
</span><span class='line'>
</span><span class='line'><span class="c1">-- build a lens with some pre-defined Iso&#39;s that offers a [Int] view on a</span>
</span><span class='line'><span class="c1">-- string that looks like, e.g. &quot;1 2 3 4 5&quot;:</span>
</span><span class='line'><span class="nf">unserializedL</span> <span class="ow">::</span> <span class="p">(</span><span class="kt">Monad</span> <span class="n">w</span><span class="p">,</span> <span class="kt">Monad</span> <span class="n">m</span><span class="p">)</span> <span class="ow">=&gt;</span> <span class="kt">Lens</span> <span class="n">w</span> <span class="n">m</span> <span class="kt">String</span> <span class="p">[</span><span class="kt">Int</span><span class="p">]</span>
</span><span class='line'><span class="nf">unserializedL</span> <span class="ow">=</span> <span class="n">isoL</span> <span class="o">$</span> <span class="n">ifmap</span> <span class="p">(</span><span class="n">inverseI</span> <span class="n">showI</span><span class="p">)</span> <span class="o">.</span> <span class="n">wordsI</span>
</span><span class='line'>
</span><span class='line'><span class="c1">-- now add &quot;persistence&quot; effects to the above lens so everytime we do a &quot;set&quot;</span>
</span><span class='line'><span class="c1">-- we update the file &quot;yall-test&quot; to redlect the new type.</span>
</span><span class='line'><span class="nf">unserializedLP</span> <span class="ow">::</span> <span class="p">(</span><span class="kt">Monad</span> <span class="n">m</span><span class="p">)</span> <span class="ow">=&gt;</span> <span class="kt">Lens</span> <span class="kt">IO</span> <span class="n">m</span> <span class="kt">String</span> <span class="p">[</span><span class="kt">Int</span><span class="p">]</span>
</span><span class='line'><span class="nf">unserializedLP</span> <span class="ow">=</span> <span class="n">unserializedL</span> <span class="o">.</span> <span class="n">persistL</span> <span class="n">tmpFile</span>
</span><span class='line'>
</span><span class='line'><span class="nf">demo2</span> <span class="ow">::</span> <span class="kt">IO</span> <span class="nb">()</span>
</span><span class='line'><span class="nf">demo2</span> <span class="ow">=</span> <span class="kr">do</span>
</span><span class='line'>    <span class="c1">-- apply the lens setter to `mempty` for some Monoid ([Char] in this case)</span>
</span><span class='line'>    <span class="n">str</span> <span class="ow">&lt;-</span> <span class="n">setEmptyW</span> <span class="n">unserializedLP</span> <span class="p">[</span><span class="mi">1</span><span class="o">..</span><span class="mi">5</span><span class="p">]</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">-- LOGGING: the string we got above (by setting [Int]) was written to a file:</span>
</span><span class='line'>    <span class="n">print</span> <span class="n">str</span>
</span><span class='line'>    <span class="n">printFileContents</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">str&#39;</span> <span class="ow">&lt;-</span> <span class="n">modifyW</span> <span class="n">unserializedLP</span> <span class="p">(</span><span class="n">map</span> <span class="p">(</span><span class="o">*</span><span class="mi">2</span><span class="p">)</span> <span class="o">.</span> <span class="p">(</span><span class="mi">6</span> <span class="kt">:</span><span class="p">)</span> <span class="o">.</span> <span class="n">reverse</span><span class="p">)</span> <span class="n">str</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">-- LOGGING: now the file was modified to reflect the changed value:</span>
</span><span class='line'>    <span class="n">print</span> <span class="n">str&#39;</span>
</span><span class='line'>    <span class="n">printFileContents</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Future</h2>

<p>I still need to create TH deriving functionality for the package, and will
announce when that happens. Been busy lately so I&#8217;m not sure when I&#8217;ll get to
it, but let me know your questions/comments/concerns and I&#8217;ll try to address
them promptly.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[the Monoid instance for Ordering]]></title>
    <link href="http://brandon.si/code/the-monoid-instance-for-ordering/"/>
    <updated>2012-04-02T22:01:00-04:00</updated>
    <id>http://brandon.si/code/the-monoid-instance-for-ordering</id>
    <content type="html"><![CDATA[<p>I was just looking at the <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Monoid.html">Monoid</a>
docs, when I found an instance that surprised me: <code>Ordering</code>.</p>

<p>Here is how it&#8217;s defined:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>-- lexicographical ordering
</span><span class='line'>instance Monoid Ordering where
</span><span class='line'>        mempty         = EQ
</span><span class='line'>        LT `mappend` _ = LT
</span><span class='line'>        EQ `mappend` y = y
</span><span class='line'>        GT `mappend` _ = GT</span></code></pre></td></tr></table></div></figure>


<p>Without the comment I don&#8217;t know if I would have gotten it right away, but
check this out:</p>

<pre><code>Prelude&gt; :m + Data.Monoid 
Prelude Data.Monoid&gt; zipWith compare "asff" "asdf"
[EQ,EQ,GT,EQ]
Prelude Data.Monoid&gt; let compare' s = mconcat . zipWith compare s
Prelude Data.Monoid&gt; compare' "asff" "asdf"
GT
</code></pre>

<p>A string comparison function can be defined using the comparisons of
corresponding letters (, numbers, etc.) as Monoids.</p>

<p>It&#8217;s easy to see how <code>mappend</code> defined above works, when you think of it
applied as a left fold on <code>[EQ,EQ,GT,EQ]</code>. But here is the really cool result:
it follows from the definition of a Monoid&#8230;</p>

<pre><code>mappend x (mappend y z) = mappend (mappend x y) z
</code></pre>

<p>that the reduction can take place <em>in any order</em>:</p>

<pre><code>Prelude Data.Monoid&gt; EQ `mappend` EQ `mappend` GT `mappend` EQ
GT
Prelude Data.Monoid&gt; EQ `mappend` (EQ `mappend` GT) `mappend` EQ
GT
Prelude Data.Monoid&gt; EQ `mappend` ((EQ `mappend` GT) `mappend` EQ)
GT
Prelude Data.Monoid&gt; (EQ `mappend` (EQ `mappend` GT)) `mappend` EQ
GT
Prelude Data.Monoid&gt; ((EQ `mappend` EQ) `mappend` GT) `mappend` EQ
</code></pre>

<p>That surprised me!</p>

<p>The wikipedia page for <a href="http://en.wikipedia.org/wiki/Lexicographical_order">Lexicographical order</a>
has some awesome information, and nice illustrations that give a good intuition
about this stuff.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[growth]]></title>
    <link href="http://brandon.si/art/growth/"/>
    <updated>2012-03-26T21:48:00-04:00</updated>
    <id>http://brandon.si/art/growth</id>
    <content type="html"><![CDATA[<p><img src="http://brandon.si/art/prints/growth.jpg" title="a back lot thing" alt="growth" /></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Optimization fun: Minimum Edit Distance]]></title>
    <link href="http://brandon.si/code/optimization-fun-minimum-edit-distance/"/>
    <updated>2012-03-20T22:07:00-04:00</updated>
    <id>http://brandon.si/code/optimization-fun-minimum-edit-distance</id>
    <content type="html"><![CDATA[<p>I&#8217;m doing Stanford&#8217;s free online <a href="NLP%20class">NLP class</a>,
and last week&#8217;s lesson introduced
<a href="http://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein Distance</a>
and the traditional matrix-based algorithm. I implemented
the algorithm in haskell to get a better understanding of it, but then got a bit
obsessive about optimizing.</p>

<p>I wanted to develop an approach iteratively so I&#8217;d learn something along the way,
but I didn&#8217;t take great pains to document the process very well, nor do I have any
analysis here of low level details.</p>

<p>The best version is a github <a href="https://gist.github.com/2149007">gist</a> here if
you want to play with it and optimize further.</p>

<h2>Playing with the algorithm</h2>

<p>First here&#8217;s a very naive declarative approach. This describes the nature of
the problem beautifully, but is slow as hell since we don&#8217;t try to re-use
computations:</p>

<pre><code>medNaive :: String -&gt; String -&gt; Int
medNaive [] s2 = length s2
medNaive s1 [] = length s1
medNaive s1@(c1:cs1) s2@(c2:cs2) = minimum 
    [ medNaive cs1 s2 + 1
    , medNaive s1 cs2 + 1
    , medNaive cs1 cs2 + if c1==c2 then 0 else 2
    ]
</code></pre>

<p>And here&#8217;s a version that is pretty much the standard matrix algorithm.
Because we&#8217;re using a boxed array we can actually query the array while
we build it:</p>

<pre><code>import Data.Array

-- boxed array are what allow for this:
med :: String -&gt; String -&gt; Int
med s1 s2 = 
    let bnd = (length s1, length s2)
        prep = zip [0..] . ('\NUL' :)

        -- a list comprehension might fuse here where do notation doesn't
        a = array ((0,0),bnd) $ do
            (n1,c1) &lt;- prep s1
            (n2,c2) &lt;- prep s2
            let minEd 
                  | n1==0 = n2
                  | n2==0 = n1
                  -- compare w/ min + min:
                  | otherwise = minimum
                      -- insert:
                      [ (a!(n1-1,n2)) + 1
                      -- delete:
                      , (a!(n1,n2-1)) + 1
                      -- substitute:
                      , (a!(n1-1,n2-1)) + if c1==c2 then 0 else 2
                      ]
            return ((n1,n2), minEd)

     in a ! bnd
</code></pre>

<p>Initially, I&#8217;ll be benchmarking with <a href="http://hackage.haskell.org/package/criterion">criterion</a>
on two random 200-character strings. The test <code>main</code> function looks like:</p>

<pre><code>main = defaultMain [
            bench "simple array version" $ whnf (uncurry med) (string1, string2)
            [
</code></pre>

<p>For this initial array version, compiled with <code>-O2</code> we get:</p>

<pre><code>collecting 100 samples, 1 iterations each, in estimated 6.440210 s
mean: 68.72456 ms, lb 68.40039 ms, ub 69.60141 ms, ci 0.950
std dev: 2.539885 ms, lb 1.197168 ms, ub 5.383915 ms, ci 0.950
</code></pre>

<p>But we don&#8217;t need to keep around the entire matrix, especially if we only want
the final edit distance value, so iterating over the first string for each
character of the second string should be a more efficient approach.</p>

<p>Here&#8217;s a version just using lists. This is the logical flavor of the algorithm
we&#8217;ll be using going forward:</p>

<pre><code>medList :: String -&gt; String -&gt; Int
medList s1 = finalCost . foldl' scanS1 (zip [1..] s1, 0) -- 0 is cost comparing nul -&gt; nul
          -- "fills in" what would be a column of our matrix
    where scanS1 (v, costSW_i) c2 = 
              let (_, v') = mapAccumL scanVec (costSW_i, costSW_i + 1) v
                  -- given accumulator corresponding to costs to the southwest
                  -- and south, and the current character and cost from the
                  -- previous step (cost to the west) find min sub-edit:
                  scanVec (costSW, costS) (costW, c1) = 
                     let cost = min (min costS costW + 1)
                                    (costSW + if c1 == c2 then 0 else 2)
                      in ((costW, cost), (cost, c1))
               in (v' , costSW_i + 1)
          finalCost = fst . last . fst
</code></pre>

<p>This runs a bit slower than the array version above, but is a good starting
point for further enhancement:</p>

<pre><code>collecting 100 samples, 1 iterations each, in estimated 9.095287 s
mean: 103.2585 ms, lb 102.7181 ms, ub 103.8645 ms, ci 0.950
std dev: 2.926384 ms, lb 2.473240 ms, ub 3.647964 ms, ci 0.950
</code></pre>

<h2>Vectors</h2>

<p>Let&#8217;s see if we can translate the algorithm we developed with lists to use the
<code>Vector</code> type from the <a href="http://hackage.haskell.org/package/vector">vectors</a>
package, to see how much benefit we can get from the highly-optimized
<a href="http://stackoverflow.com/questions/578063/what-is-haskells-stream-fusion">stream-fusable</a>
operations in that package.</p>

<p>Here we&#8217;ve just replaced one of the lists since there&#8217;s no drop-in replacement
for the <code>mapAccumL</code> we&#8217;re using:</p>

<pre><code>medVec :: String -&gt; String -&gt; Int
medVec s1 = finalCost . V.ifoldl' scanS1 (zip [1..] s1) . V.fromList
    where scanS1 v costSW_i c2 = 
              -- TODO: see if we can turn this into a fold, scanl, or zipWith?
              --       or perhaps accum from Vector?
              let (_, v') = mapAccumL scanVec (costSW_i, costSW_i + 1) v
                  scanVec (costSW, costS) (costW, c1) = 
                     let cost = min (min costS costW + 1)
                                    (costSW + if c1 == c2 then 0 else 2)
                      in ((costW, cost), (cost, c1))
               in v'
          finalCost = fst . last
</code></pre>

<p>This runs about as fast as <code>medList</code> above. We need more <code>Vector</code> juice.</p>

<p>With a little thought we can turn the <code>mapAccumL</code> above into a <code>scan</code> and
iterate our scan over a <code>Vector</code> for S1 as well. Using the strict <code>postscanl'</code>
function here also yielded a huge speed-up from the non-strict version.</p>

<pre><code>medVecFinal :: String -&gt; String -&gt; Int
medVecFinal s1 = V.last . V.ifoldl' scanS1 costs_i . V.fromList
    where vs1 = V.fromList s1
          costs_i =  V.enumFromN 1 $ V.length vs1 -- [0.. length s1]
          scanS1 costs_W costSW_i c2 = 
              let v =  V.zip vs1 costs_W
                  v' =  V.postscanl' scanVec (costSW_i, costSW_i + 1) v
                  scanVec (costSW, costS) (c1, costW) = 
                     (costW, min (min costS costW + 1)
                                 (costSW + if c1 == c2 then 0 else 2))
               in snd $ V.unzip v'
</code></pre>

<p>This is about twice as fast. Sweet!</p>

<pre><code>collecting 100 samples, 2 iterations each, in estimated 9.639692 s
mean: 49.64144 ms, lb 49.33944 ms, ub 49.94830 ms, ci 0.950
std dev: 1.561553 ms, lb 1.359085 ms, ub 1.955104 ms, ci 0.950
</code></pre>

<p>Notice that the code above does no indexing or destructive updates; it&#8217;s
written entirely as though we were working on lists.</p>

<h3>Unboxed Vectors</h3>

<p>By just changing my vector import line to <code>import qualified
Data.Vector.Unboxed.Safe as V</code> I got a huge speed-up on the last
implementation above (15x in fact&#8230; spooky stuff).</p>

<pre><code>collecting 100 samples, 19 iterations each, in estimated 6.332280 s
mean: 3.379753 ms, lb 3.371200 ms, ub 3.391660 ms, ci 0.950
std dev: 51.03072 us, lb 39.59751 us, ub 76.56945 us, ci 0.950
</code></pre>

<p>And it appears to run in constant space which is a good thing.</p>

<p>The LLVM backend didn&#8217;t seem to improve the benchmarks.</p>

<h2>Summary and TODOs</h2>

<p>So our final vector version is about 30x faster than the original list version
we used as a prototype, and it still just looks like list-processing code and
we haven&#8217;t needed to muck around with strictness hints, or INLINE pragma
(not that there aren&#8217;t improvements to be had there).</p>

<p>I would like to play with a further optimization to the algorithm that drops
non-ascending prefixes from the cost vector we iterate over, but ran out of
time. If I mess with that, I&#8217;ll probably explore the effects of destructive
updates at the same time.</p>

<p>Improvements will end up on the gist I linked to above. Feel free to fork and
improve!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[van]]></title>
    <link href="http://brandon.si/art/van/"/>
    <updated>2012-03-14T22:38:00-04:00</updated>
    <id>http://brandon.si/art/van</id>
    <content type="html"><![CDATA[<p><img src="http://brandon.si/art/prints/van.jpg" title="ilford delta 3200. huge grain, yet subtle beautiful tones. I'm in love with the look of the pine branches in the actual print" alt="Van" /></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[shapely-data: a library for structuralizing Haskell data types]]></title>
    <link href="http://brandon.si/code/shapely-data/"/>
    <updated>2012-03-06T20:37:00-05:00</updated>
    <id>http://brandon.si/code/shapely-data</id>
    <content type="html"><![CDATA[<p>This was a quick, on-a-whim sort of project that ended up taking me all week,
as I learned my way around
<a href="http://www.haskell.org/ghc/docs/7.0.2/html/users_guide/template-haskell.html">template haskell</a>.
It felt like trying to make a sandwich with your feet for the first time, and
was about as traumatizing.</p>

<p>Anyway the result is my library named
<a href="http://hackage.haskell.org/package/shapely-data">shapely-data</a>
which you can get with the usual&#8230;</p>

<pre><code>cabal install shapely-data
</code></pre>

<p>and is up on github <a href="https://github.com/jberryman/shapely-data">here</a>.</p>

<p>The library can be used to convert an algebraic data type into a form that
replaces its constructors with a combination of <code>(,)</code>, <code>Either</code> and <code>()</code>. See
the haddocks for usage information, and implementation details.</p>

<p>This first <code>0.0</code> version is very raw. Please let me know if you might find
this useful or have any ideas/feature-requests. If there is any interest I will
polish this thing sooner rather than later.</p>

<h2>Motivation</h2>

<p>I wanted to demonstrate that <code>Either</code> and <code>(,)</code> are haskell&#8217;s primitive sum and
product types, and to show that we can more or less represent any regular type
using these in combination with the unit type (standing in for the empty
constructor a.la <code>Nothing</code>).</p>

<p>So the type</p>

<pre><code>data Foo a = FooPair a a
           | FooInt Int
           | FooEmpty
</code></pre>

<p>can be converted into</p>

<pre><code>newtype ShapelyFoo a = ShapelyFoo { 
    shapelyFoo :: Either (a,a) (Either Int ())
}
</code></pre>

<p>The deeper motivation is that there are a lot of
<a href="http://hackage.haskell.org/package/categories">neat abstractions</a>
(mostly having some relation to category theory) that require some notion of
sums and products, and I don&#8217;t see any better way of representing this notion
in the type system. It seems most straightforward to design abstractions
around <code>(,)</code> and <code>Either</code>.</p>

<p><code>Arrow</code> gets criticized for (among other things) its explicit use of these
types, but a class parameterized over the sum or product type (as in A. Megacz&#8217;
<a href="http://www.cs.berkeley.edu/~megacz/garrows/">&#8220;generalized arrows&#8221;</a>) becomes
complicated and the abstraction breaks down with no suitable way to talk about
products and sums in general AFAICT.</p>

<p>So this gets at the problem from the other direction: we reduce arbitrary
types to haskell&#8217;s primitive sum and product types, allowing code to be written
against these types, and then &#8220;flattening&#8221; the primitive representation back
onto a normal type of the same shape. I&#8217;m imagining list processing using
the <code>ArrowChoice</code> interface on <code>Either (a, List a) ()</code> for instance.</p>

<p>Ultimately maybe this can get us some of the goodness of
<a href="http://en.wikipedia.org/wiki/Structural_type_system">Structural Typing</a>
for certain applications. It&#8217;s also a somewhat lighter-weight approach to
generic programming, and might be useful for:</p>

<ul>
<li>generic view functions and lenses</li>
<li>conversions between similarly-structured data, or &#8220;canonical representations&#8221; of types</li>
<li>incremental <code>Category</code>-level modification of data structures, e.g. with <code>Arrow</code></li>
<li>serializing data types</li>
</ul>


<p>&#8230;but again, I&#8217;m not an expert and this is just scratching a personal itch of
mine.</p>

<h2>TODOs</h2>

<p>Here&#8217;s a quick list of things on my mind of things to do and questions to be
answered for potential future releases:</p>

<ul>
<li>lots of misc. polishing like handling record types, derived instances, etc.</li>
<li>handle constructor-less (bottom) types: <code>data Foo</code></li>
<li>handle recursive types in some intelligent way, so that we can do conversions
between e.g. a custom <code>List a</code> and <code>[a]</code></li>
<li>figure out how to think about ordering of sum types: how can we make <code>Either
Int ()</code> equivalent to <code>Either () Int</code> during conversions? Should we?</li>
<li>what about &#8220;deep&#8221; conversions that also look at a constructor&#8217;s arguments?</li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[United Daughters of the Confederacy]]></title>
    <link href="http://brandon.si/art/united-daughters-of-the-confedracy/"/>
    <updated>2012-02-22T09:24:00-05:00</updated>
    <id>http://brandon.si/art/united-daughters-of-the-confedracy</id>
    <content type="html"><![CDATA[<p><img src="http://brandon.si/art/prints/united_daughters_of_the_confederacy.jpg" title="lots of white" alt="United Daughters of the Confederacy" /></p>

<p>med. format prints here always taken with a yashica 635 TLR and printed at safelight, in Studio Two Three.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[found glasses photograms]]></title>
    <link href="http://brandon.si/art/found-glasses/"/>
    <updated>2012-02-14T15:01:00-05:00</updated>
    <id>http://brandon.si/art/found-glasses</id>
    <content type="html"><![CDATA[<p><img src="http://brandon.si/art/found_glasses_series/1.jpg" title="found glasses 1" alt="found glasses series 1" /></p>

<p><img src="http://brandon.si/art/found_glasses_series/2.jpg" title="found glasses 2" alt="found glasses series 2" /></p>

<p><img src="http://brandon.si/art/found_glasses_series/3.jpg" title="found glasses 3" alt="found glasses series 3" /></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Categories that want to be Arrows]]></title>
    <link href="http://brandon.si/code/categories-that-want-to-be-arrows/"/>
    <updated>2012-02-11T19:35:00-05:00</updated>
    <id>http://brandon.si/code/categories-that-want-to-be-arrows</id>
    <content type="html"><![CDATA[<p>This is me recording some half-formed thoughts that have been rattling around
in my head for the last week. They concern haskell&#8217;s
<a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Arrow.html">Arrow</a>
typeclass; in particular it&#8217;s frustrating inability to be applied to types that
are in <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Category.html">Category</a>
but have no suitable implementation for <code>arr</code>.</p>

<p>Consider something as simple as:</p>

<pre><code>newtype Bij a b = Bij (a -&gt; b) (b -&gt; a)
</code></pre>

<p>a <code>Category</code> instance is trivial, but an <code>Arrow</code> instance is impossible, since
we would need to supply a <code>b -&gt; a</code> given only a <code>a -&gt; b</code>.</p>

<p>And yet most of the <code>Arrow</code> methods (except <code>arr</code> and <code>&amp;&amp;&amp;</code>) would be useful
for, and can be implemented in a very reasonable way, for the type above:</p>

<pre><code>(Bij bc cb) *** (Bij xy yx) = Bij (bc *** xy) (cb *** yx)
first b                     = b *** id
second b                    = id *** b
</code></pre>

<p>We omit <code>&amp;&amp;&amp;</code> above because there isn&#8217;t a reasonable way to define a general
function <code>:: (c -&gt; b) -&gt; (c' -&gt; b) -&gt; ((c,c') -&gt; b</code></p>

<pre><code>(Bij bc cb) &amp;&amp;&amp; (Bij bc' c'b) = Bij (bc &amp;&amp;&amp; bc') undefined
</code></pre>

<p>&#8230;without something like a &#8220;restricted Arrow&#8221; where <code>b</code> is constrained to
<code>Monoid</code>. (but I&#8217;m getting ahead of myself; more on why I don&#8217;t think <code>&amp;&amp;&amp;</code>
belongs in Arrow anyway below).</p>

<p>Or as a <em>reductio ad absurdum</em>, consider simply the following type:</p>

<pre><code>newtype Flipped a b = Flipped (b -&gt; a)
</code></pre>

<p>is there any reason we shouldn&#8217;t have an Arrow-like class for which the above
can be an instance?</p>

<p>None of this is new; it is a <a href="http://www.reddit.com/r/haskell/comments/g7atm/tensor_products_part_2_monoids_and_arrows/c1lpwoh">common complaint</a>
about Arrow: that it is overly complex (to the point of feeling arbitrary),
while being extremely limited.</p>

<h2>Won&#8217;t someone think of the Lenses?</h2>

<p>Anyone who has tried to write a
<a href="http://stackoverflow.com/a/5769285/176841">lens</a> library has wished they
could use the Arrow abstraction and slammed their head into a wall for at least
an hour before giving up (except probably Edward Kmett). They just really
<em>ought</em> to be Arrows.</p>

<p>Consider this lens representation:</p>

<pre><code>newtype Lens a b = Lens (a -&gt; (b -&gt; a, b))
</code></pre>

<p><code>&amp;&amp;&amp;</code> will give us the same problems as the (admittedly very similar) <code>Bij</code>
example above, but the other methods <code>(***)</code>,<code>first</code> and <code>second</code> have good
implementations that would even preserve the Lens Laws (they are what you
would expect, but also have some <a href="http://r6research.livejournal.com/23705.html">foundations in CT</a>)</p>

<p>An ArrowChoice implementation should also be no problem to implement while also
being practically useful for lenses.</p>

<p>Again though, <code>arr</code> presents a problem. One might even try to implement it as a
getter combined with a const/&#8221;read-only&#8221; setter continuation like:</p>

<pre><code>arr f = Lens $ \a-&gt; (const a, f a)
</code></pre>

<p>But this violates the first Arrow law <code>arr id = id</code>.</p>

<h2>What is the nature of the problem?</h2>

<p>From the above, it is obvious that we have problems with types where the flow
of the computation is reversed from the order of the type variables. We can
also probably find types that are sort of <em>composite categories</em> with a
natural Category instance but no way to lift a pure computation.</p>

<p>But here&#8217;s another slightly different type of example; a computation with an
associated cost, perhaps defining the &#8220;energy required&#8221; for a certain
transformation:</p>

<pre><code>data Transformation a b = T Int (a -&gt; b)

instance Category Transformation where
    id = T 0 id
    (T n f) . (T n' g) = T (n+n') (f . g)
</code></pre>

<p>Again, this type lends itself well to the parallel composition operators in
Arrow. For instance <code>&amp;&amp;&amp;</code> can capture that composing two transformations into a
single one that &#8220;fans out&#8221; carries the cost of the sum of their energy
requirements:</p>

<pre><code>(T n f) &amp;&amp;&amp; (T n' g) = T (n+n') (f  g)
</code></pre>

<p>But the only logical implementation for <code>arr</code> that we can define,
<code>arr f = T 0 f</code>, breaks the law <code>arr (f &gt;&gt;&gt; g) = arr f &gt;&gt;&gt; arr g</code>.</p>

<p>I started to do a survey of types on hackage that are <code>Category</code> but not
<code>Arrow</code>, but got burnt out at the stage where I had to actually look through
the code. Still this would be a great thing to do.</p>

<h2>Default implementations without <code>arr</code></h2>

<p>If we rip <code>arr</code> out of the Arrow class, we lose a lot of the default methods,
which are implemented in terms of some primitive &#8220;identity-like&#8221; functions
lifted to <code>Arrow</code> with <code>arr</code>. Here are those functions from the main class:</p>

<pre><code>-- second in terms of first, and vice versa:
\(x,y) -&gt; (y,x)
-- &amp;&amp;&amp; in terms of ***:
\b -&gt; (b,b)
</code></pre>

<p>and these are the helpers from <code>ArrowChoice</code>:</p>

<pre><code>-- right in terms of left:
either Right Left
-- ||| in terms of +++:
either id id
</code></pre>

<p>It&#8217;s useful to try to think of implementing these primitive helpers in a given
Category, e.g. for some <code>Category c</code> can we implement <code>swap :: c (x,y) (y,x)</code>?
And for any Category where we can define <code>swap</code> does it follow that we should
always be able to define the corresponding <code>ArrowChoice</code> helper
<code>swapE :: c (Either a b) (Either b a)</code>? If so, then they should be in the same
new sub-class of Category, etc., etc.</p>

<p>I think these primitive helpers would probably be a good basis for the methods
in a new class or set of classes to act as an Arrow alternative.</p>

<h2>what about all those laws?</h2>

<p>Most of the invariants that should hold for an Arrow are defined in terms of
<code>arr</code>, but I think there are probably reasonable replacements, especially since
there was never anything particularly rigorous about the original Arrow laws.</p>

<p>For example, here are some relationships which I think should be expected to
hold:</p>

<ul>
<li><code>first id = second id = id</code></li>
<li><code>f *** g = first f &gt;&gt;&gt; second g</code> (straight from default implementation)</li>
</ul>


<p>but I&#8217;m not very good at this.</p>

<p>I suspect <code>arr</code> is either the anchor that allows for a well-defined Arrow
class, or that all the laws are necessary to deal with the inclusion of <code>arr</code>.
I hope the latter, and that a revised set of laws for Arrow-without-arr would
look simpler and more abstract, like
<a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Monoid.html">Monoid</a>.</p>

<h2>About <code>&amp;&amp;&amp;</code></h2>

<p>While an arrow that can &#8220;fan out&#8221; is useful, this doesn&#8217;t belong in this class
for a number of reasons:</p>

<ol>
<li><p>It doesn&#8217;t depend on <code>Category</code> at all and doesn&#8217;t even require a type of kind <code>* -&gt; * -&gt; *</code>;
since any Arrow
<a href="http://cdsmith.wordpress.com/2011/07/30/arrow-category-applicative-part-i/">can be made an Applicative</a>
anyway, this could be re-written as
<code>(&amp;&amp;&amp;) :: Applicative a=&gt; a c -&gt;  a c' -&gt; a (c,c')</code></p></li>
<li><p>it appears only <em>once</em> in the entire implementation (in the <code>Arrow</code> class
declaration). The Arrow laws don&#8217;t require it, nor do any of the default
class implementations use it.</p></li>
<li><p>because there are many Arrow-like things which have no suitable
implementation for such a function (a bit of circular logic, I know)</p></li>
</ol>


<h2>Concluding remarks</h2>

<p>Arrow fails as a generally-useful and coherent class for composing Categories
vertically or &#8220;in parallel&#8221;, which is I think what people are looking for.</p>

<p>Maybe I can come up with some code soon for a better Arrow. Such a set of
classes would hopefully be simpler, more flexible, and take advantage of the
Arrow = Category + Applicative correspondence.</p>

<p>Also as I was finishing this I just stumbled on
<a href="http://cs-www.cs.yale.edu/c2/images/uploads/ICFP-CCA.pdf">Causal Commutative Arrows</a>
(PDF) which look interesting.</p>

<p>Let me know your thoughts.</p>

<h3>Update 2/13</h3>

<p>Thanks for all the feedback everyone. From the comments I was pointed to Adam
Megacz&#8217;s work on
<a href="http://www.cs.berkeley.edu/~megacz/garrows/">&#8220;generalized arrows&#8221;</a>, and there
are also <a href="http://www.reddit.com/r/haskell/comments/pmp8t/categories_that_want_to_be_arrows_should_arr_and/">a few comments</a>
on the haskell subreddit.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How the Haskell Prelude avoids overlapping instances in Show]]></title>
    <link href="http://brandon.si/code/how-the-haskell-prelude-avoids-overlapping-types-in-show/"/>
    <updated>2012-02-06T21:47:00-05:00</updated>
    <id>http://brandon.si/code/how-the-haskell-prelude-avoids-overlapping-types-in-show</id>
    <content type="html"><![CDATA[<p>In reading about overlapping instances in haskell, I came across <a href="http://hackage.haskell.org/trac/haskell-prime/wiki/OverlappingInstances">this</a>
proposal that mentioned that:</p>

<blockquote><p>[Overlapping types] can sometimes be simulated with the extra-method trick
used in the Show class of the Prelude for showing lists of characters
differently than lists of other things.</p></blockquote>

<p>I&#8217;d never thought about how haskell-98 can support a <code>show "asdf"</code> that returns</p>

<pre><code>"\"asdf\""
</code></pre>

<p>while <code>show [1,2,3,4]</code> returns</p>

<pre><code>"[1,2,3,4]"
</code></pre>

<p>And I was surprised at the complexity of <code>Show</code> when I looked at the <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#t:Show">docs</a> and
implementation (to be honest, I had no idea how the class was implemented or
that <code>show</code> was not the only method).</p>

<p>I thought the &#8220;extra-method trick&#8221; to avoid overlapping types was sufficiently
cool and difficult to understand at first to warrant a short post about it. So
here goes!</p>

<h2>The basic problem</h2>

<p>Remember that</p>

<pre><code>type String = [Char]
</code></pre>

<p>so we can&#8217;t create an instance declaration for it in haskell-98. Something like</p>

<pre><code>instance Show [Char] where
    ...
</code></pre>

<p>would require both <code>FlexibleInstances</code> and would also cause overlapping
instances when we declare</p>

<pre><code>instance Show a=&gt; [a] where
    ...
</code></pre>

<p>since a <code>[Char]</code> is also a <code>Show a=&gt; [a]</code>. This will never do!</p>

<h2>The solution</h2>

<p>To get around this, the Creators added a <code>showList</code> method, which allows an
instance to define how <em>a list of values of its type</em> should be displayed. Here
is the <code>Show</code> class:</p>

<pre><code>-- note: showS is just String -&gt; String, a CPS optimization for building up strings
class Show a where
    showsPrec :: Int -&gt; a -&gt; ShowS
    show :: a -&gt; String
    showList :: [a] -&gt; ShowS
</code></pre>

<p>Here&#8217;s the instance declaration for <code>[a]</code> where I&#8217;ve added the default <code>show</code>
implementation from the class declaration:</p>

<pre><code>instance Show a =&gt; Show [a]  where
    showsPrec _     = showList 
    show x          = shows x ""    -- default  
</code></pre>

<p>after a bit of indirection, we see <code>show str</code> is implemented as:</p>

<pre><code>showList str "" 
</code></pre>

<p>where <code>showList</code> is from the <code>Show</code> instance for <code>Char</code>.</p>

<h2>The &#8220;extra-method&#8221; trick pattern</h2>

<p>So the general pattern here is when you have a perhaps-limited number of
possibly-overlapping, recursive instances</p>

<pre><code>instance Foo (Maybe Int) where
instance Foo (Maybe Bool) where
</code></pre>

<p>you can instead create an instance for the outer constructor:</p>

<pre><code>instance Foo a=&gt; Foo (Maybe a) where
</code></pre>

<p>define a <em>new method</em> (say <code>maybeToFoo :: Maybe a -&gt; Foo</code>). And then delegate
the behavior of <code>Maybe Int</code> and <code>Maybe Char</code> to the <code>Int</code> and <code>Char</code> instances
respectively.</p>

<pre><code>instance Foo Int where
instance Foo Bool where
</code></pre>

<p>Hopefully that makes sense.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Haskell state of the Lens, etc.]]></title>
    <link href="http://brandon.si/code/haskell-state-of-the-lens/"/>
    <updated>2012-01-31T21:40:00-05:00</updated>
    <id>http://brandon.si/code/haskell-state-of-the-lens</id>
    <content type="html"><![CDATA[<p>For my own purposes, I wanted to take a tour of all the various formulations of
lenses on hackage and thought I would post the lightly-curated results here. I
just grepped the package list page for the following terms: lens, label,
record, accessor, editor, and reference.  Some were not sufficiently general to
include here.</p>

<p>Here were the ones implementing &#8220;lens-like&#8221; functionality, loosely in order of
my opinion on their usefulness for my own purposes:</p>

<ul>
<li><a href="http://hackage.haskell.org/package/fclabels">fclabels</a>: straightforward, lenses built on underlying <a href="http://hackage.haskell.org/packages/archive/fclabels/1.1.0.2/doc/html/Data-Label-Abstract.html#t:Point"><code>Point</code> type</a>, with support for lenses that can fail in <code>ArrowZero</code></li>
<li><a href="http://hackage.haskell.org/package/data-lens">data-lens</a>: uses natural <code>a -&gt; (s -&gt; a, s)</code> formulation for lens, leveraging category theory abstractions from the packages created after the breakup of Edward Kmett&#8217;s <code>category-extras</code> (a.k.a. the Big Bang)</li>
<li><a href="http://hackage.haskell.org/package/partial-lens">partial-lens</a>: the above but suppporting failure on the container</li>
<li><a href="http://hackage.haskell.org/package/data-accessor">data-accessor</a>: package description has nice background, implementation (not exported, oddly) is same as Data.Lens, <a href="http://stackoverflow.com/a/5769285/176841">apparently</a> used to have wonky State monad implementation, seems from a similar school as &#8220;lenses&#8221; package</li>
<li><a href="http://hackage.haskell.org/package/state-record">state-record</a>: Lens type composed of simple setter/getter function pair, with TH generator and misc. functions for use with <code>State</code> monad</li>
<li><a href="http://hackage.haskell.org/package/lenses">lenses</a>: based on MonadState/StateT, odd formulation with no concrete type representation for the lens itself</li>
<li><a href="http://hackage.haskell.org/package/edit-lenses">edit-lenses</a>: implementation of ideas from this <a href="http://dmwit.com/papers/201107EL.pdf">paper</a> with demos <a href="http://hackage.haskell.org/package/edit-lenses-demo">here</a>, rather&#8230; involved</li>
<li><a href="http://hackage.haskell.org/package/pointless-lenses-0.0.7">pointless-lenses</a>: based on <a href="http://www.cis.upenn.edu/~bcpierce/papers/newlenses-popl.pdf">this</a> paper. also rather involved, for instance <a href="http://hackage.haskell.org/packages/archive/pointless-lenses/0.0.7/doc/html/src/Generics-Pointless-Lenses-Examples-Examples.html#preOrd_lns">here</a> is a <code>Lens (Tree a) [a]</code></li>
<li><a href="http://hackage.haskell.org/package/recursion-schemes">recursion-schemes</a>: another of EK&#8217;s packages. there&#8217;s allegedly a lens hiding here among the zygohistomorphic prepromorphisms (you think I&#8217;m joking)</li>
</ul>


<p>For an analysis of various approaches to lenses which don&#8217;t necessarily have an
implementation on hackage, <a href="http://twanvl.nl/blog/news/2011-05-19-lenses-talk">these slides</a>
by Twan van Laarhoven were quite good, even without the accompanying talking
human. Conal Elliot&#8217;s <a href="http://conal.net/blog/posts/semantic-editor-combinators">Semantic editor combinators</a>
pattern seems also relevant to mention here.</p>

<p>Here&#8217;s a list of the <a href="http://packdeps.haskellers.com/reverse">reverse dependencies</a>
for these, as a guage of popularity/general usefulness:</p>

<table>
<tr><td>data-accessor</td> <td>46</td></tr>
<tr><td>fclabels</td> <td>33</td></tr>
<tr><td>data-lens</td> <td>12</td> </tr>
<tr><td>pointless-lenses</td> <td>3</td></tr>
<tr><td>recursion-schemes</td> <td>2</td></tr>
</table>


<h3>What about record-y packages?</h3>

<p>As a bonus, here are the packages which attempt to augment or improve on
records. I didn&#8217;t spend much time trying to grok these:</p>

<ul>
<li><a href="http://hackage.haskell.org/package/ixset-1.0.2">ixset</a>: fancy indexable, groupable records gone wild</li>
<li><a href="http://hackage.haskell.org/package/records">records</a>: records as groupable name/value pairs, perhaps similar to ixset</li>
<li><a href="http://hackage.haskell.org/package/has">has</a>: entity-based records, looks novel but don&#8217;t understand it after a quick look</li>
<li><a href="http://hackage.haskell.org/package/grapefruit-records-0.1.0.0">grapefruit-records</a>: record system for grapefruit FRP, haven&#8217;t looked at implementation</li>
<li><a href="http://hackage.haskell.org/package/fields">fields</a>: high-level interface and cute syntax for record operations, built on fclabels, unmaintained</li>
<li><a href="http://hackage.haskell.org/package/setters">setters</a>: just generates &#8220;setter&#8221; functions for record fields using TH</li>
</ul>


<h2>My own thoughts</h2>

<p>The appeal of lenses for me is that they offer a first-class setter/getter on
which one can <a href="http://hackage.haskell.org/package/pez">build abstractions</a>
and more powerful libraries, not simply save the programmer some key strokes.
Lenses that simply throw an error when applied to the wrong constructor are not
suitable for this purpose.</p>

<p>IMHO the only package above that provides a straightforward lens type for real
algebraic data types is the seemingly unused &#8216;partial-lens&#8217; variant on
Data.Lens. In which the simplified representation is:</p>

<pre><code>newtype Lens a b = Lens (a -&gt; Maybe (b -&gt; a, b))
</code></pre>

<p>The &#8216;fclabels&#8217; package is great, but handles failure on <code>set</code> only w/r/t <em>both</em>
the outer value and the inner value to be set. This means we can perform
validation on a data type with its setter (cool!), but means we
cannot partially apply a lens and get back a pure setter <code>b -&gt; a</code> which is a
real problem for me.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[pez v0.1.0 released]]></title>
    <link href="http://brandon.si/code/pez-v0-dot-1-0-released/"/>
    <updated>2012-01-29T11:40:00-05:00</updated>
    <id>http://brandon.si/code/pez-v0-dot-1-0-released</id>
    <content type="html"><![CDATA[<p><a href="http://hackage.haskell.org/packages/archive/pez/0.1.0/doc/html/Data-Label-Zipper.html">pez</a>
is a powerful, generic zipper library that can be used with a minimum of
boilerplate, using <a href="http://hackage.haskell.org/package/fclabels">fclabels</a>
lenses as an interface. This new version supports fclabels 1.0 and uses the new
lenses supporting failure.</p>

<p>The API has changed significantly, but should be more stable at this point. You
can try it with a:</p>

<pre><code>$ cabal install pez
</code></pre>

<p>You can find the code on github <a href="https://github.com/jberryman/pez">here</a>. I
will try to post some fun examples here in the next week or two.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[simple-actors 0.1.0 released]]></title>
    <link href="http://brandon.si/code/simple-actors-0-1-0-released/"/>
    <updated>2011-10-11T14:02:50-04:00</updated>
    <id>http://brandon.si/code/simple-actors-0-1-0-released</id>
    <content type="html"><![CDATA[<p>Just a quick announcement of the release of
<a href="http://hackage.haskell.org/packages/archive/simple-actors/0.1.0/doc/html/Control-Concurrent-Actors.html">simple-actors</a>,
a DSL-style haskell
library for more structured concurrent programs via the
<a href="http://en.wikipedia.org/wiki/Actor_model">Actor Model</a>. You can fork it on
<a href="https://github.com/jberryman/simple-actors">github</a>, and install it via cabal
with a</p>

<pre><code>cabal install simple-actors
</code></pre>

<p>This version is significantly more coherent, powerful and simple than the
original 0.0.1 version (which was something I just whipped together for a blog
post I haven&#8217;t gotten around to writing yet).</p>

<p>Let me know if you have any comments or suggestions!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A brief tutorial-introduction to 'fclabels' 1.0]]></title>
    <link href="http://brandon.si/code/a-brief-tutorial-introduction-to-fclabels-1-0/"/>
    <updated>2011-08-21T14:39:16-04:00</updated>
    <id>http://brandon.si/code/a-brief-tutorial-introduction-to-fclabels-1-0</id>
    <content type="html"><![CDATA[<p>Sebastiaan Visser et al. last week announced the release of v1.0 of
<a href="http://hackage.haskell.org/package/fclabels">fclabels</a>. This is a short
introduction to the changes for people who are already somewhat familiar with
the package.</p>

<blockquote><p><strong>Que?</strong> The fclabels package is a haskell library providing &#8220;first class
labels&#8221; for haskell data types and some Template Haskell code for
automatically generating said labels. This makes for a more composable and
much more powerful alternative to haskell&#8217;s built-in record syntactic sugar.
<a href="http://blog.ezyang.com/2010/04/inessential-guide-to-fclabels/">Here</a> is a
good introductory tutorial.</p></blockquote>

<p>The new version features (besides some better names) a type for
<a href="http://hackage.haskell.org/packages/archive/fclabels/1.0.1/doc/html/Data-Label-Maybe.html">lenses that can fail</a>.
S.V. et al. added this functionality in a brilliant
and mostly (except for the name changes) backwards compatible way. We&#8217;ll see
how it all works now.</p>

<p>We&#8217;ll prepare a module for fclabels in the usual way:</p>

<pre><code>{-# LANGUAGE TemplateHaskell, TypeOperators #-}
import Control.Category
import Data.Label
import qualified Data.Label.Maybe as M
import Prelude hiding ((.), id)
</code></pre>

<p>The only odd thing above is our qualified import of <code>Data.Label.Maybe</code> which
provides getters, setters etc. that can fail.</p>

<p>We want to generate lenses for the following type, so we do the underdash
thing:</p>

<pre><code>data Example = X { _int :: Int , _char :: Char}
             | Y { _int :: Int , _example :: Example }
</code></pre>

<p>Notice how <code>_int</code> is a valid record for <em>both</em> constructors <code>X</code> and <code>Y</code>, where
the other two are partial functions.</p>

<p>Lastly, the usual splice for generating labels:</p>

<pre><code>$(mkLabels[''Example])
</code></pre>

<p>Let&#8217;s load our file into GHCi and play a little:</p>

<pre><code>Prelude&gt; :l test.hs
[1 of 1] Compiling Main             ( test.hs, interpreted )
Ok, modules loaded: Main.
*Main&gt; get int $ X 1 'a'
1
*Main&gt; M.get int $ X 1 'a'
Just 1
*Main&gt; M.get char $ X 1 'a'
Just 'a'
*Main&gt; M.get example $ X 1 'a'
Nothing
*Main&gt; get example $ X 1 'a'
:1:5:
    No instance for (Control.Arrow.ArrowZero (-&gt;))
      arising from a use of `example'
    Possible fix:
      add an instance declaration for (Control.Arrow.ArrowZero (-&gt;))
    In the first argument of `get', namely `example'
    In the expression: get example
    In the expression: get example $ X 1 'a'
</code></pre>

<p>Above we saw that:</p>

<ul>
<li><p>the total <code>int</code> label could be used in both <code>get</code> and <code>Data.Label.Maybe.get</code></p></li>
<li><p>M.get on our &#8220;partial lenses&#8221; (<code>example</code> and <code>char</code>) safely returned a Maybe value.</p></li>
<li><p>pure <code>get</code> used with partial lenses doesn&#8217;t type check</p></li>
</ul>


<p>We need to look at some types (note I&#8217;ve cleaned up some of these type
signatures, yours may look uglier):</p>

<pre><code>*Main&gt; :t get
get :: (f :-&gt; a) -&gt; f -&gt; a
*Main&gt; :t M.get
M.get :: (f M.:~&gt; a) -&gt; f -&gt; Maybe a
*Main&gt; :info (:-&gt;)
type (:-&gt;) f a = Data.Label.Pure.PureLens f a
          -- Defined in Data.Label.Pure
*Main&gt; :info (M.:~&gt;)
type (M.:~&gt;) f a = Data.Label.Maybe.MaybeLens f a
          -- Defined in Data.Label.Maybe
</code></pre>

<p>You can see above that setters and getters are monomorphic. But how then were
we able to use <code>int</code> in both <code>get</code> and <code>M.get</code>? Time to look at the types of
our TH-generated lenses:</p>

<pre><code>*Main&gt; :t int
int
  :: Control.Arrow.Arrow (~&gt;) =&gt; Lens (~&gt;) Example Int
*Main&gt; :t char
char
  :: (Control.Arrow.ArrowZero (~&gt;),
      Control.Arrow.ArrowChoice (~&gt;)) =&gt;
     Lens (~&gt;) Example Char
*Main&gt; :t example
example
  :: (Control.Arrow.ArrowZero (~&gt;),
      Control.Arrow.ArrowChoice (~&gt;)) =&gt;
     Lens (~&gt;) Example Example
</code></pre>

<p>Whoah! Lenses themselves are polymorphic in the Arrow class; partial lenses
have additional restrictions of <code>ArrowZero</code> and <code>ArrowChoice</code> allowing for
failure and
<a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Arrow.html#t:ArrowChoice">choice</a>.</p>

<p>This is wizardry of the highest order.</p>

<p>Notice how we can still compose lenses freely, whether partial or total:</p>

<pre><code>*Main&gt; :t (.) (.) :: Category cat =&gt; cat b c -&gt; cat a b -&gt; cat a c 
*Main&gt; M.get (int . example) (Y 1 (X 2 'a')) Just 2
</code></pre>

<h2>A note on <code>mkLabelsNoTypes</code></h2>

<p>I had been using the noTypes variation to generate lenses that I was exporting
in a module, because the TH-assigned type sigs looked pretty nasty. If you do
this with >1.0 you will run into the monomorphism restriction and ambiguous
type variables.</p>

<p>Instead I would suggest defining <em>exported</em> lables by hand and giving them a
nicer looking (or monomorphic if you prefer) type sig.</p>

<p>You can even let fclabels generate the code and just paste it in, e.g.:</p>

<pre><code>Prelude&gt; :set -ddump-splices
Prelude&gt; :l test.hs
[1 of 1] Compiling Main             ( test.hs, interpreted )
test.hs:1:1: Splicing declarations
    mkLabels ['Example]
  ======&gt;
    test.hs:40:3-21
    char ::
      forall ~&gt;[a1kk]. (Control.Arrow.ArrowChoice ~&gt;[a1kk],
                        Control.Arrow.ArrowZero ~&gt;[a1kk]) =&gt;
      Lens ~&gt;[a1kk] Example Char
    {-# INLINE[0] CONLIKE char #-}
    char
      = let
          c[a1kl]
            = (Control.Arrow.zeroArrow Control.Arrow.||| Control.Arrow.returnA)
        in
          Data.Label.Abstract.lens
            (c[a1kl]
           . Control.Arrow.arr
               (\ p[a1km]
                  -&gt; case p[a1km] of {
                       X {} -&gt; Right (_char p[a1km])
                       _ -&gt; Left GHC.Unit.() }))
            (c[a1kl]
           . Control.Arrow.arr
               (\ (v[a1kn], p[a1ko])
                  -&gt; case p[a1ko] of {
                       X {} -&gt; Right (p[a1ko] {_char = v[a1kn]})
                       _ -&gt; Left GHC.Unit.() }))
</code></pre>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Module 'chan-split' released]]></title>
    <link href="http://brandon.si/code/module-chan-split-released/"/>
    <updated>2011-07-17T22:17:09-04:00</updated>
    <id>http://brandon.si/code/module-chan-split-released</id>
    <content type="html"><![CDATA[<h2>Whaa?</h2>

<p>chan-split is a haskell library that is a wrapper around
<a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Concurrent-Chan.html"><code>Control.Concurrent.Chan</code></a>s
that separates a Chan into a readable side and
a writable side.</p>

<p>We also provide two other modules: <code>Data.Cofunctor</code> (because there didn&#8217;t seem
to be one anywhere), and <code>Control.Concurrent.Chan.Class</code>. The latter creates
two classes: <code>ReadableChan</code> and <code>WritableChan</code>, making the fundamental chan
functions polymorphic, and defining an instance for standard <code>Chan</code> as well as
<code>MVar</code> (an MVar is a singleton bounded channel, wanna fight about it?).</p>

<h2>Why?</h2>

<p>Having separate read/write sides makes it easier to reason about your code,
supports doing some cool things (defining <code>Functor</code> and <code>Cofunctor</code>
instances), and makes more sense (e.g. the function of
<a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Concurrent-Chan.html#t:dupChan">dupChan</a>
in the base library is much easier to
understand as an operation that happens on an <code>OutChan</code>).</p>

<p>Also I use it in (the coming new, less stupid version of) my module
<a href="http://hackage.haskell.org/package/simple-actors">simple-actors</a>.</p>

<h2>Where?</h2>

<p>You can get it with a:</p>

<pre><code>cabal install chan-split
</code></pre>

<p>And check out the <a href="http://hackage.haskell.org/package/chan-split">docs on hackage</a>.
Or check out the <a href="https://github.com/jberryman/chan-split">source on github</a>
and send me pull requests.</p>

<h1>Usage</h1>

<p>Let&#8217;s write the numbers 1 - 10 to the InChan and read them as a stream in the
OutChan:</p>

<pre><code>module Main
    where

import Control.Concurrent.Chan.Split
import Control.Concurrent(forkIO)

main = do
    -- Instead of a single Chan, we initialize a pair of (InChan,OutChan)
    (inC,outC) &lt;- newSplitChan
    -- fork a writer on the InChan
    forkIO $ writeStuffTo inC [1..10]
    -- read from the OutChan in the main thread:
    getStuffOutOf outC &gt;&gt;=
        mapM_ print . take 10
</code></pre>

<p>And we&#8217;ll make <code>writeStuffTo</code> and <code>getStuffOutOf</code>, simply be the standard
functions. Note that <code>writeListToChan</code> is actually polymorphic.</p>

<pre><code>writeStuffTo :: InChan Int -&gt; [Int] -&gt; IO ()
writeStuffTo = writeList2Chan

getStuffOutOf :: OutChan Int -&gt; IO [Int]
getStuffOutOf = getChanContents
</code></pre>

<p>Now I&#8217;ll demonstrate the use of our Functor and Cofunctor instances by re-
defining those two functions above, after importing our Cofunctor class</p>

<pre><code>import Data.Cofunctor

...

-- we could convert the [Int] to [String] here but will instead demonstrate the
-- Cofmap instance:
writeStuffTo :: InChan String -&gt; [Int] -&gt; IO ()
writeStuffTo = writeList2Chan . cofmap show

-- likewise this demonstrates the Functor instance of OutChan:
getStuffOutOf :: OutChan String -&gt; IO [Int]
getStuffOutOf = getChanContents . fmap read
</code></pre>

<p>All right, leave your love or hate and stay tuned for the new (less stupider)
simple-actors lib.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[simple-actors: a simple Actor Model concurrency library]]></title>
    <link href="http://brandon.si/code/simple-actors-a-simple-actor-model-concurrency-library/"/>
    <updated>2011-05-30T15:31:13-04:00</updated>
    <id>http://brandon.si/code/simple-actors-a-simple-actor-model-concurrency-library</id>
    <content type="html"><![CDATA[<blockquote><p><strong>EDIT:</strong> I&#8217;ve just released
<a href="http://hackage.haskell.org/packages/archive/simple-actors/0.1.0/doc/html/Control-Concurrent-Actors.html">version 0.1.0</a>
of this library. It is a
complete re-write / re-think that I think makes the library much more
attractive, simple and powerful. There won&#8217;t be any more dramatic API changes.</p></blockquote>

<p>I was in need of a simple, tight library implementing the
<a href="http://en.wikipedia.org/wiki/Actor_model">Actor Model of concurrency</a> and didn&#8217;t find one on
hackage, so I wrote my own. You can check out the docs
<a href="http://hackage.haskell.org/package/simple-actors-0.0.1">here</a> and get it with
a</p>

<pre><code>$ cabal install simple-actors
</code></pre>

<p>The library is really just a thin layer around <code>Chan</code>s, and I made no great
effort to ensure that the library conforms to any particular formal definition
of the actor model, but rather tried to make an idiomatic haskell library for
more structured concurrent programming.</p>

<p>I&#8217;ve been going all sorts of ways with this and would appreciate any feedback
anyone would like to share.</p>

<p>I&#8217;ll be using it in some (hopefully fun and interesting) posts in the near
future, to model concurrent systems, and also exploring creating a more
involved concurrency library. So stay tuned if that&#8217;s what you&#8217;re into.</p>
]]></content>
  </entry>
  
</feed>

