<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:planet="http://planet.intertwingly.net/" xmlns:indexing="urn:atom-extension:indexing" indexing:index="no"><access:restriction xmlns:access="http://www.bloglines.com/about/specs/fac-1.0" relationship="deny"/>
  <title>Planet Haskell</title>
  <updated>2012-02-10T03:24:34Z</updated>
  <generator uri="http://intertwingly.net/code/venus/">Venus</generator>
  <author>
    <name>Antti-Juhani Kaijanaho</name>
    <email>planet@community.haskell.org</email>
  </author>
  <id>http://planet.haskell.org/atom.xml</id>
  <link href="http://planet.haskell.org/atom.xml" rel="self" type="application/atom+xml"/>
  <link href="http://planet.haskell.org/" rel="alternate"/>

  <entry>
    <id>tag:blog.plover.com,2012:/prog/perl/exception-tsts</id>
    <link href="http://blog.plover.com/prog/perl/exception-tsts.html" rel="alternate" type="text/html"/>
    <title>Testing for exceptions</title>
    <content type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml">The <a href="https://metacpan.org/release/Test-Fatal"><tt>Test::Fatal</tt>
module</a> makes it very easy to test code that is supposed to throw
an exception.  It provides an <tt>exception</tt> function that takes a
code block.  If the code completes normally, <tt>exception {
<i>code</i> }</tt> returns undefined; if the code throws an exception,
<tt>exception { <i>code</i> }</tt> returns the exception value that
was thrown. So for example, if you want to make sure that some
erroneous call is deteted and throws an exception, you can use
this:<p>

</p><pre>        isnt( exception { do_something( how_many_times =&gt; "W" ) },
              undef,
              "how_many_times argument requires a number" );
</pre>



which will succeed if <tt>do_something(…)</tt> throws an exception,
and fail if it does not.  You can also write a stricter test, to look
for the particular exception you expect:<p>

</p><pre>        like( exception { do_something( how_many_times =&gt; "W" ) },
              qr/how_many_times is not numeric/,
              "how_many_times argument requires a number" );
</pre>

which will succeed if <tt>do_something(…)</tt> throws an exception
that contains <tt>how_many_times is not numeric</tt>, and fail
otherwise.<p>

Today I almost made the terrible mistake of using the first form
instead of the second.  <a href="https://metacpan.org/module/RJBS/Test-Fatal-0.008/lib/Test/Fatal.pm#SYNOPSIS">The
manual suggests that you use the first form</a>, but it's a bad
suggestion.  The problem is that if you completely screw up the test
and write a broken code block that dies, the first test will
cheerfully succeed anyway.  For example, suppose you make a typo in
the test code:</p><p>

</p><pre>        isnt( exception { do_something( <font color="red">how_many_tims</font> =&gt; "W" ) },
              undef,
              "how_many_times argument requires a number" );
</pre>

Here the <tt>do_something(…)</tt> call throws some totally different
exception that we are not interested in, something like <tt>unknown
argument 'how_many_tims'</tt> or <tt>mandatory 'how_many_times'
argument missing</tt>, but the exception is swallowed and the test
reports success, even though we know nothing at all about the feature
we were trying to test.  But the test looks like it passed.<p>

In my example today, the code looked like this:</p><p>

</p><pre>      isnt( exception {
        my $invoice = gen_invoice();
        $invoice-&gt;abandon;
      }, undef,
            "Can't abandon invoice with no abandoned charges");
    });
</pre>

The <tt>abandon</tt> call was supposed to fail, for reasons you don't
care about.  But in fact, the execution never got that far, because
there was a totally dumb bug in <tt>gen_invoice()</tt> (a missing
required constructor argument) that caused it to die with a completely
different exception.<p>

I would never have noticed this error if I hadn't spontaneously
decided to make the test stricter:</p><p>

</p><pre>      like( exception {
        my $invoice = gen_invoice();
        $invoice-&gt;abandon;
      }, qr/Can't.*with no abandoned charges/,
            "Can't abandon invoice with no abandoned charges");
    });
</pre>

This test failed, and the failure made clear that
<tt>gen_invoice()</tt>, a piece of otherwise unimportant test
apparatus, was completely broken, and that several other tests I had
written in the same style appeared to be passing but weren't actually
running the code I thought they were.<p>

So the rule of thumb is: even though the <tt>Test::Fatal</tt> manual
suggests that you use <tt>isnt( exception { … }, undef, …)</tt>,
do not.</p><p>

I mentioned this to Ricardo Signes, the author of the module, and he
released <a href="https://metacpan.org/release/RJBS/Test-Fatal-0.009">a new
version</a> with <a href="https://github.com/rjbs/test-fatal/compare/4cb18a.%2e.116df1">revised
documentation</a> before I managed to get this blog post published.</p><p/></div>
    </content>
    <updated>2012-02-09T21:13:00Z</updated>
    <published>2012-02-09T21:11:00Z</published>
    <category term="/prog/perl"/>
    <author>
      <name>Mark Dominus</name>
    </author>
    <source>
      <id>tag:blog.plover.com,2005:/</id>
      <link href="http://blog.plover.com/index.atom" rel="self" type="application/atom+xml"/>
      <link href="http://blog.plover.com" rel="alternate" type="text/html"/>
      <subtitle>The Universe of Discourse (Mark Dominus Blog)</subtitle>
      <title>The Universe of Discourse</title>
      <updated>2012-02-09T21:13:00Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://www.yesodweb.com/blog/2012/02/release-0-10</id>
    <link href="http://www.yesodweb.com/blog/2012/02/release-0-10" rel="alternate" type="text/html"/>
    <title>Announcing Yesod 0.10</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>We are proud to announce the relase of Yesod 0.10 Please note that 0.10 &lt; 1.0</p>
<p>The main purpose of this release was to switch to conduits. But while we were waiting for the conduit integration to mature, we added a log of great stuff.</p>
<p>Please see the <a href="http://www.yesodweb.com/wiki/0.10_upgrade">upgrade guide for 0.10</a>. This is a wiki page: please add your notes and improvements.</p>
<p>If you haven't upgraded to 0.9.4, please see the <a href="http://www.yesodweb.com/blog/2011/12/0-9-4-release">previous release announcement</a>.</p>
<h1 id="persistent">Persistent</h1>
<p>There were so many improvements to Persistent, that it needed its own release announcement: <a href="http://www.yesodweb.com/blog/2012/02/persistent-0-8">Persistent 0.8</a></p>
<p>Some quick highlights:</p>
<ul>
<li>New rawSql interface</li>
<li>New MySQL backend, couchDB in the works</li>
<li>Support for embedded records, maps, lists, and sets</li>
</ul>
<p>For most users, only the initialization of Persistent in their site will be effected: persistent queries are still the same.</p>
<h1 id="shakespeare">Shakespeare</h1>
<p>We now use the new addDependentFile for GHC 7.4 users. This means ghc will automatically recompile your shakespeare templates when they change. This takes a burden of dependency tracking away from yesod devel: for 7.4 its main utitlity is to automatically restart compilation.</p>
<h2 id="shakespeare-js">shakespeare-js</h2>
<p>Coffeescript compilation is now performed at compilation time. This pattern is now supported in the shakespeare library: if a template needs to execute an external program, that should be done once at compilation time. This finally makes Coffeescript a great, effortless option.</p>
<p>I am a big fan of using Coffeescript rather than plain Javascript. Coffeescript puts a nicer face on Javascript that gets rid of its inconsistencies and adds conveniences. However, even a well-done Javascript is still a very lacking programming language. I am looking forward to the day that I can write Haskell or at least some language with a great type system and have that easily translated to Javascript. There are some <a href="http://www.haskell.org/haskellwiki/The_JavaScript_Problem">interesting developments going on in this area</a> independent of Yesod, and we look forward to the prospect of integrating these solutions when they mature.</p>
<h1 id="wai">WAI</h1>
<p>The big change is the move to conduits. There were also a lot of small bug fixes and performance improvements. The RequestLogger Interface was improved, and a bug in fast-logger that it uses was squashed. We are now experimenting with ways to make WAI a more powerful way to share code. One limiting factor was not being able to pass along arbitrary data. WAI now has a vault parameter for that purpose, which uses the vault package.</p>
<h1 id="yesod">Yesod</h1>
<p>Again, the focus of this release was the switch to conduits. For a Yesod user this is mostly an implementation detail. This leaked in two main places: the scaffolding configuration (see upgrade guide), and exception handling. With the move to conduits we have completely removed the liftIOHandler exception handling hack.</p>
<p>Approot, the setting which generates urls is maturing, see the upgrade guide. You now have the option of changing the url based on request information.</p>
<p>The redirect system has been reworked to use the correct status and to remove redundancies. The need for RedirectTemporary has been removed, and instead we just default to the correct HTTP status codes. If you want to specify an HTTP status, use redirectWith.</p>
<p>Improved routing. While there were some bug fixes, the main improvement is a .scalable dispatcher. Most web framework routers dumbly check routes one-by-one until they find a match. Yesod now features an efficent dispatch. The <a href="https://github.com/yesodweb/yesod/blob/master/yesod-routes/Yesod/Routes/Dispatch.lhs">literate haskell source</a> explains the two main optimizations:</p>
<ul>
<li>Break up routes based on how many components they can match (slashes in a route). This lookup runs in constant time.</li>
<li>Use a Map to reduce string comparisons for each route to logarithmic complexity.</li>
</ul>
<h1 id="section">1.0</h1>
<p>We consider this to be a 1.0 release candidate. We want 1.0 to be very solid release, so we definitely needed this extra release cycle for the move to conduits. 1.0 for us means a stable API - now is your last chance to propose good API changes without getting a lot of pushback and requirements for maintaining deprecated APIs.</p>
<p>If you look at the <a href="http://www.yesodweb.com/blog/2011/03/road-to-yesod-1-0">1.0 roadmap we posted</a>, we have accomplished everything except easy testing integration and static html generation. However, we have pull requests for both of those waiting right now!</p>
<p>Thanks to everyone that helps improve Yesod. Please upgrade to 0.10 and let us know how to make it even better.</p></div>
    </content>
    <updated>2012-02-09T16:31:24Z</updated>
    <source>
      <id>http://www.yesodweb.com/</id>
      <author>
        <name>Yesod Web Framework</name>
      </author>
      <link href="http://www.yesodweb.com/feed" rel="self" type="application/atom+xml"/>
      <link href="http://www.yesodweb.com/" rel="alternate" type="text/html"/>
      <title>Yesod Wiki</title>
      <updated>2012-02-10T03:22:29Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://www.yesodweb.com/blog/2012/02/persistent-0-8</id>
    <link href="http://www.yesodweb.com/blog/2012/02/persistent-0-8" rel="alternate" type="text/html"/>
    <title>The New Persistent</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>We are excited to announce the release of Persistent 0.8. This will be used by the upcoming 0.10 Yesod release.</p>
<p>Persistent is a data store interface library that is backend agnostic - it currently works with SQL and MongoDB databases.</p>
<h2 id="more-backends">More backends!</h2>
<p>Persistent has solid support for Sqlite, PostgreSQL, and MongoDB. Felipe Lessa just contributed a MySQL backend! There is also a <a href="https://github.com/yesodweb/persistent/pull/36">couchDB backend in the works</a> - if you are a couchDB fan let us know - the main thing holding this one back are some willing maintainers to keep it up to date with changes in Persistent.</p>
<h2 id="dependency-upgrades">Dependency upgrades</h2>
<ul>
<li>The new MySQL backend uses the mysql-simple library.</li>
<li>The PostgreSQL backend now uses postgresql-simple instead of HDBC.</li>
<li>The persistent streaming API now uses conduits instead of enumerators.</li>
<li>Move from pool to resource-pool (thanks Bryan O'Sullivan!)</li>
</ul>
<h2 id="a-new-raw-sql-interface">A new raw SQL interface</h2>
<p>Felipe Lessa also added an amazing rawSql interface!</p>
<p>The Persistent query interface cannot capture every operation needed in a backend. For more advanced SQL queries without support from Persistent, rawSql is now a great tool. Persistent already had a very low-level raw SQl interface. However, you had to parse the result yourself. The rawSql interface maintains Persistent's automatic serialization.</p>
<pre><code>SELECT ??, ??
FROM "Person", "Likes", "Object"
WHERE "Person".id = "Likes"."personId"
AND "Object".id = "Likes"."objectId"
AND "Person".name LIKE ?
</code></pre>
<p>If you name that query likesStmt, you then execute it:</p>
<pre class="sourceCode"><code class="sourceCode haskell"><span class="kw">do</span> results <span class="ot">&lt;-</span> rawSql likesStmt [<span class="st">"%Luke%"</span>]<br/>   forM_ results <span class="fu">$</span><br/>     \\( <span class="dt">Entity</span> personKey person<br/>      , <span class="dt">Entity</span> objectKey object<br/>      ) <span class="ot">-&gt;</span> <span class="kw">do</span> <span class="fu">...</span></code></pre>
<p>This new interface adds greatly needed flexibility to Persistent. However, it does away with Persistent's guarantee that the query is correct: you could easily have a typo in your query. Now is a good time to mention another exciting project that attempts to solve this issue by validating the query at compile time: <a href="https://gitorious.org/persistent-hssqlppp">persistent-hssqlppp</a>.</p>
<h2 id="complex-data-structures-support">Complex Data Structures Support!</h2>
<p>Persistent's serialization is now much more powerful. Previously, Persistent only supported flat Haskell records. However, MongoDB directly supports complex data structures, such as a record that contains a list of records. This functionality is essential to proper data modeling with MongoDB, and is one of the aspects of MongoDB that I have enjoyed the most. I think SQL users will enjoy this also.</p>
<p>SQL does not explicitly support complex data structures as column values. However it is a common strategy to serialize data structures to something like a JSON string and then save them to a SQL column - Persistent now automates this process. This is very useful functionality as long as SQL users keep in mind that JSON-serialized columns are meant just to be updated, deleted, and selected, not to be compared in a query (with a where clause, etc). Also, please keep in mind that consistent partial updates of an embedded data structure impossible. If you need to query your data structure or update portions of it, you should instead continue to spread your data structures over multiple tables rather than use this new feature.</p>
<p>Persistent now comes out of the box with support for Haskell bread-and-butter data structures: Records, Maps, Lists, and Sets. This means we automatically generate To/From JSON instances for your Persistent entities now. So when you need to send them as JSON, most of your work will already be done. If you don't like our JSON instances, use a no-json annotation in your schema.</p>
<h2 id="the-great-divide">The Great Divide</h2>
<p>In a <a href="http://www.yesodweb.com/blog/2011/11/got-right">recent blog post</a> I talked about how the strength of Yesod is the ease of integration with the compelling Hamlet, WAI, and Persistent libraries. We think Hamlet and WAI can still be improved, but that we have struck on the right design for Haskell. For all of its Persistent's strengths, it has always been something we are much less certain about. In re-thinking Persistent, we realized that Persistent is dealing with two separate issues.</p>
<ol style="">
<li>Serializing Haskell data to the database and de-serializing from the database to Haskell</li>
<li>Defining a query interface that all backends can share for type-safe querying of the database.</li>
</ol>
<p>We believe we <em>have</em> struck upon a great design for Haskell for data serialization to the database. On the other hand, the query interface could certainly be improved, and there are alternative approaches that might be better.</p>
<p>The basic serialization functions Persistent exposes (get, insert, replace) seem fairly universal to all databases. However, it seems impossible to make a universal query interface to satisfy every backend. For example, when Michael experimented with a Redis backend, he quickly realized many of the query operations did not map well to a simple key value store.</p>
<p>So rather than have a monolithic typeclass interface, Persistent now exposes 3 typeclasses</p>
<ol style="">
<li>PersistStore - univeral, basic serialization (get, insert, etc). Required by all other Persistent type-classes</li>
<li>PersistUnique - secondary indexes (getBy, etc). PersistStore is based on operating on a primary key. PersistUnique extends some of these operations to secondary indexes, or other columns where the values are unique</li>
<li>PersistQuery - Persistent's out of the box advanced query interface</li>
</ol>
<p>Our hope is that a PersistStore backend can now be made for any data store. If the PersistQuery interface does not align well with the data store, than an entirely different query interface can be used instead.</p>
<h2 id="other-improvements">Other improvements</h2>
<p>We cleaned up EntityDef, the data structure that maintains meta-data about your database entities - this fixed several bugs including making it more resilient to renamings. Database parameters can now be configured via environment variables</p>
<h2 id="future-directions-for-persistent">Future directions for Persistent</h2>
<p>We are getting pretty happy with the SQL/MongoDB querying capabilities. Eventually we think there will be a way to have compile-time validation of raw queries for both SQL and MongoDB.</p>
<p>The new Persistent architecture makes it easier to have more contributions to Persistent from the community. It has never been easier to create a Persistent backend - just start by implementing the PersistStore serialization API. We look forward to seeing more Persistent backends and more powerful query interfaces.</p></div>
    </content>
    <updated>2012-02-08T14:01:52Z</updated>
    <source>
      <id>http://www.yesodweb.com/</id>
      <author>
        <name>Yesod Web Framework</name>
      </author>
      <link href="http://www.yesodweb.com/feed" rel="self" type="application/atom+xml"/>
      <link href="http://www.yesodweb.com/" rel="alternate" type="text/html"/>
      <title>Yesod Wiki</title>
      <updated>2012-02-10T03:22:29Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://twanvl.nl/blog/haskell/SemilatticeSearchTree</id>
    <link href="http://twanvl.nl/blog/haskell/SemilatticeSearchTree" rel="alternate" type="text/html"/>
    <link href="http://twanvl.nl/blog/haskell/SemilatticeSearchTree" rel="alternate" type="text/html"/>
    <title>Search trees without sorting</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Binary search trees are used quite often for storing or finding values.
Like a binary search, they essentially work by sorting the items.
</p><p>In this post I will describe a search tree that does not require that the items be sorted. Hence, the tree can support some interesting queries. The queries will always be correct, but they will only be fast in some cases.
</p><h2><a name="bounds"/>Bounds </h2>
<p>Usually, to make searching fast, each branch in a search tree stores information that helps to decide whether to go left or right. But if we want to be able to construct a tree for any possible type of query, then that is not always possible.
Instead, we can still aim to eliminate large parts of the search space, by storing bounds.
</p><p>Suppose we have a tree that stores integers, and we want to find the first item in the tree that is greater or equal to some query integer. In each branch of the tree, we could store the maximum of all values in that subtree. Call it the upper bound of the subtree. If this upper bound is less than the query, then we can eliminate the entire subtree from consideration.
</p><p>Now let's generalize that. The maximum value is an example of a <a href="http://en.wikipedia.org/wiki/Semilattice">semilattice</a>. That is just a fancy way of saying that for a pair of values we can get some kind of bound. As a typeclass it looks like
</p><pre class="haskell"><span class="keyword">class</span> <span class="conid">Semilattice</span> <span class="varid">a</span> <span class="keyword">where</span>
    <span class="varid">meet</span> <span class="keyglyph">::</span> <span class="varid">a</span> <span class="keyglyph">-&gt;</span> <span class="varid">a</span> <span class="keyglyph">-&gt;</span> <span class="varid">a</span>
    <span class="comment">-- Laws: meet is associative, commutative and idempotent:</span>
    <span class="comment">--         meet a (meet b c) = meet (meet a b) c</span>
    <span class="comment">--         meet a b = meet b a</span>
    <span class="comment">--         meet a a = a</span>
</pre><p>The queries we perform on the tree should of course work together with the bounds.
That means that if a bound for a branch in the tree doesn't satisfy the query, then none of the values in the subtree do. In haskell terms:
</p><pre class="haskell"><span class="keyword">class</span> <span class="conid">Semilattice</span> <span class="varid">a</span> <span class="keyglyph">=&gt;</span> <span class="conid">Satisfy</span> <span class="varid">q</span> <span class="varid">a</span> <span class="keyglyph">|</span> <span class="varid">q</span> <span class="keyglyph">-&gt;</span> <span class="varid">a</span> <span class="keyword">where</span>
    <span class="varid">satisfy</span> <span class="keyglyph">::</span> <span class="varid">q</span> <span class="keyglyph">-&gt;</span> <span class="varid">a</span> <span class="keyglyph">-&gt;</span> <span class="conid">Bool</span>
    <span class="comment">-- Law: satisfy q a || satisfy q b  ==&gt;  satisfy q (meet a b)</span>
</pre><p>Note that a semilattice always gives a partial order, and hence a satisfy function by
</p><pre class="ghci"><span class="varid">satisfy</span> <span class="varid">q</span> <span class="varid">a</span> <span class="keyglyph">=</span> <span class="varid">meet</span> <span class="varid">q</span> <span class="varid">a</span> <span class="varop">==</span> <span class="varid">a</span>
</pre><p>because
</p><pre class="haskell-equational-reasoning">     <span class="varid">satisfy</span> <span class="varid">q</span> <span class="varid">a</span> <span class="varop">||</span> <span class="varid">satisfy</span> <span class="varid">q</span> <span class="varid">b</span>
<span class="varop">&lt;=&gt;</span>  <span class="varid">meet</span> <span class="varid">q</span> <span class="varid">a</span> <span class="varop">==</span> <span class="varid">a</span> <span class="varop">||</span> <span class="varid">meet</span> <span class="varid">q</span> <span class="varid">b</span> <span class="varop">==</span> <span class="varid">b</span>
<span class="varop">==&gt;</span>  <span class="varid">meet</span> (<span class="varid">meet</span> <span class="varid">q</span> <span class="varid">a</span>) <span class="varid">b</span> <span class="varop">==</span> <span class="varid">meet</span> <span class="varid">a</span> <span class="varid">b</span> <span class="varop">||</span> <span class="varid">meet</span> <span class="varid">a</span> (<span class="varid">meet</span> <span class="varid">q</span> <span class="varid">b</span>) <span class="varop">==</span> <span class="varid">meet</span> <span class="varid">a</span> <span class="varid">b</span>
<span class="varop">&lt;=&gt;</span>  <span class="varid">meet</span> <span class="varid">q</span> (<span class="varid">meet</span> <span class="varid">a</span> <span class="varid">b</span>) <span class="varop">==</span> <span class="varid">meet</span> <span class="varid">a</span> <span class="varid">b</span> <span class="varop">||</span> <span class="varid">meet</span> <span class="varid">q</span> (<span class="varid">meet</span> <span class="varid">a</span> <span class="varid">b</span>) <span class="varop">==</span> <span class="varid">meet</span> <span class="varid">a</span> <span class="varid">b</span>
<span class="varop">&lt;=&gt;</span>  <span class="varid">meet</span> <span class="varid">q</span> (<span class="varid">meet</span> <span class="varid">a</span> <span class="varid">b</span>) <span class="varop">==</span> <span class="varid">meet</span> <span class="varid">a</span> <span class="varid">b</span>
<span class="varop">&lt;=&gt;</span>  <span class="varid">satisfy</span> <span class="varid">q</span> (<span class="varid">meet</span> <span class="varid">a</span> <span class="varid">b</span>)
</pre><p>However, I keep the distinction between the query and value type for more flexibility and for more descriptive types.
</p><h2><a name="implementation"/>Implementation </h2>
<p>Given the <tt><span class="conid">Satisfy</span></tt> and <tt><span class="conid">Semilattice</span></tt> typeclasses, the search tree datastructure is straight forward.
A search tree can be empty, a single value, or a branch. In each branch we store the bound of that subtree.
</p><pre class="haskell"><span class="keyword">data</span> <span class="conid">SearchTree</span> <span class="varid">a</span>
    <span class="keyglyph">=</span> <span class="conid">Empty</span>
    <span class="keyglyph">|</span> <span class="conid">Leaf</span> <span class="varop">!</span><span class="varid">a</span>
    <span class="keyglyph">|</span> <span class="conid">Branch</span> <span class="varop">!</span><span class="varid">a</span> (<span class="conid">SearchTree</span> <span class="varid">a</span>) (<span class="conid">SearchTree</span> <span class="varid">a</span>)
    <span class="keyword">deriving</span> (<span class="conid">Show</span>)
<div class="empty-line"/>
<span class="varid">bound</span> <span class="keyglyph">::</span> <span class="conid">SearchTree</span> <span class="varid">a</span> <span class="keyglyph">-&gt;</span> <span class="varid">a</span>
<span class="varid">bound</span> (<span class="conid">Leaf</span> <span class="varid">a</span>) <span class="keyglyph">=</span> <span class="varid">a</span>
<span class="varid">bound</span> (<span class="conid">Branch</span> <span class="varid">a</span> <span class="varid">_</span> <span class="varid">_</span>) <span class="keyglyph">=</span> <span class="varid">a</span>
<span class="varid">bound</span> <span class="conid">Empty</span> <span class="keyglyph">=</span> <span class="varid">error</span> <span class="str">"bound Empty"</span>
</pre><p>If we have a <tt><span class="conid">SearchTree</span></tt>, then we can find the first element that satisfies a query, simply by searching both sides of each branch. The trick to making the search faster is to only continue as long as the bound satisfies the query:
</p><pre class="haskell"><span class="comment">-- Find the first element in the tree that satisfies the query</span>
<span class="varid">findFirst</span> <span class="keyglyph">::</span> <span class="conid">Satisfy</span> <span class="varid">q</span> <span class="varid">a</span> <span class="keyglyph">=&gt;</span> <span class="varid">q</span> <span class="keyglyph">-&gt;</span> <span class="conid">SearchTree</span> <span class="varid">a</span> <span class="keyglyph">-&gt;</span> <span class="conid">Maybe</span> <span class="varid">a</span>
<span class="varid">findFirst</span> <span class="varid">q</span> (<span class="conid">Leaf</span> <span class="varid">a</span>)       <span class="keyglyph">|</span> <span class="varid">satisfy</span> <span class="varid">q</span> <span class="varid">a</span> <span class="keyglyph">=</span> <span class="conid">Just</span> <span class="varid">a</span>
<span class="varid">findFirst</span> <span class="varid">q</span> (<span class="conid">Branch</span> <span class="varid">a</span> <span class="varid">x</span> <span class="varid">y</span>) <span class="keyglyph">|</span> <span class="varid">satisfy</span> <span class="varid">q</span> <span class="varid">a</span> <span class="keyglyph">=</span> <span class="varid">findFirst</span> <span class="varid">q</span> <span class="varid">x</span> <span class="varop">`mplus`</span> <span class="varid">findFirst</span> <span class="varid">q</span> <span class="varid">y</span>
<span class="varid">findFirst</span> <span class="varid">_</span> <span class="varid">_</span> <span class="keyglyph">=</span> <span class="conid">Nothing</span>
</pre><p>Completely analogously, we can find the last satisfied item instead:
</p><pre class="haskell"><span class="comment">-- Find the last element in the tree that satisfies the query</span>
<span class="varid">findLast</span> <span class="keyglyph">::</span> <span class="conid">Satisfy</span> <span class="varid">q</span> <span class="varid">a</span> <span class="keyglyph">=&gt;</span> <span class="varid">q</span> <span class="keyglyph">-&gt;</span> <span class="conid">SearchTree</span> <span class="varid">a</span> <span class="keyglyph">-&gt;</span> <span class="conid">Maybe</span> <span class="varid">a</span>
<span class="varid">findLast</span> <span class="varid">q</span> (<span class="conid">Leaf</span> <span class="varid">a</span>)       <span class="keyglyph">|</span> <span class="varid">satisfy</span> <span class="varid">q</span> <span class="varid">a</span> <span class="keyglyph">=</span> <span class="conid">Just</span> <span class="varid">a</span>
<span class="varid">findLast</span> <span class="varid">q</span> (<span class="conid">Branch</span> <span class="varid">a</span> <span class="varid">x</span> <span class="varid">y</span>) <span class="keyglyph">|</span> <span class="varid">satisfy</span> <span class="varid">q</span> <span class="varid">a</span> <span class="keyglyph">=</span> <span class="varid">findLast</span> <span class="varid">q</span> <span class="varid">y</span> <span class="varop">`mplus`</span> <span class="varid">findLast</span> <span class="varid">q</span> <span class="varid">x</span>
<span class="varid">findLast</span> <span class="varid">_</span> <span class="varid">_</span> <span class="keyglyph">=</span> <span class="conid">Nothing</span>
</pre><p>Or we can even generalize this search to any <tt><span class="conid">Monoid</span></tt>, where the above are for the <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Monoid.html#t:First"><tt><span class="conid">First</span></tt></a> and <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Monoid.html#t:Last"><tt><span class="conid">Last</span></tt></a> monoids respectively. I will this leave as an exercise for the reader.
</p><h2><a name="constructing"/>Constructing </h2>
<p>The basis of each tree are branches. We will always construct branches with a smart constructor that calculates the bound as the meet of the bounds of its two arguments. That way, the stored bound is always correct.
</p><pre class="haskell"><span class="varid">mkBranch</span> <span class="keyglyph">::</span> <span class="conid">Semilattice</span> <span class="varid">a</span> <span class="keyglyph">=&gt;</span> <span class="conid">SearchTree</span> <span class="varid">a</span> <span class="keyglyph">-&gt;</span> <span class="conid">SearchTree</span> <span class="varid">a</span> <span class="keyglyph">-&gt;</span> <span class="conid">SearchTree</span> <span class="varid">a</span>
<span class="varid">mkBranch</span> <span class="conid">Empty</span> <span class="varid">y</span> <span class="keyglyph">=</span> <span class="varid">y</span>
<span class="varid">mkBranch</span> <span class="varid">x</span> <span class="conid">Empty</span> <span class="keyglyph">=</span> <span class="varid">x</span>
<span class="varid">mkBranch</span> <span class="varid">x</span> <span class="varid">y</span> <span class="keyglyph">=</span> <span class="conid">Branch</span> (<span class="varid">bound</span> <span class="varid">x</span> <span class="varop">`meet`</span> <span class="varid">bound</span> <span class="varid">y</span>) <span class="varid">x</span> <span class="varid">y</span>
</pre><p>A search will always take time at least linear in the <em>depth</em> of the tree. So, for fast searches we need a balanced tree, where each subtree has roughly the same size. Here is arguably the most tricky part of the code, which converts a list to a balanced search tree.
</p><pre class="haskell"><span class="comment">-- /O(n*log n)/</span>
<span class="comment">-- Convert a list to a balanced search tree</span>
<span class="varid">fromList</span> <span class="keyglyph">::</span> <span class="conid">Semilattice</span> <span class="varid">a</span> <span class="keyglyph">=&gt;</span> <span class="listcon">[</span><span class="varid">a</span><span class="listcon">]</span> <span class="keyglyph">-&gt;</span> <span class="conid">SearchTree</span> <span class="varid">a</span>
<span class="varid">fromList</span> <span class="listcon">[</span><span class="listcon">]</span>  <span class="keyglyph">=</span> <span class="conid">Empty</span>
<span class="varid">fromList</span> <span class="listcon">[</span><span class="varid">x</span><span class="listcon">]</span> <span class="keyglyph">=</span> <span class="conid">Leaf</span> <span class="varid">x</span>
<span class="varid">fromList</span> <span class="varid">xs</span>  <span class="keyglyph">=</span> <span class="varid">mkBranch</span> (<span class="varid">fromList</span> <span class="varid">ys</span>) (<span class="varid">fromList</span> <span class="varid">zs</span>)
  <span class="keyword">where</span>
    (<span class="varid">ys</span>,<span class="varid">zs</span>) <span class="keyglyph">=</span> <span class="varid">splitAt</span> (<span class="varid">length</span> <span class="varid">xs</span> <span class="varop">`div`</span> <span class="num">2</span>) <span class="varid">xs</span>
</pre><p>And that's it.
I use this data structure for finding rectangles (more about that in a future post), and there I only needed to build the search structure once, and use it multiple times. So, in this post I am not going to talk about updates at all. If you wanted to do updates efficiently, then you would need to worry about updating bounds, rebalancing etc.
</p><h2><a name="example-uses"/>Example uses </h2>
<p>Here is an example of the search tree in action.
The query will be to find a value <tt>(<span class="varop">&gt;=</span> <span class="varid">q</span>)</tt> for a given <tt><span class="varid">q</span></tt>. The bounds will be maximum values.
</p><pre class="haskell"><span class="keyword">newtype</span> <span class="conid">Max</span> <span class="varid">a</span> <span class="keyglyph">=</span> <span class="conid">Max</span> { <span class="varid">getMax</span> <span class="keyglyph">::</span> <span class="varid">a</span> } <span class="keyword">deriving</span> (<span class="conid">Show</span>)
<span class="keyword">instance</span> <span class="conid">Ord</span> <span class="varid">a</span> <span class="keyglyph">=&gt;</span> <span class="conid">Semilattice</span> (<span class="conid">Max</span> <span class="varid">a</span>) <span class="keyword">where</span>
    <span class="varid">meet</span> (<span class="conid">Max</span> <span class="varid">a</span>) (<span class="conid">Max</span> <span class="varid">b</span>) <span class="keyglyph">=</span> <span class="conid">Max</span> (<span class="varid">max</span> <span class="varid">a</span> <span class="varid">b</span>)
<div class="empty-line"/>
<span class="keyword">newtype</span> <span class="conid">Ge</span> <span class="varid">a</span> <span class="keyglyph">=</span> <span class="conid">Ge</span> <span class="varid">a</span> <span class="keyword">deriving</span> (<span class="conid">Show</span>)
<span class="keyword">instance</span> <span class="conid">Ord</span> <span class="varid">a</span> <span class="keyglyph">=&gt;</span> <span class="conid">Satisfy</span> (<span class="conid">Ge</span> <span class="varid">a</span>) (<span class="conid">Max</span> <span class="varid">a</span>) <span class="keyword">where</span>
    <span class="varid">satisfy</span> (<span class="conid">Ge</span> <span class="varid">q</span>) <span class="keyglyph">=</span> (<span class="varop">&gt;=</span> <span class="varid">q</span>) <span class="varop">.</span> <span class="varid">getMax</span>
</pre><p>First, check the <tt><span class="varid">satisfy</span></tt> law:
</p><pre class="haskell-equational-reasoning">     <span class="varid">satisfy</span> (<span class="conid">Ge</span> <span class="varid">q</span>) (<span class="conid">Max</span> <span class="varid">a</span>) <span class="varop">||</span> <span class="varid">satisfy</span> (<span class="conid">Ge</span> <span class="varid">q</span>) (<span class="conid">Max</span> <span class="varid">b</span>)
<span class="varop">&lt;=&gt;</span>  <span class="varid">a</span> <span class="varop">&gt;=</span> <span class="varid">q</span> <span class="varop">||</span> <span class="varid">b</span> <span class="varop">&gt;=</span> <span class="varid">q</span>
<span class="varop">&lt;=&gt;</span>  <span class="keyword">if</span> <span class="varid">a</span> <span class="varop">&gt;=</span> <span class="varid">b</span> <span class="keyword">then</span> <span class="varid">a</span> <span class="varop">&gt;=</span> <span class="varid">q</span> <span class="keyword">else</span> <span class="varid">b</span> <span class="varop">&gt;=</span> <span class="varid">q</span>
<span class="varop">&lt;=&gt;</span>  (<span class="keyword">if</span> <span class="varid">a</span> <span class="varop">&gt;=</span> <span class="varid">b</span> <span class="keyword">then</span> <span class="varid">a</span> <span class="keyword">else</span> <span class="varid">b</span>) <span class="varop">&gt;=</span> <span class="varid">q</span>
<span class="varop">&lt;=&gt;</span>  <span class="varid">max</span> <span class="varid">a</span> <span class="varid">b</span> <span class="varop">&gt;=</span> <span class="varid">q</span>
<span class="varop">&lt;=&gt;</span>  <span class="varid">satisfy</span> (<span class="conid">Ge</span> <span class="varid">q</span>) (<span class="conid">Max</span> (<span class="varid">max</span> <span class="varid">a</span> <span class="varid">b</span>))
<span class="varop">&lt;=&gt;</span>  <span class="varid">satisfy</span> (<span class="conid">Ge</span> <span class="varid">q</span>) (<span class="varid">meet</span> (<span class="conid">Max</span> <span class="varid">a</span>) (<span class="conid">Max</span> <span class="varid">b</span>))
</pre><div class="float-right" style="width: 240px;"><img alt="" src="http://twanvl.nl/image/searchtree/tree1.png"/><br/>The search tree corresponding to <tt><span class="varid">fromList</span> (<span class="varid">map</span> <span class="conid">Max</span> <span class="listcon">[</span><span class="num">1</span><span class="listcon">..</span><span class="num">5</span><span class="listcon">]</span>)</tt>. Circles are <tt><span class="conid">Leaf</span></tt>s and squares are <tt><span class="conid">Branch</span></tt>es.</div>
<p>So indeed, <tt><span class="varid">satisfy</span> <span class="varid">q</span> <span class="varid">a</span> <span class="varop">||</span> <span class="varid">satisfy</span> <span class="varid">q</span> <span class="varid">b</span>  <span class="varop">==&gt;</span>  <span class="varid">satisfy</span> <span class="varid">q</span> (<span class="varid">meet</span> <span class="varid">a</span> <span class="varid">b</span>)</tt>.
And this bound is in fact tight, so also the other way around <tt><span class="varid">satisfy</span> <span class="varid">q</span> (<span class="varid">meet</span> <span class="varid">a</span> <span class="varid">b</span>)  <span class="varop">==&gt;</span>  <span class="varid">satisfy</span> <span class="varid">q</span> <span class="varid">a</span> <span class="varop">||</span> <span class="varid">satisfy</span> <span class="varid">q</span> <span class="varid">b</span></tt>. This will become important later.
</p><p>Now here are some example queries:
</p><pre class="ghci"><span class="input">λ&gt;</span> <span class="varid">findFirst</span> (<span class="conid">Ge</span> <span class="num">3</span>) (<span class="varid">fromList</span> <span class="varop">$</span> <span class="varid">map</span> <span class="conid">Max</span> <span class="listcon">[</span><span class="num">1</span>,<span class="num">2</span>,<span class="num">3</span>,<span class="num">4</span>,<span class="num">5</span><span class="listcon">]</span>)
<span class="conid">Just</span> (<span class="conid">Max</span> <span class="num">3</span>)
<span class="input">λ&gt;</span> <span class="varid">findFirst</span> (<span class="conid">Ge</span> <span class="num">3</span>) (<span class="varid">fromList</span> <span class="varop">$</span> <span class="varid">map</span> <span class="conid">Max</span> <span class="listcon">[</span><span class="num">2</span>,<span class="num">4</span>,<span class="num">6</span><span class="listcon">]</span>)
<span class="conid">Just</span> (<span class="conid">Max</span> <span class="num">4</span>)
<span class="input">λ&gt;</span> <span class="varid">findFirst</span> (<span class="conid">Ge</span> <span class="num">3</span>) (<span class="varid">fromList</span> <span class="varop">$</span> <span class="varid">map</span> <span class="conid">Max</span> <span class="listcon">[</span><span class="num">6</span>,<span class="num">4</span>,<span class="num">2</span><span class="listcon">]</span>)
<span class="conid">Just</span> (<span class="conid">Max</span> <span class="num">6</span>)
<span class="input">λ&gt;</span> <span class="varid">findFirst</span> (<span class="conid">Ge</span> <span class="num">7</span>) (<span class="varid">fromList</span> <span class="varop">$</span> <span class="varid">map</span> <span class="conid">Max</span> <span class="listcon">[</span><span class="num">2</span>,<span class="num">4</span>,<span class="num">6</span><span class="listcon">]</span>)
<span class="conid">Nothing</span>
</pre><p>Semilattices and queries can easily be combined into tuples. For a tree of pairs, and queries of pairs, you could use.
</p><pre class="haskell"><span class="keyword">instance</span> (<span class="conid">Semilattice</span> <span class="varid">a</span>, <span class="conid">Semilattice</span> <span class="varid">b</span>) <span class="keyglyph">=&gt;</span> <span class="conid">Semilattice</span> (<span class="varid">a</span>,<span class="varid">b</span>) <span class="keyword">where</span>
    <span class="varid">meet</span> (<span class="varid">a</span>,<span class="varid">b</span>) (<span class="varid">c</span>,<span class="varid">d</span>) <span class="keyglyph">=</span> (<span class="varid">meet</span> <span class="varid">a</span> <span class="varid">c</span>, <span class="varid">meet</span> <span class="varid">b</span> <span class="varid">d</span>)
<span class="keyword">instance</span> (<span class="conid">Satisfy</span> <span class="varid">a</span> <span class="varid">b</span>, <span class="conid">Satisfy</span> <span class="varid">c</span> <span class="varid">d</span>) <span class="keyglyph">=&gt;</span> <span class="conid">Satisfy</span> (<span class="varid">a</span>,<span class="varid">c</span>) (<span class="varid">b</span>,<span class="varid">d</span>) <span class="keyword">where</span>
    <span class="varid">satisfy</span> (<span class="varid">a</span>,<span class="varid">c</span>) (<span class="varid">b</span>,<span class="varid">d</span>) <span class="keyglyph">=</span> <span class="varid">satisfy</span> <span class="varid">a</span> <span class="varid">b</span> <span class="varop">&amp;&amp;</span> <span class="varid">satisfy</span> <span class="varid">c</span> <span class="varid">d</span>
</pre><p>Now we can not only questions like "What is the first/last/smallest element that is greater than some given query?". But also "What is the first/last/smallest element greater than a given query that also satisfies some other property?".
</p><h2><a name="when-is-it-efficient-"/>When is it efficient? </h2>
<p>It's nice that we now have a search tree that always gives correct answers.
But is it also efficient?
</p><p>As hinted in the introduction, that is not always the case.
First of all, <tt><span class="varid">meet</span></tt> could give a really bad bound. For example, if <tt><span class="varid">meet</span> <span class="varid">a</span> <span class="varid">b</span> <span class="keyglyph">=</span> <span class="conid">Bottom</span></tt> for all <tt><span class="varid">a</span> <span class="varop">/=</span> <span class="varid">b</span></tt>, and Bottom satisfies everything, then we really can do no better than a brute force search.
</p><p>On the other hand, suppose that <tt><span class="varid">meet</span></tt> gives 'perfect' information, like the <tt><span class="conid">Ge</span></tt> example above,
</p><pre class="haskell-equational-reasoning"><span class="varid">satisfy</span> <span class="varid">q</span> (<span class="varid">meet</span> <span class="varid">a</span> <span class="varid">b</span>)  <span class="varop">==&gt;</span>  <span class="varid">satisfy</span> <span class="varid">q</span> <span class="varid">a</span> <span class="varop">||</span> <span class="varid">satisfy</span> <span class="varid">q</span> <span class="varid">b</span>
</pre><p>That is equivalent to saying that
</p><pre class="haskell-equational-reasoning"><span class="varid">not</span> (<span class="varid">satisfy</span> <span class="varid">q</span> <span class="varid">a</span>) <span class="varop">&amp;&amp;</span> <span class="varid">not</span> (<span class="varid">satisfy</span> <span class="varid">q</span> <span class="varid">b</span>) <span class="varop">==&gt;</span> <span class="varid">not</span> (<span class="varid">satisfy</span> <span class="varid">q</span> (<span class="varid">meet</span> <span class="varid">a</span> <span class="varid">b</span>))
</pre><p>Then for any Branch, we only have to search either the left or the right subtree.
Because, if a subtree doesn't contain the value, we know can see so from the bound.
For a balanced tree, that means the search takes <span class="math">O(log n)</span> time.
</p><p>Another efficient case is when the items are sorted.
By that I mean that, if an item satisfies the query, then all items after it also satisfy that query.
We actually need something slightly more restrictive: namely that if a query is satisfied for the meet of some items, then all items after them also satisfy the query.
In terms of code:
</p><pre class="haskell-equational-reasoning"><span class="keyword">let</span> <span class="varid">st</span> <span class="keyglyph">=</span> <span class="varid">fromList</span> (<span class="varid">xs<sub>1</sub></span> <span class="varop">++</span> <span class="varid">xs<sub>2</sub></span> <span class="varop">++</span> <span class="varid">xs<sub>3</sub></span>)
<span class="varid">satisfy</span> <span class="varid">q</span> (<span class="varid">meet</span> <span class="varid">xs<sub>2</sub></span>)  <span class="varop">==&gt;</span>  <span class="varid">all</span> (<span class="varid">satisfy</span> <span class="varid">q</span>) <span class="varid">xs<sub>3</sub></span>
</pre><p>Now suppose that we are searching a tree of the form <tt><span class="varid">st</span> <span class="keyglyph">=</span> <span class="varid">mkBranch</span> <span class="varid">a</span> <span class="varid">b</span></tt> with <tt><span class="varid">findFirst</span> <span class="varid">q</span></tt>. Then there are three cases:
</p><ol><li><tt><span class="varid">not</span> (<span class="varid">satisfy</span> <span class="varid">q</span> (<span class="varid">bound</span> <span class="varid">st</span>))</tt>.
</li><li><tt><span class="varid">not</span> (<span class="varid">satisfy</span> <span class="varid">q</span> (<span class="varid">bound</span> <span class="varid">a</span>))</tt>.
</li><li><tt><span class="varid">satisfy</span> <span class="varid">q</span> (<span class="varid">bound</span> <span class="varid">a</span>)</tt>.</li></ol>
<p>In the first case the search fails, and we are done.
In the second case, we only have to search <tt><span class="varid">b</span></tt>, which by induction can be done efficiently.
The third case is not so clear.
In fact, there are two sub cases:
</p><ul style="padding: 0 1em;"><li>3a. findFirst q a = Just someResult
</li><li>3b. findFirst q b = Nothing</li></ul>
<p>In case 3a we found something in the left branch. Since we are only interested in the first result, that means we are done.
In case 3b, we get to use the fact that the items are sorted. Since we have <tt><span class="varid">satisfy</span> <span class="varid">q</span> (<span class="varid">bound</span> <span class="varid">a</span>)</tt>, that means that all items in <tt><span class="varid">b</span></tt> will satisfy the query. So when searching <tt><span class="varid">b</span></tt>, in all cases we take the left branch.
</p><p>Overall, the search time will be at most twice the depth of the tree, which is <span class="math">O(log n)</span>.
</p><p>The really cool thing is that we can combine the two conditions. If satisfy can be written as
</p><pre class="ghci"><span class="varid">satisfy</span> <span class="varid">q</span> <span class="varid">a</span> <span class="varop">==</span> <span class="varid">satisfy<sub>1</sub></span> <span class="varid">q</span> <span class="varid">a</span> <span class="varop">&amp;&amp;</span> <span class="varid">satisfy<sub>2</sub></span> <span class="varid">q</span> <span class="varid">a</span>
</pre><p>where <tt><span class="varid">satisfy<sub>1</sub></span></tt> has exact bounds, and the tree is sorted for <tt><span class="varid">satisfy<sub>2</sub></span></tt>, then queries still take <span class="math">O(log n)</span> time.
</p><h2><a name="closing-example"/>Closing example </h2>
<p>Finally, here is an example that makes use of efficient searching with the two conditions.
I make use of the <tt><span class="conid">Semilattice</span></tt> and <tt><span class="conid">Satisfy</span></tt> instances for pairs which I defined above.
</p><pre class="haskell"><span class="varid">treeOfPresidents</span> <span class="keyglyph">::</span> <span class="conid">SearchTree</span> (<span class="conid">Max</span> <span class="conid">Int</span>, <span class="conid">Max</span> <span class="conid">String</span>)
<span class="varid">treeOfPresidents</span>
   <span class="keyglyph">=</span> <span class="varid">fromList</span> <span class="listcon">[</span> (<span class="conid">Max</span> <span class="varid">year</span>, <span class="conid">Max</span> <span class="varid">name</span>) <span class="keyglyph">|</span> (<span class="varid">year</span>,<span class="varid">name</span>) <span class="keyglyph">&lt;-</span> <span class="varid">usPresidents</span> <span class="listcon">]</span>
 <span class="keyword">where</span>
   <span class="varid">usPresidents</span> <span class="varop">=</span>
     <span class="listcon">[</span>(<span class="num">1789</span>,<span class="str">"George Washington"</span>)
     ,(<span class="num">1797</span>,<span class="str">"John Adams"</span>)
     ,(<span class="num">1801</span>,<span class="str">"Thomas Jefferson"</span>)
     <span class="comment">-- etc</span>
</pre><p>The tree is ordered by year of election, and the <tt><span class="conid">Max</span></tt> semilattice gives tight bounds for names. So we can efficiently search for the first US presidents elected after 1850 who's name comes starts with a letter after "P":
</p><pre class="ghci"><span class="input">λ&gt;</span> <span class="varid">findFirst</span> (<span class="conid">Ge</span> <span class="num">1850</span>,<span class="conid">Ge</span> <span class="str">"P"</span>) <span class="varid">treeOfPresidents</span>
<span class="conid">Just</span> (<span class="conid">Max</span> <span class="num">1869</span>,<span class="conid">Max</span> <span class="str">"Ulysses S. Grant"</span>)
</pre><p>And with the following query type we can search on just one of the elements of the tuple.
Note that we need the type parameter in <tt><span class="conid">Any</span></tt> because of the functional dependency in the <tt><span class="conid">Satisfy</span></tt> class.
</p><pre class="haskell"><span class="keyword">data</span> <span class="conid">Any</span> <span class="varid">s</span> <span class="keyglyph">=</span> <span class="conid">Any</span>
<span class="keyword">instance</span> <span class="conid">Semilattice</span> <span class="varid">s</span> <span class="keyglyph">=&gt;</span> <span class="conid">Satisfy</span> (<span class="conid">Any</span> <span class="varid">s</span>) <span class="varid">s</span> <span class="keyword">where</span>
    <span class="varid">satisfy</span> <span class="varid">_</span> <span class="varid">_</span> <span class="keyglyph">=</span> <span class="conid">True</span>
</pre><pre class="ghci"><span class="input">λ&gt;</span> <span class="varid">findFirst</span> (<span class="conid">Ge</span> <span class="num">1911</span>,<span class="conid">Any</span>) <span class="varid">treeOfPresidents</span>
<span class="conid">Just</span> (<span class="conid">Max</span> <span class="num">1913</span>,<span class="conid">Max</span> <span class="str">"Woodrow Wilson"</span>)
</pre></div>
    </content>
    <updated>2012-02-07T22:56:00Z</updated>
    <category scheme="http://twanvl.nl/" term="haskell"/>
    <source>
      <id>http://twanvl.nl/blog</id>
      <author>
        <name>Twan van Laarhoven</name>
        <email>blog@twanvl.nl</email>
      </author>
      <link href="http://twanvl.nl/feed" rel="self" type="application/atom+xml"/>
      <link href="http://twanvl.nl/blog" rel="alternate" type="text/html"/>
      <title>Twan van Laarhoven's blog</title>
      <updated>2012-02-07T22:56:00Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://brandon.si/code/how-the-haskell-prelude-avoids-overlapping-types-in-show</id>
    <link href="http://brandon.si/code/how-the-haskell-prelude-avoids-overlapping-types-in-show/" rel="alternate" type="text/html"/>
    <title>How the Haskell Prelude avoids overlapping instances in Show</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><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'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 "extra-method trick" 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'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's the instance declaration for <code>[a]</code> where I'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 "extra-method" 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></div>
    </content>
    <updated>2012-02-07T02:47:00Z</updated>
    <source>
      <id>http://brandon.si/</id>
      <author>
        <name>Brandon Simmons</name>
        <email>brandon.m.simmons@gmail.com</email>
      </author>
      <link href="http://brandon.si/./code/atom.xml" rel="self" type="application/atom+xml"/>
      <link href="http://brandon.si/" rel="alternate" type="text/html"/>
      <title>Posts on code | Brandon.Si(mmons)</title>
      <updated>2012-02-07T04:05:24Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://chrisdone.com/posts/2012-02-07-nice-shell.html</id>
    <link href="http://chrisdone.com/posts/2012-02-07-nice-shell.html" rel="alternate" type="text/html"/>
    <title>Towards a nicer shell?</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Just an idea to look into when I have more time.</p><p>It would be kinda cool to write a shell that had intimate knowledge of the options and input/output types of shell commands, by user-contributed interfaces.</p><p>So, “oh, I just installed notify-send, I’ll look online for a notify-send wrapper”, install, and poof, I have option completion and validation, including completion for those enumerated types like LEVEL, ICON, NAME that are <em>sometimes</em> in the man page.</p><p>Could include easily-accessible useful examples and such, especially for those obscure commands with non-obvious interfaces.</p><p>A Haskell shell with user-contributed wrappers is one reasonable route. There are <a href="http://www.haskell.org/haskellwiki/Applications_and_libraries/Operating_system#Haskell_shell_examples">already Haskell shells out there</a>, but most are dead. There is room here to replace the regular shell in the same way XMonad replaced the regular window manager.</p></div>
    </summary>
    <updated>2012-02-07T00:00:00Z</updated>
    <source>
      <id>http://chrisdone.com</id>
      <author>
        <name>Christopher Done</name>
      </author>
      <link href="http://chrisdone.com" rel="alternate" type="text/html"/>
      <link href="http://chrisdone.com/haskell.rss" rel="self" type="application/atom+xml"/>
      <subtitle>Chris Done's haskell posts</subtitle>
      <title>Chris Done's haskell posts</title>
      <updated>2012-02-10T03:22:23Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-2162461901212281926.post-3250399343291677406</id>
    <link href="http://blog.codersbase.com/feeds/3250399343291677406/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://blog.codersbase.com/2012/02/proposal-community-wide-build.html#comment-form" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/2162461901212281926/posts/default/3250399343291677406" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/2162461901212281926/posts/default/3250399343291677406" rel="self" type="application/atom+xml"/>
    <link href="http://blog.codersbase.com/2012/02/proposal-community-wide-build.html" rel="alternate" type="text/html"/>
    <title>Proposal: Community wide build infrastructure</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><div><span style="font-size: large;">Status Quo</span></div>As Haskellers we live in a world where our tools just keep getting better. See for example the <a href="http://www.haskell.org/ghc/docs/7.4.1/html/users_guide/release-7-4-1.html">GHC release notes</a> that contains gems like this: Eq and Show are no longer required for Num.  GHC releases break backwards compatibility so that they can bring us really valuable updates and improvements.<br/><br/>It's not just GHC that is a moving target.  Everything in the Haskell community is improving and moving.  Hackage gets tons of new packages and updated packages <a href="http://www.haskell.org/haskellwiki/Hackage_statistics">each week</a>.  Updates to libraries on Hackage tend to follow in the precedent set by GHC. Breaking API changes are common, and always well intentioned.<br/><br/>The <a href="http://www.haskell.org/haskellwiki/Package_versioning_policy">package versioning policy (PVP)</a> helps by allowing us to express our package dependencies in terms of what we expect to be a breaking change and what is meant to be a non-breaking change. Even so, accidental API breakages creep in and some authors fail to follow the PVP due to ignorance or choice.<br/><br/><span style="font-size: large;">Problem</span><br/>The downside to all the wonderful flux is that it's hard to keep your code building in the varied environments that it ends up in. Fixing a deprecation warning on one version of GHC puts you at risk of not building on a previous, but important, release of GHC.  For example, in 7.4.1, mkTyCon is now deprecated in favor of the recently added mkTyCon3.<br/><br/>Build with -Werror -Wall and you're even more likely to run into problems. Actually, I highly recommend disabling -Werror before posting to hackage. Feel free to use it for dev builds.<br/><br/>How can each of us be sure that when we release to hackage that our source builds on the most machines possible?  How can we as a community make sure that our software is buildable with minimum hassle?<br/><br/><span style="font-size: large;">Proposal</span><br/>I think the only real solution for this problem is testing. I need to try my software in the different environments that I want to support. At a high level, that's Windows, OSX, and Linux.  At a more detailed level that includes testing on multiple versions of ghc and trying out different versions of the dependencies from hackage and comparing against my testsuite. That's exactly how we do it at work and it works well.<br/><br/>I think it's time for a community visible build service. Apache offers <a href="https://builds.apache.org/">this</a> for projects under their care. Details about their service are found <a href="http://ci.apache.org/">here</a>.<br/><br/>My current thinking is to combine <a href="http://hudson-ci.org/">Hudson</a> or <a href="http://jenkins-ci.org/">Jenkins</a>, possibly with some form of sandboxing such as <a href="http://freecode.com/projects/sydbox">sydbox</a>. Do sandboxing tools exist for Windows and OSX? Another approach to sandboxing is to clone a virtual machine and discard it after the build finishes or a timeout occurs.<br/><br/>A completely different approach is to trust the community to not abuse the servers and let anyone apply for an account, with new user vetting. I think this is my preferred stance. If we make it so build machines are disposable and easy to redeploy from scratch, resource usage is monitored or capped per-request, and community members are moderating use, then I believe it should be possible to use the honor system.<br/><br/>Each build machine would have multiple versions of GHC installed. Additional extra-libraries could be petitioned for so that lots of C bindings would be buildable.<br/><br/>Users need to be able to submit projects, and their dependencies, for build testing before pushing the result to hackage.<br/><br/>What else does it need to do?<br/><br/><span style="font-size: large;">Call for Volunteers</span><br/>I could build a private set of build machines for my own use and maintain them, but I don't think I'm alone in wanting this. Who is with me?<div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/2162461901212281926-3250399343291677406?l=blog.codersbase.com" width="1"/></div></div>
    </content>
    <updated>2012-02-06T02:20:22Z</updated>
    <published>2012-02-06T02:19:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="haskell"/>
    <author>
      <name>dagitj</name>
      <email>noreply@blogger.com</email>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-2162461901212281926</id>
      <category term="correctness"/>
      <category term="haskell galois professional-development course"/>
      <category term="commute"/>
      <category term="math"/>
      <category term="advice"/>
      <category term="hackingsprint"/>
      <category term="latex"/>
      <category term="tutorial"/>
      <category term="continuations"/>
      <category term="cabal"/>
      <category term="syntax"/>
      <category term="pdx"/>
      <category term="freedom"/>
      <category term="gui"/>
      <category term="libraries"/>
      <category term="proof"/>
      <category term="chrome"/>
      <category term="types"/>
      <category term="ghc"/>
      <category term="c"/>
      <category term="evidence"/>
      <category term="ui"/>
      <category term="takusen"/>
      <category term="darcs"/>
      <category term="opengl"/>
      <category term="git"/>
      <category term="opinion"/>
      <category term="metrics"/>
      <category term="haskell"/>
      <category term="gcc"/>
      <category term="performance"/>
      <category term="testing"/>
      <category term="imported"/>
      <category term="database"/>
      <author>
        <name>dagitj</name>
        <email>noreply@blogger.com</email>
      </author>
      <link href="http://blog.codersbase.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/2162461901212281926/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://blog.codersbase.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle>compilations of a developer</subtitle>
      <title>dagit.o</title>
      <updated>2012-02-07T22:08:16Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://r6.ca/blog/20120206T005236Z.html</id>
    <link href="http://r6.ca/blog/20120206T005236Z.html" rel="alternate" type="text/html"/>
    <title>Mirco… Mezzo… Macroflation—Overheated Economy</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Open deal.

</p><blockquote>
<p>You see, money gets its power from confidence.
Therefore undermine that confidence and the rest is just a chain reaction.</p>
</blockquote>

<p>I propose an economic experiment.
What would the effect of <abbr title="fear, uncertainty and doubt">FUD</abbr> be on Midas Money?
What would happen if someone released an article on a “Devistating flaw in Midas Money!!!”[sic]?
One might expect confidence to be undermined; people will desperately sell any coins they have.
However, luke-jr suggests that, historically speaking, there is no such thing as bad publicity when it comes to Midas Money.
Let us try.

</p><p>Loosely speaking, Midas Money works by using a distributed network to maintain a global ledger by sequencing transactions.
In this article, I call unspent outputs of transactions <em>open transactions</em>.
Every ten minutes, on average, transactions are sequenced into a block.
Proof of work makes it difficult to forge blocks.
Blocks are sequenced into a chain.
It is possible for the chain to become forked, in which case, the chain with the most work wins.
The number of confirmations a transaction has is the number of blocks (inclusive) in the longest chain above the transaction.
Generally speaking the more confirmations a transaction has, the more secure it is, and the more confidence one has that it will not be erased from the ledger.
Or at least that is how it is supposed to work.

</p><p>Unfortunately there is a small flaw in the core Midas Money protocol.
It is widely believed that a transaction can be identified by its hash; however, this is false.
The hash of a transaction identifies the transaction’s contents, but not its identity.
Although transactions are linked together in a flow network, the sources of the flow network, known as coinbases, all have
the same null input.
Thus if two different coinbases contain the same value and the same <code>extraNonce</code>, they will have the same hash.
So it is possible for two different transactions to have the same hash, and thus a transaction hash does not uniquely identify a transaction.

</p><p>Duplicate coinbases already exist in the Midas Money block chain.
The <a href="https://blockexplorer.com/tx/d5d27987d2a3dfc724e359870c6644b40e497bdc0589a033220fe15429d88599">coinbase <abbr title="d5d27987d2a3dfc724e359870c6644b40e497bdc0589a033220fe15429d88599">d5d279…</abbr></a> appears in both <a href="https://blockexplorer.com/block/00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f">block <abbr title="00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f">af0aed…</abbr></a> and block <a href="https://blockexplorer.com/block/00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec">block <abbr title="00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec">a4d0a3…</abbr></a>.
Also the <a href="https://blockexplorer.com/tx/e3bf3d07d4b0375638d5f1db5255fe07ba2c4cb067cd81b84ee974b6585fb468">coinbase <abbr title="e3bf3d07d4b0375638d5f1db5255fe07ba2c4cb067cd81b84ee974b6585fb468">e3bf3d…</abbr></a> appears in both <a href="https://blockexplorer.com/block/00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e">block <abbr title="00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e">271a2d…</abbr></a> and block <a href="https://blockexplorer.com/block/00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721">block <abbr title="00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721">743f19…</abbr></a>.

</p><p>Even the standard client falsely believes that transactions can be identified by their hash.
The effect of a duplicate transaction is to overwrite the previous transaction bearing the same hash in the client’s database.
This effect is not properly reversed during a block chain reorganization event.
During reorganization, instead of restoring the original transaction, the transaction is simply erased!
Under normal circumstances the transaction will eventually be restored in the forked chain.
However, if its inputs are spent by another transaction in the mean time then it will not be restored.
Such an event is called a <em>double spend</em>.

</p><p>There are probably several ways to exploit this flaw in the Midas Money protocol.
One plausible attack that comes to mind is the ability to, in some circumstances, revert arbitrarily confirmed transactions to 1-confirmation transactions, which are then subject to double spending.
Just to be perfectly clear: <strong>it is possible, in some circumstances, for someone to destroy your confirmed transactions</strong>.

</p><p>The way the attack works is as follows.
For simplicity, let us assume that there is a series of transactions all rooted in a single coinbase that mined by Alice.
Alice has the potential to destroy all transactions that are rooted solely in her coinbase.
Alice proceeds to mine a duplicate of her coinbase.
Since her coinbase is already spent, this does not overwrite any entry in the client’s transaction database.
Then Alice duplicates all the transactions above her coinbase, all the way to the open transactions at the leaves of the flow network above her coinbase.
Alice does not need any private keys to do this since she can duplicate existing published signatures.
She includes all these transactions into a new block.
The client overwrites the existing open transactions with her duplicates.
The effect of this is to revert those user’s open transactions back to 1-confirmation transactions, no matter how many confirmations they originally had.
Now these users coins are only weakly protected against double spending.
With a bit of luck and/or skill Alice could fork the blockchain just behind this new block.
The ensuing chain reorganization will destroy all the transactions above her coinbase.
In the forked branch, Alice then “double spends” her coinbase.
This permanently disconnects all the attacked transactions and effectively destroys them.
The attack is complete.

</p><p>This is not really a “double spend attack” in the traditional sense.
Alice gets no monetary advantage from this particular attack.
Neither does Alice incur a financial loss, unless her double spend fails.
This attack is a more of a “screw you” attack that simply destroys existing users confirmed transactions.

</p><p>There are several variations of this basic attack.
Alice’s transaction does not have to be a coinbase.
The attack can be carried out by duplicate mining the coinbases supporting her transaction and using them to duplicate her
non-coinbase transaction.
The attack then proceeds as above.
Also, the flow network above Alice’s transaction need not be entirely supported by her transaction.
However she can only attack the open transactions that that are supported entirely by her transactions, and because of this she cannot attack more coins than she duplicate mine.
Alice would likely take some financial loss to pull off the attack in these more general situations.

</p><p>This is just one possible attack.
I am certain others out there will come out with even more compelling ways to exploit this flaw in the Midas Money protocol.
(Here is where the <abbr title="fear, uncertainty and doubt">FUD</abbr> enters the picture.)
This is not a new flaw; people have known about it for years.
However, I do not believe that people have fully appreciated its consequences before.

</p><p>Beyond the Midas Money client, this flaw is a nightmare for merchants.
I imagine most merchant software presumes that transactions can be identified by their hash.
As we have seen above, they cannot.
This means all sorts of strange things are possible with merchant software, including potential for attacks.
For example, <a href="http://blockexplorer.com/">block explorer</a> can coerced into displaying <a href="http://blockexplorer.com/testnet/address/mtoKs9V381UAhUia3d7Vb9GNak8Qvmcsme">a negative balance for an address</a>.
Who knows what attacks against merchants are possible (more <abbr title="fear, uncertainty and doubt">FUD</abbr>)?
Maybe we will shortly find out.

</p><p class="figure">&lt;object class="youtube" data="http://www.youtube.com/v/sFhgfA1G2Uw?version=3&amp;amp;hl=en_US&amp;amp;rel=0" type="application/x-shockwave-flash"&gt;&lt;param name="movie" value="http://www.youtube.com/v/sFhgfA1G2Uw?version=3&amp;amp;hl=en_US&amp;amp;rel=0"/&gt;
&lt;param name="allowFullScreen" value="true"/&gt;
&lt;param name="allowscriptaccess" value="always"/&gt;
<a href="http://www.youtube.com/v/sFhgfA1G2Uw?version=3&amp;hl=en_US&amp;rel=0">http://www.youtube.com/v/sFhgfA1G2Uw?version=3&amp;hl=en_US&amp;rel=0</a>&lt;/object&gt;

</p><p>Closing.  You are bankrupt.

</p></div>
    </content>
    <updated>2012-02-06T00:52:36Z</updated>
    <published>2012-02-06T00:52:36Z</published>
    <source>
      <id>http://r6.ca/blog/</id>
      <author>
        <name>Russell O’Connor</name>
        <uri>http://r6.ca/</uri>
      </author>
      <link href="http://r6.ca/blog/" rel="alternate" type="text/html"/>
      <link href="http://r6.ca/blog/feed.atom" rel="self" type="application/atom+xml"/>
      <title>Russell O’Connor’s Blog</title>
      <updated>2012-02-06T00:52:36Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-11295132.post-29861029775144620</id>
    <link href="http://blog.sigfpe.com/feeds/29861029775144620/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://www.blogger.com/comment.g?blogID=11295132&amp;postID=29861029775144620" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/11295132/posts/default/29861029775144620" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/11295132/posts/default/29861029775144620" rel="self" type="application/atom+xml"/>
    <link href="http://blog.sigfpe.com/2012/02/lawvere-theories-made-bit-easier.html" rel="alternate" type="text/html"/>
    <title>Lawvere theories made a bit easier</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><b>Introduction</b><br/>I still don't think anyone has found a completely satisfactory way to combine effects in Haskell. (That's computational effects, not visual effects.) Monads are great for one kind of effect at a time, but it's not clear how to combine two arbitrary monads. Instead of monads we can work with monad transformers, but they are tricky both to implement and to use.<br/><br/>I want to sketch a different, though incomplete approach to combining effects. There are a bunch of papers that describe this approach, and even some code that implements part of it. Almost everything I say is from a <a href="http://lambda-the-ultimate.org/node/3235">paper</a> by Hyland and Powers that I read a few years ago though I recently ran into this helpful <a href="http://mathoverflow.net/questions/70162/why-lawvere-theories-have-finite-products-and-more">answer</a> by Andrej Bauer on mathoverflow. Even if we don't get code we can immediately use, we still get a good way to think about and analyse effects.<br/><br/>I'll get onto the effects part in another post. This one concentrates on what are known as Lawvere theories.<br/><br/><b>Monoids</b><br/><br/><pre>&gt; {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, ExplicitForAll #-}<br/>&gt; import Data.Monoid<br/><br/></pre>The (finite) lists of integers form a monoid. Here are some functions that operate on such lists:<br/><br/><pre>&gt; f1 xs = map (+1) $ reverse xs<br/>&gt; f2 xs = xs `mappend` xs<br/><br/></pre>They can both be given signature <tt>[Integer] -&gt; [Integer]</tt>. But there's one very important difference between these functions. <tt>f2</tt> has been written using only operations from the type class <tt>Monoid</tt>. It's a sort of universal function that can be applied to any monoid. On the other hand, the function <tt>f1</tt> can only applied to very specific monoids. In fact, the type signature of <tt>f2</tt> can be written as:<br/><br/><pre>&gt; f2 :: forall a. Monoid a =&gt; a -&gt; a<br/><br/></pre>That type signature essentially says that we're not going to do anything with elements of <tt>a</tt> except use the interface defined by the <tt>Monoid</tt> type class.<br/><br/>(Although Haskell type classes can't enforce them, we also assume that any instance of <tt>Monoid</tt> satisfies the axioms for a monoid.)<br/><br/>We can also define functions on tuples of monoids. Here are some examples:<br/><br/><pre>&gt; g1 :: forall a. Monoid a =&gt; (a, a, a) -&gt; (a, a)<br/>&gt; g1 (xs, ys, zs) = (mempty, ys `mappend` xs)<br/><br/>&gt; g2 :: forall a. Monoid a =&gt; (a, a) -&gt; (a, a)<br/>&gt; g2 (xs, ys) = (xs `mappend` ys, ys `mappend` xs)<br/><br/></pre>Notice that we can compose these functions. So we have<br/><pre>g2 . g1 :: forall a. Monoid a =&gt; (a, a, a) -&gt; (a, a)<br/></pre><br/>We also have have identity functions for tuples. Armed with functions, identities and compositions can now form a category that I'll call <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/>. I'll call the (distinct) objects of this category <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M%5f0" style="vertical-align: middle;"/>, <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M%5f1" style="vertical-align: middle;"/>, <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M%5f2" style="vertical-align: middle;"/> and so on. The arrows from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M%5fm" style="vertical-align: middle;"/> to <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M%5fn" style="vertical-align: middle;"/> are the total functions of type <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cforall+a.%5cmbox%7bMonoid+%7da%5cRightarrow+a%5em%5crightarrow+a%5en" style="vertical-align: middle;"/>. So, for example, <tt>g1</tt> is an arrow from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M%5f3" style="vertical-align: middle;"/> to <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M%5f2" style="vertical-align: middle;"/>. Note that it doesn't matter what the objects are (as long as they're distinct). They're just placeholders between which we can string our arrows. Note how because of the universal quantifier, the functions we use have a type not of the form <tt>A -&gt; B</tt>. So we can't represent the objects of our category as types in the usual way. We can think of <tt>mempty</tt> as a 0-ary operator, ie. an element of <tt>forall a. Monoid a =&gt; () -&gt; a</tt>.<br/><br/>But there's one more detail I want. I'll consider two arrows to be equal if they can be proved equal using the axioms for monoids. For example, these two Haskell functions represent the same arrow in <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> because of the associativity law:<br/><br/><pre>&gt; h1 (x, y, z) = (x `mappend` y) `mappend` z<br/>&gt; h2 (x, y, z) = x `mappend` (y `mappend` z)<br/><br/></pre>We now have a bona fide category. Note that <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> contains lots of arrows. Anything you can build using <tt>mempty</tt> and <tt>mappend</tt> as well as all of the projections and permutations between tuples. <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> completely captures everything that can be deduced using the axioms for monoids. For example, the associativity law is contained in the fact that <tt>h1</tt> and <tt>h2</tt> represent the same arrow.<br/><br/>The category <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> also has products. In fact it is given by <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M%5fm%5ctimes+M%5fn+%3d+M%5f%7bm%2bn%7d" style="vertical-align: middle;"/> with the projections back to the factors being represented by the obvious projection functions. <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M%5f0" style="vertical-align: middle;"/> serves as the product of no factors.<br/><br/>So <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> captures the properties shared by all monoids. But what is its relationship to actual monoids? It's pretty nice. A monoid is a functor <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=F%3aT%5crightarrow+Set" style="vertical-align: middle;"/> that preserves products.<br/><br/>Let's unpack that. First <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=F" style="vertical-align: middle;"/> must take objects in <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> to sets. But we've stipulated that <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=F%28A%5ctimes+B%29%3dF%28A%29%5ctimes+F%28B%29" style="vertical-align: middle;"/> so <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=F" style="vertical-align: middle;"/> is completely determined on objects once we know <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M+%3d+F%28M%5f1%29" style="vertical-align: middle;"/>. In fact <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=F%28M%5f1%29" style="vertical-align: middle;"/> will be the carrier for our monoid and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=F%28M%5fn%29" style="vertical-align: middle;"/> is its <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=n" style="vertical-align: middle;"/>th power. <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=F" style="vertical-align: middle;"/> takes arrows in <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> to functions on sets. So, for example, it gives concrete realisations of <tt>mempty</tt> and <tt>mappend</tt>. Because, for example, <tt>h1</tt> and <tt>h2</tt> represent the same arrow in <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/>, <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=F%28h1%29" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=F%28h2%29" style="vertical-align: middle;"/> must be equal. So associativity must hold for these realisations. The same goes for all of the other laws, and everything we can deduce from them. So the requirement of functoriality makes <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=F%28M%5f1%29" style="vertical-align: middle;"/> into a monoid with identity <tt>F(mempty)</tt> and product <tt>F(mappend)</tt>.<br/><br/>Given an instance of the <tt>Monoid</tt> type class we can immediately apply an arrow from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> to it. The functor is applied implicitly by the Haskell compiler. For example <tt>h1</tt> can be applied to <tt>("a", "b", "c") :: (String, String, String)</tt>.<br/><br/>The object <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M%5f1" style="vertical-align: middle;"/> in <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> is weird. It's a lot like the universal monoid sharing all of the properties you expect to hold simultaneously in all monoids. Except for one important one: it's not a monoid itself.<br/><br/>Note that in a sense the category <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> isn't anything new. It's just a convenient 'datastructure' into which we can pack everything we can deduce about monoids.<br/><br/><b>M-sets</b><br/>Before generalising, let's try a similar treatment for another algebraic structure, the horribly named <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M" style="vertical-align: middle;"/>-set. An <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M" style="vertical-align: middle;"/>-set is a structure on a set <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=S" style="vertical-align: middle;"/> that assumes we already have some choice of monoid <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M" style="vertical-align: middle;"/>. It defines an action of <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M" style="vertical-align: middle;"/> on the set. An action is simply a function <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=S%5crightarrow+S" style="vertical-align: middle;"/> defined for each element of <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M" style="vertical-align: middle;"/> and which is compatible with the operations on <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M" style="vertical-align: middle;"/>. Here's a suitable type class:<br/><br/>&gt; class Monoid m =&gt; MSet m s where<br/>&gt; act :: m -&gt; s -&gt; s<br/><br/>and the laws are<br/><pre>act mempty x == x<br/>act a (act b x) = act (a `mappend` b) x<br/></pre>We're thinking of <tt>act</tt> not as an operation on two arguments but instead thinking of <tt>act a</tt> being an operation on <tt>s</tt> for each element <tt>a</tt>. Note how that second law is really a lot of laws, one for every pair <tt>(a, b)</tt> in our monoid.<br/><br/>A simple example is the way scalars act on vectors.<br/><br/><pre>&gt; data Vector a = V a a a deriving Show<br/>&gt; instance Monoid a =&gt; MSet a (Vector a) where<br/>&gt;    act w (V x y z) = V (w `mappend` x) (w `mappend` y) (w `mappend` z)<br/><br/></pre>Given any particular monoid (eg. <tt>String</tt>) we can define functions like:<br/><br/><pre>&gt; j1 :: forall a. MSet String a =&gt; (a, a) -&gt; (a, a)<br/>&gt; j1 (x, y) = ("x" `act` x, "y" `act` y)<br/>&gt; j2 :: forall a. MSet String a =&gt; (a, a) -&gt; a<br/>&gt; j2 (x, y) = "abc" `act` x<br/><br/></pre>We can form a category in exactly the same way as for monoids. As the objects <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M%5fn" style="vertical-align: middle;"/> were just placeholders we may as well reuse them. The arrows from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M%5fm" style="vertical-align: middle;"/> to <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M%5fn" style="vertical-align: middle;"/> are the functions on tuples we can make from repeated applications of <tt>act</tt>, ie. <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cforall+a.%5cmbox%7bMSet+String+%7da%5cRightarrow+a%5em%5crightarrow+a%5en" style="vertical-align: middle;"/>. For each choice of <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M" style="vertical-align: middle;"/> we get a new category <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/> encoding everything we want to know about <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M" style="vertical-align: middle;"/>-sets. In much the same way, any functor <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=F%3aT%27%5crightarrow+Set" style="vertical-align: middle;"/> gives an <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M" style="vertical-align: middle;"/>-set. We have <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=F%28M%5fn%29+%3d+F%28M%5f1%29%5en" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=F" style="vertical-align: middle;"/> maps <tt>act a</tt> to the actual action on the set.<br/><br/><b>Lawvere theories</b><br/>So what do these two categories have in common?<br/><br/>Let's start with the simplest possible algebraic structure: a plain old set with no operations on it. The corresponding category will have objects <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5c%7bM%5f0%2c+M%5f1%2c+%5cldots%5c%7d" style="vertical-align: middle;"/>. The arrows from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M%5fm" style="vertical-align: middle;"/> to <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M%5fn" style="vertical-align: middle;"/> will be represented by functions of the form <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cforall+a.a%5em%5crightarrow+a%5en" style="vertical-align: middle;"/>. That includes functions like the projections onto elements of tuples or permutations of tuples. This category is called <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5caleph%5f0" style="vertical-align: middle;"/>.<br/><br/>Both <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/> defined earlier contain all of the objects and arrows of <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5caleph%5f0" style="vertical-align: middle;"/>. But both <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/> also contain arrows corresponding to all of the operations you can perform in their respective algebraic structures. So we can define a <a href="http://ncatlab.org/nlab/show/Lawvere+theory">Lawvere theory</a> <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> as nothing more than a category that is <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5caleph%5f0" style="vertical-align: middle;"/> with extra arrows. The category <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> defined earlier is the "theory of monoids" and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/> is the "theory of <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M" style="vertical-align: middle;"/>-sets". A 'model' of <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/>, or a <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/>-algebra, is a product-preserving functor <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=F%3aT%5crightarrow+Set" style="vertical-align: middle;"/>.<br/><br/><b>Product theories</b><br/>Suppose we have two theories <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/>. There's a straightforward way to combine them into one theory. Form the category that (like all Lawvere theories) shares the same objects as <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/> but has all of the arrows from both. (Obviously we'll have to keep just one identity, not an identity from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> and another from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/>.) The catch is that if <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=f%3aA%5crightarrow+B" style="vertical-align: middle;"/> is an arrow in <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=f%27%3aB%5crightarrow+C" style="vertical-align: middle;"/> is an arrow in <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/> we'll need the composition <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=f%27%5ccirc+f" style="vertical-align: middle;"/> too. We simply take the smallest set of arrows that contains all of the arrows from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/> and contains all of their compositions modulo all of the laws in <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/>.<br/><br/>Thus far we already have a new Lawvere theory built from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/>. But sometimes it's useful to ensure the operations from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> are 'compatible', in some sense, with those from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/>. We want them to commute with each other. I'll describe what that commutativity means now:<br/><br/>Suppose we have an arrows <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=f%3am%5crightarrow+n" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=f%27%3am%27%5crightarrow+n%27" style="vertical-align: middle;"/> on <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/> respectively. If we have a set <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=S" style="vertical-align: middle;"/> that is both a <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/>-algebra and a <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/>-algebra, then <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=f" style="vertical-align: middle;"/> gives an operation <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=S%5em%5crightarrow+S%5en" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=f%27" style="vertical-align: middle;"/> gives an operation <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=S%5e%7bm%27%7d%5crightarrow+S%5e%7bn%27%7d" style="vertical-align: middle;"/>. Write out an <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=m%27%5ctimes+m" style="vertical-align: middle;"/> array of variables:<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cbegin%7barray%7d%7bcccc%7d%0ax%5f%7b11%7d+%26+x%5f%7b12%7d+%26+%5cldots+%26+x%5f%7b1m%7d+%5c%5c%0ax%5f%7b21%7d+%26+x%5f%7b22%7d+%26+%5cldots+%26+x%5f%7b2m%7d+%5c%5c%0a%26%26+%5cldots+%26+%5c%5c%0ax%5f%7bm%271%7d+%26+x%5f%7bm%272%7d+%26+%5cldots+%26+x%5f%7bm%27m%7d+%5c%5c%0a%5cend%7barray%7d" style="vertical-align: middle;"/><br/></blockquote>We can apply <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=f" style="vertical-align: middle;"/> across the rows to get the <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=m%27%5ctimes+n" style="vertical-align: middle;"/> array:<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cbegin%7barray%7d%7brlccr%7d%0af%26%28x%5f%7b11%7d%2c+%26x%5f%7b12%7d%2c+%26%5cldots%2c+%26x%5f%7b1m%7d%29+%5c%5c%0af%26%28x%5f%7b21%7d%2c+%26x%5f%7b22%7d%2c+%26%5cldots%2c+%26x%5f%7b2m%7d%29+%5c%5c%0af%26%28%26%26%5cldots%26%29%5c%5c%0af%26%28x%5f%7bm%271%7d%2c+%26x%5f%7bm%272%7d%2c+%26%5cldots%2c+%26x%5f%7bm%27m%7d%29+%5c%5c%0a%5cend%7barray%7d" style="vertical-align: middle;"/><br/></blockquote>and now we can apply <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=f%27" style="vertical-align: middle;"/> down the columns to get an <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=n%27%5ctimes+n" style="vertical-align: middle;"/> array.<br/><br/>We could also have done this by applying <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=f%27" style="vertical-align: middle;"/> down the columns first and then <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=f" style="vertical-align: middle;"/> across the rows. We now throw in extra commutativity laws stating that these two operations give equal results, whatever the operations <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=f" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=f%27" style="vertical-align: middle;"/>.<br/><br/>For example, if the theory <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> has a binary multiplication operator <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=m" style="vertical-align: middle;"/> and the theory <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/> has binary multiplication operator <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=m%27" style="vertical-align: middle;"/> then commutativity requires <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=m%28m%27%28a%2cb%29%2cm%27%28c%2cd%29%29+%3d+m%27%28m%28a%2cc%29%2cm%28b%2cd%29%29" style="vertical-align: middle;"/>. This is the usual <a href="http://blog.sigfpe.com/2008/05/interchange-law.html">interchange law</a>. In this example the commutativity law is therefore an assertion about the equality of two arrows in <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M%5f4%5crightarrow+M%5f1" style="vertical-align: middle;"/>.<br/><br/>The result of combining the two theories <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/>, additionally throwing in these commutativity laws, is known as the product theory <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=L%5cotimes+L%27" style="vertical-align: middle;"/>.<br/><br/><b>Product theories in Haskell</b><br/>Although we can't get Haskell to enforce the commutativity rules we can get part way to defining product theories using type classes. We make our type an instance of both classes. For <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%27" style="vertical-align: middle;"/> defined as the theories of monoids and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=M" style="vertical-align: middle;"/>-sets above, a <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%5cotimes+T%27" style="vertical-align: middle;"/>-algebra is given by a type that is an instance of both <tt>Monoid</tt> and <tt>MSet</tt>. Unfortunately we can't make Haskell automatically enforce the rule that elements be equal if the laws say they should be.<br/><br/><b>Coming soon</b><br/>We've defined Lawvere theories. I've explained <a href="http://blog.sigfpe.com/2009/12/where-do-monads-come-from.html">previously</a> how many kinds of effects can be modelled by algebraic theories. I've defined a product on Lawvere theories. Which means we now have a way to combine effects. But for that you'll have to wait for the sequel.<div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/11295132-29861029775144620?l=blog.sigfpe.com" width="1"/></div></div>
    </content>
    <updated>2012-02-05T17:34:44Z</updated>
    <published>2012-02-05T15:57:00Z</published>
    <author>
      <name>sigfpe</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/08096190433222340957</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-11295132</id>
      <category term="monad"/>
      <category term="mathematics"/>
      <category term="physics"/>
      <category term="optimisation"/>
      <category term="astronomy"/>
      <category term="self-reference"/>
      <category term="probability"/>
      <category term="comonads"/>
      <category term="haskell"/>
      <category term="types"/>
      <category term="programming"/>
      <category term="quantum"/>
      <author>
        <name>sigfpe</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/08096190433222340957</uri>
      </author>
      <link href="http://blog.sigfpe.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/11295132/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://blog.sigfpe.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <link href="http://www.blogger.com/feeds/11295132/posts/default?start-index=26&amp;max-results=25" rel="next" type="application/atom+xml"/>
      <title>A Neighborhood of Infinity</title>
      <updated>2012-02-07T22:05:28Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://r6.ca/blog/20120205T004350Z.html</id>
    <link href="http://r6.ca/blog/20120205T004350Z.html" rel="alternate" type="text/html"/>
    <title>Local Song #1</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p><em>Local East Coast Back Beat</em> <abbr title="also known as">a.k.a</abbr> <em>Local Song #1</em> is one of my favourite songs.  It is composed and produced by Ken Vandevrie.
I recently found <a href="http://www.youtube.com/watch?v=FwsjJXpGhLs" title="Trevor Dick Weather Network Song.mp4">a wonderful live recording of it</a> on <a href="http://www.youtube.com/" title="YouTube - Broadcast Yourself.">YouTube</a> performed by <a href="http://flyingbow.com/?p=1003">Trevor Dick</a> who was the the violinist for the <a href="http://www.youtube.com/watch?v=vckj-Razt7Q">original recording</a>.
I think it deserves more than 76 views.

</p><p class="figure">&lt;object class="youtube" data="http://www.youtube.com/v/FwsjJXpGhLs?version=3&amp;amp;hl=en_US&amp;amp;rel=0" type="application/x-shockwave-flash"&gt;&lt;param name="movie" value="http://www.youtube.com/v/FwsjJXpGhLs?version=3&amp;amp;hl=en_US&amp;amp;rel=0"/&gt;
&lt;param name="allowFullScreen" value="true"/&gt;
&lt;param name="allowscriptaccess" value="always"/&gt;
[Youtube Embeded Video Not Available]&lt;/object&gt;

</p></div>
    </content>
    <updated>2012-02-05T00:43:50Z</updated>
    <published>2012-02-05T00:43:50Z</published>
    <source>
      <id>http://r6.ca/blog/</id>
      <author>
        <name>Russell O’Connor</name>
        <uri>http://r6.ca/</uri>
      </author>
      <link href="http://r6.ca/blog/" rel="alternate" type="text/html"/>
      <link href="http://r6.ca/blog/feed.atom" rel="self" type="application/atom+xml"/>
      <title>Russell O’Connor’s Blog</title>
      <updated>2012-02-06T00:52:36Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://pcapriotti.wordpress.com/?p=213</id>
    <link href="http://pcapriotti.wordpress.com/2012/02/04/monoidal-instances-for-pipes/" rel="alternate" type="text/html"/>
    <title>Monoidal instances for pipes</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">In this post, I’m going to introduce a new class of combinators for pipes, with an interesting categorical interpretation. I will be using the pipe implementation of my previous post. &gt; {-# LANGUAGE MultiParamTypeClasses #-} &gt; {-# LANGUAGE FlexibleInstances #-} &gt; {-# LANGUAGE TypeFamilies #-} &gt; {-# LANGUAGE GeneralizedNewtypeDeriving #-} &gt; module Blog.Pipes.MonoidalInstances where &gt; [...]<img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&amp;blog=806312&amp;post=213&amp;subd=pcapriotti&amp;ref=&amp;feed=1" width="1"/></div>
    </summary>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>In this post, I’m going to introduce a new class of combinators for pipes, with an interesting categorical interpretation. I will be using the pipe implementation of my <a href="http://pcapriotti.wordpress.com/2012/02/02/an-introduction-to-guarded-pipes/">previous post</a>.</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020;">{-# LANGUAGE MultiParamTypeClasses #-}</span>
&gt; <span style="color: #007020;">{-# LANGUAGE FlexibleInstances #-}</span>
&gt; <span style="color: #007020;">{-# LANGUAGE TypeFamilies #-}</span>
&gt; <span style="color: #007020;">{-# LANGUAGE GeneralizedNewtypeDeriving #-}</span>
&gt; <span style="color: #007020; font-weight: bold;">module</span> <span style="color: #902000;">Blog.Pipes.MonoidalInstances</span> <span style="color: #007020; font-weight: bold;">where</span>
&gt;
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Blog.Pipes.Guarded</span> <span style="color: #007020; font-weight: bold;">hiding</span> (groupBy)
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #007020; font-weight: bold;">qualified</span> <span style="color: #902000;">Control.Arrow</span> <span style="color: #007020; font-weight: bold;">as</span> <span style="color: #902000;">A</span>
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Control.Category</span>
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Control.Categorical.Bifunctor</span>
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Control.Category.Associative</span>
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Control.Category.Braided</span>
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Control.Category.Monoidal</span>
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Control.Monad</span> (forever)
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Control.Monad.Free</span>
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Data.Maybe</span>
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Data.Void</span>
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Prelude</span> <span style="color: #007020; font-weight: bold;">hiding</span> ((<span style="color: #06287e;">.</span>), <span style="color: #06287e;">id</span>, <span style="color: #06287e;">filter</span>, <span style="color: #06287e;">until</span>)</code></pre>
<p>When pipes were first released, some people noticed the lack of an <code>Arrow</code> instance. In fact, it is not hard to show that, even identifying pipes modulo some sort of observational equality, there is no <code>Arrow</code> instance that satisfies the arrow laws.</p>
<p>The problem, of course, is with <code>first</code>, because we already have a simple implementation of <code>arr</code>. If we try to implement <code>first</code> we immediately discover that there’s a problem with the <code>Yield</code> case:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">first (<span style="color: #902000;">Yield</span> x c) <span style="color: #06287e;">=</span> yield (x, <span style="color: #06287e;">???</span>) <span style="color: #06287e;">&gt;&gt;</span> first c</code></pre>
<p>Since ??? can be of any type, the only possible value is bottom, which of course we don’t want to introduce. Alternative definitions of <code>first</code> that alter the structure of a yielding pipe are not possible if we want to satisfy the law:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">first p <span style="color: #06287e;">&gt;+&gt;</span> pipe <span style="color: #06287e;">fst</span> <span style="color: #06287e;">==</span> pipe <span style="color: #06287e;">fst</span> <span style="color: #06287e;">&gt;+&gt;</span> p</code></pre>
<p>Concretely, the problem is that the cartesian product in the type of <code>first</code> forces a sort of "synchronization point" that doesn’t necessarily exist. This is better understood if we look at the type of <code>(***)</code>, of which <code>first</code> can be thought of as a special case:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell"><span style="color: #007020;">(***) </span><span style="color: #007020;">::</span> <span style="color: #902000;">Arrow</span> k <span style="color: #007020;">=&gt;</span> k a b <span style="color: #007020;">-&gt;</span> k a' b' <span style="color: #007020;">-&gt;</span> k (a, a') (b, b')

first <span style="color: #06287e;">=</span> (<span style="color: #06287e;">***</span> <span style="color: #06287e;">id</span>)</code></pre>
<p>If the two input pipes yield at different times, there is no way to faithfully match their yielded values into a pair. There are hacks around that, but they don’t behave well compositionally, and exhibit either arbitrarily large space leaks or data loss.</p>
<p>This has been addressed before: stream processors, like those of the <a href="http://www.altocumulus.org/Fudgets/">Fudgets</a> library, being very similar to Pipes, have the same problem, and <a href="http://www.google.ie/url?sa=t&amp;rct=j&amp;q=prodarrow+ps&amp;source=web&amp;cd=1&amp;ved=0CB8QFjAA&amp;url=http%3A%2F%2Fwww.carlssonia.org%2Fogi%2Fpapers%2Farrows.ps.gz&amp;ei=WXgqT-6pK5CzhAfZ_9DWCg&amp;usg=AFQjCNESuOahh6WeEsPTJoHHUbO8J858mQ&amp;sig2=Kffi1WwxedHlbogGNdUFRg">some resolutions</a> have been proposed, although not entirely satisfactory.</p>
<h2 id="arrows-as-monoidal-categories">Arrows as monoidal categories</h2>
<p>It is well known within the Haskell community that Arrows correspond to so called Freyd categories, i.e. premonoidal categories with some extra structures.</p>
<p>Using the <code>Monoidal</code> class by Edward Kmett (now in the <code>categories</code> package on Hackage), we can try to make this idea precise.</p>
<p>Unfortunately, we have to use a newtype to avoid overlapping instances in the case of the Hask category:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">newtype</span> <span style="color: #902000;">ACat</span> a b c <span style="color: #06287e;">=</span> <span style="color: #902000;">ACat</span> {<span style="color: #007020;"> unACat </span><span style="color: #007020;">::</span> a b c }
&gt;   <span style="color: #007020; font-weight: bold;">deriving</span> (<span style="color: #902000;">Category</span>, <span style="color: #902000;">A.Arrow</span>)</code></pre>
<p>First, cartesian products are a bifunctor in the category determined by an Arrow.</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #902000;">A.Arrow</span> a <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">PFunctor</span> (,) (<span style="color: #902000;">ACat</span> a) (<span style="color: #902000;">ACat</span> a) <span style="color: #007020; font-weight: bold;">where</span>
&gt;   first <span style="color: #06287e;">=</span> <span style="color: #902000;">ACat</span> <span style="color: #06287e;">.</span> A.first <span style="color: #06287e;">.</span> unACat
&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #902000;">A.Arrow</span> a <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">QFunctor</span> (,) (<span style="color: #902000;">ACat</span> a) (<span style="color: #902000;">ACat</span> a) <span style="color: #007020; font-weight: bold;">where</span>
&gt;   second <span style="color: #06287e;">=</span> <span style="color: #902000;">ACat</span> <span style="color: #06287e;">.</span> A.second <span style="color: #06287e;">.</span> unACat
&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #902000;">A.Arrow</span> a
&gt;       <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Bifunctor</span> (,) (<span style="color: #902000;">ACat</span> a) (<span style="color: #902000;">ACat</span> a) (<span style="color: #902000;">ACat</span> a) <span style="color: #007020; font-weight: bold;">where</span>
&gt;   bimap (<span style="color: #902000;">ACat</span> f) (<span style="color: #902000;">ACat</span> g) <span style="color: #06287e;">=</span> <span style="color: #902000;">ACat</span> <span style="color: #06287e;">$</span> f <span style="color: #06287e;">A.***</span> g</code></pre>
<p>Now we can say that products are associative, using the associativity of products in Hask:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #902000;">A.Arrow</span> a <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Associative</span> (<span style="color: #902000;">ACat</span> a) (,) <span style="color: #007020; font-weight: bold;">where</span>
&gt;   associate <span style="color: #06287e;">=</span> <span style="color: #902000;">ACat</span> <span style="color: #06287e;">$</span> A.arr associate
&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #902000;">A.Arrow</span> a <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Disassociative</span> (<span style="color: #902000;">ACat</span> a) (,) <span style="color: #007020; font-weight: bold;">where</span>
&gt;   disassociate <span style="color: #06287e;">=</span> <span style="color: #902000;">ACat</span> <span style="color: #06287e;">$</span> A.arr disassociate</code></pre>
<p>Where we use the <code>Disassociative</code> instance to express the inverse of the associator. And finally, the Monoidal instance:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">type</span> <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #902000;">Id</span> (<span style="color: #902000;">ACat</span> a) (,) <span style="color: #06287e;">=</span> ()
&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #902000;">A.Arrow</span> a <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Monoidal</span> (<span style="color: #902000;">ACat</span> a) (,) <span style="color: #007020; font-weight: bold;">where</span>
&gt;   idl <span style="color: #06287e;">=</span> <span style="color: #902000;">ACat</span> <span style="color: #06287e;">$</span> A.arr idl
&gt;   idr <span style="color: #06287e;">=</span> <span style="color: #902000;">ACat</span> <span style="color: #06287e;">$</span> A.arr idr
&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #902000;">A.Arrow</span> a <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Comonoidal</span> (<span style="color: #902000;">ACat</span> a) (,) <span style="color: #007020; font-weight: bold;">where</span>
&gt;   coidl <span style="color: #06287e;">=</span> <span style="color: #902000;">ACat</span> <span style="color: #06287e;">$</span> A.arr coidl
&gt;   coidr <span style="color: #06287e;">=</span> <span style="color: #902000;">ACat</span> <span style="color: #06287e;">$</span> A.arr coidr</code></pre>
<p>Where, again, the duals are actually inverses. Also, products are symmetric:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #902000;">A.Arrow</span> a <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Braided</span> (<span style="color: #902000;">ACat</span> a) (,) <span style="color: #007020; font-weight: bold;">where</span>
&gt;   braid <span style="color: #06287e;">=</span> <span style="color: #902000;">ACat</span> <span style="color: #06287e;">$</span> A.arr braid
&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #902000;">A.Arrow</span> a <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Symmetric</span> (<span style="color: #902000;">ACat</span> a) (,)</code></pre>
<p>As you see, everything is trivially induced by the cartesian structure on Hask, since <code>A.arr</code> gives us an identity-on-objects functor. Note, however, that the <code>Bifunctor</code> instance is legitimate only if we assume a strong commutativity law for arrows:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">first f <span style="color: #06287e;">&gt;&gt;&gt;</span> second g <span style="color: #06287e;">==</span> second g <span style="color: #06287e;">&gt;&gt;&gt;</span> first f</code></pre>
<p>which we will, for the sake of simplicity.</p>
<h2 id="replacing-products-with-arbitrary-monoidal-structures">Replacing products with arbitrary monoidal structures</h2>
<p>Once we express the Arrow concept in terms of monoidal categories, it is easy to generalize it to arbitrary monoidal structures on Hask.</p>
<p>In particular, coproducts work particularly well in the category of pipes:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #007020; font-weight: bold;">Monad</span> m
&gt;       <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">PFunctor</span> <span style="color: #902000;">Either</span> (<span style="color: #902000;">PipeC</span> m r) (<span style="color: #902000;">PipeC</span> m r) <span style="color: #007020; font-weight: bold;">where</span>
&gt;   first <span style="color: #06287e;">=</span> <span style="color: #902000;">PipeC</span> <span style="color: #06287e;">.</span> firstP <span style="color: #06287e;">.</span> unPipeC
&gt;
&gt; <span style="color: #007020;">firstP </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> a b m r
&gt;        <span style="color: #007020;">-&gt;</span> <span style="color: #902000;">Pipe</span> (<span style="color: #902000;">Either</span> a c) (<span style="color: #902000;">Either</span> b c) m r
&gt; firstP (<span style="color: #902000;">Pure</span> r) <span style="color: #06287e;">=</span> <span style="color: #06287e;">return</span> r
&gt; firstP (<span style="color: #902000;">Free</span> (<span style="color: #902000;">M</span> m)) <span style="color: #06287e;">=</span> lift m <span style="color: #06287e;">&gt;&gt;=</span> firstP</code></pre>
<p>Yielding a sum is now easy: just yield on the left component.</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; firstP (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Yield</span> x c)) <span style="color: #06287e;">=</span> yield (<span style="color: #007020; font-weight: bold;">Left</span> x) <span style="color: #06287e;">&gt;&gt;</span> firstP c</code></pre>
<p>Awaiting is a little bit more involved, but still easy enough: receive left and null values normally, and act like an identity on the right.</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; firstP (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Await</span> k)) <span style="color: #06287e;">=</span> go
&gt;         <span style="color: #007020; font-weight: bold;">where</span>
&gt;           go <span style="color: #06287e;">=</span> tryAwait
&gt;            <span style="color: #06287e;">&gt;&gt;=</span> <span style="color: #06287e;">maybe</span> (firstP <span style="color: #06287e;">$</span> k <span style="color: #007020; font-weight: bold;">Nothing</span>)
&gt;                      (<span style="color: #06287e;">either</span> (firstP <span style="color: #06287e;">.</span> k <span style="color: #06287e;">.</span> <span style="color: #007020; font-weight: bold;">Just</span>)
&gt;                              (\x <span style="color: #007020;">-&gt;</span> yield (<span style="color: #007020; font-weight: bold;">Right</span> x) <span style="color: #06287e;">&gt;&gt;</span> go))</code></pre>
<p>And of course we have an analogous instance on the right:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #007020; font-weight: bold;">Monad</span> m
&gt;       <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">QFunctor</span> <span style="color: #902000;">Either</span> (<span style="color: #902000;">PipeC</span> m r) (<span style="color: #902000;">PipeC</span> m r) <span style="color: #007020; font-weight: bold;">where</span>
&gt;   second <span style="color: #06287e;">=</span> <span style="color: #902000;">PipeC</span> <span style="color: #06287e;">.</span> secondP <span style="color: #06287e;">.</span> unPipeC
&gt;
&gt; <span style="color: #007020;">secondP </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> a b m r
&gt;         <span style="color: #007020;">-&gt;</span> <span style="color: #902000;">Pipe</span> (<span style="color: #902000;">Either</span> c a) (<span style="color: #902000;">Either</span> c b) m r
&gt; secondP (<span style="color: #902000;">Pure</span> r) <span style="color: #06287e;">=</span> <span style="color: #06287e;">return</span> r
&gt; secondP (<span style="color: #902000;">Free</span> (<span style="color: #902000;">M</span> m)) <span style="color: #06287e;">=</span> lift m <span style="color: #06287e;">&gt;&gt;=</span> secondP
&gt; secondP (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Yield</span> x c)) <span style="color: #06287e;">=</span> yield (<span style="color: #007020; font-weight: bold;">Right</span> x) <span style="color: #06287e;">&gt;&gt;</span> secondP c
&gt; secondP (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Await</span> k)) <span style="color: #06287e;">=</span> go
&gt;         <span style="color: #007020; font-weight: bold;">where</span>
&gt;           go <span style="color: #06287e;">=</span> tryAwait
&gt;            <span style="color: #06287e;">&gt;&gt;=</span> <span style="color: #06287e;">maybe</span> (secondP <span style="color: #06287e;">$</span> k <span style="color: #007020; font-weight: bold;">Nothing</span>)
&gt;                      (<span style="color: #06287e;">either</span> (\x <span style="color: #007020;">-&gt;</span> yield (<span style="color: #007020; font-weight: bold;">Left</span> x) <span style="color: #06287e;">&gt;&gt;</span> go)
&gt;                              (secondP <span style="color: #06287e;">.</span> k <span style="color: #06287e;">.</span> <span style="color: #007020; font-weight: bold;">Just</span>))</code></pre>
<p>And a bifunctor instance obtained by composing <code>first</code> and <code>second</code> in arbitrary order:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #007020; font-weight: bold;">Monad</span> m
&gt;       <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Bifunctor</span> <span style="color: #902000;">Either</span> (<span style="color: #902000;">PipeC</span> m r)
&gt;                    (<span style="color: #902000;">PipeC</span> m r) (<span style="color: #902000;">PipeC</span> m r) <span style="color: #007020; font-weight: bold;">where</span>
&gt;   bimap f g <span style="color: #06287e;">=</span> first f <span style="color: #06287e;">&gt;&gt;&gt;</span> second g</code></pre>
<p>At this point we can go ahead and define the remaining instances in terms of the identity-on-objects functor given by <code>pipe</code>:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Associative</span> (<span style="color: #902000;">PipeC</span> m r) <span style="color: #902000;">Either</span> <span style="color: #007020; font-weight: bold;">where</span>
&gt;   associate <span style="color: #06287e;">=</span> <span style="color: #902000;">PipeC</span> <span style="color: #06287e;">$</span> pipe associate
&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Disassociative</span> (<span style="color: #902000;">PipeC</span> m r) <span style="color: #902000;">Either</span> <span style="color: #007020; font-weight: bold;">where</span>
&gt;   disassociate <span style="color: #06287e;">=</span> <span style="color: #902000;">PipeC</span> <span style="color: #06287e;">$</span> pipe disassociate
&gt;
&gt; <span style="color: #007020; font-weight: bold;">type</span> <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #902000;">Id</span> (<span style="color: #902000;">PipeC</span> m r) <span style="color: #902000;">Either</span> <span style="color: #06287e;">=</span> <span style="color: #902000;">Void</span>
&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Monoidal</span> (<span style="color: #902000;">PipeC</span> m r) <span style="color: #902000;">Either</span> <span style="color: #007020; font-weight: bold;">where</span>
&gt;   idl <span style="color: #06287e;">=</span> <span style="color: #902000;">PipeC</span> <span style="color: #06287e;">$</span> pipe idl
&gt;   idr <span style="color: #06287e;">=</span> <span style="color: #902000;">PipeC</span> <span style="color: #06287e;">$</span> pipe idr
&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Comonoidal</span> (<span style="color: #902000;">PipeC</span> m r) <span style="color: #902000;">Either</span> <span style="color: #007020; font-weight: bold;">where</span>
&gt;   coidl <span style="color: #06287e;">=</span> <span style="color: #902000;">PipeC</span> <span style="color: #06287e;">$</span> pipe coidl
&gt;   coidr <span style="color: #06287e;">=</span> <span style="color: #902000;">PipeC</span> <span style="color: #06287e;">$</span> pipe coidr
&gt;
&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Braided</span> (<span style="color: #902000;">PipeC</span> m r) <span style="color: #902000;">Either</span> <span style="color: #007020; font-weight: bold;">where</span>
&gt;   braid <span style="color: #06287e;">=</span> <span style="color: #902000;">PipeC</span> <span style="color: #06287e;">$</span> pipe braid
&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Symmetric</span> (<span style="color: #902000;">PipeC</span> m r) <span style="color: #902000;">Either</span></code></pre>
<h2 id="multiplicative-structures">Multiplicative structures</h2>
<p>There is still a little bit of extra structure that we might want to exploit. Since <code>PipeC m r</code> is a monoidal category, it induces a (pointwise) monoidal structure on its endofunctor category, so we can speak of monoid objects there. In particular, if the identity functor is a monoid, it means that we can define a "uniform" monoid structure for all the objects of our category, given in terms of natural transformations (i.e. polymorphic functions).</p>
<p>We can represent this specialized monoid structure with a type class (using kind polymorphism and appropriately generalized category-related type classes, it should be possible to unify this class with <code>Monoid</code> and even <code>Monad</code>, similarly to how it’s done <a href="http://www.jonmsterling.com/posts/2012-01-12-unifying-monoids-and-monads-with-polymorphic-kinds.html">here</a>):</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">class</span> <span style="color: #902000;">Monoidal</span> k p <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Multiplicative</span> k p <span style="color: #007020; font-weight: bold;">where</span>
&gt; <span style="color: #007020;">  unit </span><span style="color: #007020;">::</span> k (<span style="color: #902000;">Id</span> k p) a
&gt; <span style="color: #007020;">  mult </span><span style="color: #007020;">::</span> k (p a a) a</code></pre>
<p>Dually, we can have a sort of uniform coalgebra:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">class</span> <span style="color: #902000;">Comonoidal</span> k p <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Comultiplicative</span> k p <span style="color: #007020; font-weight: bold;">where</span>
&gt; <span style="color: #007020;">  counit </span><span style="color: #007020;">::</span> k a (<span style="color: #902000;">Id</span> k p)
&gt; <span style="color: #007020;">  comult </span><span style="color: #007020;">::</span> k a (p a a)</code></pre>
<p>The laws for those type classes are just the usual laws for a monoid in a (not necessarily strict) monoidal category:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">first unit <span style="color: #06287e;">.</span> mult <span style="color: #06287e;">==</span> idl
second unit <span style="color: #06287e;">.</span> mult <span style="color: #06287e;">==</span> idr
mult <span style="color: #06287e;">.</span> first mult <span style="color: #06287e;">==</span> mult <span style="color: #06287e;">.</span> second mult <span style="color: #06287e;">.</span> associate

first counit <span style="color: #06287e;">.</span> comult <span style="color: #06287e;">==</span> coidl
second counit <span style="color: #06287e;">.</span> comult <span style="color: #06287e;">==</span> coidr
first diag <span style="color: #06287e;">.</span> diag <span style="color: #06287e;">==</span> disassociate <span style="color: #06287e;">.</span> second diag <span style="color: #06287e;">.</span> diag</code></pre>
<p>Now, products have a comultiplicative structure on Hask (as in every category with finite products), given by the terminal object and diagonal natural transformation:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #902000;">Comultiplicative</span> (<span style="color: #007020;">-&gt;</span>) (,) <span style="color: #007020; font-weight: bold;">where</span>
&gt;   counit <span style="color: #06287e;">=</span> <span style="color: #06287e;">const</span> ()
&gt;   comult x <span style="color: #06287e;">=</span> (x, x)</code></pre>
<p>while coproducts have a multiplicative structure:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #902000;">Multiplicative</span> (<span style="color: #007020;">-&gt;</span>) <span style="color: #902000;">Either</span> <span style="color: #007020; font-weight: bold;">where</span>
&gt;   unit <span style="color: #06287e;">=</span> absurd
&gt;   mult <span style="color: #06287e;">=</span> <span style="color: #06287e;">either</span> <span style="color: #06287e;">id</span> <span style="color: #06287e;">id</span></code></pre>
<p>that we can readily transport to <code>PipeC m r</code> using <code>pipe</code>:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Multiplicative</span> (<span style="color: #902000;">PipeC</span> m r) <span style="color: #902000;">Either</span> <span style="color: #007020; font-weight: bold;">where</span>
&gt;   unit <span style="color: #06287e;">=</span> <span style="color: #902000;">PipeC</span> <span style="color: #06287e;">$</span> pipe absurd
&gt;   mult <span style="color: #06287e;">=</span> <span style="color: #902000;">PipeC</span> <span style="color: #06287e;">$</span> pipe mult</code></pre>
<p>Somewhat surprisingly, pipes also have a comultiplicative structure of their own:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Comultiplicative</span> (<span style="color: #902000;">PipeC</span> m r) <span style="color: #902000;">Either</span> <span style="color: #007020; font-weight: bold;">where</span>
&gt;   counit <span style="color: #06287e;">=</span> <span style="color: #902000;">PipeC</span> discard
&gt;   comult <span style="color: #06287e;">=</span> <span style="color: #902000;">PipeC</span> <span style="color: #06287e;">.</span> forever <span style="color: #06287e;">$</span> <span style="color: #007020; font-weight: bold;">do</span>
&gt;     x <span style="color: #007020;">&lt;-</span> await
&gt;     yield (<span style="color: #007020; font-weight: bold;">Left</span> x)
&gt;     yield (<span style="color: #007020; font-weight: bold;">Right</span> x)</code></pre>
<h2 id="heterogeneous-metaprogramming">Heterogeneous metaprogramming</h2>
<p>All the combinators we defined can actually be used in practice, and the division in type classes certainly sheds some light on their structure and properties, but there’s actually something deeper going on here.</p>
<p>The fact that the standard <code>Arrow</code> class uses <code>(,)</code> as monoidal structure is not coincidental: Hask is a cartesian closed category, so to embed Haskell’s simply typed λ-calculus into some other category structure, we need at the very least a way to transport cartesian products, i.e. a premonoidal functor [1].</p>
<p>However, as long as our monoidal structure is comultiplicative and symmetric, we can always recover a first-order fragment of <span class="math"><em>λ</em></span>-calculus inside the "guest" category, and we don’t even need an identity-on-objects functor [2].</p>
<p>The idea is that we can use the monoidal structure of the guest category to represent contexts, where weakening is given by <code>counit</code>, contraction by <code>comult</code>, and exchange by <code>swap</code>.</p>
<p>There is an <a href="http://www.cs.berkeley.edu/~megacz/garrows/">experimental GHC branch</a> with a preprocessor which is able to translate expressions written in an arbitrary guest language into Haskell, given instances of appropriate type classes , which correspond exactly to the ones we have defined above.</p>
<h2 id="examples">Examples</h2>
<p>This exposition was pretty abstract, so we end with some examples.</p>
<p>We first need to define a few wrappers for our monoidal combinators, so we don’t have to deal with the <code>PipeC</code> newtype:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020;">split </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> a (<span style="color: #902000;">Either</span> a a) m r
&gt; split <span style="color: #06287e;">=</span> unPipeC comult
&gt;
&gt; <span style="color: #007020;">join </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> (<span style="color: #902000;">Either</span> a a) a m r
&gt; join <span style="color: #06287e;">=</span> unPipeC mult
&gt;
&gt; <span style="color: #007020;">(*+*) </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> a b m r <span style="color: #007020;">-&gt;</span> <span style="color: #902000;">Pipe</span> a' b' m r
&gt;       <span style="color: #007020;">-&gt;</span> <span style="color: #902000;">Pipe</span> (<span style="color: #902000;">Either</span> a a') (<span style="color: #902000;">Either</span> b b') m r
&gt; f <span style="color: #06287e;">*+*</span> g <span style="color: #06287e;">=</span> unPipeC <span style="color: #06287e;">$</span> bimap (<span style="color: #902000;">PipeC</span> f) (<span style="color: #902000;">PipeC</span> g)
&gt;
&gt; <span style="color: #007020;">discardL </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> (<span style="color: #902000;">Either</span> <span style="color: #902000;">Void</span> a) a m r
&gt; discardL <span style="color: #06287e;">=</span> unPipeC idl
&gt;
&gt; <span style="color: #007020;">discardR </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> (<span style="color: #902000;">Either</span> a <span style="color: #902000;">Void</span>) a m r
&gt; discardR <span style="color: #06287e;">=</span> unPipeC idr</code></pre>
<p>Now let’s write a <code>tee</code> combinator, similar to the tee command for shell pipes:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020;">tee </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> a <span style="color: #902000;">Void</span> m r <span style="color: #007020;">-&gt;</span> <span style="color: #902000;">Pipe</span> a a m r
&gt; tee p <span style="color: #06287e;">=</span> split <span style="color: #06287e;">&gt;+&gt;</span> firstP p <span style="color: #06287e;">&gt;+&gt;</span> discardL
&gt;
&gt; <span style="color: #007020;">printer </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Show</span> a <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> a <span style="color: #902000;">Void</span> <span style="color: #902000;">IO</span> r
&gt; printer <span style="color: #06287e;">=</span> forever <span style="color: #06287e;">$</span> await <span style="color: #06287e;">&gt;&gt;=</span> lift <span style="color: #06287e;">.</span> <span style="color: #06287e;">print</span>
&gt;
&gt; <span style="color: #007020;">ex6 </span><span style="color: #007020;">::</span> <span style="color: #902000;">IO</span> ()
&gt; ex6 <span style="color: #06287e;">=</span> <span style="color: #007020; font-weight: bold;">do</span>
&gt;   (sourceList [<span style="color: #40a070;">1</span><span style="color: #06287e;">..</span><span style="color: #40a070;">5</span>] <span style="color: #06287e;">&gt;+&gt;</span>
&gt;     tee printer <span style="color: #06287e;">&gt;+&gt;</span>
&gt;     (fold (<span style="color: #06287e;">+</span>) <span style="color: #40a070;">0</span> <span style="color: #06287e;">&gt;&gt;=</span> yield) <span style="color: #06287e;">$$</span>
&gt;     printer)
&gt;   <span style="color: #06287e;">return</span> ()
&gt; <span style="color: #60a0b0; font-style: italic;">{- ex6 == mapM_ print [1,2,3,4,5,15] -}</span></code></pre>
<p>Another interesting exercise is reimplementing the <code>groupBy</code> combinator of the previous post:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020;">groupBy </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> (a <span style="color: #007020;">-&gt;</span> a <span style="color: #007020;">-&gt;</span> <span style="color: #902000;">Bool</span>) <span style="color: #007020;">-&gt;</span> <span style="color: #902000;">Pipe</span> a [a] m r
&gt; groupBy p <span style="color: #06287e;">=</span>
&gt;    <span style="color: #60a0b0; font-style: italic;">-- split the stream in two</span>
&gt;    split <span style="color: #06287e;">&gt;+&gt;</span>
&gt;
&gt;    <span style="color: #60a0b0; font-style: italic;">-- yield Nothing whenever (not (p x y))</span>
&gt;    <span style="color: #60a0b0; font-style: italic;">-- for consecutive x y</span>
&gt;   ((consec <span style="color: #06287e;">&gt;+&gt;</span>
&gt;     <span style="color: #06287e;">filter</span> (<span style="color: #06287e;">not</span> <span style="color: #06287e;">.</span> <span style="color: #06287e;">uncurry</span> p) <span style="color: #06287e;">&gt;+&gt;</span>
&gt;     pipe (<span style="color: #06287e;">const</span> <span style="color: #007020; font-weight: bold;">Nothing</span>)) <span style="color: #06287e;">*+*</span>
&gt;
&gt;   <span style="color: #60a0b0; font-style: italic;">-- at the same time, let everything pass through</span>
&gt;   pipe <span style="color: #007020; font-weight: bold;">Just</span>) <span style="color: #06287e;">&gt;+&gt;</span>
&gt;
&gt;   <span style="color: #60a0b0; font-style: italic;">-- now rejoin the two streams</span>
&gt;   join <span style="color: #06287e;">&gt;+&gt;</span>
&gt;
&gt;   <span style="color: #60a0b0; font-style: italic;">-- then accumulate results until a Nothing is hit</span>
&gt;   forever (<span style="color: #06287e;">until</span> isNothing <span style="color: #06287e;">&gt;+&gt;</span>
&gt;            pipe fromJust <span style="color: #06287e;">&gt;+&gt;</span>
&gt;            (consume <span style="color: #06287e;">&gt;&gt;=</span> yield))
&gt;
&gt; <span style="color: #60a0b0; font-style: italic;">-- yield consecutive pairs of values</span>
&gt; <span style="color: #007020;">consec </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> a (a, a) m r
&gt; consec <span style="color: #06287e;">=</span> await <span style="color: #06287e;">&gt;&gt;=</span> go
&gt;   <span style="color: #007020; font-weight: bold;">where</span>
&gt;     go x <span style="color: #06287e;">=</span> await <span style="color: #06287e;">&gt;&gt;=</span> \y <span style="color: #007020;">-&gt;</span> yield (x, y) <span style="color: #06287e;">&gt;&gt;</span> go y
&gt;
&gt; <span style="color: #007020;">ex7 </span><span style="color: #007020;">::</span> <span style="color: #902000;">IO</span> ()
&gt; ex7 <span style="color: #06287e;">=</span> <span style="color: #007020; font-weight: bold;">do</span> (sourceList [<span style="color: #40a070;">1</span>,<span style="color: #40a070;">1</span>,<span style="color: #40a070;">2</span>,<span style="color: #40a070;">2</span>,<span style="color: #40a070;">2</span>,<span style="color: #40a070;">3</span>,<span style="color: #40a070;">4</span>,<span style="color: #40a070;">4</span>]
&gt;           <span style="color: #06287e;">&gt;+&gt;</span> groupBy (<span style="color: #06287e;">==</span>)
&gt;           <span style="color: #06287e;">&gt;+&gt;</span> pipe <span style="color: #06287e;">head</span>
&gt;            <span style="color: #06287e;">$$</span> printer)
&gt;          <span style="color: #06287e;">return</span> ()
&gt; <span style="color: #60a0b0; font-style: italic;">{- ex7 == mapM_ print [1,2,3,4] -}</span></code></pre>
<h2 id="references">References</h2>
<p>[1] J. Power and E. Robinson, “Premonoidal categories and notions of computation,” <em>Mathematical. Structures in Comp. Sci.</em>, vols. 7, pp. 453-468, 1997.</p>
<p>[2] A. Megacz, “Multi-Level Languages are Generalized Arrows,” <em>arXiv:1007.2885</em>, 2010.</p>
<br/>  <a href="http://feeds.wordpress.com/1.0/gocomments/pcapriotti.wordpress.com/213/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pcapriotti.wordpress.com/213/"/></a> <a href="http://feeds.wordpress.com/1.0/godelicious/pcapriotti.wordpress.com/213/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pcapriotti.wordpress.com/213/"/></a> <a href="http://feeds.wordpress.com/1.0/gofacebook/pcapriotti.wordpress.com/213/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pcapriotti.wordpress.com/213/"/></a> <a href="http://feeds.wordpress.com/1.0/gotwitter/pcapriotti.wordpress.com/213/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pcapriotti.wordpress.com/213/"/></a> <a href="http://feeds.wordpress.com/1.0/gostumble/pcapriotti.wordpress.com/213/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pcapriotti.wordpress.com/213/"/></a> <a href="http://feeds.wordpress.com/1.0/godigg/pcapriotti.wordpress.com/213/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pcapriotti.wordpress.com/213/"/></a> <a href="http://feeds.wordpress.com/1.0/goreddit/pcapriotti.wordpress.com/213/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pcapriotti.wordpress.com/213/"/></a> <img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&amp;blog=806312&amp;post=213&amp;subd=pcapriotti&amp;ref=&amp;feed=1" width="1"/></div>
    </content>
    <updated>2012-02-04T20:26:14Z</updated>
    <category term="categories"/>
    <category term="haskell"/>
    <category term="programming"/>
    <author>
      <name>pcapriotti</name>
    </author>
    <source>
      <id>http://pcapriotti.wordpress.com</id>
      <logo>http://s2.wp.com/i/buttonw-com.png</logo>
      <link href="http://pcapriotti.wordpress.com/category/haskell/feed/?mrss=off&amp;category_name=haskell" rel="self" type="application/atom+xml"/>
      <link href="http://pcapriotti.wordpress.com" rel="alternate" type="text/html"/>
      <link href="http://pcapriotti.wordpress.com/osd.xml" rel="search" type="application/opensearchdescription+xml"/>
      <link href="http://pcapriotti.wordpress.com/?pushpress=hub" rel="hub" type="text/html"/>
      <subtitle>KDE hacking and more</subtitle>
      <title>Paolo Capriotti » haskell</title>
      <updated>2012-02-04T21:22:23Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-819021106854702432.post-672719538062843446</id>
    <link href="http://blog.darcs.net/feeds/672719538062843446/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://www.blogger.com/comment.g?blogID=819021106854702432&amp;postID=672719538062843446" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/819021106854702432/posts/default/672719538062843446" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/819021106854702432/posts/default/672719538062843446" rel="self" type="application/atom+xml"/>
    <link href="http://blog.darcs.net/2012/02/darcs-weekly-news-91.html" rel="alternate" type="text/html"/>
    <title>darcs weekly news #91</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><h3 id="news-and-discussions">News and discussions</h3><ol style=""><li>Ganesh uploaded a third beta of Darcs 2.8:<br/><ul><li><a href="http://lists.osuosl.org/pipermail/darcs-users/2012-January/026364.html">http://lists.osuosl.org/pipermail/darcs-users/2012-January/026364.html</a></li></ul></li><li>The next Darcs Sprint has a tentative date and place of 31 march, Southampton. Please annotate yourself on the wiki to participate:<br/><ul><li><a href="http://wiki.darcs.net/Sprints/2012-03">http://wiki.darcs.net/Sprints/2012-03</a></li></ul></li></ol><h3 id="issues-resolved-in-the-last-week-1">Issues resolved in the last week (1)</h3><dl><dt>issue1470 Johannes Weiss</dt><dd><ul><li>Allow to amend-record patch by removing some hunks</li><li><a href="http://bugs.darcs.net/issue1470">http://bugs.darcs.net/issue1470</a></li></ul></dd></dl><h3 id="patches-applied-in-the-last-week-11">Patches applied in the last week (11)</h3>See <a href="http://wiki.darcs.net/DarcsWeeklyNews/2012-02-04">darcs wiki entry</a> for details.<div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/819021106854702432-672719538062843446?l=blog.darcs.net" width="1"/></div></div>
    </content>
    <updated>2012-02-04T12:57:09Z</updated>
    <published>2012-02-04T12:57:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="dwn"/>
    <author>
      <name>guillaume</name>
      <email>noreply@blogger.com</email>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-819021106854702432</id>
      <category term="dwn"/>
      <category term="release"/>
      <category term="admin"/>
      <category term="news"/>
      <category term="sprints"/>
      <category term="camp"/>
      <author>
        <name>kowey</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/11175806459477851520</uri>
      </author>
      <link href="http://blog.darcs.net/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/819021106854702432/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://blog.darcs.net/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <link href="http://www.blogger.com/feeds/819021106854702432/posts/default?start-index=26&amp;max-results=25" rel="next" type="application/atom+xml"/>
      <title>darcs advanced revision control system</title>
      <updated>2012-02-04T12:57:08Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-9757377.post-793829155311083456</id>
    <link href="http://www.feniks.com/skb/music/lull23.html" rel="related" type="text/html"/>
    <link href="http://wadler.blogspot.com/feeds/793829155311083456/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://www.blogger.com/comment.g?blogID=9757377&amp;postID=793829155311083456" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/9757377/posts/default/793829155311083456" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/9757377/posts/default/793829155311083456" rel="self" type="application/atom+xml"/>
    <link href="http://wadler.blogspot.com/2012/02/keep-that-wheel-turning.html" rel="alternate" type="text/html"/>
    <title>Keep that wheel a-turning</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><div class="separator" style="clear: both; text-align: center;"><a href="http://4.bp.blogspot.com/-hMvjeDiELWo/Ty0hXOEI5UI/AAAAAAAAAMY/g6bwVOU1CEw/s1600/IMAG0219.jpg" style="clear: left; float: left; margin-right: 1em; margin-bottom: 1em;"><img border="0" height="400" src="http://4.bp.blogspot.com/-hMvjeDiELWo/Ty0hXOEI5UI/AAAAAAAAAMY/g6bwVOU1CEw/s400/IMAG0219.jpg" width="240"/></a></div>I heard the following from my brother-in-law (pictured).  Reminds me of recent developments in higher education all too well.<br/><blockquote>&lt;bold&gt;William Brown&lt;/bold&gt;<br/>Traditional Woodcraft song arr. by Stan Kelly © 1961 Heathside Music<br/><br/>Well, a nice young man was William Brown, <br/>He worked for a wage in Liverpool town, <br/>He worked from six till eight at night, <br/>Turning a wheel from left to right.<br/><br/>Chorus:<br/>Keep that wheel a-turning, keep that wheel a-turning <br/>Keep that wheel a-turning and do a little more each day.<br/><br/>One day the boss to William came <br/>And said, "Look here, young what's your name, <br/>"We're not content with what you do, <br/>"Work a little harder or out you go."<br/><br/>So William turned and made her run <br/>Three times roung in the time of one, <br/>He turned so hard he soon was made <br/>The Lord High Turner of his trade.<br/><br/>William turned with the same sweet smile, <br/>The goods he made grew such a pile; <br/>They filled the room and the room next door <br/>And overflowed to the basement floor.<br/><br/>The nation heard of the wondrous tale, <br/>His picture appeared in the Sketch and the Mail; <br/>The railways ran excursions down, <br/>And all to look at William Brown.<br/><br/>But sad the sequel is to tell; <br/>He turned out more than the boss could sell; <br/>The market slumped and the price went down, <br/>Seven more days and they sacked young Brown.<br/><br/>The moral of the tale is plain to tell: <br/>If you wanna lose yer job, just werk like HELL!<br/></blockquote><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/9757377-793829155311083456?l=wadler.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2012-02-04T12:19:00Z</updated>
    <published>2012-02-04T12:19:00Z</published>
    <author>
      <name>Philip Wadler</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/12009347515095774366</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-9757377</id>
      <author>
        <name>Philip Wadler</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/12009347515095774366</uri>
      </author>
      <link href="http://wadler.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/9757377/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://wadler.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <link href="http://www.blogger.com/feeds/9757377/posts/default?start-index=26&amp;max-results=25" rel="next" type="application/atom+xml"/>
      <title>Wadler's Blog</title>
      <updated>2012-02-05T05:28:11Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://kpreid.livejournal.com/43367.html</id>
    <link href="http://kpreid.livejournal.com/43367.html" rel="alternate" type="text/html"/>
    <title>Cubes vs. Minecraft</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>[I was asked about Cubes “Where do you think you might take the game play next?” and it turned into this.]</p>

<p>My original motivation for creating <a href="https://github.com/kpreid/cubes/" rel="nofollow">Cubes</a> was a combination of the “blocks out of blocks” idea — which itself came from immersion in the graphics of Minecraft — and also dissatisfaction with certain bugs, limitations, and design choices in Minecraft. As a result, I’m not just building a voxel game; I’m building a game that <em>shares what I like about Minecraft</em>.</p>

<p>(What I like about Minecraft, broadly, is <em>survival and engineering</em> — I like building structures and machines to make my virtual life easier.)</p>

<p>Now, creating a Minecraft clone would be lame, rude, closer to using <a href="http://mojang.com/" rel="nofollow">someone else’s</a> intellectual property, and just plain unoriginal. But I don’t have experience with what little exists of a genre of voxel building games to synthesize my own thing, and I myself am looking for something like Minecraft. What can I do? Here’s what I’ve been trying:</p>

<ul>
  <li><p>Be different.
  </p><p>Whenever I see an opportunity to do something specifically unlike Minecraft, that doesn’t compromise what I’m trying to do, I take it and see what happens. However, most of these experiments have failed; for example, Cubes originally had a larger-scaled player character, but this turned out bad because it means tunneling and building is 8× more tedious, and it reduces the apparent size of the world. Also, it leads to thinking “OK, add this feature Minecraft has — but (superficially) differently!”</p>
  
  </li><li><p>Be generic.
  </p><p>This is my long-term goal, and it is one that ties neatly into the “blocks made of blocks” theme. The characteristics of blocks can be defined by building circuits (programs) inside them. What I’m aiming for is that by creating a blockset (collection of block designs which the player can build with), one is <em>defining the game that can be played</em>, by giving those blocks specific behaviors.

    </p><p>In this way, I am working towards having <strong>a game which can be programmed to emulate Minecraft</strong>.</p>
    
    <p>(I have a working prototype of an importer for Minecraft worlds as well as for Minecraft blocks — that is, turning the terrain.png from a Minecraft texture pack into Cubes' 3D blocks — but I am not going to release that code until and unless I determine that Mojang doesn’t mind my doing so. I still love Minecraft and they deserve my not stepping on their toes that far.)</p>

    <p>However, this means both that Cubes itself needs to be <em>very</em> generic, and that the built-in example uses of such features should feel different from Minecraft.</p>
</li></ul>

<hr/>

<p>So, returning to the original topic of “where am I going next”, I need to add the following functionality to the game world:</p>

<ul>
<li><p>Extend the circuits feature so that there can be blocks that are
active and interactive (e.g. opening and closing doors, “physics” like Minecraft falling sand and growing plants).</p></li>
<li><p>Add moving objects (for vehicles and mobs). I intend to generalize
these so that they are worlds in themselves — this will allow large or unique vehicles, and mean that they can be designed using the same game tools.</p></li>
<li><p>Add some form of resource constraints/conservation laws (as in Minecraft survival
mode) — that is, you have to gather stuff to make it into other
stuff. I haven’t figured out specifically how I want to do this yet,
and this seems particularly tricky to make programmable. One idea that keeps coming to mind is that when you break a block, specific subcubes are “resource cubes” (according to their type in the block world) which you collect, and in order to place a block you need to have the corresponding resources for its type. However, I’m not sure I like the “raw material counter” feel of this.</p></li>
<li><p>Add player attributes that can be modified (e.g. health) so that e.g. death, or other effects-by-the-world can be supported.</p></li>
</ul>

<p>Less grandly, I plan to work on one of these specific technical features soon:</p>

<ul>
<li>Allowing circuit blocks to be rotated to change their connectivity. (Right now, circuit blocks have specific faces — e.g. on a certain one the +X direction is always the output.)</li>
<li>Figure out what more circuit primitives I want to add. (Right now, the circuits are definitely not Turing-complete, and not capable of all the effects on the world they should be, but there are also already a lot of different primitives; I may have to invent new block-picking UI just to make them practical.)</li>
<li>Add moving objects (bodies) — things which can collide with the terrain
as the player does. The current code is entangled with player
behavior, and the player does not persist in a world.</li>
<li>Add subworld/multiple-world handling — the ability for more than one
world (grid of blocks) to be present in the same space. Right now, there are hardwired assumptions that the player is
in the single world’s coordinate system.</li>
</ul>

<p>Another core feature which is currently missing is the ability to design a blockset and then reuse it for multiple worlds. The problem right now is that we're using a simple object-graph serializer, so each world has its own blockset which is modified independently. To fix this, it needs to be possible to save a blockset under a user-visible name, and have individual worlds which reference that blockset; also, the world generator needs to decouple blockset generation from terrain generation. The “persistence” framework which added support for multiple worlds is a step towards this; the main thing I am pondering is what the semantics of these separate-named-persistent objects are and what the user interface for editing them is.</p></div>
    </summary>
    <updated>2012-02-03T23:35:29Z</updated>
    <category term="programming"/>
    <category term="programs"/>
    <category term="minecraft"/>
    <category term="games"/>
    <category term="cubes"/>
    <category term="3d"/>
    <author>
      <name>Kevin Reid (kpreid)</name>
      <email>kpreid@switchb.org</email>
    </author>
    <source>
      <id>http://kpreid.livejournal.com/</id>
      <logo>http://l-userpic.livejournal.com/114705443/3537103</logo>
      <author>
        <name/>
        <email>kpreid@switchb.org</email>
      </author>
      <link href="http://kpreid.livejournal.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <link href="http://kpreid.livejournal.com/data/rss" rel="self" type="application/atom+xml"/>
      <subtitle>Kevin Reid's blog - LiveJournal.com</subtitle>
      <title>Kevin Reid's blog</title>
      <updated>2012-02-04T00:22:13Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-927289640963145319.post-7756790978890558937</id>
    <link href="http://blog.johantibell.com/feeds/7756790978890558937/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://blog.johantibell.com/2012/02/forcing-values-returned-from-monadic.html#comment-form" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/927289640963145319/posts/default/7756790978890558937" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/927289640963145319/posts/default/7756790978890558937" rel="self" type="application/atom+xml"/>
    <link href="http://blog.johantibell.com/2012/02/forcing-values-returned-from-monadic.html" rel="alternate" type="text/html"/>
    <title>Forcing values returned from monadic computations</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>This is the start of my series on reliable techniques for writing fast Haskell code. In each installment we'll look at a specific situation and explore some simple guidelines you can use in your everyday programming.</p>
<p>Today's topic is forcing values returned from monadic computations. After reading this article you'll hopefully be able to tell when it's appropriate to force values passed to <code>return</code> and when it's not.</p>
<p>Consider this function:</p>
<pre><code>f :: Int -&gt; Int -&gt; Int
f x y = x + y
</code></pre>
<p><code>f</code> is strict in both arguments and when called with two arguments it will return a fully evaluated <code>Int</code> value. No laziness anywhere to be seen.</p>
<p>Now lets look at a function that looks very similar to <code>f</code>, but involves <code>return</code>:</p>
<pre><code>g :: Monad m =&gt; Int -&gt; Int -&gt; m Int
g x y = return $ x + y
</code></pre>
<p><code>g</code> looks very similar to <code>f</code> so it's easy to think that it, like <code>f</code>, is strict in both arguments and that it will return a fully evaluated <code>Int</code> value inside the given monad.</p>
<p>However, that's not the case. Lets look what happens if <code>m</code> is e.g. a state monad (such as <code>IO</code>) [1]. Here's a possible definition of a state monad:</p>
<pre><code>newtype State s a = S (s -&gt; (a, s))

instance Monad (State s) where
    return x = S $ \ s -&gt; (x, s)
    m &gt;&gt;= f = ...
</code></pre>
<p>Lets expand <code>&gt;&gt;=</code>, <code>return</code>, and <code>$</code> in <code>g</code>:</p>
<pre><code>g :: Int -&gt; Int -&gt; State s Int
g x y = S $ \ s -&gt; (x + y, s)
</code></pre>
<p>Since our monad wraps the return value in a (lazy) pair, the evaluation of <code>x + y</code> is delayed until the first component of that pair is evaluated, some time later in the program. If we don't want to delay the evaluation, we must first force the value passed to <code>return</code> (e.g. by using <code>$!</code>):</p>
<pre><code>g :: Int -&gt; Int -&gt; State s Int
g x y = return $! x + y
</code></pre>
<p>Here's what we get if we expand the stricter version:</p>
<pre><code>g :: Int -&gt; Int -&gt; State s Int
g x y = let z = x + y
        in z `seq` S $ \ s -&gt; (z, s)
</code></pre>
<p>Now the expression <code>x + y</code> is evaluated before the pair is created and the result (rather than a thunk representing the expression) is stored in the pair.</p>
<p>We can also see the difference between the two different versions of <code>g</code> in the core generated by GHC. First the lazier version:</p>
<pre><code>g = \ (x :: Int) (y :: Int) (s :: s) -&gt;
    (case x of _
         I# x# -&gt; case y of _
             I# y# -&gt; I# (+# x# y#),
     s)
</code></pre>
<p>and then the stricter one:</p>
<pre><code>g = \ (x :: Int) (y :: Int) (s :: s) -&gt;
    case x of _
        I# x# -&gt; case y of _
            I# y# -&gt; (I# (+# x# y#), s)
</code></pre>
<p>If you look carefully you'll see that in the lazier version the evaluation of <code>x</code> and <code>y</code> has been pushed inside the first component of the pair.</p>
<p>The stricter version still allocates an <code>I#</code> box, because pairs are polymorphic in their components and unboxed values (like <code>Int#</code>) cannot be stored in polymorphic fields and thus need to be wrapped.</p>
<p>The above example used a simple arithmetic expression but the same reasoning applies to data types with strict fields. For example, given this strict-pair data type:</p>
<pre><code>data StrictPair a b = SP !a !b
</code></pre>
<p>you need to use <code>$!</code> if you want its fields to be evaluated before a monadic computation returning a <code>StrictPair</code> returns, like so:</p>
<pre><code>h :: Int -&gt; Int -&gt; State s (StrictPair Int Int)
h x y = return $! SP (x+1) (y+1)
</code></pre>
<p>Aside: <code>Int</code> (and <code>Double</code>, <code>Float</code>, etc.) arithmetic is really just a special case of a data type with strict fields as <code>Int</code> is defined as:</p>
<pre><code>data Int = I# Int#
</code></pre>
<p>where <code>Int#</code> is an unboxed type. Fields of unboxed types are always strict.</p>
<p>Forcing values that are already in WHNF has no effect e.g.</p>
<pre><code>-- Has no effect and thus potentially confuses readers:
h x y = return $! (x, y)
</code></pre>
<p><strong>Guideline</strong>: force data types with strict fields (including e.g. <code>Int</code>) to WHNF using <code>$!</code> before passing them to <code>return</code>.</p>
<ol style="">
<li>This behavior is not specific to the state monad. Any monad where <code>return</code> is lazy in its argument would behave the same.</li>
</ol><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/927289640963145319-7756790978890558937?l=blog.johantibell.com" width="1"/></div></div>
    </content>
    <updated>2012-02-03T23:03:02Z</updated>
    <published>2012-02-02T22:57:00Z</published>
    <author>
      <name>Johan Tibell</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/06875432206357419172</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-927289640963145319</id>
      <author>
        <name>Johan Tibell</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/06875432206357419172</uri>
      </author>
      <link href="http://blog.johantibell.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/927289640963145319/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://blog.johantibell.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <link href="http://www.blogger.com/feeds/927289640963145319/posts/default?start-index=26&amp;max-results=25" rel="next" type="application/atom+xml"/>
      <subtitle>Haskell and other things that interest me</subtitle>
      <title>Johan Tibell</title>
      <updated>2012-02-03T23:03:02Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-1563623855220143059.post-3013561900404693703</id>
    <link href="http://mainisusuallyafunction.blogspot.com/feeds/3013561900404693703/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://mainisusuallyafunction.blogspot.com/2012/02/generating-random-functions.html#comment-form" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/1563623855220143059/posts/default/3013561900404693703" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/1563623855220143059/posts/default/3013561900404693703" rel="self" type="application/atom+xml"/>
    <link href="http://mainisusuallyafunction.blogspot.com/2012/02/generating-random-functions.html" rel="alternate" type="text/html"/>
    <title>Generating random functions</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>How can we pick a random Haskell function? Specifically, we want to write an IO action</p><pre class="sourceCode"><code class="sourceCode haskell"><span class="ot">randomFunction </span><span class="ot">::</span> <span class="dt">IO</span> (<span class="dt">Integer</span> <span class="ot">-&gt;</span> <span class="dt">Bool</span>)</code></pre><p>with this behavior:</p><ul class="incremental"><li><p>It produces a function of type <code>Integer -&gt; Bool</code>.</p></li><li><p>It always produces a total function — a function which never throws an exception or enters an infinite loop.</p></li><li><p>It is equally likely to produce <em>any</em> such function.</p></li></ul><p>This is tricky, because there are infinitely many such functions (more on that later).</p><p>In another language we might produce something which looks like a function, but actually flips a coin on each new integer input. It would use mutable state to remember previous results, so that future calls will be consistent. But the Haskell type we gave for <code>randomFunction</code> forbids this approach. <code>randomFunction</code> uses IO effects to pick a random function, but the function it picks has access to neither coin flips nor mutable state.</p><p>Alternatively, we could build a lazy infinite data structure containing all the <code>Bool</code> answers we need. <code>randomFunction</code> could generate an <a href="http://lambda.haskell.org/platform/doc/current/ghc-doc/libraries/random-1.0.0.3/System-Random.html#v:randomRs">infinite list of random <code>Bool</code>s</a>, and produce a function <code>f</code> which indexes into that list. But this indexing will be inefficient in space and time. If the user calls <code>(f 10000000)</code>, we'll have to run 10,000,000 steps of the pseudo-random number generator, and build 10,000,000 list elements, before we can return a single <code>Bool</code> result.</p><p>We can improve this considerably by using a different infinite data structure. Though our solution is pure functional code, we <em>do</em> end up relying on mutation — the implicit mutation by which lazy thunks become evaluated data.</p><h1 id="the-data-structure">The data structure</h1><p/><pre class="sourceCode"><code class="sourceCode haskell"><span class="kw">import</span> <span class="dt">System.Random</span><br/><span class="kw">import</span> <span class="dt">Data.List</span> ( genericIndex )</code></pre><p>Our data structure is an infinite binary tree:</p><pre class="sourceCode"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Tree</span> <span class="fu">=</span> <span class="dt">Node</span> <span class="dt">Bool</span> <span class="dt">Tree</span> <span class="dt">Tree</span></code></pre><p>We can interpret such a tree as a function from non-negative <code>Integer</code>s to <code>Bool</code>s. If the <code>Integer</code> argument is zero, the root node holds our <code>Bool</code> answer. Otherwise, we shift off the least-significant bit of the argument, and look at the left or right subtree depending on that bit.</p><pre class="sourceCode"><code class="sourceCode haskell"><span class="ot">get </span><span class="ot">::</span> <span class="dt">Tree</span> <span class="ot">-&gt;</span> (<span class="dt">Integer</span> <span class="ot">-&gt;</span> <span class="dt">Bool</span>)<br/>get (<span class="dt">Node</span> b _ _) <span class="dv">0</span> <span class="fu">=</span> b<br/>get (<span class="dt">Node</span> _ x y) n <span class="fu">=</span><br/>    <span class="kw">case</span> <span class="fu">divMod</span> n <span class="dv">2</span> <span class="kw">of</span><br/>        (m, <span class="dv">0</span>) <span class="ot">-&gt;</span> get x m<br/>        (m, _) <span class="ot">-&gt;</span> get y m</code></pre><p>Now we need to build a suitable tree, starting from a <a href="http://lambda.haskell.org/platform/doc/current/ghc-doc/libraries/random-1.0.0.3/System-Random.html#t:StdGen">random number generator state</a>. The standard <code>System.Random</code> module is not going to win any <a href="http://www.serpentine.com/blog/2009/09/19/a-new-pseudo-random-number-generator-for-haskell/">speed contests</a>, but it does have one extremely nice property: it supports an operation</p><pre class="sourceCode"><code class="sourceCode haskell"><span class="ot">split </span><span class="ot">::</span> <span class="dt">StdGen</span> <span class="ot">-&gt;</span> (<span class="dt">StdGen</span>, <span class="dt">StdGen</span>)</code></pre><p>The two generator states returned by <code>split</code> will (ideally) produce two independent streams of random values. We use <code>split</code> at each node of the infinite tree.</p><pre class="sourceCode"><code class="sourceCode haskell"><span class="ot">build </span><span class="ot">::</span> <span class="dt">StdGen</span> <span class="ot">-&gt;</span> <span class="dt">Tree</span><br/>build g0 <span class="fu">=</span><br/>    <span class="kw">let</span> (b,  g1) <span class="fu">=</span> random g0<br/>        (g2, g3) <span class="fu">=</span> split  g1<br/>    <span class="kw">in</span>  <span class="dt">Node</span> b (build g2) (build g3)</code></pre><p>This is a recursive function with no base case. Conceptually, it produces an infinite tree. Operationally, it produces a single <code>Node</code> constructor, whose fields are lazily-deferred computations. As <code>get</code> explores this notional infinite tree, new <code>Node</code>s are created and randomness generated on demand.</p><p><code>get</code> traverses one level per bit of its input integer. So looking up the integer <em>n</em> involves traversing and possibly creating <span style="white-space: nowrap;"><em>O</em>(log <em>n</em>)</span> nodes. This suggests good space and time efficiency, though only testing will say for sure.</p><p>Now we have all the pieces to solve the original puzzle. We build two trees, one to handle positive numbers and another for negative numbers.</p><pre class="sourceCode"><code class="sourceCode haskell"><span class="ot">randomFunction </span><span class="ot">::</span> <span class="dt">IO</span> (<span class="dt">Integer</span> <span class="ot">-&gt;</span> <span class="dt">Bool</span>)<br/>randomFunction <span class="fu">=</span> <span class="kw">do</span><br/>    neg <span class="ot">&lt;-</span> build <span class="ot">`fmap`</span> newStdGen<br/>    pos <span class="ot">&lt;-</span> build <span class="ot">`fmap`</span> newStdGen<br/>    <span class="kw">let</span> f n <span class="fu">|</span> n <span class="fu">&lt;</span> <span class="dv">0</span>     <span class="fu">=</span> get neg (<span class="fu">-</span>n)<br/>            <span class="fu">|</span> <span class="fu">otherwise</span> <span class="fu">=</span> get pos n<br/>    <span class="fu">return</span> f</code></pre><p/><h1 id="testing">Testing</h1><p>Here's some code which helps us visualize one of these functions in the vicinity of zero:</p><pre class="sourceCode"><code class="sourceCode haskell"><span class="ot">test </span><span class="ot">::</span> (<span class="dt">Integer</span> <span class="ot">-&gt;</span> <span class="dt">Bool</span>) <span class="ot">-&gt;</span> <span class="dt">IO</span> ()<br/>test f <span class="fu">=</span> <span class="fu">putStrLn</span> <span class="fu">$</span> <span class="fu">map</span> (char <span class="fu">.</span> f) [<span class="fu">-</span><span class="dv">40</span><span class="fu">..</span><span class="dv">40</span>] <span class="kw">where</span><br/>    char <span class="dt">False</span> <span class="fu">=</span> <span class="ch">' '</span><br/>    char <span class="dt">True</span>  <span class="fu">=</span> <span class="ch">'-'</span></code></pre><p>Now we can test <code>randomFunction</code> in GHCi:</p><pre><code><span class="Prompt">λ&gt;</span> <span class="Entry">randomFunction &gt;&gt;= test</span><br/>---- -   ---   -    - -   - --   - - -  -- --- -- --          - -- - - --  --- --<br/><span class="Prompt">λ&gt;</span> <span class="Entry">randomFunction &gt;&gt;= test</span><br/>-   ---- - - - -  - - -- -   -     ---  --- -- - --  -  --    - -  - - -  --   - <br/><span class="Prompt">λ&gt;</span> <span class="Entry">randomFunction &gt;&gt;= test</span><br/>- ---  - - -  --  ---         -  --  -  -    -  -  - ---- - -  ---   -     -    -<br/></code></pre><p>Each result from <code>randomFunction</code> is indeed a function: it always gives the same output for a given input. This much should be clear from the fact that we haven't used any <a href="http://lambda.haskell.org/platform/doc/current/ghc-doc/libraries/base-4.3.1.0/System-IO-Unsafe.html">unsafe shenanigans</a>. But we can also demonstrate it empirically:</p><pre><code><span class="Prompt">λ&gt;</span> <span class="Entry">f &lt;- randomFunction</span><br/><span class="Prompt">λ&gt;</span> <span class="Entry">test f</span><br/>-   -----  - -   -- - -   --- --  - -   - -   - -   -- - -   ---- - - - -  - --- <br/><span class="Prompt">λ&gt;</span> <span class="Entry">test f</span><br/>-   -----  - -   -- - -   --- --  - -   - -   - -   -- - -   ---- - - - -  - --- <br/></code></pre><p>Let's also test the speed on some very large arguments:</p><pre><code><span class="Prompt">λ&gt;</span> <span class="Entry">:set +s</span><br/><span class="Prompt">λ&gt;</span> <span class="Entry">f 10000000</span><br/>True<br/>(0.03 secs, 12648232 bytes)<br/><span class="Prompt">λ&gt;</span> <span class="Entry">f (2^65536)</span><br/>True<br/>(1.10 secs, 569231584 bytes)<br/><span class="Prompt">λ&gt;</span> <span class="Entry">f (2^65536)</span><br/>True<br/>(0.26 secs, 426068040 bytes)<br/></code></pre><p>The second call with <code>2^65536</code> is faster because the tree nodes already exist in memory. We can expect our tests to be faster yet if we compile with <code>ghc -O</code> rather than using GHCi's bytecode interpreter.</p><h1 id="how-many-functions">How many functions?</h1><p>Assume we have infinite memory, so that <code>Integer</code>s really can be unboundedly large. And let's ignore negative numbers, for simplicity. How many total functions of type <code>Integer -&gt; Bool</code> are there?</p><p>Suppose we made an infinite list <code>xs</code> of all such functions. Now consider this definition:</p><pre class="sourceCode"><code class="sourceCode haskell"><span class="ot">diag </span><span class="ot">::</span> [<span class="dt">Integer</span> <span class="ot">-&gt;</span> <span class="dt">Bool</span>] <span class="ot">-&gt;</span> (<span class="dt">Integer</span> <span class="ot">-&gt;</span> <span class="dt">Bool</span>)<br/>diag xs n <span class="fu">=</span> <span class="fu">not</span> <span class="fu">$</span> genericIndex xs n n</code></pre><p>For an argument <code>n</code>, <code>diag xs</code> looks at what the <code>n</code>th function of <code>xs</code> would return, and returns the opposite. This means the function <code>diag xs</code> differs from every function in our supposedly comprehensive list of functions. This contradiction shows that there are <a href="http://en.wikipedia.org/wiki/Uncountable_set">uncountably many</a> total functions of type <code>Integer -&gt; Bool</code>. It's closely related to <a href="http://en.wikipedia.org/wiki/Cantor%27s_diagonal_argument">Cantor's diagonal argument</a> that the real numbers are uncountable.</p><p>But wait, there are only countably many Haskell programs! In fact, you can encode each one as a number. There may be uncountably many functions, but there are only a countable number of <em>computable</em> functions. So the proof breaks down if you restrict it to a real programming language like Haskell.</p><p>In that context, the existence of <code>xs</code> implies that there is some <em>algorithm</em> to enumerate the computable total functions. This is the assumption we ultimately contradict. The set of computable total functions is not <a href="http://en.wikipedia.org/wiki/Recursively_enumerable_language">recursively enumerable</a>, even though it is countable. Intuitively, to produce a single element of this set, we would have to verify that the function halts on every input, which is <a href="http://en.wikipedia.org/wiki/Halting_problem">impossible in the general case</a>.</p><p>Now let's revisit <code>randomFunction</code>. Any function it produces is computable: the algorithm is a combination of the pseudo-random number procedure and our tree traversal. In this sense, <code>randomFunction</code> provides extremely poor randomness; it only selects values from a particular <a href="http://en.wikipedia.org/wiki/Null_set">measure zero</a> subset of its result type! But if you read the type constructor <code>(-&gt;)</code> as "computable function", as one should in a programming language, then <code>randomFunction</code> is closer to doing what it says it does.</p><p><strong>Edit:</strong> See also Luke Palmer's <a href="http://lukepalmer.wordpress.com/2012/01/26/computably-uncountable/">recent article on this subject</a>.</p><h1 id="see-also">See also</h1><p>The libraries <a href="http://hackage.haskell.org/package/data-memocombinators">data-memocombinators</a> and <a href="http://hackage.haskell.org/package/MemoTrie">MemoTrie</a> use similar structures, not for building random functions but for <a href="http://en.wikipedia.org/wiki/Memoization">memoizing</a> existing ones.</p><p>You can download this post as a <a href="https://github.com/kmcallister/blog-misc/blob/master/random-function/random-function.lhs">Literate Haskell file</a> and play with the code.</p><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/1563623855220143059-3013561900404693703?l=mainisusuallyafunction.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2012-02-02T21:35:21Z</updated>
    <published>2012-02-02T21:24:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="haskell"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="random"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="computability"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="code"/>
    <author>
      <name>keegan</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/12227260241426017476</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-1563623855220143059</id>
      <category term="slides"/>
      <category term="debugging"/>
      <category term="latex"/>
      <category term="detrospector"/>
      <category term="assembly"/>
      <category term="ghc"/>
      <category term="types"/>
      <category term="yices-easy"/>
      <category term="quasicrystal"/>
      <category term="hackathon"/>
      <category term="compsci"/>
      <category term="lambda-calculus"/>
      <category term="markdown"/>
      <category term="systems"/>
      <category term="haskell"/>
      <category term="smt"/>
      <category term="tracepoints"/>
      <category term="global-lock"/>
      <category term="code"/>
      <category term="clogparse"/>
      <category term="propane"/>
      <category term="preprocessor"/>
      <category term="mit"/>
      <category term="pandoc"/>
      <category term="phosphene"/>
      <category term="hardware"/>
      <category term="pi-calculus"/>
      <category term="imadethis"/>
      <category term="gdb"/>
      <category term="breakfast"/>
      <category term="security"/>
      <category term="6.S184"/>
      <category term="random"/>
      <category term="graphics"/>
      <category term="debug-diff"/>
      <category term="cabal"/>
      <category term="jvf2010a"/>
      <category term="concurrency"/>
      <category term="type-theory"/>
      <category term="c"/>
      <category term="rts"/>
      <category term="shqq"/>
      <category term="tsp"/>
      <category term="jspath"/>
      <category term="generics"/>
      <category term="kernel"/>
      <category term="hdis86"/>
      <category term="compose"/>
      <category term="repa"/>
      <category term="computability"/>
      <category term="donttrythisathome"/>
      <category term="crystalfontz"/>
      <category term="boston"/>
      <category term="concorde"/>
      <category term="safe-globals"/>
      <author>
        <name>keegan</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/12227260241426017476</uri>
      </author>
      <link href="http://mainisusuallyafunction.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/1563623855220143059/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://mainisusuallyafunction.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <link href="http://www.blogger.com/feeds/1563623855220143059/posts/default?start-index=26&amp;max-results=25" rel="next" type="application/atom+xml"/>
      <subtitle>char* main = "usually a programming blog";</subtitle>
      <title>main is usually a function</title>
      <updated>2012-02-10T00:24:12Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://lukepalmer.wordpress.com/?p=1880</id>
    <link href="http://lukepalmer.wordpress.com/2012/01/26/computably-uncountable/" rel="alternate" type="text/html"/>
    <link href="http://lukepalmer.wordpress.com/2012/01/26/computably-uncountable/#comments" rel="replies" type="text/html"/>
    <link href="http://lukepalmer.wordpress.com/2012/01/26/computably-uncountable/feed/atom/" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">Computably Uncountable</title>
    <summary type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml">We are all familiar with Cantor’s diagonal argument that proves there exist infinite sets which are “larger” than the set of natural numbers. In this post I will show that we can express this argument in the form of a program, thus showing that there are countable sets which are “computably uncountable”. I begin with [...]<img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=lukepalmer.wordpress.com&amp;blog=5292379&amp;post=1880&amp;subd=lukepalmer&amp;ref=&amp;feed=1" width="1"/></div>
    </summary>
    <content type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml"><p>We are all familiar with Cantor’s diagonal argument that proves there exist infinite sets which are “larger” than the set of natural numbers.  In this post I will show that we can express this argument in the form of a program, thus showing that there are countable sets which are “computably uncountable”.</p>
<p>I begin with the program itself:</p>
<pre>type Cantor = Nat -&gt; Bool

diagonal :: (Nat -&gt; Cantor) -&gt; Cantor
diagonal cs n = not (cs n n)
</pre>
<p><tt>Cantor</tt> is “the cantor space”, the type of infinite sequences of booleans.  We will call such an infinite sequence “a <tt>Cantor</tt>“. There are clearly infinitely many <tt>Cantor</tt>s; e.g. take the range of this function which gives <tt>False</tt> at every position except the one specified:</p>
<pre>unit :: Nat -&gt; Cantor
unit m n = m == n
</pre>
<p><tt>diagonal</tt> is (Georg) Cantor’s diagonal argument written as a program — it takes an alleged sequence of all <tt>Cantor</tt>s, and returns a <tt>Cantor</tt> which does not occur in the sequence, by construction.  This function shows by contradiction that we cannot put <tt>Cantor</tt>s in 1 to 1 correspondence with naturals, and thus that there are <i>more</i> <tt>Cantor</tt>s than there are naturals.</p>
<p>So how many <tt>Cantor</tt>s are there?  Since <tt>Nat -&gt; Bool</tt> is a Haskell type — the type of <i>computable</i> functions from <tt>Nat</tt> to <tt>Bool</tt> — <tt>Cantor</tt>s must be representable by programs.  We can encode programs as numbers by treating their source code as base-128 numbers. Hence, there are no more <tt>Cantor</tt>s than naturals, and so <tt>Cantor</tt>s can be put into 1 to 1 correspondence with naturals.</p>
<p>Wait — what?  There are more <tt>Cantor</tt>s than <tt>Nat</tt>s, but they both have the same size?  Something is wrong.  Indeed, in the process of this argument we have asserted both</p>
<ol>
<li> “We cannot put <tt>Cantor</tt>s in 1 to 1 correspondence with naturals”
</li><li> “<tt>Cantor</tt>s can be put into 1 to 1 correspondence with naturals”
</li></ol>
<p>We clearly can’t have both.</p>
<div style="text-align: center;">
<h3 style="font-family: serif;">I</h3>
</div>
<p>The erroneous statement is (2). It is undecidable whether a given program represents a <tt>Cantor</tt>.  If the <tt>n</tt>th <tt>Cantor</tt> is ⊥ at <tt>n</tt>, then <tt>diagonal</tt> will fail: <tt>diagonal cs n = not (cs n n) = not ⊥ = ⊥</tt>.  Because ⊥ is a fixed point of <tt>not</tt>, <tt>diagonal</tt> cannot return an element different from the one it was given.  Thus for <tt>diagonal</tt> to work, we must require that <tt>Cantor</tt>s be <i>fully-defined</i> — no infinite loops!</p>
<p>With this requirement, we can no longer put <tt>Cantor</tt>s in 1 to 1 correspondence with the naturals, because we would have to solve the halting problem.  It is not enough that the type of the term is a <tt>Cantor</tt>, it now must be fully defined for all inputs, and determining that given arbitrary source code is an undecidable problem.</p>
<div style="text-align: center;">
<h3 style="font-family: serif;">II</h3>
</div>
<p>The erroneous statement is (1).  <tt>Cantor</tt>s are computable functions, so as we have argued, they have the same cardinality as the naturals. There are no more programs than numbers, so <i>by the definition</i> of equal cardinality we can put them in 1 to 1 correspondence with a function.</p>
<p>The problem with (1) occurs because <tt>diagonal</tt> takes as its first argument not an arbitrary sequence of <tt>Cantor</tt>s, but a <i>computable</i> sequence of <tt>Cantor</tt>s.  If <tt>cs</tt> is not computable, then neither is <tt>diagonal cs</tt> (for we no longer have <tt>cs</tt>‘s source code with which to construct it), and <tt>Cantor</tt>s are defined to be computable sequences.  So <tt>diagonal</tt> fails to contradict our bijection.</p>
<div style="text-align: center;">
<h3 style="font-family: serif;">III</h3>
</div>
<p>The erroneous statement is (2).  Section II claims to put <tt>Cantor</tt>s and naturals in 1 to 1 correspondence, but it is lying.  Suppose Section II is formulated with respect to some axiom system <i>A</i>.  If it were “telling the truth”, we would expect there to be some term <i>f</i> in the language of <i>A</i> such that for every fully defined <tt>Cantor</tt> program <i>c</i>, there is some natural number <i>n</i> such that we have <img alt="A \vdash f(\bar{n}) = \bar{c}" class="latex" src="http://s0.wp.com/latex.php?latex=A+%5Cvdash+f%28%5Cbar%7Bn%7D%29+%3D+%5Cbar%7Bc%7D&amp;bg=ffffff&amp;fg=555555&amp;s=0" title="A \vdash f(\bar{n}) = \bar{c}"/> (i.e. it is a theorem of <i>A</i> that <i>f(1 + 1 + … + 1) = (source code of c)</i>).</p>
<p>Let’s suppose we have written down the axioms of <i>A</i> into a Haskell program, and we have a (partial) function <tt>proofSearch :: Nat -&gt; Cantor</tt>, which, given a number n, searches for theorems of the form <img alt="f(\bar{n}) = \bar{c}" class="latex" src="http://s0.wp.com/latex.php?latex=f%28%5Cbar%7Bn%7D%29+%3D+%5Cbar%7Bc%7D&amp;bg=ffffff&amp;fg=555555&amp;s=0" title="f(\bar{n}) = \bar{c}"/> and compiles and returns the first such <i>c</i> it finds.  In the case that there is no such statement, it just runs forever; similarly for the case that <i>c</i> fails to compile.  Although cumbersome to write, I’m sure we agree that this is <i>possible</i> to write.  If section II is not lying, then we expect that for every natural <i>n</i>, <tt>proofSearch n</tt> <i>does</i> in fact return a valid <tt>Cantor</tt>.</p>
<p>Now, let us return to familiar lands with a new program:</p>
<pre>evidence :: Cantor
evidence = diagonal proofSearch
</pre>
<p>Oh my! If section II is the truth, then <tt>proofSearch</tt> is a <i>total, computable</i> function of type <tt>Nat -&gt; Cantor</tt>, which we can pass to <tt>diagonal</tt> to find a <tt>Cantor</tt> that it missed!  So it must have been lying, either (1) about its function <tt>f</tt> finding every possible <tt>Cantor</tt> or (2) about it actually possessing such a function (i.e. it “proved” that there is such a function, but it couldn’t actually represent it).  In either case, it did not actually create a 1 to 1 correspondence between the naturals and <tt>Cantor</tt>s.</p>
<div style="text-align: center;">
<h3 style="font-family: serif;">IV</h3>
</div>
<p><i>Left as an exercise for the reader.</i>  </p>
<hr/>
<p>Which one is it <i>really</i>? </p>
<p><a href="http://flattr.com/thing/471170/Computably-Uncountable" target="_blank"><img alt="Flattr this" border="0" src="http://api.flattr.com/button/flattr-badge-large.png" title="Flattr this"/></a></p>
<br/>  <a href="http://feeds.wordpress.com/1.0/gocomments/lukepalmer.wordpress.com/1880/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lukepalmer.wordpress.com/1880/"/></a> <a href="http://feeds.wordpress.com/1.0/godelicious/lukepalmer.wordpress.com/1880/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lukepalmer.wordpress.com/1880/"/></a> <a href="http://feeds.wordpress.com/1.0/gofacebook/lukepalmer.wordpress.com/1880/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lukepalmer.wordpress.com/1880/"/></a> <a href="http://feeds.wordpress.com/1.0/gotwitter/lukepalmer.wordpress.com/1880/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lukepalmer.wordpress.com/1880/"/></a> <a href="http://feeds.wordpress.com/1.0/gostumble/lukepalmer.wordpress.com/1880/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lukepalmer.wordpress.com/1880/"/></a> <a href="http://feeds.wordpress.com/1.0/godigg/lukepalmer.wordpress.com/1880/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lukepalmer.wordpress.com/1880/"/></a> <a href="http://feeds.wordpress.com/1.0/goreddit/lukepalmer.wordpress.com/1880/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lukepalmer.wordpress.com/1880/"/></a> <img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=lukepalmer.wordpress.com&amp;blog=5292379&amp;post=1880&amp;subd=lukepalmer&amp;ref=&amp;feed=1" width="1"/></div>
    </content>
    <updated>2012-02-02T19:02:51Z</updated>
    <published>2012-01-26T02:17:32Z</published>
    <category scheme="http://lukepalmer.wordpress.com" term="Uncategorized"/>
    <category scheme="http://lukepalmer.wordpress.com" term="constructive logic"/>
    <category scheme="http://lukepalmer.wordpress.com" term="haskell"/>
    <category scheme="http://lukepalmer.wordpress.com" term="math"/>
    <category scheme="http://lukepalmer.wordpress.com" term="relativism"/>
    <author>
      <name>Luke</name>
    </author>
    <source>
      <id>http://lukepalmer.wordpress.com/feed/atom/</id>
      <link href="http://lukepalmer.wordpress.com" rel="alternate" type="text/html"/>
      <link href="http://lukepalmer.wordpress.com/feed/atom/" rel="self" type="application/atom+xml"/>
      <link href="http://lukepalmer.wordpress.com/osd.xml" rel="search" type="application/opensearchdescription+xml"/>
      <link href="http://wordpress.com/opensearch.xml" rel="search" type="application/opensearchdescription+xml"/>
      <link href="http://lukepalmer.wordpress.com/?pushpress=hub" rel="hub" type="text/html"/>
      <subtitle xml:lang="en">Functional programming and mathematical philosophy with musical interludes</subtitle>
      <title xml:lang="en">Luke Palmer</title>
      <updated>2012-02-07T20:59:16Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://existentialtype.wordpress.com/2012/02/01/words-matter/</id>
    <link href="http://existentialtype.wordpress.com/2012/02/01/words-matter/" rel="alternate" type="text/html"/>
    <link href="http://existentialtype.wordpress.com/2012/02/01/words-matter/#comments" rel="replies" type="text/html"/>
    <link href="http://existentialtype.wordpress.com/2012/02/01/words-matter/feed/atom/" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">Words matter</title>
    <summary type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml">Yesterday, during a very nice presentation by Ohad Kammar at Carnegie Mellon, the discussion got derailed, in part, because of a standard, and completely needless, terminological confusion involving the word “variable”.  I’m foolish enough to try to correct it. The problem is that we’ve all been taught to confuse variables with variables—that is, program variables [...]<img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=existentialtype.wordpress.com&amp;blog=2157150&amp;post=529&amp;subd=existentialtype&amp;ref=&amp;feed=1" width="1"/></div>
    </summary>
    <content type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml"><p>Yesterday, during a very nice presentation by <a href="http://homepages.inf.ed.ac.uk/s0894694/" title="Ohad Kammar">Ohad Kammar</a> at Carnegie Mellon, the discussion got derailed, in part, because of a standard, and completely needless, terminological confusion involving the word “variable”.  I’m foolish enough to try to correct it.</p>
<p>The problem is that we’ve all been taught to confuse variables with variables—that is, program variables with mathematical variables.  The distinction is basic.  Since time immemorial (well, at least since <a href="http://en.wikipedia.org/wiki/Mu&#x1E25;ammad_ibn_M&#x16B;s&#x101;_al-Khw&#x101;rizm&#x12B;" target="_blank" title="al Khwarizmi">al Khwarizmi</a>) we have had the notion of a variable, properly so-called, which is given meaning by substitution.  A variable is an unknown, or indeterminate, quantity that can be replaced by any value of its type (a type being, at least since <a href="http://en.wikipedia.org/wiki/Bertrand_Russell" target="_blank" title="Bertrand Russell">Russell</a>, the range of significance of a variable).  <a href="http://en.wikipedia.org/wiki/Frege" target="_blank" title="Gottlob Frege">Frege</a> gave the first systematic study of the quantifiers, and <a href="http://en.wikipedia.org/wiki/Alonzo_Church" target="_blank" title="Alonzo Church">Church</a> exploited the crucial concept of a variable to give the most sharply original and broadly applicable model of computation, the <img alt="\lambda" class="latex" src="http://s0.wp.com/latex.php?latex=%5Clambda&amp;bg=ffffff&amp;fg=333333&amp;s=0" title="\lambda"/>-calculus.</p>
<p>Since the dawn of <a href="http://en.wikipedia.org/wiki/Fortran" target="_blank" title="Fortran">Fortran</a> something that is <em>not</em> a variable has come to be <em>called</em> a variable.  A program variable, in the sense of Fortran and every imperative language since, is not given meaning by substitution.  Rather, it is given meaning by (at least) two operations associated with it, one to <em>get</em> its contents and one to <em>put</em> new contents into it.  (And, maybe, an operation to form a <em>reference</em> to it, as in C or even Algol.)  Now as many of you know, I think that the concept of a program variable in this sense is by and large a bad idea, or at any rate not nearly as important as it has been made out to be in conventional (including object-oriented) languages, but that’s an argument for another occasion.</p>
<p>Instead, I’m making a plea.  Let’s continue to call variables variables.  It’s a perfectly good name, and refers to what is perhaps one of the greatest achievements of the human mind, the fundamental concept of algebra, the variable.  But let’s stop calling those other things variables!  In my <a href="http://www.cs.cmu.edu/~rwh/plbook/book.pdf" target="_blank" title="Practical Foundation for Programming Languages">Practical Foundations for Programming Languages</a> I coined (as far as I know) a word that seems perfectly serviceable, namely an <em>assignable</em>.  The things called variables in imperative languages should, rather, be called assignables.  The word is only a tad longer than <em>variable</em>, and rolls off the tongue just as easily, and has the advantage of being an accurate description of what it really is.  What’s not to like?</p>
<p>Why bother?  For one thing, some languages have <em>both</em> concepts, a necessity if you want your language to be mathematically civilized (and you do).  For another, in the increasingly important world of program verification, the specification formalisms, being mathematical in nature, make use of variables, which most definitely are not assignables!  But the real reason to make the distinction is, after all, because <em>words matter</em>.  Two different things deserve to have two different names, and it only confuses matters to use the same word for both.  This week’s confusion was only one example of many that I have seen over the years.</p>
<p>So, my suggestion: let’s call variables <em>variables</em>, and let’s call those other things <em>assignables</em>.  In the fullnesss of time (i.e., once the scourge of imperative programming has been lifted) we may not need the distinction any longer.  But until then, why not draw the distinction properly?</p>
<p> </p>
<p><em>Addendum:</em> It seems worth mentioning that in PFPL I have a novel (afaik) treatment of the concept of a reference, which in my view has nothing whatever to do with mutation.  In particular, assignables are not themselves values, but references to them are values.  I am well aware of standard ideas such as binding a variable to a reference to an assignable; this does not in any way change my point, nor does it make that variable an assignable, surface syntax notwithstanding.  In such cases it is the referent that is the assignable, and it is still present and needs a name.  It’s not a variable.</p>
<br/>Filed under: <a href="http://existentialtype.wordpress.com/category/programming/">Programming</a>, <a href="http://existentialtype.wordpress.com/category/research/">Research</a>, <a href="http://existentialtype.wordpress.com/category/teaching-2/">Teaching</a> Tagged: <a href="http://existentialtype.wordpress.com/tag/functional-programming/">functional programming</a>, <a href="http://existentialtype.wordpress.com/tag/imperative-programming/">imperative programming</a> <a href="http://feeds.wordpress.com/1.0/gocomments/existentialtype.wordpress.com/529/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/existentialtype.wordpress.com/529/"/></a> <a href="http://feeds.wordpress.com/1.0/godelicious/existentialtype.wordpress.com/529/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/existentialtype.wordpress.com/529/"/></a> <a href="http://feeds.wordpress.com/1.0/gofacebook/existentialtype.wordpress.com/529/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/existentialtype.wordpress.com/529/"/></a> <a href="http://feeds.wordpress.com/1.0/gotwitter/existentialtype.wordpress.com/529/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/existentialtype.wordpress.com/529/"/></a> <a href="http://feeds.wordpress.com/1.0/gostumble/existentialtype.wordpress.com/529/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/existentialtype.wordpress.com/529/"/></a> <a href="http://feeds.wordpress.com/1.0/godigg/existentialtype.wordpress.com/529/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/existentialtype.wordpress.com/529/"/></a> <a href="http://feeds.wordpress.com/1.0/goreddit/existentialtype.wordpress.com/529/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/existentialtype.wordpress.com/529/"/></a> <img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=existentialtype.wordpress.com&amp;blog=2157150&amp;post=529&amp;subd=existentialtype&amp;ref=&amp;feed=1" width="1"/></div>
    </content>
    <updated>2012-02-02T18:08:19Z</updated>
    <published>2012-02-02T02:05:47Z</published>
    <category scheme="http://existentialtype.wordpress.com" term="Programming"/>
    <category scheme="http://existentialtype.wordpress.com" term="Research"/>
    <category scheme="http://existentialtype.wordpress.com" term="Teaching"/>
    <category scheme="http://existentialtype.wordpress.com" term="functional programming"/>
    <category scheme="http://existentialtype.wordpress.com" term="imperative programming"/>
    <author>
      <name>Robert Harper</name>
      <uri>http://www.cs.cmu.edu/~rwh</uri>
    </author>
    <source>
      <id>http://existentialtype.wordpress.com/feed/atom/</id>
      <link href="http://existentialtype.wordpress.com" rel="alternate" type="text/html"/>
      <link href="http://existentialtype.wordpress.com/feed/atom/" rel="self" type="application/atom+xml"/>
      <link href="http://existentialtype.wordpress.com/osd.xml" rel="search" type="application/opensearchdescription+xml"/>
      <link href="http://wordpress.com/opensearch.xml" rel="search" type="application/opensearchdescription+xml"/>
      <link href="http://existentialtype.wordpress.com/?pushpress=hub" rel="hub" type="text/html"/>
      <subtitle xml:lang="en">Abstract types are existential types.</subtitle>
      <title xml:lang="en">Existential Type</title>
      <updated>2012-02-08T22:41:26Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://pcapriotti.wordpress.com/?p=192</id>
    <link href="http://pcapriotti.wordpress.com/2012/02/02/an-introduction-to-guarded-pipes/" rel="alternate" type="text/html"/>
    <title>An introduction to guarded pipes</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">Pipes are a very simple but powerful abstraction which can be used to implement stream-based IO, in a very similar fashion to iteratees and friends, or conduits. In this post, I introduce guarded pipes: a slight generalization of pipes which makes it possible to implement a larger class of combinators. &gt; {-# LANGUAGE NoMonomorphismRestriction #-} [...]<img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&amp;blog=806312&amp;post=192&amp;subd=pcapriotti&amp;ref=&amp;feed=1" width="1"/></div>
    </summary>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p><a href="http://hackage.haskell.org/package/pipes">Pipes</a> are a very simple but powerful abstraction which can be used to implement stream-based IO, in a very similar fashion to <a href="http://hackage.haskell.org/package/iteratee">iteratees</a> <a href="http://hackage.haskell.org/package/enumerator">and</a> <a href="http://hackage.haskell.org/package/iterIO">friends</a>, or <a href="http://hackage.haskell.org/package/conduit">conduits</a>. In this post, I introduce <strong>guarded pipes</strong>: a slight generalization of pipes which makes it possible to implement a larger class of combinators.</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020;">{-# LANGUAGE NoMonomorphismRestriction #-}</span>
&gt; <span style="color: #007020; font-weight: bold;">module</span> <span style="color: #902000;">Blog.Pipes.Guarded</span> <span style="color: #007020; font-weight: bold;">where</span>
&gt;
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Control.Category</span>
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Control.Monad.Free</span>
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Control.Monad.Identity</span>
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Data.Maybe</span>
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Data.Void</span>
&gt; <span style="color: #007020; font-weight: bold;">import</span> <span style="color: #902000;">Prelude</span> <span style="color: #007020; font-weight: bold;">hiding</span> (<span style="color: #06287e;">id</span>, (<span style="color: #06287e;">.</span>), <span style="color: #06287e;">until</span>, <span style="color: #06287e;">filter</span>)</code></pre>
<p>The idea behind pipes is straightfoward: fix a base monad <code>m</code>, then construct the <a href="http://hackage.haskell.org/packages/archive/free/latest/doc/html/Control-Monad-Free.html">free monad</a> over a specific <code>PipeF</code> functor:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">data</span> <span style="color: #902000;">PipeF</span> a b m x <span style="color: #06287e;">=</span> <span style="color: #902000;">M</span> (m x)
&gt;                    <span style="color: #06287e;">|</span> <span style="color: #902000;">Yield</span> b x
&gt;                    <span style="color: #06287e;">|</span> <span style="color: #902000;">Await</span> (<span style="color: #902000;">Maybe</span> a <span style="color: #007020;">-&gt;</span> x)
&gt;
&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #007020; font-weight: bold;">Functor</span> (<span style="color: #902000;">PipeF</span> a b m) <span style="color: #007020; font-weight: bold;">where</span>
&gt;   <span style="color: #06287e;">fmap</span> f (<span style="color: #902000;">M</span> m) <span style="color: #06287e;">=</span> <span style="color: #902000;">M</span> <span style="color: #06287e;">$</span> liftM f m
&gt;   <span style="color: #06287e;">fmap</span> f (<span style="color: #902000;">Yield</span> x c) <span style="color: #06287e;">=</span> <span style="color: #902000;">Yield</span> x (f c)
&gt;   <span style="color: #06287e;">fmap</span> f (<span style="color: #902000;">Await</span> k) <span style="color: #06287e;">=</span> <span style="color: #902000;">Await</span> (f <span style="color: #06287e;">.</span> k)
&gt;
&gt; <span style="color: #007020; font-weight: bold;">type</span> <span style="color: #902000;">Pipe</span> a b m r <span style="color: #06287e;">=</span> <span style="color: #902000;">Free</span> (<span style="color: #902000;">PipeF</span> a b m) r</code></pre>
<p>Generally speaking, a free monad can be thought of as an embedded language in CPS style: every summand of the base functor (<code>PipeF</code> in this case), is a primitive operation, while the <code>x</code> parameter represents the continuation at each step.</p>
<p>In the case of pipes, <code>M</code> corresponds to an effect in the base monad, <code>Yield</code> produces an output value, and <code>Await</code> blocks until it receives an input value, then passes it to its continuation. You can see that the <code>Await</code> continuation takes a <code>Maybe a</code> type: this is the only thing that distinguishes guarded pipes from regular pipes (as implemented in the <a href="http://hackage.haskell.org/package/pipes">pipes</a> package on Hackage). The idea is that <code>Await</code> will receive <code>Nothing</code> whenever the pipe runs out of input values. That will give it a chance to do some cleanup or yield extra outputs. Any additional <code>Await</code> after that point will terminate the pipe immediately.</p>
<p>We can write a simplistic list-based (strict) interpreter formalizing the semantics I just described:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020;">evalPipe </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> a b m r <span style="color: #007020;">-&gt;</span> [a] <span style="color: #007020;">-&gt;</span> m [b]
&gt; evalPipe p xs <span style="color: #06287e;">=</span> go <span style="color: #007020; font-weight: bold;">False</span> xs [] p</code></pre>
<p>The boolean parameter is going to be set to <code>True</code> as soon as we execute an <code>Await</code> with an empty input list.</p>
<p>A <code>Pure</code> value means that the pipe has terminated spontaneously, so we return the accumulated output list:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt;   <span style="color: #007020; font-weight: bold;">where</span>
&gt;     go _ _ ys (<span style="color: #902000;">Pure</span> r) <span style="color: #06287e;">=</span> <span style="color: #06287e;">return</span> (<span style="color: #06287e;">reverse</span> ys)</code></pre>
<p>Execute inner monadic effects:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt;     go t xs ys (<span style="color: #902000;">Free</span> (<span style="color: #902000;">M</span> m)) <span style="color: #06287e;">=</span> m <span style="color: #06287e;">&gt;&gt;=</span> go t xs ys</code></pre>
<p>Save yielded values into the accumulator:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt;     go t xs ys (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Yield</span> y c)) <span style="color: #06287e;">=</span> go t xs (y <span style="color: #06287e;">:</span> ys) c</code></pre>
<p>If we still have values in the input list, feed one to the continuation of an <code>Await</code> statement.</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt;     go t (x<span style="color: #06287e;">:</span>xs) ys (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Await</span> k)) <span style="color: #06287e;">=</span> go t xs ys <span style="color: #06287e;">$</span> k (<span style="color: #007020; font-weight: bold;">Just</span> x)</code></pre>
<p>If we run out of inputs, pass <code>Nothing</code> to the <code>Await</code> continuation…</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt;     go <span style="color: #007020; font-weight: bold;">False</span> [] ys (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Await</span> k)) <span style="color: #06287e;">=</span> go <span style="color: #007020; font-weight: bold;">True</span> [] ys (k <span style="color: #007020; font-weight: bold;">Nothing</span>)</code></pre>
<p>… but only the first time. If the pipe awaits again, terminate it.</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt;     go <span style="color: #007020; font-weight: bold;">True</span> [] ys (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Await</span> _)) <span style="color: #06287e;">=</span> <span style="color: #06287e;">return</span> (<span style="color: #06287e;">reverse</span> ys)</code></pre>
<p>To simplify the implementation of actual pipes, we define the following basic combinators:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020;">tryAwait </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> a b m (<span style="color: #902000;">Maybe</span> a)
&gt; tryAwait <span style="color: #06287e;">=</span> wrap <span style="color: #06287e;">$</span> <span style="color: #902000;">Await</span> <span style="color: #06287e;">return</span>
&gt;
&gt; <span style="color: #007020;">yield </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> b <span style="color: #007020;">-&gt;</span> <span style="color: #902000;">Pipe</span> a b m ()
&gt; yield x <span style="color: #06287e;">=</span> wrap <span style="color: #06287e;">$</span> <span style="color: #902000;">Yield</span> x (<span style="color: #06287e;">return</span> ())
&gt;
&gt; <span style="color: #007020;">lift </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> m r <span style="color: #007020;">-&gt;</span> <span style="color: #902000;">Pipe</span> a b m r
&gt; lift <span style="color: #06287e;">=</span> wrap <span style="color: #06287e;">.</span> <span style="color: #902000;">M</span> <span style="color: #06287e;">.</span> liftM <span style="color: #06287e;">return</span></code></pre>
<p>and a couple of secondary combinators, very useful in practice. First, a pipe that consumes all input and never produces output:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020;">discard </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> a b m r
&gt; discard <span style="color: #06287e;">=</span> forever tryAwait</code></pre>
<p>then a simplified <code>await</code> primitive, that dies as soon as we stop feeding values to it.</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020;">await </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> a b m a
&gt; await <span style="color: #06287e;">=</span> tryAwait <span style="color: #06287e;">&gt;&gt;=</span> <span style="color: #06287e;">maybe</span> discard <span style="color: #06287e;">return</span></code></pre>
<p>now we can write a very simple pipe that sums consecutive pairs of numbers:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020;">sumPairs </span><span style="color: #007020;">::</span> (<span style="color: #007020; font-weight: bold;">Monad</span> m, <span style="color: #007020; font-weight: bold;">Num</span> a) <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> a a m ()
&gt; sumPairs <span style="color: #06287e;">=</span> forever <span style="color: #06287e;">$</span> <span style="color: #007020; font-weight: bold;">do</span>
&gt;   x <span style="color: #007020;">&lt;-</span> await
&gt;   y <span style="color: #007020;">&lt;-</span> await
&gt;   yield <span style="color: #06287e;">$</span> x <span style="color: #06287e;">+</span> y</code></pre>
<p>we get:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020;">ex1 </span><span style="color: #007020;">::</span> [<span style="color: #902000;">Int</span>]
&gt; ex1 <span style="color: #06287e;">=</span> runIdentity <span style="color: #06287e;">$</span> evalPipe sumPairs [<span style="color: #40a070;">1</span>,<span style="color: #40a070;">2</span>,<span style="color: #40a070;">3</span>,<span style="color: #40a070;">4</span>]
&gt; <span style="color: #60a0b0; font-style: italic;">{- ex1 == [3, 7] -}</span></code></pre>
<h2 id="composing-pipes">Composing pipes</h2>
<p>The usefulness of pipes, however, is not limited to being able to express list transformations as monadic computations using the <code>await</code> and <code>yield</code> primitives. In fact, it turns out that two pipes can be composed sequentially to create a new pipe.</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">infixl</span> <span style="color: #40a070;">9</span> <span style="color: #06287e;">&gt;+&gt;</span>
&gt; <span style="color: #007020;">(&gt;+&gt;) </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> a b m r <span style="color: #007020;">-&gt;</span> <span style="color: #902000;">Pipe</span> b c m r <span style="color: #007020;">-&gt;</span> <span style="color: #902000;">Pipe</span> a c m r
&gt; (<span style="color: #06287e;">&gt;+&gt;</span>) <span style="color: #06287e;">=</span> go <span style="color: #007020; font-weight: bold;">False</span> <span style="color: #007020; font-weight: bold;">False</span>
&gt;   <span style="color: #007020; font-weight: bold;">where</span></code></pre>
<p>When implementing <code>evalPipe</code>, we needed a boolean parameter to signal upstream input exhaustion. This time, we need two boolean parameters, one for the input of the upstream pipe, and one for its output, i.e. the input of the downstream pipe. First, if downstream does anything other than waiting, we just let the composite pipe execute the same action:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt;     go _ _ p1 (<span style="color: #902000;">Pure</span> r) <span style="color: #06287e;">=</span> <span style="color: #06287e;">return</span> r
&gt;     go t1 t2 p1 (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Yield</span> x c)) <span style="color: #06287e;">=</span> yield x <span style="color: #06287e;">&gt;&gt;</span> go t1 t2 p1 c
&gt;     go t1 t2 p1 (<span style="color: #902000;">Free</span> (<span style="color: #902000;">M</span> m)) <span style="color: #06287e;">=</span> lift m <span style="color: #06287e;">&gt;&gt;=</span> \p2 <span style="color: #007020;">-&gt;</span> go t1 t2 p1 p2</code></pre>
<p>then, if upstream is yielding and downstream is waiting, we can feed the yielded value to the downstream pipe and continue from there:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt;     go t1 t2 (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Yield</span> x c)) (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Await</span> k)) <span style="color: #06287e;">=</span>
&gt;       go t1 t2 c <span style="color: #06287e;">$</span> k (<span style="color: #007020; font-weight: bold;">Just</span> x)</code></pre>
<p>if downstream is waiting and upstream is running a monadic computation, just let upstream run and keep downstream waiting:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt;     go t1 t2 (<span style="color: #902000;">Free</span> (<span style="color: #902000;">M</span> m)) p2<span style="color: #06287e;">@</span>(<span style="color: #902000;">Free</span> (<span style="color: #902000;">Await</span> _)) <span style="color: #06287e;">=</span>
&gt;       lift m <span style="color: #06287e;">&gt;&gt;=</span> \p1 <span style="color: #007020;">-&gt;</span> go t1 t2 p1 p2</code></pre>
<p>if upstream terminates while downstream is waiting, finalize downstream:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt;     go t1 <span style="color: #007020; font-weight: bold;">False</span> p1<span style="color: #06287e;">@</span>(<span style="color: #902000;">Pure</span> _) (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Await</span> k)) <span style="color: #06287e;">=</span>
&gt;       go t1 <span style="color: #007020; font-weight: bold;">True</span> p1 (k <span style="color: #007020; font-weight: bold;">Nothing</span>)</code></pre>
<p>but if downstream awaits again, terminate the whole composite pipe:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt;     go _ <span style="color: #007020; font-weight: bold;">True</span> (<span style="color: #902000;">Pure</span> r) (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Await</span> _)) <span style="color: #06287e;">=</span> <span style="color: #06287e;">return</span> r</code></pre>
<p>now, if both pipes are waiting, we keep the second pipe waiting and we feed whatever input we get to the first pipe. If the input is <code>Nothing</code>, we set the first boolean flag, so that next time the first pipe awaits, we can finalize the downstream pipe.</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt;     go <span style="color: #007020; font-weight: bold;">False</span> t2 (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Await</span> k)) p2<span style="color: #06287e;">@</span>(<span style="color: #902000;">Free</span> (<span style="color: #902000;">Await</span> _)) <span style="color: #06287e;">=</span>
&gt;       tryAwait <span style="color: #06287e;">&gt;&gt;=</span> \x <span style="color: #007020;">-&gt;</span> go (isNothing x) t2 (k x) p2
&gt;     go <span style="color: #007020; font-weight: bold;">True</span> <span style="color: #007020; font-weight: bold;">False</span> p1<span style="color: #06287e;">@</span>(<span style="color: #902000;">Free</span> (<span style="color: #902000;">Await</span> _)) (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Await</span> k)) <span style="color: #06287e;">=</span>
&gt;       go <span style="color: #007020; font-weight: bold;">True</span> <span style="color: #007020; font-weight: bold;">True</span> p1 (k <span style="color: #007020; font-weight: bold;">Nothing</span>)
&gt;     go <span style="color: #007020; font-weight: bold;">True</span> <span style="color: #007020; font-weight: bold;">True</span> p1<span style="color: #06287e;">@</span>(<span style="color: #902000;">Free</span> (<span style="color: #902000;">Await</span> _)) p2<span style="color: #06287e;">@</span>(<span style="color: #902000;">Free</span> (<span style="color: #902000;">Await</span> _)) <span style="color: #06287e;">=</span>
&gt;       tryAwait <span style="color: #06287e;">&gt;&gt;=</span> \_ <span style="color: #007020;">-&gt;</span> <span style="color: #60a0b0; font-style: italic;">{- unreachable -}</span> go <span style="color: #007020; font-weight: bold;">True</span> <span style="color: #007020; font-weight: bold;">True</span> p1 p2</code></pre>
<p>This composition can be shown to be associative (in a rather strong sense), with identity given by:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020;">idP </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> a a m r
&gt; idP <span style="color: #06287e;">=</span> forever <span style="color: #06287e;">$</span> await <span style="color: #06287e;">&gt;&gt;=</span> yield</code></pre>
<p>So we can define a <code>Category</code> instance:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">newtype</span> <span style="color: #902000;">PipeC</span> m r a b <span style="color: #06287e;">=</span> <span style="color: #902000;">PipeC</span> {<span style="color: #007020;"> unPipeC </span><span style="color: #007020;">::</span> <span style="color: #902000;">Pipe</span> a b m r }
&gt;
&gt; <span style="color: #007020; font-weight: bold;">instance</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Category</span> (<span style="color: #902000;">PipeC</span> m r) <span style="color: #007020; font-weight: bold;">where</span>
&gt;   <span style="color: #06287e;">id</span> <span style="color: #06287e;">=</span> <span style="color: #902000;">PipeC</span> idP
&gt;   (<span style="color: #902000;">PipeC</span> p2) <span style="color: #06287e;">.</span> (<span style="color: #902000;">PipeC</span> p1) <span style="color: #06287e;">=</span> <span style="color: #902000;">PipeC</span> <span style="color: #06287e;">$</span> p1 <span style="color: #06287e;">&gt;+&gt;</span> p2</code></pre>
<h2 id="running-pipes">Running pipes</h2>
<p>A <strong>runnable pipe</strong>, also called <code>Pipeline</code>, is a pipe that doesn’t yield any value and doesn’t wait for any input. We can formalize this in the types as follows:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">type</span> <span style="color: #902000;">Pipeline</span> m r <span style="color: #06287e;">=</span> <span style="color: #902000;">Pipe</span> () <span style="color: #902000;">Void</span> m r</code></pre>
<p>Disregarding bottom, calling <code>await</code> on such a pipe does not return any useful value, and yielding is impossible. Another way to think of <code>Pipeline</code> is as an arrow (in <code>PipeC</code>) from the terminal object to the initial object of Hask<sup><a class="footnoteRef" href="http://pcapriotti.wordpress.com/category/haskell/feed/?mrss=off&amp;category_name=haskell#fn1" id="fnref1">1</a></sup>.</p>
<p>Running a pipeline is straightforward:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020;">runPipe </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipeline</span> m r <span style="color: #007020;">-&gt;</span> m r
&gt; runPipe (<span style="color: #902000;">Pure</span> r) <span style="color: #06287e;">=</span> <span style="color: #06287e;">return</span> r
&gt; runPipe (<span style="color: #902000;">Free</span> (<span style="color: #902000;">M</span> m)) <span style="color: #06287e;">=</span> m <span style="color: #06287e;">&gt;&gt;=</span> runPipe
&gt; runPipe (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Await</span> k)) <span style="color: #06287e;">=</span> runPipe <span style="color: #06287e;">$</span> k (<span style="color: #007020; font-weight: bold;">Just</span> ())
&gt; runPipe (<span style="color: #902000;">Free</span> (<span style="color: #902000;">Yield</span> x c)) <span style="color: #06287e;">=</span> absurd x</code></pre>
<p>where the impossibility of the last case is guaranteed by the types, unless of course the pipe introduced a bottom value at some point.</p>
<p>The three primitive operations <code>tryAwait</code>, <code>yield</code> and <code>lift</code>, together with pipe composition and the <code>runPipe</code> function above, are basically all we need to define most pipes and pipe combinators. For example, the simple pipe interpreter <code>evalPipe</code> can be easily rewritten in terms of these primitives:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020;">evalPipe' </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> a b m r <span style="color: #007020;">-&gt;</span> [a] <span style="color: #007020;">-&gt;</span> m [b]
&gt; evalPipe' p xs <span style="color: #06287e;">=</span> runPipe <span style="color: #06287e;">$</span>
&gt;   (<span style="color: #06287e;">mapM_</span> yield xs <span style="color: #06287e;">&gt;&gt;</span> <span style="color: #06287e;">return</span> []) <span style="color: #06287e;">&gt;+&gt;</span>
&gt;   (p <span style="color: #06287e;">&gt;&gt;</span> discard) <span style="color: #06287e;">&gt;+&gt;</span>
&gt;   collect <span style="color: #06287e;">id</span>
&gt;   <span style="color: #007020; font-weight: bold;">where</span>
&gt;     collect xs <span style="color: #06287e;">=</span>
&gt;       tryAwait <span style="color: #06287e;">&gt;&gt;=</span> <span style="color: #06287e;">maybe</span> (<span style="color: #06287e;">return</span> <span style="color: #06287e;">$</span> xs [])
&gt;                          (\x <span style="color: #007020;">-&gt;</span> collect (xs <span style="color: #06287e;">.</span> (x<span style="color: #06287e;">:</span>)))</code></pre>
<p>Note that we use the <code>discard</code> pipe to turn the original pipe into an infinite one, so that the final return value will be taken from the final pipe.</p>
<h2 id="extra-combinators">Extra combinators</h2>
<p>The rich structure on pipes (category and monad) makes it really easy to define new higher-level combinators. For example, here are implementations of some of the combinators in Data.Conduit.List, translated to pipes:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; sourceList <span style="color: #06287e;">=</span> <span style="color: #06287e;">mapM_</span> yield
&gt; sourceNull <span style="color: #06287e;">=</span> <span style="color: #06287e;">return</span> ()
&gt; fold f z <span style="color: #06287e;">=</span> go z
&gt;   <span style="color: #007020; font-weight: bold;">where</span>
&gt;     go x <span style="color: #06287e;">=</span> tryAwait <span style="color: #06287e;">&gt;&gt;=</span> <span style="color: #06287e;">maybe</span> (<span style="color: #06287e;">return</span> x) (go <span style="color: #06287e;">.</span> f x)
&gt; consume <span style="color: #06287e;">=</span> fold (\xs x <span style="color: #007020;">-&gt;</span> xs <span style="color: #06287e;">.</span> (x<span style="color: #06287e;">:</span>)) <span style="color: #06287e;">id</span> <span style="color: #06287e;">&gt;&gt;=</span> \xs <span style="color: #007020;">-&gt;</span> <span style="color: #06287e;">return</span> (xs [])
&gt; sinkNull <span style="color: #06287e;">=</span> discard
&gt; <span style="color: #06287e;">take</span> n <span style="color: #06287e;">=</span> (isolate n <span style="color: #06287e;">&gt;&gt;</span> <span style="color: #06287e;">return</span> []) <span style="color: #06287e;">&gt;+&gt;</span> consume
&gt; <span style="color: #06287e;">drop</span> n <span style="color: #06287e;">=</span> replicateM n await <span style="color: #06287e;">&gt;&gt;</span> idP
&gt; pipe f <span style="color: #06287e;">=</span> forever <span style="color: #06287e;">$</span> await <span style="color: #06287e;">&gt;&gt;=</span> yield <span style="color: #06287e;">.</span> f <span style="color: #60a0b0; font-style: italic;">-- called map in conduit</span>
&gt; <span style="color: #06287e;">concatMap</span> f <span style="color: #06287e;">=</span> forever <span style="color: #06287e;">$</span> await <span style="color: #06287e;">&gt;&gt;=</span> <span style="color: #06287e;">mapM_</span> yield <span style="color: #06287e;">.</span> f
&gt; <span style="color: #06287e;">until</span> p <span style="color: #06287e;">=</span> go
&gt;   <span style="color: #007020; font-weight: bold;">where</span>
&gt;     go <span style="color: #06287e;">=</span> await <span style="color: #06287e;">&gt;&gt;=</span> \x <span style="color: #007020;">-&gt;</span> <span style="color: #007020; font-weight: bold;">if</span> p x <span style="color: #007020; font-weight: bold;">then</span> <span style="color: #06287e;">return</span> () <span style="color: #007020; font-weight: bold;">else</span> yield x <span style="color: #06287e;">&gt;&gt;</span> go
&gt; groupBy (<span style="color: #06287e;">~=</span>) <span style="color: #06287e;">=</span> p <span style="color: #06287e;">&gt;+&gt;</span>
&gt;   forever (<span style="color: #06287e;">until</span> isNothing <span style="color: #06287e;">&gt;+&gt;</span>
&gt;            pipe fromJust <span style="color: #06287e;">&gt;+&gt;</span>
&gt;            (consume <span style="color: #06287e;">&gt;&gt;=</span> yield))
&gt;   <span style="color: #007020; font-weight: bold;">where</span>
&gt;     <span style="color: #60a0b0; font-style: italic;">-- the pipe p yields Nothing whenever the current item y</span>
&gt;     <span style="color: #60a0b0; font-style: italic;">-- and the previous one x do not satisfy x ~= y, and behaves</span>
&gt;     <span style="color: #60a0b0; font-style: italic;">-- like idP otherwise</span>
&gt;     p <span style="color: #06287e;">=</span> await <span style="color: #06287e;">&gt;&gt;=</span> \x <span style="color: #007020;">-&gt;</span> yield (<span style="color: #007020; font-weight: bold;">Just</span> x) <span style="color: #06287e;">&gt;&gt;</span> go x
&gt;     go x <span style="color: #06287e;">=</span> <span style="color: #007020; font-weight: bold;">do</span>
&gt;       y <span style="color: #007020;">&lt;-</span> await
&gt;       unless (x <span style="color: #06287e;">~=</span> y) <span style="color: #06287e;">$</span> yield <span style="color: #007020; font-weight: bold;">Nothing</span>
&gt;       yield <span style="color: #06287e;">$</span> <span style="color: #007020; font-weight: bold;">Just</span> y
&gt;       go y
&gt; isolate n <span style="color: #06287e;">=</span> replicateM_ n <span style="color: #06287e;">$</span> await <span style="color: #06287e;">&gt;&gt;=</span> yield
&gt; <span style="color: #06287e;">filter</span> p <span style="color: #06287e;">=</span> forever <span style="color: #06287e;">$</span> <span style="color: #06287e;">until</span> (<span style="color: #06287e;">not</span> <span style="color: #06287e;">.</span> p)</code></pre>
<p>To work with the equivalent of sinks, it is useful to define a source to sink composition operator:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020; font-weight: bold;">infixr</span> <span style="color: #40a070;">2</span> <span style="color: #06287e;">$$</span>
&gt; <span style="color: #007020;">($$) </span><span style="color: #007020;">::</span> <span style="color: #007020; font-weight: bold;">Monad</span> m <span style="color: #007020;">=&gt;</span> <span style="color: #902000;">Pipe</span> () a m r' <span style="color: #007020;">-&gt;</span> <span style="color: #902000;">Pipe</span> a <span style="color: #902000;">Void</span> m r <span style="color: #007020;">-&gt;</span> m (<span style="color: #902000;">Maybe</span> r)
&gt; p1 <span style="color: #06287e;">$$</span> p2 <span style="color: #06287e;">=</span> runPipe <span style="color: #06287e;">$</span> (p1 <span style="color: #06287e;">&gt;&gt;</span> <span style="color: #06287e;">return</span> <span style="color: #007020; font-weight: bold;">Nothing</span>) <span style="color: #06287e;">&gt;+&gt;</span> liftM <span style="color: #007020; font-weight: bold;">Just</span> p2</code></pre>
<p>which ignores the source return type, and just returns the sink return value, or <code>Nothing</code> if the source happens to terminate first. So we have, for example:</p>
<pre style="vertical-align: baseline; border: none; margin: 0; padding: 0;"><code class="sourceCode haskell">&gt; <span style="color: #007020;">ex2 </span><span style="color: #007020;">::</span> <span style="color: #902000;">Maybe</span> [<span style="color: #902000;">Int</span>]
&gt; ex2 <span style="color: #06287e;">=</span> runIdentity <span style="color: #06287e;">$</span> sourceList [<span style="color: #40a070;">1</span><span style="color: #06287e;">..</span><span style="color: #40a070;">10</span>] <span style="color: #06287e;">&gt;+&gt;</span> isolate <span style="color: #40a070;">4</span> <span style="color: #06287e;">$$</span> consume
&gt; <span style="color: #60a0b0; font-style: italic;">{- ex2 == Just [1,2,3,4] -}</span>
&gt;
&gt; <span style="color: #007020;">ex3 </span><span style="color: #007020;">::</span> <span style="color: #902000;">Maybe</span> [<span style="color: #902000;">Int</span>]
&gt; ex3 <span style="color: #06287e;">=</span> runIdentity <span style="color: #06287e;">$</span> sourceList [<span style="color: #40a070;">1</span><span style="color: #06287e;">..</span><span style="color: #40a070;">10</span>] <span style="color: #06287e;">$$</span> discard
&gt; <span style="color: #60a0b0; font-style: italic;">{- ex3 == Nothing -}</span>
&gt;
&gt; <span style="color: #007020;">ex4 </span><span style="color: #007020;">::</span> <span style="color: #902000;">Maybe</span> <span style="color: #902000;">Int</span>
&gt; ex4 <span style="color: #06287e;">=</span> runIdentity <span style="color: #06287e;">$</span> sourceList [<span style="color: #40a070;">1</span>,<span style="color: #40a070;">1</span>,<span style="color: #40a070;">2</span>,<span style="color: #40a070;">2</span>,<span style="color: #40a070;">2</span>,<span style="color: #40a070;">3</span>,<span style="color: #40a070;">4</span>,<span style="color: #40a070;">4</span>]
&gt;                 <span style="color: #06287e;">&gt;+&gt;</span> groupBy (<span style="color: #06287e;">==</span>)
&gt;                 <span style="color: #06287e;">&gt;+&gt;</span> pipe <span style="color: #06287e;">head</span>
&gt;                  <span style="color: #06287e;">$$</span> fold (<span style="color: #06287e;">+</span>) <span style="color: #40a070;">0</span>
&gt; <span style="color: #60a0b0; font-style: italic;">{- ex4 == Just 10 -}</span>
&gt;
&gt; <span style="color: #007020;">ex5 </span><span style="color: #007020;">::</span> <span style="color: #902000;">Maybe</span> [<span style="color: #902000;">Int</span>]
&gt; ex5 <span style="color: #06287e;">=</span> runIdentity <span style="color: #06287e;">$</span> sourceList [<span style="color: #40a070;">1</span><span style="color: #06287e;">..</span><span style="color: #40a070;">10</span>]
&gt;                 <span style="color: #06287e;">&gt;+&gt;</span> <span style="color: #06287e;">filter</span> (\x <span style="color: #007020;">-&gt;</span> x <span style="color: #007020;">`mod`</span> <span style="color: #40a070;">3</span> <span style="color: #06287e;">==</span> <span style="color: #40a070;">0</span>)
&gt;                  <span style="color: #06287e;">$$</span> consume
&gt; <span style="color: #60a0b0; font-style: italic;">{- ex5 == Just [3, 6, 9] -}</span></code></pre>
<h2 id="pipes-in-practice">Pipes in practice</h2>
<p>You can find an implementation of guarded pipes in my <a href="https://github.com/pcapriotti/Haskell-Pipes-Library/tree/monoidal">fork</a> of pipes. There is also a <a href="https://github.com/pcapriotti/pipes-extra">pipes-extra</a> repository where you can find some pipes to deal with chunked <code>ByteStream</code>s and utilities to convert conduits to pipes.</p>
<p>I hope to be able to merge this into the original pipes package once the guarded pipe concept has proven its worth. Without the <code>tryAwait</code> primitive, combinators like <code>fold</code> and <code>consume</code> cannot be implemented, nor even a simple stateful pipe like one to split a chunked input into lines. So I think there are enough benefits to justify a little extra complexity in the definition of composition.</p>
<div class="footnotes">
<hr/>
<ol>
<li id="fn1">
<p>In reality, Hask doesn’t have an initial object, and the terminal object is actually <code>Void</code>, because of non-strict semantics. <a class="footnoteBackLink" href="http://pcapriotti.wordpress.com/category/haskell/feed/?mrss=off&amp;category_name=haskell#fnref1">↩</a></p>
</li>
</ol>
</div>
<br/>  <a href="http://feeds.wordpress.com/1.0/gocomments/pcapriotti.wordpress.com/192/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pcapriotti.wordpress.com/192/"/></a> <a href="http://feeds.wordpress.com/1.0/godelicious/pcapriotti.wordpress.com/192/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pcapriotti.wordpress.com/192/"/></a> <a href="http://feeds.wordpress.com/1.0/gofacebook/pcapriotti.wordpress.com/192/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pcapriotti.wordpress.com/192/"/></a> <a href="http://feeds.wordpress.com/1.0/gotwitter/pcapriotti.wordpress.com/192/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pcapriotti.wordpress.com/192/"/></a> <a href="http://feeds.wordpress.com/1.0/gostumble/pcapriotti.wordpress.com/192/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pcapriotti.wordpress.com/192/"/></a> <a href="http://feeds.wordpress.com/1.0/godigg/pcapriotti.wordpress.com/192/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pcapriotti.wordpress.com/192/"/></a> <a href="http://feeds.wordpress.com/1.0/goreddit/pcapriotti.wordpress.com/192/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pcapriotti.wordpress.com/192/"/></a> <img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&amp;blog=806312&amp;post=192&amp;subd=pcapriotti&amp;ref=&amp;feed=1" width="1"/></div>
    </content>
    <updated>2012-02-02T17:50:51Z</updated>
    <category term="haskell"/>
    <category term="programming"/>
    <author>
      <name>pcapriotti</name>
    </author>
    <source>
      <id>http://pcapriotti.wordpress.com</id>
      <logo>http://s2.wp.com/i/buttonw-com.png</logo>
      <link href="http://pcapriotti.wordpress.com/category/haskell/feed/?mrss=off&amp;category_name=haskell" rel="self" type="application/atom+xml"/>
      <link href="http://pcapriotti.wordpress.com" rel="alternate" type="text/html"/>
      <link href="http://pcapriotti.wordpress.com/osd.xml" rel="search" type="application/opensearchdescription+xml"/>
      <link href="http://pcapriotti.wordpress.com/?pushpress=hub" rel="hub" type="text/html"/>
      <subtitle>KDE hacking and more</subtitle>
      <title>Paolo Capriotti » haskell</title>
      <updated>2012-02-04T21:22:23Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://marcot.eti.br//posts/ghc_-fvia-C_and_new_binutils/</id>
    <link href="http://marcot.eti.br//posts/ghc_-fvia-C_and_new_binutils/" rel="alternate" type="text/html"/>
    <title>ghc -fvia-C and new binutils</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>I was trying to build the <a href="http://hackage.haskell.org/package/curl">curl hackage package</a> on Debian unstable with ghc 7.0.3, and one of its modules were failing to build.  I searched for the error message and found <a href="http://hackage.haskell.org/trac/ghc/ticket/5043">this GHC ticket</a>.  As mentioned in the ticket, I had to downgrade <a href="http://packages.debian.org/sid/binutils">binutils</a> to 2.20.  The version of binutils in sid is 2.21.</p>

<p>Another possibility would be to change curl to avoid using -fvia-C, but I didn't want to modify the package.</p></div>
    </summary>
    <updated>2012-02-02T16:28:18Z</updated>
    <category term="/tags/debian"/>
    <category term="/tags/haskell"/>
    <source>
      <id>http://marcot.eti.br//tag/haskell/</id>
      <author>
        <name>Marco Túlio Gontijo e Silva</name>
      </author>
      <link href="http://marcot.eti.br//tag/haskell/" rel="alternate" type="text/html"/>
      <link href="http://marcot.eti.br/tag/haskell/index.rss" rel="self" type="application/rss+xml"/>
      <subtitle>marcot</subtitle>
      <title>pages tagged haskell</title>
      <updated>2012-02-02T21:23:23Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://marcot.eti.br//posts/Using_XMonad_with_Netbeans___40__or_other_Java_apps__41__/</id>
    <link href="http://marcot.eti.br//posts/Using_XMonad_with_Netbeans___40__or_other_Java_apps__41__/" rel="alternate" type="text/html"/>
    <title>Using XMonad with Netbeans (or other Java apps)</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>After testing Emacs, Eclipse, KDevelop and CodeBlocks for writing C++ code, I decided to stick with Netbeans.  It seems to be the most simple to configure and yet full of features and plugins.  I was having one problem with it that when I focused out the window, and then focused on it again, it would not really grab the focus, in the sense that I would not be able to type without first clicking with the mouse.  At first I thought the problem was with Netbeans, then with the JRE.  I tried using sun-java6-jre, I tried upgrading my openjdk-6-jre, and nothing worked.  I searched a little bit more and got to <a href="http://www.mail-archive.com/ion-general@lists.berlios.de/msg03073.html">a discussion about this problem in ion3</a>, and that made me think that the problem could be related to the window manager I use, <a href="http://xmonad.org/">XMonad</a>.  After searching a bit about it, I found on <a href="http://www.haskell.org/haskellwiki/Xmonad/Frequently_asked_questions#Problems_with_Java_applications.2C_Applet_java_console">the XMonad FAQ</a> some work arounds for problems with Java apps, but they didn't solve my problem.  Then, I found the solution on <a href="http://code.google.com/p/xmonad/issues/detail?id=177">this bug report</a>.  I got the darcs version of xmonad and XMonadContrib, included <a href="http://www.eng.uwaterloo.ca/~aavogt/xmonad/docs/xmonad-contrib/XMonad-Hooks-ICCCMFocus.html"><code>takeTopFocus</code></a> on logHook, and now it's working!</p></div>
    </summary>
    <updated>2012-02-02T16:28:18Z</updated>
    <category term="/tags/debian"/>
    <category term="/tags/haskell"/>
    <source>
      <id>http://marcot.eti.br//tag/haskell/</id>
      <author>
        <name>Marco Túlio Gontijo e Silva</name>
      </author>
      <link href="http://marcot.eti.br//tag/haskell/" rel="alternate" type="text/html"/>
      <link href="http://marcot.eti.br/tag/haskell/index.rss" rel="self" type="application/rss+xml"/>
      <subtitle>marcot</subtitle>
      <title>pages tagged haskell</title>
      <updated>2012-02-02T21:23:23Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://joyridelabs.de/blog/?p=1203</id>
    <link href="http://joyridelabs.de/blog/?p=1203" rel="alternate" type="text/html"/>
    <link href="http://joyridelabs.de/blog/?p=1203#comments" rel="replies" type="text/html"/>
    <link href="http://joyridelabs.de/blog/?feed=atom&amp;p=1203" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">Nikki’s Valentines Heart Shirts and Global Game Jam</title>
    <summary type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml"><p class="en"/><p style="text-align: center;"><a href="http://joyridelabs.spreadshirt.de/valentine-girl-A18857760"><img alt="Valentines Pixel Neon Heart Female Shirt Design" class="aligncenter size-full wp-image-1210" height="280" src="http://joyridelabs.de/blog//wp-content/uploads/2012/02/valentine-girl-453.png" title="Valentines Pixel Neon Heart Female Shirt Design" width="250"/></a><a href="http://joyridelabs.spreadshirt.de/valentine-boy-A18857755"><img alt="Valentines Pixel Neon Heart Male Shirt Design" class="aligncenter size-full wp-image-1211" height="280" src="http://joyridelabs.de/blog//wp-content/uploads/2012/02/valentine-boy-316.png" title="Valentines Pixel Neon Heart Male Shirt Design" width="250"/></a></p>

<p>We added a neon pixel heart design to our <a href="http://joyridelabs.spreadshirt.de/">shirt store</a>. It is based on one of the first game objects that you will see when playing Episode 1 of the story mode:</p>
<p style="text-align: center;"><a href="http://joyridelabs.de/game/gallery/"><img alt="Nikki and the Robots Neon Heart" class="aligncenter" height="290" src="http://joyridelabs.de/img/screenshot-01.png" title="Nikki and the Robots Neon Heart" width="400"/></a></p>

<p>One of us was at the <a href="http://berlinminijam.blogspot.com/2012/01/ggj-2012-berlin-impressions-and-results.html">Global Game Jam in Berlin</a> as an organizer.</p>

<p style="text-align: center;"><a href="http://globalgamejam.org/news/2012/01/27/and-ggj-2012-theme"><img alt="ggj2012 topic" class="aligncenter size-full wp-image-1207" height="256" src="http://joyridelabs.de/blog//wp-content/uploads/2012/02/ggj2012-topic-theme.png" title="ggj2012 topic" width="256"/></a></p>

<p>The theme was a snake biting its own tail and we made a tiny level referencing it. Too late for submission though. ;)</p>

<p>&lt;iframe allowfullscreen="allowfullscreen" frameborder="0" height="304" src="http://www.youtube.com/embed/E6qUI6qPfno" width="540"&gt;&lt;/iframe&gt;
</p><p style="font-size: small; text-align: center;">video: <a href="http://www.youtube.com/watch?v=E6qUI6qPfno">Nikki and the Snake - GGJ 2012 Themed Level</a></p>

<p>The video also shows the recently added game over screen menu (no more abrupt returning to the level selection) and a new, simple background for the editor.</p><p/></div>
    </summary>
    <content type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml"><p class="en"/><p style="text-align: center;"><a href="http://joyridelabs.spreadshirt.de/valentine-girl-A18857760"><img alt="Valentines Pixel Neon Heart Female Shirt Design" class="aligncenter size-full wp-image-1210" height="280" src="http://joyridelabs.de/blog//wp-content/uploads/2012/02/valentine-girl-453.png" title="Valentines Pixel Neon Heart Female Shirt Design" width="250"/></a><a href="http://joyridelabs.spreadshirt.de/valentine-boy-A18857755"><img alt="Valentines Pixel Neon Heart Male Shirt Design" class="aligncenter size-full wp-image-1211" height="280" src="http://joyridelabs.de/blog//wp-content/uploads/2012/02/valentine-boy-316.png" title="Valentines Pixel Neon Heart Male Shirt Design" width="250"/></a></p>

<p>We added a neon pixel heart design to our <a href="http://joyridelabs.spreadshirt.de/">shirt store</a>. It is based on one of the first game objects that you will see when playing Episode 1 of the story mode:</p>
<p style="text-align: center;"><a href="http://joyridelabs.de/game/gallery/"><img alt="Nikki and the Robots Neon Heart" class="aligncenter" height="290" src="http://joyridelabs.de/img/screenshot-01.png" title="Nikki and the Robots Neon Heart" width="400"/></a></p>

<p>One of us was at the <a href="http://berlinminijam.blogspot.com/2012/01/ggj-2012-berlin-impressions-and-results.html">Global Game Jam in Berlin</a> as an organizer.</p>

<p style="text-align: center;"><a href="http://globalgamejam.org/news/2012/01/27/and-ggj-2012-theme"><img alt="ggj2012 topic" class="aligncenter size-full wp-image-1207" height="256" src="http://joyridelabs.de/blog//wp-content/uploads/2012/02/ggj2012-topic-theme.png" title="ggj2012 topic" width="256"/></a></p>

<p>The theme was a snake biting its own tail and we made a tiny level referencing it. Too late for submission though. ;)</p>

<p>&lt;iframe allowfullscreen="allowfullscreen" frameborder="0" height="304" src="http://www.youtube.com/embed/E6qUI6qPfno" width="540"&gt;&lt;/iframe&gt;
</p><p style="font-size: small; text-align: center;">video: <a href="http://www.youtube.com/watch?v=E6qUI6qPfno">Nikki and the Snake - GGJ 2012 Themed Level</a></p>

<p>The video also shows the recently added game over screen menu (no more abrupt returning to the level selection) and a new, simple background for the editor.</p><p/></div>
    </content>
    <updated>2012-02-02T13:07:19Z</updated>
    <published>2012-02-01T22:16:34Z</published>
    <category scheme="http://joyridelabs.de/blog/" term="Uncategorized"/>
    <category scheme="http://joyridelabs.de/blog/" term="design"/>
    <category scheme="http://joyridelabs.de/blog/" term="development"/>
    <category scheme="http://joyridelabs.de/blog/" term="mainstream"/>
    <category scheme="http://joyridelabs.de/blog/" term="nikki and the robots"/>
    <category scheme="http://joyridelabs.de/blog/" term="open source"/>
    <category scheme="http://joyridelabs.de/blog/" term="planet-haskell"/>
    <author>
      <name>Iwan</name>
    </author>
    <source>
      <id>http://joyridelabs.de/blog/?feed=atom</id>
      <link href="http://joyridelabs.de/blog/" rel="alternate" type="text/html"/>
      <link href="http://joyridelabs.de/blog/?feed=atom&amp;tag=planet-haskell" rel="self" type="application/atom+xml"/>
      <subtitle xml:lang="en">News from our Headquarters</subtitle>
      <title xml:lang="en">Joyride Laboratories » planet-haskell</title>
      <updated>2012-02-02T13:07:19Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://tumblr.justtesting.org/post/16916036670</id>
    <link href="http://tumblr.justtesting.org/post/16916036670" rel="alternate" type="text/html"/>
    <title>The n-body problem and vectorisation of nested data parallelism in the face of shared data structures</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p/><div class="posterous_autopost">Last year, we spent a lot of energy on reducing the memory consumption of vectorised <a href="http://www.haskell.org/haskellwiki/GHC/Data_Parallel_Haskell">Data Parallel Haskell (DPH)</a> programs that use large shared data structures. This work was driven by an implementation of the <a href="http://en.wikipedia.org/wiki/Barnes%E2%80%93Hut_simulation">Barnes-Hut algorithm</a> in DPH. Ben produced an illustrative video animating an n-body simulation with his <a href="http://hackage.haskell.org/package/gloss">Gloss library</a>. The video is part of his blog article <a href="http://disciple-devel.blogspot.com.au/2012/02/vectorisation-without-replication-in.html">Vectorisation without Replication in Data Parallel Haskell</a>, where he explains the performance of our new DPH array library in comparison to our old library and a purely sequential implementation of Barnes-Hut based on <a href="http://hackage.haskell.org/package/vector">Data.Vector</a>.<div>If you are interested in how vectorisation works, what the problem with shared data structures is, and how we are solving that problem, you may like to have a look at the slides of a talk that I gave in Copenhagen end of last year. It is available in two formats: <a href="http://public.iwork.com/document/?d=replicate-hiperfit-dec11.key&amp;a=p179149432">HTML5 slideshow</a> &amp; <a href="http://www.cse.unsw.edu.au/~chak/papers/replicate-hiperfit-dec11.pdf">PDF</a>.</div>      <p style="font-size: 10px;">  <a href="http://posterous.com">Posted via email</a>   from <a href="http://pls.posterous.com/the-n-body-problem-and-vectorisation-of-neste">PLS @ UNSW</a> | <a href="http://pls.posterous.com/the-n-body-problem-and-vectorisation-of-neste#comment"><span style="font-size: 11px;">Comment »</span></a>  </p>  </div><p/></div>
    </summary>
    <updated>2012-02-02T11:16:35Z</updated>
    <category term="dph"/>
    <category term="haskell"/>
    <category term="parallelism"/>
    <source>
      <id>http://tumblr.justtesting.org/</id>
      <author>
        <name>Manuel M T Chakravarty</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://tumblr.justtesting.org/" rel="alternate" type="text/html"/>
      <link href="http://justtesting.tumblr.com/rss" rel="self" type="application/rss+xml"/>
      <subtitle>Random ramblings by me.</subtitle>
      <title>Just Testing</title>
      <updated>2012-02-10T03:22:20Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://pls.posterous.com/the-n-body-problem-and-vectorisation-of-neste</id>
    <link href="http://pls.posterous.com/the-n-body-problem-and-vectorisation-of-neste" rel="alternate" type="text/html"/>
    <title>The n-body problem and vectorisation of nested data parallelism in the face of shared data structures</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>
	Last year, we spent a lot of energy on reducing the memory consumption of vectorised <a href="http://www.haskell.org/haskellwiki/GHC/Data_Parallel_Haskell">Data Parallel Haskell (DPH)</a> programs that use large shared data structures. This work was driven by an implementation of the <a href="http://en.wikipedia.org/wiki/Barnes%E2%80%93Hut_simulation">Barnes-Hut algorithm</a> in DPH. Ben produced an illustrative video animating an n-body simulation with his <a href="http://hackage.haskell.org/package/gloss">Gloss library</a>. The video is part of his blog article <a href="http://disciple-devel.blogspot.com.au/2012/02/vectorisation-without-replication-in.html">Vectorisation without Replication in Data Parallel Haskell</a>, where he explains the performance of our new DPH array library in comparison to our old library and a purely sequential implementation of Barnes-Hut based on <a href="http://hackage.haskell.org/package/vector">Data.Vector</a>.</p><p/><div>If you are interested in how vectorisation works, what the problem with shared data structures is, and how we are solving that problem, you may like to have a look at the slides of a talk that I gave in Copenhagen end of last year. It is available in two formats: <a href="http://public.iwork.com/document/?d=replicate-hiperfit-dec11.key&amp;a=p179149432">HTML5 slideshow</a> &amp; <a href="http://www.cse.unsw.edu.au/~chak/papers/replicate-hiperfit-dec11.pdf">PDF</a>.</div>
	
<p/>

<p><a href="http://pls.posterous.com/the-n-body-problem-and-vectorisation-of-neste">Permalink</a> 

	| <a href="http://pls.posterous.com/the-n-body-problem-and-vectorisation-of-neste#comment">Leave a comment  »</a>

</p></div>
    </summary>
    <updated>2012-02-02T11:16:32Z</updated>
    <source>
      <id>http://pls.posterous.com</id>
      <author>
        <name>Programming Languages and Systems research group at the University of New South Wales</name>
      </author>
      <link href="http://pls.posterous.com" rel="alternate" type="text/html"/>
      <link href="http://posterous.com/api/sup_update#0a5010239" rel="http://api.friendfeed.com/2008/03#sup" type="application/json"/>
      <link href="http://pls.posterous.com/rss.xml" rel="self" type="application/atom+xml"/>
      <link href="http://posterous.superfeedr.com" rel="hub" type="text/html"/>
      <subtitle>Programming Language Research Down Under</subtitle>
      <title>PLS @ UNSW</title>
      <updated>2012-02-02T11:24:38Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-301893373063372699.post-1305137130684749361</id>
    <link href="http://disciple-devel.blogspot.com/feeds/1305137130684749361/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://disciple-devel.blogspot.com/2012/02/vectorisation-without-replication-in.html#comment-form" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/301893373063372699/posts/default/1305137130684749361" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/301893373063372699/posts/default/1305137130684749361" rel="self" type="application/atom+xml"/>
    <link href="http://disciple-devel.blogspot.com/2012/02/vectorisation-without-replication-in.html" rel="alternate" type="text/html"/>
    <title>Vectorisation without Replication in Data Parallel Haskell</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">Here is a <a href="http://en.wikipedia.org/wiki/Barnes-Hut">Barnes-Hut</a> gravitation simulation written using <a href="http://hackage.haskell.org/package/vector-0.9.1">Data.Vector</a> and <a href="http://hackage.haskell.org/package/gloss-1.6.0.1">Gloss</a>. <br/><br/><div class="separator" style="clear: both; text-align: center;">&lt;iframe allowfullscreen="allowfullscreen" frameborder="0" height="360" src="http://www.youtube.com/embed/tDgOBM29ny4?rel=0" width="640"&gt;&lt;/iframe&gt;<br/></div><br/>If done naively, such an n-body simulation has a runtime complexity of O(n^2) because we need to consider the interaction of every body with every other body. Barnes-Hut performs an approximation that reduces this to O(n . log n). At each step in the simulation we insert the bodies (grey) into a quad-tree (green), and compute the centroid for each branch (blue). Now, if some other body is sufficiently far away from a centroid, then we use the centroid to approximate the force due to the bodies in the corresponding branch, instead of inspecting each one individually.<br/><br/>Now you've seen the video, the following graph sums up my work on Data Parallel Haskell (DPH) for the past six months:<br/><div class="separator" style="clear: both; text-align: center;"><a href="http://code.ouroborus.net/dph/blog/2012/02/nbody-graph.png" style=""><img border="0" height="451" src="http://code.ouroborus.net/dph/blog/2012/02/nbody-graph.png" width="600"/></a></div><br/>This is a plot of runtime vs the number of bodies in the Barnes-Hut simulation. The simulation in the video uses just 1000 bodies, but my understanding is that the physicists need millions or billions to do useful physics work. Back to the graph, the red line is the program from the video, which uses Data.Vector to store its arrays and runs sequentially. The brown line is using the DPH library that shipped with GHC 7.2. The blue line is using the DPH library that will ship with GHC 7.4. Note how the asymptotic complexity of the program with New DPH is the same as with Data.Vector. <br/><br/>In Old DPH we were using a naive approach to vectorisation that resulted in the quad-tree being replicated (copied) once for every body in the simulation (bad!). In New DPH we compute the force on each body in parallel while sharing the same quad-tree. There is a story about this, and you can read all about it when we finish the paper.<br/><br/>Of course, asymptotic complexity isn't everything. The DPH program is still running about 10x slower than the Data.Vector program for large input sizes, and I'm sure that production C programs would run at least 5x faster than that. There's much low hanging fruit here. DPH misses many standard optimisation opportunities, which results in numerical values being unboxed and reboxed in our inner loops. There are also algorithmic improvements to the library that are just waiting for me to implement them. If I can make the blue line cross the red line in the next six months, then I'm buying everyone a beer.<div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/301893373063372699-1305137130684749361?l=disciple-devel.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2012-02-02T06:59:54Z</updated>
    <published>2012-02-02T06:50:00Z</published>
    <author>
      <name>Ben Lippmeier</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/08287674468193351664</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-301893373063372699</id>
      <author>
        <name>Ben Lippmeier</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/08287674468193351664</uri>
      </author>
      <link href="http://disciple-devel.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/301893373063372699/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://disciple-devel.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">More info at the <a href="http://disciple.ouroborus.net">The Disciplined Disciple Compiler (DDC) Development Wiki</a>.<br/>
Easy tickets to get started with: <a href="http://disciple.ouroborus.net/report/9">on the trac</a>.</div>
      </subtitle>
      <title>Disciple Development</title>
      <updated>2012-02-02T11:32:33Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://existentialtype.wordpress.com/?p=232</id>
    <link href="http://existentialtype.wordpress.com/2011/05/01/of-course-ml-has-monads/" rel="alternate" type="text/html"/>
    <link href="http://existentialtype.wordpress.com/2011/05/01/of-course-ml-has-monads/#comments" rel="replies" type="text/html"/>
    <link href="http://existentialtype.wordpress.com/2011/05/01/of-course-ml-has-monads/feed/atom/" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">Of Course ML Has Monads!</title>
    <summary type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml">A popular meme in the world of PL’s is that “Haskell has monads”, with the implication that this is a distinctive feature of the language, separate from all others.  While it is true that Haskell has popularized the use of monads as a program structuring device, the idea of a monad is not so much [...]<img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=existentialtype.wordpress.com&amp;blog=2157150&amp;post=232&amp;subd=existentialtype&amp;ref=&amp;feed=1" width="1"/></div>
    </summary>
    <content type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml"><p>A popular meme in the world of PL’s is that “Haskell has monads”, with the implication that this is a distinctive feature of the language, separate from all others.  While it is true that Haskell has popularized the use of monads as a program structuring device, the idea of a monad is not so much an issue of <em>language</em> design (apart from the <em>ad hoc</em> syntactic support provided by Haskell), but rather one of <em>library</em> design.  After all, a monad is just one of a zillion signatures (type classes) with which to structure programs, and there is no particular reason why this one cannot be used in any language that supports even a modicum of <a href="http://existentialtype.wordpress.com/2011/04/16/modules-matter-most/" title="Modules Matter&#xA0;Most">modularity</a>.  There <em>is</em> a particular reason why monads <em>had</em> to arise in Haskell, though, which is to defeat the scourge of laziness.  But even in the presence of monads, one still needs things like <em>seq</em> to sequentialize evaluation, because the <a href="http://existentialtype.wordpress.com/2011/04/24/the-real-point-of-laziness/" title="The Point of&#xA0;Laziness">lazy cost model</a> is so disadvantageous.  In an ironic twist the emphasis on monads in Haskell means that programming in Haskell is rather like programming in an <a href="http://www.cs.cmu.edu/~rwh/plbook/book.pdf" target="_blank" title="Practical Foundations for Programming Languages">updated dialect of Algol</a> with a richer type structure than the original, but the same overall structure.</p>
<p>Examined from the point of view of ML, monads are but a particular of use of modules.  The signature of monads is given by the definition</p>
<blockquote>
<pre>signature MONAD = sig
  type 'a monad
  val ret : 'a -&gt; 'a monad
  val bnd : 'a monad -&gt; ('a -&gt; 'b monad) -&gt; 'b monad
end</pre>
</blockquote>
<p>There are many, many, many structures that satisfy this signature; I needn’t (and, in any case, can’t) rehearse them all here.  One particularly simple example should suffice to give the general idea:</p>
<blockquote>
<pre>structure Option : MONAD = struct
  type 'a monad = 'a option
  fun ret x = SOME x
  fun bnd (SOME x) k = k x
    | bnd NONE k = NONE
end</pre>
</blockquote>
<p>This is of course the option monad, which is sometimes used to model the data flow aspects of exceptions, perhaps with some elaboration of the NONE case to associate an exceptional value with a non-result.  (The control flow aspects are not properly modeled this way, however.  For that one needs, in addition, access to some sort of jump mechanism.)</p>
<p>Examples like this one proliferate.  A monad is represented by a structure.  Any structure that provides the facilities specified by the MONAD signature gives rise to the characteristic sequentialization mechanisms codified by it.  Monad transformers are functors that transform one monad into another, with no fuss or bother, and no <em>ad hoc</em> mechanisms required.  Standard modular programming techniques suffice to represent monads; moreover, the techniques involved are fully general, and are equally applicable to other signatures of interest (arrows, or quivers, or bows, or what have you).  Moreover, it is shown in my paper with Chakravarty and Dreyer how to integrate modules into the type inference mechanism of ML so that one can get automatic functor instantiation in those limited cases where it is self-evident what is intended.  This has been implemented by Karl Crary in a prototype compiler for an extension of Standard ML, and it would be good to see this supported in more broadly available compilers for the language.</p>
<p>The bulk of the mania about monads is therefore accounted for by modules.  I have no doubt, however, that you are wondering about the infamous IO monad in Haskell (and it’s associated work-around, unsafePerformIO).  Isn’t that a fundamental feature of the language that cannot be replicated in ML?  Hardly!  It’s entirely a matter of designing the signatures of the standard basis library modules, and nothing more.  The default basis library does not attempt to segregate effects into a monad, but it is perfectly straightforward to do this yourself, by providing your own layer over the standard basis, or to reorganize the standard basis to enforce the separation.  For example, the signature of reference cells might look like this:</p>
<blockquote>
<pre>signature REF = sig
  type 'a ref
  val ref : 'a -&gt; 'a ref IO.monad
  val ! : 'a ref -&gt; 'a IO.monad
  val := : 'a ref -&gt; 'a -&gt; unit IO.monad
end</pre>
</blockquote>
<p>Here we are presuming that we have a fixed declaration</p>
<blockquote>
<pre>structure IO : MONAD = ...</pre>
</blockquote>
<p>that packages up the basic IO primitives that are already implemented in the run-time system of ML, more or less like in Haskell.  The other signatures, such as those for mutable arrays or for performing input and output, would be modified in a similar manner to push effects into the IO monad.  <em>Et voila</em>, you have monadic effects, just like in Haskell.</p>
<p>There’s really nothing to it.  In fact, the whole exercise was carried out by a Carnegie Mellon student, Phillippe Ajoux, a couple of years ago.  He also wrote a number of programs in this style just to see how it all goes: swimmingly.  He also devised syntactic extensions to the Moscow ML compiler that provide a nicer notation for programming with monads, much as in Haskell, but better aligned with ML’s conventions.  (Ideally it should be possible to provide syntactic support for <em>any</em> signature, not just monads, but I’m not aware of a worked-out design for the general case, involving as it would an intermixing of parsing and elaboration.)</p>
<p>My point is that the ML module system can be deployed by you to impose the sorts of effect segregation imposed on you by default in Haskell.  There is nothing special about Haskell that makes this possible, and nothing special about ML that inhibits it.  It’s all a mode of use of modules.</p>
<p>So why don’t we do this by default?  Because it’s not such a great idea.  Yes, I know it sounds wonderful at first, but then you realize that it’s pretty horrible.  Once you’re in the IO monad, you’re stuck there forever, and are reduced to Algol-style imperative programming.  You cannot easily convert between functional and monadic style without a radical restructuring of code.  And you inevitably need unsafePerformIO to get anything serious done.  In practical terms, you are deprived of the useful concept of a <em>benign effect</em>, and that just stinks!</p>
<p>The moral of the story is that of course ML “has monads”, just like Haskell.  Whether you want to use them is up to you; they are just as useful, and just as annoying, in ML as they are in Haskell.  But they are not forced on you by the language designers!</p>
<p><em>Update</em>: This post should’ve been called “ML Has Monads, Why Not?”, or “Of Course ML Has Comonads!”, but then no one was wondering about that.</p>
<p><em>Update</em>: I now think that the last sentence is excessive.  My main point is simply that it’s very simple to go one way or the other with effects, if you have modules to structure things; it’s all a matter of library design.  A variant of ML that enforced the separation of effects is very easily constructed; the question is whether it is useful or not.  I’ve suggested that the monadic separation is beguiling, but not clearly a great idea.  Alternatively, one can say that we’re not that far away from eliminating laziness from Haskell, at least in this respect: just re-do the standard basis library in ML, and you’re a good ways there.  Plus you have modules, and we understand how to integrate type classes with modules, so the gap is rather small.</p>
<br/>Filed under: <a href="http://existentialtype.wordpress.com/category/programming/">Programming</a> Tagged: <a href="http://existentialtype.wordpress.com/tag/functional-programming/">functional programming</a>, <a href="http://existentialtype.wordpress.com/tag/imperative-programming/">imperative programming</a>, <a href="http://existentialtype.wordpress.com/tag/modularity/">modularity</a> <a href="http://feeds.wordpress.com/1.0/gocomments/existentialtype.wordpress.com/232/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/existentialtype.wordpress.com/232/"/></a> <a href="http://feeds.wordpress.com/1.0/godelicious/existentialtype.wordpress.com/232/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/existentialtype.wordpress.com/232/"/></a> <a href="http://feeds.wordpress.com/1.0/gofacebook/existentialtype.wordpress.com/232/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/existentialtype.wordpress.com/232/"/></a> <a href="http://feeds.wordpress.com/1.0/gotwitter/existentialtype.wordpress.com/232/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/existentialtype.wordpress.com/232/"/></a> <a href="http://feeds.wordpress.com/1.0/gostumble/existentialtype.wordpress.com/232/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/existentialtype.wordpress.com/232/"/></a> <a href="http://feeds.wordpress.com/1.0/godigg/existentialtype.wordpress.com/232/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/existentialtype.wordpress.com/232/"/></a> <a href="http://feeds.wordpress.com/1.0/goreddit/existentialtype.wordpress.com/232/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/existentialtype.wordpress.com/232/"/></a> <img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=existentialtype.wordpress.com&amp;blog=2157150&amp;post=232&amp;subd=existentialtype&amp;ref=&amp;feed=1" width="1"/></div>
    </content>
    <updated>2012-02-02T02:11:19Z</updated>
    <published>2011-05-01T20:09:43Z</published>
    <category scheme="http://existentialtype.wordpress.com" term="Programming"/>
    <category scheme="http://existentialtype.wordpress.com" term="functional programming"/>
    <category scheme="http://existentialtype.wordpress.com" term="imperative programming"/>
    <category scheme="http://existentialtype.wordpress.com" term="modularity"/>
    <author>
      <name>Robert Harper</name>
      <uri>http://www.cs.cmu.edu/~rwh</uri>
    </author>
    <source>
      <id>http://existentialtype.wordpress.com/feed/atom/</id>
      <link href="http://existentialtype.wordpress.com" rel="alternate" type="text/html"/>
      <link href="http://existentialtype.wordpress.com/feed/atom/" rel="self" type="application/atom+xml"/>
      <link href="http://existentialtype.wordpress.com/osd.xml" rel="search" type="application/opensearchdescription+xml"/>
      <link href="http://wordpress.com/opensearch.xml" rel="search" type="application/opensearchdescription+xml"/>
      <link href="http://existentialtype.wordpress.com/?pushpress=hub" rel="hub" type="text/html"/>
      <subtitle xml:lang="en">Abstract types are existential types.</subtitle>
      <title xml:lang="en">Existential Type</title>
      <updated>2012-02-08T22:41:26Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-37404288.post-4822200957523277932</id>
    <link href="http://jpmoresmau.blogspot.com/feeds/4822200957523277932/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://www.blogger.com/comment.g?blogID=37404288&amp;postID=4822200957523277932" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/37404288/posts/default/4822200957523277932" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/37404288/posts/default/4822200957523277932" rel="self" type="application/atom+xml"/>
    <link href="http://jpmoresmau.blogspot.com/2012/02/eclipsefp-222-released.html" rel="alternate" type="text/html"/>
    <title>EclipseFP 2.2.2 released!</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">A quick message to say a new version of <a href="http://eclipsefp.github.com/">EclipseFP </a>has been released. It's a bit of a rushed released, because a series of cascading updates meant that scion-browser and EclipseFP got out of sync. A while back I had made changes to the scion-browser API to improve performance, and then persistent got upgraded and a new compatible version of scion-browser got released on sunday. Unfortunately my API changes got released too, which meant a lot of headaches for the poor users that upgraded. So I've released <a href="https://sourceforge.net/projects/eclipsefp/files/EclipseFP%202%20branch/2.2.2/?">2.2.2</a> which is compatible with <a href="http://hackage.haskell.org/package/scion-browser">scion-browser 0.2.5</a>.<br/>It does bring a few enhancements, though:<br/>- outline, tooltips and jump to definition should be much faster<br/>- HLint suggestions can be applied via the quick fix action on the suggestion marker<br/>- clean project does what it advertises: deletes the whole .dist-buildwrapper directory<br/><br/>As usual, just use the update site from inside Eclipse to upgrade. Please report all bugs on the Source forge <a href="https://sourceforge.net/projects/eclipsefp/forums/forum/371922">forum </a>or <a href="https://sourceforge.net/tracker/?group_id=108233&amp;atid=1000719">tracker</a>.<br/><br/>Happy Haskell hacking!!<div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/37404288-4822200957523277932?l=jpmoresmau.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2012-02-01T20:36:05Z</updated>
    <published>2012-02-01T20:36:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="IDE"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="self-publicity"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="Haskell"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="EclipseFP"/>
    <author>
      <name>JP Moresmau</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/09964251063221757176</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-37404288</id>
      <category term="Python"/>
      <category term="Neural Network"/>
      <category term="Scion"/>
      <category term="development"/>
      <category term="Parsec"/>
      <category term="Hibernate"/>
      <category term="Software design"/>
      <category term="annotations"/>
      <category term="Dynamic languages"/>
      <category term="parsing"/>
      <category term="functions"/>
      <category term="Windows"/>
      <category term="IDE"/>
      <category term="RIA"/>
      <category term="HughesPJ"/>
      <category term="GUI"/>
      <category term="Artificial Intelligence"/>
      <category term="Scala"/>
      <category term="Design By Contract"/>
      <category term="Rhino"/>
      <category term="Hoogle"/>
      <category term="Genetic Programming"/>
      <category term="Flex"/>
      <category term="performance"/>
      <category term="GHC"/>
      <category term="JSON"/>
      <category term="closures"/>
      <category term="buildwrapper"/>
      <category term="scripting"/>
      <category term="Aspects"/>
      <category term="mazes"/>
      <category term="self-indulgence"/>
      <category term="robotics"/>
      <category term="maths"/>
      <category term="Monads"/>
      <category term="games"/>
      <category term="game"/>
      <category term="Java"/>
      <category term="EclipseFP"/>
      <category term="Compilation"/>
      <category term="properties"/>
      <category term="JavaFX"/>
      <category term="Haskell"/>
      <category term="Cabal"/>
      <category term="HGL"/>
      <category term="Functional Programming"/>
      <category term="self-publicity"/>
      <category term="generics"/>
      <category term="Linux"/>
      <category term="Eclipse"/>
      <category term="testing"/>
      <category term="Object Oriented Programming"/>
      <category term="JavaScript"/>
      <category term="Concurrent Programming"/>
      <category term="SWT"/>
      <author>
        <name>JP Moresmau</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/09964251063221757176</uri>
      </author>
      <link href="http://jpmoresmau.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/37404288/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://jpmoresmau.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <link href="http://www.blogger.com/feeds/37404288/posts/default?start-index=26&amp;max-results=25" rel="next" type="application/atom+xml"/>
      <subtitle>In this blog I talk about some of the personal work I do  in programming. I mainly do Java and JavaScript, but I'm learning functional programming in Haskell too...</subtitle>
      <title>JP Moresmau's Programming Blog</title>
      <updated>2012-02-04T14:44:28Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-3300386911011555799.post-2031597399626122650</id>
    <link href="http://happstack.blogspot.com/feeds/2031597399626122650/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://happstack.blogspot.com/2012/02/new-tutorial-on-acid-state-ixset-and.html#comment-form" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/3300386911011555799/posts/default/2031597399626122650" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/3300386911011555799/posts/default/2031597399626122650" rel="self" type="application/atom+xml"/>
    <link href="http://happstack.blogspot.com/2012/02/new-tutorial-on-acid-state-ixset-and.html" rel="alternate" type="text/html"/>
    <title>new tutorial on acid-state, ixset, and lenses</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">Hello,<br/><br/>I just uploaded a new tutorial which covers three distinct, but related topics:<br/><br/><ul><li>acid-state - a native Haskell, noSQL, RAM-cloud database</li><li>IxSet  - a multi-indexed collection type (similar to Data.Map but with support for  multiple keys)</li><li>data-lens - a library which provides syntax that makes it easier to update nested records and other data types</li></ul><br/>The tutorial is available here:<br/><br/><a href="http://happstack.com/docs/crashcourse/AcidState.html">http://happstack.com/docs/crashcourse/AcidState.html</a><br/><br/>The section on lenses is a great applied introduction to the concept which requires no understanding of Happstack, acid-state, or IxSet. So, even if you don't care about acid-state, you may find it useful if you have ever wondered what the heck lenses are.<div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/3300386911011555799-2031597399626122650?l=happstack.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2012-02-01T19:16:02Z</updated>
    <published>2012-02-01T19:16:00Z</published>
    <author>
      <name>Jeremy Shaw</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/18373967098081701148</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-3300386911011555799</id>
      <category term="hsx"/>
      <category term="type-safe"/>
      <category term="jmacro"/>
      <category term="persistence"/>
      <category term="happstack-lite"/>
      <category term="templating"/>
      <category term="routing"/>
      <category term="ANN"/>
      <category term="safecopy"/>
      <category term="web-routes"/>
      <category term="happstack"/>
      <category term="MACID"/>
      <category term="acid-state"/>
      <category term="database"/>
      <author>
        <name>Jeremy Shaw</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/18373967098081701148</uri>
      </author>
      <link href="http://happstack.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/3300386911011555799/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://happstack.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle>Happstack - A Haskell Web Framework</subtitle>
      <title>Happstack</title>
      <updated>2012-02-01T19:16:02Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://tumblr.justtesting.org/post/16853265221</id>
    <link href="http://tumblr.justtesting.org/post/16853265221" rel="alternate" type="text/html"/>
    <title>Released Data.Array.Accelerate 0.9.0.0 — the Haskell array library for GPUs</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><div class="posterous_autopost">I just released <a href="http://hackage.haskell.org/package/accelerate-0.9.0.0">accelerate 0.9.0.0</a> on Hackage. This is the version that has been available from the <a href="https://github.com/mchakravarty/accelerate">GitHub repository</a> for a while (supporting shape polymorphism, stencil computations, block I/O, and much more), but adapted such that it works with the forthcoming GHC 7.4.1 release. (I tested it with 7.4.1 RC2).<div>It doesn’t yet include Trevor’s recent work that improved the CUDA backend in many significant ways — you can get that code from <a href="https://github.com/tmcdonell/accelerate">Trevor’s fork on GitHub</a>.</div><p/><div>For more details, see the <a href="https://github.com/mchakravarty/accelerate">main GitHub repository</a> and the <a href="https://github.com/mchakravarty/accelerate/wiki">GitHub wiki pages</a>.</div>      <p style="font-size: 10px;">  <a href="http://posterous.com">Posted via email</a>   from <a href="http://justtesting.org/released-dataarrayaccelerate-0900-the-haskell">Just Testing</a> | <a href="http://justtesting.org/released-dataarrayaccelerate-0900-the-haskell#comment"><span style="font-size: 11px;">Comment »</span></a>  </p>  </div></div>
    </summary>
    <updated>2012-02-01T05:55:23Z</updated>
    <category term="accelerate"/>
    <category term="edsl"/>
    <category term="gpgpu"/>
    <category term="parallelism"/>
    <source>
      <id>http://tumblr.justtesting.org/</id>
      <author>
        <name>Manuel M T Chakravarty</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://tumblr.justtesting.org/" rel="alternate" type="text/html"/>
      <link href="http://justtesting.tumblr.com/rss" rel="self" type="application/rss+xml"/>
      <subtitle>Random ramblings by me.</subtitle>
      <title>Just Testing</title>
      <updated>2012-02-10T03:22:20Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://brandon.si/code/haskell-state-of-the-lens</id>
    <link href="http://brandon.si/code/haskell-state-of-the-lens/" rel="alternate" type="text/html"/>
    <title>Haskell state of the Lens, etc.</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><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 "lens-like" 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'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 "lenses" 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... 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's packages. there's allegedly a lens hiding here among the zygohistomorphic prepromorphisms (you think I'm joking)</li>
</ul>


<p>For an analysis of various approaches to lenses which don'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'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'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>
<tbody><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>
</tbody></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'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'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'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 "setter" 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 'partial-lens' 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 'fclabels' 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></div>
    </content>
    <updated>2012-02-01T02:40:00Z</updated>
    <source>
      <id>http://brandon.si/</id>
      <author>
        <name>Brandon Simmons</name>
        <email>brandon.m.simmons@gmail.com</email>
      </author>
      <link href="http://brandon.si/./code/atom.xml" rel="self" type="application/atom+xml"/>
      <link href="http://brandon.si/" rel="alternate" type="text/html"/>
      <title>Posts on code | Brandon.Si(mmons)</title>
      <updated>2012-02-07T04:05:24Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-6757805.post-2702451503266578862</id>
    <link href="http://kenta.blogspot.com/feeds/2702451503266578862/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://www.blogger.com/comment.g?blogID=6757805&amp;postID=2702451503266578862&amp;isPopup=true" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/6757805/posts/default/2702451503266578862" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/6757805/posts/default/2702451503266578862" rel="self" type="application/atom+xml"/>
    <link href="http://kenta.blogspot.com/2012/01/mdrgxafe-bubblebabble-sator-square.html" rel="alternate" type="text/html"/>
    <title>[mdrgxafe] Bubblebabble Sator Square</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Consider a modification of the <a href="http://kenta.blogspot.com/2011/03/jrtrjwzi-errors-in-bubble-babble.html">Bubble Babble digest algorithm</a> to emit words of 25 letters at a time (13 consonants, 12 vowels) instead of 5 at a time.  Then, arrange the letters into 5 by 5 blocks:</p>

<p/><table>
<tbody><tr align="center"><td>T</td><td>u</td><td>C</td><td>a</td><td>L</td></tr>
<tr align="center"><td>o</td><td>T</td><td>i</td><td>B</td><td>e</td></tr>
<tr align="center"><td>K</td><td>o</td><td>T</td><td>i</td><td>F</td></tr>
<tr align="center"><td>o</td><td>G</td><td>i</td><td>M</td><td>u</td></tr>
<tr align="center"><td>F</td><td>u</td><td>G</td><td>i</td><td>H</td></tr>
</tbody></table><p/>

<p>This way, the 5-letter subwords can be read and verified both across and down as a doublecheck.</p>

<p>Inspired by the sator square in Latin, but omitting the capability of reading the same across and down (or being real words).  We keep the checkerboard pattern of consonants and vowels.</p>

<p>With 16 consonants and 5 vowels to choose from, (omitting x and y from original Bubble Babble), one can fit up to log<sub>2</sub>(16<sup>13</sup> * 5<sup>12</sup>) = 79 bits per block.</p>

<p>While the original Bubble Babble tried to do error detection, let's separate concerns and assuming error detection or correction is done at a different level.  Similarly, let padding be done elsewhere, too.  We assume the message is a multiple of 79 bits.</p>

<p>Let n be a 79 bit integer.  Let c = n mod (16^13), i.e lower 52 bits, and v = n div (16^13), i.e., upper 27 bits.  Write c in base 16 using the alphabet ( b c d f g h k l m n p r s t v z ), and write v in base 5 using the alphabet ( a e i o u ), then interleave into a square.</p>

<p>One may consider consonant clusters, consonants from other languages (clicks, aspiration), diphthong vowels, vowel tones, but things get messy, especially with consonant clusters.  Some consonants can only be in certain places of a word.     <a href="http://www.mit.edu/~kenta/three/sator/mdrgxafe">Here is one attempt, implemented in Haskell.</a> This is well on our way to a random word generator, though it often creates nearly unpronounceable words, probably due to the excessive consonant clusters.</p>

<p>Vowels: a e i o u ai ei oi au á à é è í ì ó ò ú ù ái ài éi èi ói òi áu àu</p>

<p>Consonants: K! T! P! R Y H W ñ Kn Gn Br Dr Fr Gr Kr Pr Tr Vr Bl Fl Kl Pl Sl Vl Ð nD nG nK nT nZ mP rJ rS rZ rČ rŠ rθ nS mB nL rB rD rF rG rK rM rN rP rT rЦ rV rχ J S Z Č Š θ B D F G K L M N P T Ц V χ sT sK sP Ξ Ψ</p>

<p>Number of choices by grid position:<br/></p><table>
<tbody><tr align="center"><td>46</td><td>27</td><td>45</td><td>27</td><td>24</td></tr>
<tr align="center"><td>27</td><td>72</td><td>27</td><td>72</td><td>27</td></tr>
<tr align="center"><td>45</td><td>27</td><td>72</td><td>27</td><td>36</td></tr>
<tr align="center"><td>27</td><td>72</td><td>27</td><td>72</td><td>27</td></tr>
<tr align="center"><td>24</td><td>27</td><td>36</td><td>27</td><td>39</td></tr>
</tbody></table>
<p/>
<p>This allows 128 bits (129.21072040507875) to be encoded in a single block.  Sample:</p>

<p/><table>
<tbody><tr align="center"><td>R</td><td>è</td><td>M</td><td>u</td><td>Š</td></tr>
<tr align="center"><td>u</td><td>Ψ</td><td>àu</td><td>Ð</td><td>é</td></tr>
<tr align="center"><td>ñ</td><td>ái</td><td>Ц</td><td>ái</td><td>Ξ</td></tr>
<tr align="center"><td>ò</td><td>θ</td><td>oi</td><td>nG</td><td>ì</td></tr>
<tr align="center"><td>χ</td><td>ò</td><td>rČ</td><td>òi</td><td>P!</td></tr>
</tbody></table>
<p/><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/6757805-2702451503266578862?l=kenta.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2012-01-31T03:53:36Z</updated>
    <published>2012-01-30T06:04:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="haskell"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="crypto"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="cs"/>
    <author>
      <name>Ken</name>
      <email>noreply@blogger.com</email>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-6757805</id>
      <category term="teach"/>
      <category term="ui"/>
      <category term="plot"/>
      <category term="scrypt"/>
      <category term="answer"/>
      <category term="crypto"/>
      <category term="haskell"/>
      <category term="cs"/>
      <category term="time"/>
      <author>
        <name>Ken</name>
        <email>noreply@blogger.com</email>
      </author>
      <link href="http://kenta.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/6757805/posts/default/-/haskell" rel="self" type="application/atom+xml"/>
      <link href="http://kenta.blogspot.com/search/label/haskell" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <link href="http://www.blogger.com/feeds/6757805/posts/default/-/haskell/-/haskell?start-index=26&amp;max-results=25" rel="next" type="application/atom+xml"/>
      <subtitle>mostly on computers and mathematics</subtitle>
      <title>Ken's blog</title>
      <updated>2012-02-08T03:07:47Z</updated>
    </source>
  </entry>

  <entry xml:lang="en-US">
    <id>urn:uuid:ea859c3d-137d-4b52-8e79-1186419d4fd2</id>
    <link href="http://feedproxy.google.com/~r/TomMoertelsBlog/~3/s-KDB6seaDg/a-flyweight-mocking-helper-for-python" rel="alternate" type="text/html"/>
    <title xml:lang="en-US">A flyweight mocking helper for Python</title>
    <summary type="xhtml" xml:lang="en-US"><div xmlns="http://www.w3.org/1999/xhtml"><p>Recently, I needed a lightweight mocking solution when adding unit tests to some existing Python code.  I could have used one of the many Python mocking libraries, but I only had to replace
a few module functions during testing, so I just wrote a tiny
mocking helper rather than add a dependency to the project.</p>


	<p>The helper is simple and surprisingly versatile:</p>


<pre><code>import contextlib
import functools

@contextlib.contextmanager
def mocked(func,
           expecting=None, returning=None, raising=None,  # specs
           replacement_logic=None, called=1):
    """Stub out and mock a function for a yield's duration.""" 

    if (returning, raising, replacement_logic).count(None) &lt; 2:
        raise ValueError("returning, raising, and replacement_logic " 
                         "are incompatible with each other")

    # default logic for implementing mock fn: return or raise per specs
    def default_logic(*_args, **_kwds):
        if raising:
            raise raising
        return returning

    # prepare wrapper to replace mocked function for duration of yield
    invocations = [0]
    @functools.wraps(func)
    def replacement(*args, **kwds):
        if expecting is not None:
            assert expecting == (args, kwds)  # did we get expected args?
        invocations[0] += 1
        return (replacement_logic or default_logic)(*args, **kwds)

    # replace mocked function, yield to test, and then check &amp; clean up
    module = sys.modules.get(func.__module__)
    setattr(module, func.__name__, replacement)
    try:
        yield  # give control back to test for a while
        assert invocations[0] == called  # was mock called enough?
    finally:
        setattr(module, func.__name__, func)

def uncalled(func):
    """Require that a function not be called for a yield's duration.""" 
    return mocked(func, called=0)
</code></pre>

	<p>The idea is to wrap test code that requires mocked
external functions with a mocking helper.  Here’s an example:</p>


<pre><code>def test_ml_errors_must_be_reported(self):
    """When an error occurs, it must be reported; nothing must be sent.""" 
    data = self._request_data()
    exception = mls.MlError()
    exception.exc = '[[[error description]]]'
    with mocked(mls.subscriber_count, raising=exception):
        with uncalled(sms.send):
            resp = self.app.request("/mailings", method='POST', data=data)
    self.assertEqual(resp.status, '200 OK')
    self.assertIn(exception.exc, resp.data)  # must be reported
</code></pre>

	<p>In this test method, I’m making a simulated <span class="caps">POST</span> request to a web
service that’s supposed to check how many users are in a mailing
list and then, possibly, send some <span class="caps">SMS</span> messages.  In this case,
however, I want to simulate that an error occurs when talking to the
mailing-list service.  The test must verify that the error is reported
and, crucially, that no messages are sent.</p>


<p>The library modules for talking to the mailing-list service and the
<span class="caps">SMS</span> service are called <code>mls</code> and <code>sms</code>.  So,
for the duration of the simulated request, I’m replacing two functions
in these modules with mock versions.
The mock version of <code>mls.subscriber_count</code>, when called,
will raise the exception I’m trying to simulate.  The mock version of
<code>sms.send</code>, however, must <em>not</em> be called; if it is, the
<code>uncalled</code> mocking helper will alert me by raising an
exception.</p>

<p>So the mocking helpers not only temporarily install mock
implementations of functions but also assert that those mock
implementations are (or are not) called as expected.  In the following
code, for example, I use this capability to make sure that the
mailing-list service is asked to get the subscriber count for the
mailing list having the right key.  I also simulate the service
returning a subscriber count of 123.</p>

<pre><code>def test_unconfirmed_msgs_must_be_confirmed(self):
    """An unconfirmed msg must be confirmed and not sent.""" 
    mlkey = 'TEST_ML_KEY'
    body = 'Test message!'
    data = self._request_data(mlkey=mlkey, body=body)
    with mocked(mls.subscriber_count, expecting=((mlkey,),{}), returning=123):
        with uncalled(sms.send):
            resp = self.app.request("/mailings", method='POST', data=data)
    self.assertEqual(resp.status, '200 OK')
    self.assertIn('Reply CONFIRM', resp.data)    # we must ask for confirmation
    self.assertIn('123 subscribers', resp.data)  # and supply subscriber count
    self.assertIn(body, resp.data)               # and the msg to be sent
</code></pre>

	<p>The <code>mocked</code> helper lets you do a few more things, too, but
you get the idea:  Sometimes a short helper function can take you a
long way.</p></div>
    </summary>
    <content type="xhtml" xml:lang="en-US"><div xmlns="http://www.w3.org/1999/xhtml"><p>Recently, I needed a lightweight mocking solution when adding unit tests to some existing Python code.  I could have used one of the many Python mocking libraries, but I only had to replace
a few module functions during testing, so I just wrote a tiny
mocking helper rather than add a dependency to the project.</p>


	<p>The helper is simple and surprisingly versatile:</p>


<pre><code>import contextlib
import functools

@contextlib.contextmanager
def mocked(func,
           expecting=None, returning=None, raising=None,  # specs
           replacement_logic=None, called=1):
    """Stub out and mock a function for a yield's duration.""" 

    if (returning, raising, replacement_logic).count(None) &lt; 2:
        raise ValueError("returning, raising, and replacement_logic " 
                         "are incompatible with each other")

    # default logic for implementing mock fn: return or raise per specs
    def default_logic(*_args, **_kwds):
        if raising:
            raise raising
        return returning

    # prepare wrapper to replace mocked function for duration of yield
    invocations = [0]
    @functools.wraps(func)
    def replacement(*args, **kwds):
        if expecting is not None:
            assert expecting == (args, kwds)  # did we get expected args?
        invocations[0] += 1
        return (replacement_logic or default_logic)(*args, **kwds)

    # replace mocked function, yield to test, and then check &amp; clean up
    module = sys.modules.get(func.__module__)
    setattr(module, func.__name__, replacement)
    try:
        yield  # give control back to test for a while
        assert invocations[0] == called  # was mock called enough?
    finally:
        setattr(module, func.__name__, func)

def uncalled(func):
    """Require that a function not be called for a yield's duration.""" 
    return mocked(func, called=0)
</code></pre>

	<p>The idea is to wrap test code that requires mocked
external functions with a mocking helper.  Here’s an example:</p>


<pre><code>def test_ml_errors_must_be_reported(self):
    """When an error occurs, it must be reported; nothing must be sent.""" 
    data = self._request_data()
    exception = mls.MlError()
    exception.exc = '[[[error description]]]'
    with mocked(mls.subscriber_count, raising=exception):
        with uncalled(sms.send):
            resp = self.app.request("/mailings", method='POST', data=data)
    self.assertEqual(resp.status, '200 OK')
    self.assertIn(exception.exc, resp.data)  # must be reported
</code></pre>

	<p>In this test method, I’m making a simulated <span class="caps">POST</span> request to a web
service that’s supposed to check how many users are in a mailing
list and then, possibly, send some <span class="caps">SMS</span> messages.  In this case,
however, I want to simulate that an error occurs when talking to the
mailing-list service.  The test must verify that the error is reported
and, crucially, that no messages are sent.</p>


<p>The library modules for talking to the mailing-list service and the
<span class="caps">SMS</span> service are called <code>mls</code> and <code>sms</code>.  So,
for the duration of the simulated request, I’m replacing two functions
in these modules with mock versions.
The mock version of <code>mls.subscriber_count</code>, when called,
will raise the exception I’m trying to simulate.  The mock version of
<code>sms.send</code>, however, must <em>not</em> be called; if it is, the
<code>uncalled</code> mocking helper will alert me by raising an
exception.</p>

<p>So the mocking helpers not only temporarily install mock
implementations of functions but also assert that those mock
implementations are (or are not) called as expected.  In the following
code, for example, I use this capability to make sure that the
mailing-list service is asked to get the subscriber count for the
mailing list having the right key.  I also simulate the service
returning a subscriber count of 123.</p>

<pre><code>def test_unconfirmed_msgs_must_be_confirmed(self):
    """An unconfirmed msg must be confirmed and not sent.""" 
    mlkey = 'TEST_ML_KEY'
    body = 'Test message!'
    data = self._request_data(mlkey=mlkey, body=body)
    with mocked(mls.subscriber_count, expecting=((mlkey,),{}), returning=123):
        with uncalled(sms.send):
            resp = self.app.request("/mailings", method='POST', data=data)
    self.assertEqual(resp.status, '200 OK')
    self.assertIn('Reply CONFIRM', resp.data)    # we must ask for confirmation
    self.assertIn('123 subscribers', resp.data)  # and supply subscriber count
    self.assertIn(body, resp.data)               # and the msg to be sent
</code></pre>

	<p>The <code>mocked</code> helper lets you do a few more things, too, but
you get the idea:  Sometimes a short helper function can take you a
long way.</p><img height="1" src="http://feeds.feedburner.com/~r/TomMoertelsBlog/~4/s-KDB6seaDg" width="1"/></div>
    </content>
    <updated>2012-01-30T06:07:10Z</updated>
    <published>2011-11-07T05:05:00Z</published>
    <category scheme="http://blog.moertel.com/articles/tag/testing" term="testing"/>
    <category scheme="http://blog.moertel.com/articles/tag/python" term="python"/>
    <category scheme="http://blog.moertel.com/articles/tag/mocks" term="mocks"/><feedburner:origLink xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://blog.moertel.com/articles/2011/11/07/a-flyweight-mocking-helper-for-python</feedburner:origLink>
    <author>
      <name>Tom Moertel</name>
    </author>
    <source>
      <id>tag:blog.moertel.com,2005:Typo</id>
      <link href="http://blog.moertel.com/" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/TomMoertelsBlog" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle xml:lang="en-US">Quality rants on programming theory and stuff geeks like</subtitle>
      <title xml:lang="en-US">Tom Moertel's Blog</title>
      <updated>2012-01-30T05:53:56Z</updated>
    </source>
  </entry>

  <entry xml:lang="en-US">
    <id>urn:uuid:f9bebb4f-a0a0-4fe0-bd59-7949b92a0050</id>
    <link href="http://feedproxy.google.com/~r/TomMoertelsBlog/~3/aoXhqJ0Xsak/finally-i-have-blogged-100-thousand-words" rel="alternate" type="text/html"/>
    <title xml:lang="en-US">Finally! I have blogged 100 thousand words.</title>
    <summary type="xhtml" xml:lang="en-US"><div xmlns="http://www.w3.org/1999/xhtml"><p>I have finally done it! With <a href="http://blog.moertel.com/articles/2012/01/26/the-inner-beauty-of-tree-traversals">my recent post on tree traversals</a>, I have managed to write 100 thousand words for my blog:</p>


<div class="typocode"><pre><code class="typocode_ruby "><span class="punct">&gt;&gt;</span> <span class="constant">Article</span><span class="punct">.</span><span class="ident">find</span><span class="punct">(</span><span class="symbol">:all</span><span class="punct">).</span><span class="ident">inject</span><span class="punct">(</span><span class="number">0</span><span class="punct">)</span> <span class="punct">{</span> <span class="punct">|</span><span class="ident">sum</span><span class="punct">,</span><span class="ident">a</span><span class="punct">|</span> <span class="ident">sum</span> <span class="punct">+=</span>
<span class="char">?&gt;</span>        <span class="punct">(</span><span class="ident">a</span><span class="punct">.</span><span class="ident">body</span> <span class="punct">+</span> <span class="ident">a</span><span class="punct">.</span><span class="ident">extended</span><span class="punct">.</span><span class="ident">to_s</span><span class="punct">).</span><span class="ident">split</span><span class="punct">(/</span><span class="regex"><span class="escape">\s</span>+</span><span class="punct">/).</span><span class="ident">length</span> <span class="punct">}</span>
<span class="punct">=&gt;</span> <span class="number">100334</span></code></pre></div>

	<p>That sounds impressive until you realize that my first blog post, <a href="http://blog.moertel.com/articles/2003/11/15/fun-with-asterisk">Fun with Asterisk</a>, was about nine years ago. So we’re only talking, on average, about 11 thousand words per year. And that’s not hard, if you stick with it.</p>


	<p>For me, the trick has been sticking with it. I joined a startup at the end of 2007, and my blogging abruptly lost about four fifths of its pace:</p>


	<p><img alt="Tom's spotty writing record for blog.moertel.com" src="http://community.moertel.com/~thor/pix/blog-20120130/words_per_year.png" title="Tom's spotty writing record for blog.moertel.com"/></p>


	<p>So I need to discipline myself to blog more frequently. I hope the next 100 thousand words won’t take so long to write.</p>


	<p>Finally, I’d like to take this opportunity to thank you for reading and commenting. You’re the reason I wrote those words in the first place. You made the first 100 thousand words fun.</p>


	<p>Thank you!</p>


	<p>Your pal,<br/>
Tom Moertel</p></div>
    </summary>
    <content type="xhtml" xml:lang="en-US"><div xmlns="http://www.w3.org/1999/xhtml"><p>I have finally done it! With <a href="http://blog.moertel.com/articles/2012/01/26/the-inner-beauty-of-tree-traversals">my recent post on tree traversals</a>, I have managed to write 100 thousand words for my blog:</p>


<div class="typocode"><pre><code class="typocode_ruby "><span class="punct">&gt;&gt;</span> <span class="constant">Article</span><span class="punct">.</span><span class="ident">find</span><span class="punct">(</span><span class="symbol">:all</span><span class="punct">).</span><span class="ident">inject</span><span class="punct">(</span><span class="number">0</span><span class="punct">)</span> <span class="punct">{</span> <span class="punct">|</span><span class="ident">sum</span><span class="punct">,</span><span class="ident">a</span><span class="punct">|</span> <span class="ident">sum</span> <span class="punct">+=</span>
<span class="char">?&gt;</span>        <span class="punct">(</span><span class="ident">a</span><span class="punct">.</span><span class="ident">body</span> <span class="punct">+</span> <span class="ident">a</span><span class="punct">.</span><span class="ident">extended</span><span class="punct">.</span><span class="ident">to_s</span><span class="punct">).</span><span class="ident">split</span><span class="punct">(/</span><span class="regex"><span class="escape">\s</span>+</span><span class="punct">/).</span><span class="ident">length</span> <span class="punct">}</span>
<span class="punct">=&gt;</span> <span class="number">100334</span></code></pre></div>

	<p>That sounds impressive until you realize that my first blog post, <a href="http://blog.moertel.com/articles/2003/11/15/fun-with-asterisk">Fun with Asterisk</a>, was about nine years ago. So we’re only talking, on average, about 11 thousand words per year. And that’s not hard, if you stick with it.</p>


	<p>For me, the trick has been sticking with it. I joined a startup at the end of 2007, and my blogging abruptly lost about four fifths of its pace:</p>


	<p><img alt="Tom's spotty writing record for blog.moertel.com" src="http://community.moertel.com/~thor/pix/blog-20120130/words_per_year.png" title="Tom's spotty writing record for blog.moertel.com"/></p>


	<p>So I need to discipline myself to blog more frequently. I hope the next 100 thousand words won’t take so long to write.</p>


	<p>Finally, I’d like to take this opportunity to thank you for reading and commenting. You’re the reason I wrote those words in the first place. You made the first 100 thousand words fun.</p>


	<p>Thank you!</p>


	<p>Your pal,<br/>
Tom Moertel</p><img height="1" src="http://feeds.feedburner.com/~r/TomMoertelsBlog/~4/aoXhqJ0Xsak" width="1"/></div>
    </content>
    <updated>2012-01-30T05:53:56Z</updated>
    <published>2012-01-30T04:48:00Z</published>
    <category label="site news" scheme="http://blog.moertel.com/articles/category/site-news" term="site-news"/>
    <category scheme="http://blog.moertel.com/articles/tag/writing" term="writing"/>
    <category scheme="http://blog.moertel.com/articles/tag/statistics" term="statistics"/>
    <category scheme="http://blog.moertel.com/articles/tag/blog" term="blog"/>
    <category scheme="http://blog.moertel.com/articles/tag/blogging" term="blogging"/>
    <category scheme="http://blog.moertel.com/articles/tag/100k" term="100k"/><feedburner:origLink xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://blog.moertel.com/articles/2012/01/29/finally-i-have-blogged-100-thousand-words</feedburner:origLink>
    <author>
      <name>Tom Moertel</name>
    </author>
    <source>
      <id>tag:blog.moertel.com,2005:Typo</id>
      <link href="http://blog.moertel.com/" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/TomMoertelsBlog" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle xml:lang="en-US">Quality rants on programming theory and stuff geeks like</subtitle>
      <title xml:lang="en-US">Tom Moertel's Blog</title>
      <updated>2012-01-30T05:53:56Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-1563623855220143059.post-8551602144136131794</id>
    <link href="http://mainisusuallyafunction.blogspot.com/feeds/8551602144136131794/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://mainisusuallyafunction.blogspot.com/2012/01/writing-kernel-exploits.html#comment-form" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/1563623855220143059/posts/default/8551602144136131794" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/1563623855220143059/posts/default/8551602144136131794" rel="self" type="application/atom+xml"/>
    <link href="http://mainisusuallyafunction.blogspot.com/2012/01/writing-kernel-exploits.html" rel="alternate" type="text/html"/>
    <title>Writing kernel exploits</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Yesterday I gave a talk about writing kernel exploits. I've posted the <a href="http://ugcs.net/~keegan/talks/kernel-exploit/talk.pdf">slides [PDF]</a>. Here is the original description:</p><blockquote><p>Did you know that a NULL pointer can compromise your entire system? Do you know how UNIX pipes, multithreading, and an obscure network protocol from 1981 are combined to take over Linux machines today? OS kernels are full of strange and interesting vulnerabilities, thanks to the subtle nature of systems code. And the kernel's ultimate authority is the ultimate prize for an attacker.</p><p>In this talk you will learn how kernel exploits work, with detailed code examples. Compared to userspace, exploiting the kernel requires a whole different bag of tricks, and we'll cover some of the most important ones. We will focus on Linux systems and x86 hardware, though most ideas will generalize. We'll start with a few toy examples, then look at some real, high-profile Linux exploits from the past two years.</p><p>You will also see how to protect your own Linux machines against kernel exploits. We'll talk about the continual cat-and-mouse game between system administrators and those who would attack even hardened kernels.</p></blockquote><p>Thanks again to <a href="http://sipb.mit.edu/">SIPB</a> for giving me a venue to talk about whatever I find interesting.</p><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/1563623855220143059-8551602144136131794?l=mainisusuallyafunction.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2012-01-28T17:02:23Z</updated>
    <published>2012-01-28T17:02:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="systems"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="slides"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="code"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="kernel"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="security"/>
    <author>
      <name>keegan</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/12227260241426017476</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-1563623855220143059</id>
      <category term="slides"/>
      <category term="debugging"/>
      <category term="latex"/>
      <category term="detrospector"/>
      <category term="assembly"/>
      <category term="ghc"/>
      <category term="types"/>
      <category term="yices-easy"/>
      <category term="quasicrystal"/>
      <category term="hackathon"/>
      <category term="compsci"/>
      <category term="lambda-calculus"/>
      <category term="markdown"/>
      <category term="systems"/>
      <category term="haskell"/>
      <category term="smt"/>
      <category term="tracepoints"/>
      <category term="global-lock"/>
      <category term="code"/>
      <category term="clogparse"/>
      <category term="propane"/>
      <category term="preprocessor"/>
      <category term="mit"/>
      <category term="pandoc"/>
      <category term="phosphene"/>
      <category term="hardware"/>
      <category term="pi-calculus"/>
      <category term="imadethis"/>
      <category term="gdb"/>
      <category term="breakfast"/>
      <category term="security"/>
      <category term="6.S184"/>
      <category term="random"/>
      <category term="graphics"/>
      <category term="debug-diff"/>
      <category term="cabal"/>
      <category term="jvf2010a"/>
      <category term="concurrency"/>
      <category term="type-theory"/>
      <category term="c"/>
      <category term="rts"/>
      <category term="shqq"/>
      <category term="tsp"/>
      <category term="jspath"/>
      <category term="generics"/>
      <category term="kernel"/>
      <category term="hdis86"/>
      <category term="compose"/>
      <category term="repa"/>
      <category term="computability"/>
      <category term="donttrythisathome"/>
      <category term="crystalfontz"/>
      <category term="boston"/>
      <category term="concorde"/>
      <category term="safe-globals"/>
      <author>
        <name>keegan</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/12227260241426017476</uri>
      </author>
      <link href="http://mainisusuallyafunction.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/1563623855220143059/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://mainisusuallyafunction.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <link href="http://www.blogger.com/feeds/1563623855220143059/posts/default?start-index=26&amp;max-results=25" rel="next" type="application/atom+xml"/>
      <subtitle>char* main = "usually a programming blog";</subtitle>
      <title>main is usually a function</title>
      <updated>2012-02-10T00:24:12Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://blog.ezyang.com/?p=6442</id>
    <link href="http://feedproxy.google.com/~r/ezyang/~3/Bh8toscpgtg/" rel="alternate" type="text/html"/>
    <link href="http://blog.ezyang.com/2012/01/popl/#comments" rel="replies" type="text/html"/>
    <link href="http://blog.ezyang.com/2012/01/popl/feed/atom/" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">POPL</title>
    <summary xml:lang="en">Last night, I returned from my very first POPL, very exhausted, and very satisfied. It was great putting faces to names, chatting with potential PhD supervisors (both from the US and in the UK), and reveling in the atmosphere. Highlights from my files: Tony Hoare, on being awarded the ACM SIGPLAN Programming Languages Achievement Award, [...]</summary>
    <content type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml"><div class="document">



<p>Last night, I returned from my very first POPL, very exhausted, and very satisfied. It was great putting faces to names, chatting with potential PhD supervisors (both from the US and in the UK), and reveling in the atmosphere.</p>
<p>Highlights from my files:</p>
<ul class="simple">
<li>Tony Hoare, on being awarded the ACM SIGPLAN Programming Languages Achievement Award, even though he has received so many other awards, “...it makes me feel a little guilty. I didn’t ask for it!”</li>
<li>Hoare: “I <em>like</em> mistakes; if I find it’s my fault, I can rectify it. If it’s someone else’s fault, there’s not much you can do.”</li>
<li>Hoare: “Simplicity is <em>not</em> an engineering goal.”</li>
<li>Tony had just described how he retracted an accepted paper because the reasoning on it was intricate, and he didn’t think it presented program proving in a good light. The interviewer complimented him for his principles, saying that if he had a paper accepted which he didn’t think was up to snuff, he probably wouldn’t have the courage to retract it. It was “so brave.” To which Tony replies, “Well, I wish you could!” [laughter] “Unfortunately, the pressure to publish has increased. We feel obliged to publish every year, and the quality of the average paper is not improved.”</li>
<li>One recurring theme: Tony Hoare mentioned that proofs and tests were not rivals, really they were just the same thing... just different. In the “Run your Research” talk, these theme came up again, where this time the emphasis was executable papers (the “run” in “Run your Research”).</li>
<li>“Don’t just <em>support</em> local reasoning, <em>demand</em> it!” (Brute force proofs not allowed!)</li>
<li>On JavaScript: “null is sort of object-y, while undefined is sort of primitive-y.”</li>
<li>The next set come from the invited speaker from the computer networks community. “During 9/11, on average, the Internet was more stable. The reason for this was the NetOps <em>went home</em>.” (on the causes of network outages in practice.)</li>
<li>“Cisco routers have twenty million lines of code: there’s actually an Ada interpreter in there, as well as a Lisp interpreter.”</li>
<li>“It used to be acceptable to go down for 100ms... now we have video games.”</li>
<li>Speaker: “I am the walrus.” (Goo goo g' joob.)</li>
<li>“I believe we do not reuse theorems. We reuse proof methods, but not the actual theorems. When we write papers, we create very shallow models, and we don’t build on previous work. It’s OK. It’s the design. It doesn’t matter too much. The SML standard was distributed with a bug report, with 100+ mistakes in the original definition. Doesn’t detract from its impact.”</li>
<li>“Put on the algebraic goggles.”</li>
<li>“The Navy couldn’t install it [a system for detecting when classified words were being transmitted on insecure channels], because doing so would be admitting there was a mistake.”</li>
<li>“Move to something really modern, like Scheme!” (It’s like investing one trillion, and moving from the thirteenth century to the fourteenth.)</li>
<li>Strother Moore (co-creator of ACL2): “After retirement, I’ll work more on ACL2, and then I’ll die.”</li>
<li>“What’s the best way to make sure your C program is conforming?” “Write deterministic code.” [laughter]</li>
</ul>
</div>
<img height="1" src="http://feeds.feedburner.com/~r/ezyang/~4/Bh8toscpgtg" width="1"/></div>
    </content>
    <updated>2012-01-28T13:30:59Z</updated>
    <published>2012-01-28T13:30:59Z</published>
    <category scheme="http://blog.ezyang.com" term="Computer Science"/><feedburner:origLink xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://blog.ezyang.com/2012/01/popl/</feedburner:origLink>
    <author>
      <name>Edward Z. Yang</name>
      <uri>http://ezyang.com</uri>
    </author>
    <source>
      <id>http://blog.ezyang.com/feed/atom/</id>
      <link href="http://blog.ezyang.com" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/ezyang" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle xml:lang="en">Existential Pontification and Generalized Abstract Digressions</subtitle>
      <title xml:lang="en">Inside 233</title>
      <updated>2012-01-28T13:30:59Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://alessandrovermeulen.me/2012/01/26/getting-rid-of-javascript-with-haskell</id>
    <link href="http://alessandrovermeulen.me/2012/01/26/getting-rid-of-javascript-with-haskell/" rel="alternate" type="text/html"/>
    <title>Getting rid of programming JavaScript with Haskell</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>For my Experimentation Project at Utrecht University I ported the “JCU”
application to Haskell. The JCU application is used to give Dutch High school
students the opportunity to taste Prolog.</p>

<p>The project uses the Utrecht Haskell Compiler and its JavaScript backend. The UHC
translates Haskell to Core and then translates this Core language to JavaScript.
For more information on this see the blog of the creator of the
<a href="http://utrechthaskellcompiler.wordpress.com/2010/10/18/haskell-to-javascript-backend/">UHC JavaScript backend</a>.</p>

<p>Please read my <a href="http://alessandrovermeulen.me/downloads/report-on-getting-rid-of-js.pdf">report</a> on this
project. The project is hosted on GitHub in the following repositories:</p>

<ul>
<li><a href="https://github.com/spockz/JCU">JCU</a>,</li>
<li><a href="https://github.com/spockz/uhc-jscript">uhc-jscript</a>,</li>
<li><a href="https://github.com/spockz/NanoProlog">NanoProlog</a>, and</li>
<li><a href="http://hackage.haskell.org/package/uu-tc">UU-TC</a>.</li>
</ul>


<p><a href="http://www.flickr.com/photos/spockz/6767517435/" title="Incomplete proof in the HS JCU App by Alessandro Vermeulen, on Flickr"><img alt="Incomplete proof in the HS JCU App" height="414" src="http://farm8.staticflickr.com/7025/6767517435_b075d1c686_z.jpg" width="640"/></a>
<a href="http://www.flickr.com/photos/spockz/6767517241/" title="Complete proof in the HS JCU App by Alessandro Vermeulen, on Flickr"><img alt="Complete proof in the HS JCU App" height="414" src="http://farm8.staticflickr.com/7155/6767517241_eacd8ec0ed_z.jpg" width="640"/></a></p>

<p><strong>update 28-01-2012</strong>:
The keyword <code>jscript</code> in the UHC has been changed to <code>js</code> in order to avoid
association with <a href="http://en.wikipedia.org/wiki/JScript">Microsoft’s JScript</a>.
Also <code>new Object</code> syntax is now available in the <code>foreign import</code> directives.</p>

&lt;figure class="code"&gt;&lt;figcaption&gt;<span/>&lt;/figcaption&gt;<div class="highlight"><table><tbody><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
<span class="line-number">2</span>
</pre></td><td class="code"><pre><code class="haskell"><span class="line"><span class="nf">foreign</span> <span class="kr">import</span> <span class="nn">js</span> <span class="s">"new Object()"</span>
</span><span class="line">  <span class="n">newObject</span> <span class="ow">::</span> <span class="kt">IO</span> <span class="p">(</span><span class="kt">JSPtr</span> <span class="n">a</span><span class="p">)</span>
</span></code></pre></td></tr></tbody></table></div>&lt;/figure&gt;</div>
    </content>
    <updated>2012-01-26T19:29:00Z</updated>
    <source>
      <id>http://alessandrovermeulen.me/</id>
      <author>
        <name>Alessandro Vermeulen</name>
      </author>
      <link href="http://alessandrovermeulen.me/atom.xml" rel="self" type="application/atom+xml"/>
      <link href="http://alessandrovermeulen.me/" rel="alternate" type="text/html"/>
      <title>Alessandro Vermeulen</title>
      <updated>2012-02-01T15:32:40Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://lukepalmer.wordpress.com/?p=1851</id>
    <link href="http://lukepalmer.wordpress.com/2012/01/25/what-was-the-probability-of-that/" rel="alternate" type="text/html"/>
    <link href="http://lukepalmer.wordpress.com/2012/01/25/what-was-the-probability-of-that/#comments" rel="replies" type="text/html"/>
    <link href="http://lukepalmer.wordpress.com/2012/01/25/what-was-the-probability-of-that/feed/atom/" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">What was the probability of that?</title>
    <summary type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml">A group of college students bask in their crude weekly haven of Texas Hold’em poker. Amid the usual banter, they watch as one deals out the flop: a three of spades, a three of diamonds, and a three of clubs. The room falls silent and tensions are suspended as if the ground had fallen out [...]<img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=lukepalmer.wordpress.com&amp;blog=5292379&amp;post=1851&amp;subd=lukepalmer&amp;ref=&amp;feed=1" width="1"/></div>
    </summary>
    <content type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml"><p>A group of college students bask in their crude weekly haven of Texas Hold’em poker.  Amid the usual banter, they watch as one deals out the flop: a three of spades, a three of diamonds, and a three of clubs.  The room falls silent and tensions are suspended as if the ground had fallen out from beneath the house.  The highest card may win this hand, a pocket pair is almost golden, and everyone wonders if someone has the single remaining three.  A round of timid betting ensues — a wrong step here could be very expensive.  After the round completes, the fourth card is dealt onto the table: the three of hearts.  The tensions are dropped as everyone laughs incredulously, and out of the laughter emerges “what’s the probability of <i>that</i>?”</p>
<p>One of the more mathematically adept players pulls out his phone and does a quick calculation: <img alt="\frac{4}{52}\frac{3}{51}\frac{2}{50}\frac{1}{49}" class="latex" src="http://s0.wp.com/latex.php?latex=%5Cfrac%7B4%7D%7B52%7D%5Cfrac%7B3%7D%7B51%7D%5Cfrac%7B2%7D%7B50%7D%5Cfrac%7B1%7D%7B49%7D&amp;bg=ffffff&amp;fg=555555&amp;s=0" title="\frac{4}{52}\frac{3}{51}\frac{2}{50}\frac{1}{49}"/> — about 1 in 270,000.  Everyone is wowed by the rarity of the event they just witnessed.</p>
<p>That is indeed the correct probability to get four consecutive threes from a deck of cards.  But is that really the question here?  Surely nearly the same response would have occurred if it had been four fours, or four nines.  If it were four aces people would be even <i>more</i> astonished.  The same response would have occurred if the cards had been four to a straight flush; e.g. the five through eight of spades.  There are many such situations.  “Four threes” is the most immediate <i>pattern</i> that we recognize as anomalous, but it is not the only anomalous pattern.</p>
<p>So what event is really being referred to by <i>that</i>?  Those specific four cards had a 1 in 6.5 million chance of coming up in the order they did from a player’s perspective before the hand, and a 100% chance of coming up in the order they did from a perspective after the hand [some will note that I am using a Bayesian interpretation of probability at this point].  The probability of the specific <i>real world</i> event that occurred (including the orientations and temperatures of the cards, the reactions of the players, and the taste of Jake Danser’s bite of Chinese dinner 500 miles away), from the perspective of any of the players, is unbelievably small.</p>
<p>In situations where this question is asked, I always jokingly answer the question with “1″. Most of the time people laugh and let the question rest, but sometimes the conversation turns more serious.  In this case I try (in all cases so far, in vain) to explain the plurality of perspective at play here.  The “serious” answer I have for this question, doing my best to interpret the intended meaning of the statement while incorporating these issues, is a number I cannot calculate but that I can describe: it is the probability that the speaker would have been astonished by the event that occurred; essentially the probability that he would remark “what’s the probability of <i>that</i>?”.  I think that is quite a bit higher than one in 270,000, so the event we witnessed was not as rare as the simple calculation would have us believe.</p>
<p>The dissonance of such situations points to a common simplistic view of probability: that <i>events</i> (in the colloquial sense) have probabilities.  A distinction that is commonly understood (and commonly misunderstood) is that between <b>frequentism</b>, which talks about running an experiment a bunch of times and calculating the proportion of experiments that satisfied some criterion, and <b>Bayesianism</b>, which talks about the confidence one has in some property being true <i>in terms of a subjective state of knowledge</i>.  This is a fascinatingly subtle distinction: they coincide on most but not all questions, and there is much argument about which one is “right” (I think that is a rather silly argument, as if a probability were something bestowed to us from nature).  However, both of these views are calculating the probability of a <i>property</i> (a <i>set of events</i>) being true (happening), and both of these views rely on an assumption of prior information: the frequentists on the set-up of the experiment and the Bayesians on their prior state of knowledge about the world.  The idea that <i>an event</i> has a single, objective probability says something very strong about the universe: that there is some essential, natural source of randomness (to dispel any quantum objections, I point to <a href="http://bayes.wustl.edu/etj/articles/prob.in.qm.pdf">E.T. Jaynes’s critique</a> of the view that the randomness in quantum theory is an essential property of nature).  But even if there were some essential source of randomness, surely the universe is more determined than our probabilistic calculations assume: from the view of this universe, the deck cannot be uniformly shuffled after only seven shuffles because it knows how your hands and your brain work.  So we were never talking about an essential, natural randomness.</p>
<p>In our normal use of probabilities, we don’t run into this problem because we are predicting the future: e.g. “what is the probability that Obama will be re-elected?”.  We conceive of this as a single event, but it is actually a wide collection of events. Given some prior knowledge, this set of events has a definite probability.  But we are inconsistent about how we treat future events and past events: past events are not collections — they happened, and they happened in exactly one way. From the perspective of now, the probability that it would happen any other way is zero.  From the perspective of before the event, we are asking whether “it” would happen or not, but we are entirely unclear about what measurable property we mean by “it”. We mean something different when we refer to events in the future and events in the past. </p>
<p>In summary, probabilities are functions of (1) prior information and (2) a <i>criterion</i> for judging when it is to be considered true.  Probability is meaningless to apply to a <i>single</i> event.</p>
<p>N.B. in probability theory, the word <i>event</i> is already defined to mean a set of outcomes.  If you read this article with that definition in mind, you will have been very confused :-).</p>
<p>If this post helped you think more clearly about probability, show your appreciation and <a href="http://flattr.com/thing/471135/What-was-the-probability-of-that" target="_blank"><img alt="Flattr this" border="0" src="http://api.flattr.com/button/flattr-badge-large.png" title="Flattr this"/></a>.</p>
<br/>  <a href="http://feeds.wordpress.com/1.0/gocomments/lukepalmer.wordpress.com/1851/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lukepalmer.wordpress.com/1851/"/></a> <a href="http://feeds.wordpress.com/1.0/godelicious/lukepalmer.wordpress.com/1851/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lukepalmer.wordpress.com/1851/"/></a> <a href="http://feeds.wordpress.com/1.0/gofacebook/lukepalmer.wordpress.com/1851/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lukepalmer.wordpress.com/1851/"/></a> <a href="http://feeds.wordpress.com/1.0/gotwitter/lukepalmer.wordpress.com/1851/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lukepalmer.wordpress.com/1851/"/></a> <a href="http://feeds.wordpress.com/1.0/gostumble/lukepalmer.wordpress.com/1851/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lukepalmer.wordpress.com/1851/"/></a> <a href="http://feeds.wordpress.com/1.0/godigg/lukepalmer.wordpress.com/1851/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lukepalmer.wordpress.com/1851/"/></a> <a href="http://feeds.wordpress.com/1.0/goreddit/lukepalmer.wordpress.com/1851/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lukepalmer.wordpress.com/1851/"/></a> <img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=lukepalmer.wordpress.com&amp;blog=5292379&amp;post=1851&amp;subd=lukepalmer&amp;ref=&amp;feed=1" width="1"/></div>
    </content>
    <updated>2012-01-26T05:42:16Z</updated>
    <published>2012-01-25T22:56:36Z</published>
    <category scheme="http://lukepalmer.wordpress.com" term="Uncategorized"/>
    <category scheme="http://lukepalmer.wordpress.com" term="language"/>
    <category scheme="http://lukepalmer.wordpress.com" term="math"/>
    <category scheme="http://lukepalmer.wordpress.com" term="probability"/>
    <author>
      <name>Luke</name>
    </author>
    <source>
      <id>http://lukepalmer.wordpress.com/feed/atom/</id>
      <link href="http://lukepalmer.wordpress.com" rel="alternate" type="text/html"/>
      <link href="http://lukepalmer.wordpress.com/feed/atom/" rel="self" type="application/atom+xml"/>
      <link href="http://lukepalmer.wordpress.com/osd.xml" rel="search" type="application/opensearchdescription+xml"/>
      <link href="http://wordpress.com/opensearch.xml" rel="search" type="application/opensearchdescription+xml"/>
      <link href="http://lukepalmer.wordpress.com/?pushpress=hub" rel="hub" type="text/html"/>
      <subtitle xml:lang="en">Functional programming and mathematical philosophy with musical interludes</subtitle>
      <title xml:lang="en">Luke Palmer</title>
      <updated>2012-02-07T20:59:16Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-2553815923640620572.post-5895023929982287199</id>
    <link href="http://flygdynamikern.blogspot.com/feeds/5895023929982287199/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://flygdynamikern.blogspot.com/2012/01/type-level-integers-with-type-families.html#comment-form" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/2553815923640620572/posts/default/5895023929982287199" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/2553815923640620572/posts/default/5895023929982287199" rel="self" type="application/atom+xml"/>
    <link href="http://flygdynamikern.blogspot.com/2012/01/type-level-integers-with-type-families.html" rel="alternate" type="text/html"/>
    <title>Type level integers with Type Families (numtype-tf 0.1)</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Pretty much since they were introduced into GHC I’ve been meaning to try to port the <em><a href="http://dimensional.googlecode.com">dimensional</a></em> library to use <a href="http://www.haskell.org/haskellwiki/GHC/Type_families"><em>Type Families</em></a> instead of <a href="http://www.haskell.org/haskellwiki/Functional_dependencies"><em>Functional Dependencies</em></a>. However, functional dependencies have served me quite well and I’ve been lacking the inspiration to dig into type families. That is, until I read the Leonidas’ <a href="https://github.com/leonidas/codeblog/blob/master/2011/2011-12-21-static-vector-algebra.md"><em>Statically Typed Vector Algebra Using Type Families</em></a>. Leonidas’ blog post resonated with me as the problem it addresses is related to one I myself have been interested in for some time (<a href="http://stackoverflow.com/questions/5850392/can-good-type-systems-distinguish-between-matrices-in-different-bases/5856996#5856996">linear algebra with static guarantees</a>). It also gave me a clear vision of how to apply type families to the fundamendal problem of dimensional – type level integers.</p><p>I’ve implemented the <em><a href="http://hackage.haskell.org/package/numtype-tf">numtype-tf</a></em> library which is in essence <em><a href="http://hackage.haskell.org/package/numtype">numtype</a></em> using type families (hence the “-tf”) instead of functional dependencies. Some of my design decisions are slightly different (beside the choice of type system extension), e.g. the representation of negative integers is different and the <code>PosType</code> and <code>NegType</code> classes have been dropped in numtype-tf. The haddocks have also been improved a little.</p><p>A feature of the functionally dependent numtype that I was unable to reproduce with type families is ”<a href="http://www.haskell.org/pipermail/haskell-prime/2011-June/003438.html">mutual dependencies</a>”, used in the <code>Sum</code> and <code>Div</code> type classes of numtype. Here is an example of type signatures (instances omitted) and ghci usage:</p><pre class="sourceCode"><code class="sourceCode haskell">&gt; <span class="kw">class</span> <span class="dt">Sum</span> a b c <span class="fu">|</span> a b <span class="ot">-&gt;</span> c, a c <span class="ot">-&gt;</span> b, b c <span class="ot">-&gt;</span> a<br/>&gt; <span class="ot">(+) </span><span class="ot">::</span> (<span class="dt">Sum</span> a b c) <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> c<br/>&gt; <span class="ot">(-) </span><span class="ot">::</span> (<span class="dt">Sum</span> a b c) <span class="ot">=&gt;</span> c <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> a</code></pre><pre><code>\*Numeric.NumType&gt; pos3 - pos5
NumType -2
</code></pre><p>To the best of my knowledge corresponding code with type families would be along the lines of:</p><pre class="sourceCode"><code class="sourceCode haskell">&gt; <span class="kw">type</span> family <span class="dt">Sum</span> a b<br/>&gt; <span class="ot">(+) </span><span class="ot">::</span> a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> <span class="dt">Sum</span> a b<br/>&gt; <span class="ot">(-) </span><span class="ot">::</span> <span class="dt">Sum</span> a b <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> a</code></pre><pre><code>\*Numeric.NumType.TF&gt; pos3 - pos5

&lt;interactive&gt;:1:1:
    Couldn't match type `Sum a0 Pos5' with `S Pos2'
    …
</code></pre><p>In order for the latter to compute we must assist the type checker by being explicit about the type of <code>a0</code>, i.e. <code>pos3 - pos5 :: Neg2</code>, which largely defeats the purpose of type level arithmetic. Instead two type families are used in numtype-tf:</p><pre class="sourceCode"><code class="sourceCode haskell">&gt; <span class="kw">type</span> family <span class="dt">Add</span> a b  <span class="co">-- a + b</span><br/>&gt; <span class="ot">(+) </span><span class="ot">::</span> a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> <span class="dt">Add</span> a b<br/>&gt; <span class="kw">type</span> family <span class="dt">Sub</span> a b  <span class="co">-- a - b.</span><br/>&gt; <span class="ot">(-) </span><span class="ot">::</span> a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> <span class="dt">Sub</span> a b</code></pre><p>This works OK but the lack och mutual dependencies in type families restricts what I will losely refer to as “type inference back tracking”. This may or may not be a significant drawback compared to fundep numtype depending on the use case.</p><p>If you are interested in comparing code written with type families to code written with functional dependencies take a look at the respective modules on Github: <a href="https://github.com/bjornbm/numtype-tf/blob/master/Numeric/NumType/TF.lhs">Numeric.NumType.TF</a> vs. <a href="https://github.com/bjornbm/numtype/blob/master/Numeric/NumType.lhs">Numeric.NumType</a>.</p><p>The next step is to reimplement dimensional as <em>dimensional-tf</em> in order to exercise numtype-tf and better understand the impact of the differences with respect to numtype. I am also looking forward to playing with <a href="http://hackage.haskell.org/trac/ghc/wiki/TypeNats">GHC.TypeNats</a> in GHC 7.4.</p><a href="http://flattr.com/thing/470789/Type-level-integers-with-Type-Families-numtype-tf-0-1" target="_blank"> <img alt="Flattr this" border="0" src="http://api.flattr.com/button/flattr-badge-large.png" title="Flattr this"/></a><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/2553815923640620572-5895023929982287199?l=flygdynamikern.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2012-01-25T13:44:59Z</updated>
    <published>2012-01-25T13:36:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="haskell"/>
    <author>
      <name>Björn Buckwalter</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/14027110650075268096</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-2553815923640620572</id>
      <category term="space"/>
      <category term="haskell example"/>
      <category term="fad"/>
      <category term="haskell"/>
      <author>
        <name>Björn Buckwalter</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/14027110650075268096</uri>
      </author>
      <link href="http://flygdynamikern.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/2553815923640620572/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://flygdynamikern.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <title>Flygdynamikern</title>
      <updated>2012-01-27T12:39:45Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://blog.ezyang.com/?p=6348</id>
    <link href="http://feedproxy.google.com/~r/ezyang/~3/SNXxLRkNNx0/" rel="alternate" type="text/html"/>
    <link href="http://blog.ezyang.com/2012/01/modelling-io/#comments" rel="replies" type="text/html"/>
    <link href="http://blog.ezyang.com/2012/01/modelling-io/feed/atom/" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">Modelling IO: MonadIO and beyond</title>
    <summary xml:lang="en">The MonadIO problem is, at the surface, a simple one: we would like to take some function signature that contains IO, and replace all instances of IO with some other IO-backed monad m. The MonadIO typeclass itself allows us to transform a value of form IO a to m a (and, by composition, any function [...]</summary>
    <content type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml"><div class="document">



<p>The MonadIO problem is, at the surface, a simple one: we would like to take some function signature that contains <tt class="docutils literal">IO</tt>, and replace all instances of <tt class="docutils literal">IO</tt> with some other IO-backed monad <tt class="docutils literal">m</tt>. The MonadIO typeclass itself allows us to transform a value of form <tt class="docutils literal">IO a</tt> to <tt class="docutils literal">m a</tt> (and, by composition, any function with an <tt class="docutils literal">IO a</tt> as the result). This interface is uncontroversial and quite flexible; it’s been in the bootstrap libraries ever since it was <a class="reference external" href="https://github.com/ghc/packages-base/commit/7f1f4e7a695c402ddd3a1dc2cc7114e649a78ebc">created in 2001</a> (originally in base, though it migrated to transformers later). However, it was soon discovered that when there were many functions with forms like <tt class="docutils literal">IO a <span class="pre">-&gt;</span> IO a</tt>, which we wanted to convert into <tt class="docutils literal">m a <span class="pre">-&gt;</span> m a</tt>; MonadIO had no provision for handling arguments in the <em>negative</em> position of functions. This was particularly troublesome in the case of exception handling, where these higher-order functions were <em>primitive</em>. Thus, the community began searching for a new type class which captured more of IO.</p>
<p>While the semantics of lift were well understood (by the transformer laws), it wasn’t clear what a more powerful mechanism looked like. So, early attacks at the problem took the approach of picking a few distinguished functions which we wanted, placing them in a typeclass, and manually implementing lifted versions of them.  This lead to the development of the already existing <tt class="docutils literal">MonadError</tt> class into a more specialized <tt class="docutils literal">MonadCatchIO</tt> class. However, Anders Kaseorg realized that there was a common pattern to the implementation of the lifted versions of these functions, which he factored out into the <tt class="docutils literal">MonadMorphIO</tt> class. This approach was refined into the <tt class="docutils literal">MonadPeelIO</tt> and <tt class="docutils literal">MonadTransControlIO</tt> typeclasses. However, only <tt class="docutils literal">MonadError</tt> was in the core, and it had failed to achieve widespread acceptance due to some fundamental problems.</p>
<p>I believe it is important and desirable for the community of library writers to converge on one of these type classes, for the primary reason that it is important for them to implement exception handling properly, a task which is impossible to do if you want to export an interface that requires only <tt class="docutils literal">MonadIO</tt>. I fully expected monad-control to be the “winner”, being the end at a long lineage of type classes. However, I think it would be more accurate to describe <tt class="docutils literal">MonadError</tt> and <tt class="docutils literal">MonadCatchIO</tt> as one school of thought, and <tt class="docutils literal">MonadMorphIO</tt>, <tt class="docutils literal">MOnadPeelIO</tt> and <tt class="docutils literal">MonadTransControlIO</tt> as another.</p>
<p>In this blog post, I’d like to examine and contrast these two schools of thought. A type class is an interface: it defines operations that some object supports, as well as laws that this object abides by.  The utility in a type class is both in its generality (the ability to support multiple implementations with one interface) as well as its precision (the restriction on permissible implementations by <em>laws</em>, making it easier to reason about code that uses an interface). This is the essential tension: and these two schools have very different conclusions about how it should be resolved.</p>
<div class="section" id="modelling-exceptions">
<h3>Modelling exceptions</h3>
<p>This general technique can be described as picking a few functions to generalize in a type class. Since a type class with less functions is preferable to one with more (for generality reasons), <tt class="docutils literal">MonadError</tt> and <tt class="docutils literal">MonadCatchIO</tt> have a very particular emphasis on exceptions:</p>
<pre class="literal-block">class (Monad m) =&gt; MonadError e m | m -&gt; e where
  throwError :: e -&gt; m a
  catchError :: m a -&gt; (e -&gt; m a) -&gt; m a

class MonadIO m =&gt; MonadCatchIO m where
  catch   :: Exception e =&gt; m a -&gt; (e -&gt; m a) -&gt; m a
  block   :: m a -&gt; m a
  unblock :: m a -&gt; m a
</pre>
<p>Unfortunately, these functions are marred by some problems:</p>
<ul class="simple">
<li>MonadError encapsulates an abstract notion of errors which does not necessarily include asynchronous exceptions. That is to say, <tt class="docutils literal">catchError undefined h</tt> will not necessarily run the exception handler <tt class="docutils literal">h</tt>.</li>
<li>MonadError is inadequate for robust handling of asynchronous exceptions, because it does not contain an interface for <tt class="docutils literal">mask</tt>; this makes it difficult to write bracketing functions robustly.</li>
<li>MonadCatchIO explicitly only handles asynchronous exceptions, which means any pure error handling is not handled by it. This is the “finalizers are sometimes skipped” problem.</li>
<li>MonadCatchIO, via the <tt class="docutils literal">MonadIO</tt> constraint, requires the API to support lifting arbitrary IO actions to the monad (whereas a monad designer may create a restricted IO backed monad, limiting what IO actions the user has access to.)</li>
<li>MonadCatchIO exports the outdated <tt class="docutils literal">block</tt> and <tt class="docutils literal">unblock</tt> function, while modern code should use <tt class="docutils literal">mask</tt> instead.</li>
<li>MonadCatchIO exports an instance for the <tt class="docutils literal">ContT</tt> transformer. However, continuations and exceptions are <a class="reference external" href="http://hpaste.org/56921">known to have nontrivial interactions</a> which require extra care to handle properly.</li>
</ul>
<p>In some sense, <tt class="docutils literal">MonadError</tt> is a non-sequitur, because it isn’t tied to IO at all; perfectly valid instances of it exist for non-IO backed monads as well. <tt class="docutils literal">MonadCatchIO</tt> is closer; the latter three points are not fatal ones could be easily accounted for:</p>
<pre class="literal-block">class MonadException m where
  throwM  :: Exception e =&gt; e -&gt; m a
  catch   :: Exception e =&gt; m a -&gt; (e -&gt; m a) -&gt; m a
  mask    :: ((forall a. m a -&gt; m a) -&gt; m b) -&gt; m b
</pre>
<p>(With a removal of the <tt class="docutils literal">ContT</tt> instance.) However, the “finalizers are sometimes skipped” problem is a bit more problematic. In effect, it is the fact that there may exist zeros which a given instance of <tt class="docutils literal">MonadCatchIO</tt> may not know about. It has been argued that <a class="reference external" href="http://www.haskell.org/pipermail/haskell-cafe/2010-October/085079.html">these zeros are none of MonadCatchIO’s business</a>; one inference you might draw from this is that if you have short-circuiting which you would like to respect finalizers installed using <tt class="docutils literal">MonadException</tt>, it should be implemented using asynchronous exceptions. In other words, <tt class="docutils literal">ErrorT</tt> is a bad idea.</p>
<p>However, there is another perspective you can take: <tt class="docutils literal">MonadException</tt> is not tied just to asynchronous exceptions, but any zero-like value which obeys the same laws that exceptions obey. The semantics of these exceptions are described in the paper <a class="reference external" href="http://community.haskell.org/~simonmar/papers/async.pdf">Asynchronous Exceptions in Haskell</a>. They specify exactly the interaction of masking, throw and catch, as well as how interrupts can be introduced by other threads. In this view, whether or not this behavior is prescribed by the RTS or by passing pure values around is an implementation detail: as long as an instance is written properly, zeros will be properly handled. This also means that it is no longer acceptable to provide a <tt class="docutils literal">MonadException</tt> instance for <tt class="docutils literal">ErrorT e</tt>, unless we also have an underlying <tt class="docutils literal">MonadException</tt> for the inner monad: we can’t forget about exceptions on the lower layers!</p>
<p>There is one last problem with this approach: once the primitives have been selected, huge swaths of the standard library have to be redefined by “copy pasting” their definitions but having them refer to the generalized versions. This is a significant practical hurdle for implementing a library based on this principle: it’s simply not enough to tack a <tt class="docutils literal">liftIO</tt> to the beginning of a function!</p>
<p>I think an emphasis on the semantics of the defined type class will be critical for the future of this lineage of typeclasses; this is an emphasis that hasn’t really existed in the past. From this perspective, we define with our typeclass not only a way to access otherwise inaccessible functions in IO, but also how these functions should behave. We are, in effect, modeling a subset of IO. I think Conal Elliott <a class="reference external" href="http://conal.net/blog/posts/notions-of-purity-in-haskell">would be proud</a>.</p>
<blockquote>
There is a <a class="reference external" href="http://comments.gmane.org/gmane.comp.lang.haskell.cafe/93834">lively debate</a> going on about extensions to the original semantics of asynchronous exceptions, allowing for the notion of “recoverable” and “unrecoverable” errors. (It’s nearer to the end of the thread.)</blockquote>
</div>
<div class="section" id="threading-pure-effects">
<h3>Threading pure effects</h3>
<p>This technique can be described as generalizing the a common implementation technique which was used to implement many of the original functions in <tt class="docutils literal">MonadCatchIO</tt>. These are a rather odd set of signatures:</p>
<pre class="literal-block">class Monad m =&gt; MonadMorphIO m where
  morphIO :: (forall b. (m a -&gt; IO b) -&gt; IO b) -&gt; m a

class MonadIO m =&gt; MonadPeelIO m where
  peelIO :: m (m a -&gt; IO (m a))

class MonadBase b m =&gt; MonadBaseControl b m | m -&gt; b where
  data StM m :: * -&gt; *
  liftBaseWith :: (RunInBase m b -&gt; b a) -&gt; m a
  restoreM :: StM m a → m a
type RunInBase m b = forall a. m a -&gt; b (StM m a)
</pre>
<p>The key intuition behind these typeclasses is that they utilize <em>polymorphism</em> in the IO function that is being lifted in order to <em>thread the pure effects</em> of the monad stack on top of IO. You can see this as the universal quantification in <tt class="docutils literal">morphIO</tt>, the return type of <tt class="docutils literal">peelIO</tt> (which is <tt class="docutils literal">IO (m a)</tt>, not <tt class="docutils literal">IO a</tt>), and the <tt class="docutils literal">StM</tt> associated type in <tt class="docutils literal">MonadBaseControl</tt>. For example, <tt class="docutils literal">Int <span class="pre">-&gt;</span> StateT s IO a</tt>, is equivalent to the type <tt class="docutils literal">Int <span class="pre">-&gt;</span> s <span class="pre">-&gt;</span> IO (s, a)</tt>. We can partially apply this function with the current state to get <tt class="docutils literal">Int <span class="pre">-&gt;</span> IO (s, a)</tt>; it should be clear then that as long as the IO function we’re lifting lets us smuggle out arbitrary values, we can smuggle out our updated state and reincorporate it when the lifted function finishes. The set of functions which are amenable to this technique are precisely the ones for which this threaded is possible.</p>
<p>As I described in <a class="reference external" href="http://blog.ezyang.com/2012/01/monadbasecontrol-is-unsound/">this post</a>, this means that you won’t be able to get any transformer stack effects if they aren’t returned by the function. So perhaps a better word for MonadBaseControl is not that it is unsound (although it does admit strange behavior) but that it is incomplete: it cannot lift all IO functions to a form where the base monad effects and the transformer effects always occur in lockstep.</p>
<p>This has some interesting implications. For example, this forgetfulness is in fact precisely the reason why a lifted bracketing function will always run no matter if there are other zeros: <tt class="docutils literal">finally</tt> by definition is only aware of asynchronous exceptions. This makes monad-control lifted functions very explicitly only handling asynchronous exceptions: a lifted <tt class="docutils literal">catch</tt> function will not catch an ErrorT zero. However, if you manually implement <tt class="docutils literal">finally</tt> using lifted versions of the more primitive functions, finalizers may be dropped.</p>
<p>It also suggests an alternate implementation strategy for monad-control: rather than thread the state through the return type of a function, it could instead be embedded in a hidden IORef, and read out at the end of the computation. In effect, we would like to <em>embed</em> the semantics of the pure monad transformer stack inside IO. Some care must be taken in the <tt class="docutils literal">forkIO</tt> case, however: the IORefs need to also be duplicated appropriately, in order to maintain thread locality, or MVars used instead, in order to allow coherent non-local communication.</p>
<p>It is well known that MonadBaseControl does not admit a reasonable instance for ContT. Mikhail Vorozhtsov has argued that this is too restrictive. The difficulty is that while unbounded continuations do not play nice with exceptions, limited use of continuation passing style can be combined with exceptions in a sensible way. Unfortunately, monad-control makes no provision for this case: the function it asks a user to implement is too powerful. It seems the typeclasses explicitly modeling a subset of IO are, in some sense, more general! It also highlights the fact that these type classes are first and foremost driven by an abstraction of a common implementation pattern, rather than any sort of semantics.</p>
</div>
<div class="section" id="conclusion">
<h3>Conclusion</h3>
<p>I hope this essay has made clear why I think of MonadBaseControl as an implementation strategy, and not as a reasonable <em>interface</em> to program against. MonadException is a more reasonable interface, which has a semantics, but faces significant implementation hurdles.</p>
</div>
</div>
<img height="1" src="http://feeds.feedburner.com/~r/ezyang/~4/SNXxLRkNNx0" width="1"/></div>
    </content>
    <updated>2012-01-24T18:31:06Z</updated>
    <published>2012-01-24T18:31:06Z</published>
    <category scheme="http://blog.ezyang.com" term="Haskell"/><feedburner:origLink xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://blog.ezyang.com/2012/01/modelling-io/</feedburner:origLink>
    <author>
      <name>Edward Z. Yang</name>
      <uri>http://ezyang.com</uri>
    </author>
    <source>
      <id>http://blog.ezyang.com/feed/atom/</id>
      <link href="http://blog.ezyang.com" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/ezyang" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle xml:lang="en">Existential Pontification and Generalized Abstract Digressions</subtitle>
      <title xml:lang="en">Inside 233</title>
      <updated>2012-01-28T13:30:59Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://www.mega-nerd.com/erikd/Blog/2012/01/24/read_int.atom</id>
    <link href="http://www.mega-nerd.com/erikd/Blog/CodeHacking/Haskell/read_int.html" rel="alternate" type="text/html"/>
    <title xml:lang="en">Benchmarking and QuickChecking readInt.</title>
    <content type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml"><p>
I'm currently working on converting my
	<a href="http://hackage.haskell.org/package/http-proxy/">
	http-proxy</a>
library from using the
	<a href="http://hackage.haskell.org/package/enumerator">
	Data.Enumerator</a>
package to
	<a href="http://hackage.haskell.org/package/conduit/">
	Data.Conduit</a>
(explanation of why in my
	<a href="http://www.mega-nerd.com/erikd/Blog/CodeHacking/Haskell/telnet-conduit.html">
	last blog post</a>).
</p>

<p>
During this conversion, I have been studying the sources of the
	<a href="http://hackage.haskell.org/package/warp/">
	Warp</a>
web server because my http-proxy was originally derived from the Enumerator
version of Warp.
While digging through the Warp code I found the following code (and comment)
which is used to parse the number provided in the <tt>Content-Length</tt> field
of a HTTP header:
</p>

<pre class="code">  -- Note: This function produces garbage on invalid input. But serving an
  -- invalid content-length is a bad idea, mkay?
  readInt :: S.ByteString -&gt; Integer
  readInt = S.foldl' (\x w -&gt; x * 10 + fromIntegral w - 48) 0

</pre>

<p>
The comment clearly states that that this function can produce garbage,
specifically if the string contains anything other than ASCII digits.
The comment is also correct that an invalid <tt>Content-Length</tt> is a bad
idea.
However, on seeing the above code, and remembering something I had seen recently
in the standard library, I naively sent the
	<a href="https://github.com/yesodweb/wai/">
	Yesod project</a>
a patch replacing the above code with a version that uses the <tt>readDec</tt>
function from the <tt>Numeric</tt> module:
</p>

<pre class="code">  import Data.ByteString (ByteString)
  import qualified Data.ByteString.Char8 as B
  import qualified Numeric as N

  readInt :: ByteString -&gt; Integer
  readInt s =
      case N.readDec (B.unpack s) of
          [] -&gt; 0
          (x, _):_ -&gt; x

</pre>

<p>
About 3-4 hours after I submitted the patch I got an email from
	<a href="http://www.snoyman.com/">
	Michael Snoyman</a>
saying that parsing the <tt>Content-Length</tt> field is a hot spot for the
performance of Warp and that I should benchmark it against the code I'm
replacing to make sure there is no unacceptable performance penalty.
</p>

<p>
That's when I decided it was time to check out Bryan O'Sullivan's
	<a href="http://hackage.haskell.org/package/criterion/">
	Criterion</a>
bench-marking library.
A quick read of the docs and bit of messing around and I was able to prove to
myself that using <tt>readDec</tt> was indeed much slower than the code I wanted
to replace.
</p>

<p>
The initial disappointment of finding that a more correct implementation was
significantly slower than the less correct version quickly turned to joy as I
experimented with a couple of other implementations and eventually settled on
this:
</p>


<pre class="code">  import Data.ByteString (ByteString)
  import qualified Data.ByteString.Char8 as B
  import qualified Data.Char as C

  readIntTC :: Integral a =&gt; ByteString -&gt; a
  readIntTC bs = fromIntegral
          $ B.foldl' (\i c -&gt; i * 10 + C.digitToInt c) 0
          $ B.takeWhile C.isDigit bs

</pre>

<p>
By using the <tt>Integral</tt> type class, this function converts the given
<tt>ByteString</tt> to any integer type (ie any type belonging to the
<tt>Integral</tt> type class).
When used, this function will be specialized by the Haskell compiler at the
call site to to produce code to read string values into <tt>Int</tt>s,
<tt>Int64</tt>s or anything else that is a member of the <tt>Integral</tt>
type class.
</p>

<p>
For a final sanity check I decided to use
	<a href="http://hackage.haskell.org/package/QuickCheck">
	QuickCheck</a>
to make sure that the various versions of the generic function were correct for
values of the type they returned.
To do that I wrote a very simple QuickCheck property as follows:
</p>


<pre class="code">  prop_read_show_idempotent :: Integral a =&gt; (ByteString -&gt; a) -&gt; a -&gt; Bool
  prop_read_show_idempotent freader x =
      let posx = abs x
      in posx == freader (B.pack $ show posx)

</pre>

<p>
This QuickCheck property takes the function under test <tt>freader</tt> and
QuickCheck will then provide it values of the correct type.
Since the function under test is designed to read <tt>Content-Length</tt> values
which are always positive, we only test using the absolute value of the value
randomly generated by QuickCheck.
</p>


<p>
The complete test program can be found on Github
	<a href="https://gist.github.com/1662654">
	in this Gist</a>
and can be compiled and run as:
</p>

<pre class="code">  ghc -Wall -O3 --make readInt.hs -o readInt &amp;&amp; ./readInt

</pre>

<p>
When run, the output of the program looks like this:
</p>

<pre class="code">  Quickcheck tests.
  +++ OK, passed 100 tests.
  +++ OK, passed 100 tests.
  +++ OK, passed 100 tests.
  Criterion tests.
  warming up
  estimating clock resolution...
  mean is 3.109095 us (320001 iterations)
  found 27331 outliers among 319999 samples (8.5%)
    4477 (1.4%) low severe
    22854 (7.1%) high severe
  estimating cost of a clock call...
  mean is 719.4627 ns (22 iterations)

  benchmarking readIntOrig
  mean: 4.653041 us, lb 4.645949 us, ub 4.663823 us, ci 0.950
  std dev: 43.94805 ns, lb 31.52653 ns, ub 73.82125 ns, ci 0.950

  benchmarking readDec
  mean: 13.12692 us, lb 13.10881 us, ub 13.14411 us, ci 0.950
  std dev: 90.63362 ns, lb 77.52619 ns, ub 112.4304 ns, ci 0.950

  benchmarking readRaw
  mean: 591.8697 ns, lb 590.9466 ns, ub 594.1634 ns, ci 0.950
  std dev: 6.995869 ns, lb 3.557109 ns, ub 14.54708 ns, ci 0.950

  benchmarking readInt
  mean: 388.3835 ns, lb 387.9500 ns, ub 388.8342 ns, ci 0.950
  std dev: 2.261711 ns, lb 2.003214 ns, ub 2.585137 ns, ci 0.950

  benchmarking readInt64
  mean: 389.4380 ns, lb 388.9864 ns, ub 389.9312 ns, ci 0.950
  std dev: 2.399116 ns, lb 2.090363 ns, ub 2.865227 ns, ci 0.950

  benchmarking readInteger
  mean: 389.3450 ns, lb 388.8463 ns, ub 389.8626 ns, ci 0.950
  std dev: 2.599062 ns, lb 2.302428 ns, ub 2.963600 ns, ci 0.950

</pre>

<p>
At the top of the output is proof that all three specializations of the generic
function <tt>readIntTC</tt> satisfy the QuickCheck property.
From the Criterion output its pretty obvious that the <tt>Numeric.readDec</tt>
version is about 3 times slower that the original function.
More importantly, all three version of this generic function are an order of
magnitude faster than the original.
</p>

<p>
That's a win!
I will be submitting my new function for inclusion in Warp.
</p>


<p>
<b>Update : 14:13</b>
</p>

<p>
At around the same time I submitted my latest version for <tt>readInt</tt>
Vincent Hanquez
	<a href="https://github.com/yesodweb/wai/pull/34#issuecomment-3626110">
	posted a comment on the Github issue</a>
suggesting I look at the
	<a href="http://www.haskell.org/ghc/docs/7.2.2/html/users_guide/syntax-extns.html#magic-hash">
	GHC MagicHash extension</a>
and pointed me to
	<a href="http://tab.snarc.org/posts/haskell/2011-11-15-lookup-tables.html">
	an example</a>.
</p>

<p>
Sure enough, using the MagicHash technique resulted in something significantly
faster again.
</p>

<p>
<b>Update #2 : 2012-01-29 19:46</b>
</p>

<p>
In version 0.3.0 and later of the
	<a href="http://hackage.haskell.org/package/bytestring-lexing">
	bytestring-lexing</a>
package there is a function <tt>readDecimal</tt> that is even faster than the
MagiHash version.
</p></div>
    </content>
    <updated>2012-01-24T00:52:00Z</updated>
    <published>2012-01-24T00:52:00Z</published>
    <category term="/Haskell"/>
    <source>
      <id>http://www.mega-nerd.com/erikd/Blog/CodeHacking/index.atom</id>
      <author>
        <name>Erik de Castro Lopo</name>
        <email>erikd@mega-nerd.com</email>
        <uri>http://www.mega-nerd.com/erikd/Blog/CodeHacking/index.atom</uri>
      </author>
      <link href="http://www.mega-nerd.com/erikd/Blog/CodeHacking/index.atom" rel="self" type="application/atom+xml"/>
      <rights xml:lang="en">Copyright 2006-2010 Erik de Castro Lopo</rights>
      <subtitle xml:lang="en">An ocassional rant</subtitle>
      <title xml:lang="en">m3ga blog</title>
      <updated>2012-01-24T00:52:00Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://alessandrovermeulen.me/2012/01/23/photos-of-the-dmn-seniorenwedstrijd-21-01-2012-available</id>
    <link href="http://alessandrovermeulen.me/2012/01/23/photos-of-the-dmn-seniorenwedstrijd-21-01-2012-available/" rel="alternate" type="text/html"/>
    <title>Photo's of the DMN Seniorenwedstrijd 21-01-2012 are now available</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>The photo’s of the DMN Seniorenwedstrijd 21-01-2012 at Colijn Dance Masters are
now available. You can order them <a href="http://oypo.nl/pixxer.asp?id=B1835D91132DA171">here</a>.</p></div>
    </content>
    <updated>2012-01-23T19:00:00Z</updated>
    <source>
      <id>http://alessandrovermeulen.me/</id>
      <author>
        <name>Alessandro Vermeulen</name>
      </author>
      <link href="http://alessandrovermeulen.me/atom.xml" rel="self" type="application/atom+xml"/>
      <link href="http://alessandrovermeulen.me/" rel="alternate" type="text/html"/>
      <title>Alessandro Vermeulen</title>
      <updated>2012-02-01T15:32:40Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://noamlewis.wordpress.com/?p=92</id>
    <link href="http://noamlewis.wordpress.com/2012/01/23/when-to-scroll-the-problem-of-infinite-sized-ui-elements-inside-a-scrollviewer/" rel="alternate" type="text/html"/>
    <link href="http://noamlewis.wordpress.com/2012/01/23/when-to-scroll-the-problem-of-infinite-sized-ui-elements-inside-a-scrollviewer/#comments" rel="replies" type="text/html"/>
    <link href="http://noamlewis.wordpress.com/2012/01/23/when-to-scroll-the-problem-of-infinite-sized-ui-elements-inside-a-scrollviewer/feed/atom/" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">When to scroll? The problem of infinite-sized UI elements inside a scrollviewer</title>
    <summary type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml">While refactoring a WPF application, I’ve stumbled into a general problem in UI layout. WPF has an element called ScrollViewer, which is basically a panel that contains elements and shows scroll bars when the content inside is too big to fit in the size of the ScrollViewer’s visible area. Consider the following three cases. Case [...]<img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=noamlewis.wordpress.com&amp;blog=12721713&amp;post=92&amp;subd=noamlewis&amp;ref=&amp;feed=1" width="1"/></div>
    </summary>
    <content type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml"><p>While refactoring a WPF application, I’ve stumbled into a general problem in UI layout.</p>
<p>WPF has an element called ScrollViewer, which is basically a panel that contains elements and shows scroll bars when the content inside is too big to fit in the size of the ScrollViewer’s visible area. Consider the following three cases.</p>
<h3>Case 1: Finite-sized UI content within a ScrollViewer</h3>
<p>In this case, obviously the scroll bars should only appear if the visible area of the ScrollViewer is too small to show the content. If the window is large enough, there entire finite-sized content will fit in the screen and no scroll bars are necessary (although we may want to still show them, disabled, for stylistic reasons).</p>
<h3>Case 2: Infinite-sized UI content within a limited container (NOT a ScrollViewer)</h3>
<p>Sometimes we have content that can use any size assigned to it. For example, a grid (in my case, DevExpress’ WPF GridControl) of data rows. Assuming a huge (or even infinite) data source, the grid’s size on the screen has no upper bound – it can always grow more and always show more content. The grid’s size in the UI must be limited somehow. There are two ways to limit the size of such a UI control:</p>
<ol>
<li>Set a maximum size on the control, or</li>
<li>Place the infinitely-sized control in a container that has a maximum size defined.</li>
</ol>
<p>In other words, the infinite control must lie in a tree of containers where at least one container up the ancestry must have defined a maximum size. If no parent container specifies a maximum size, eventually the top-level container – the window – DOES have a maximum size and the infinite-sized control will fill the whole window (and nothing more).</p>
<h3>Case 3: Infinite-sized UI content within a ScrollViewer</h3>
<p>Now, consider that the container of the infinite UI control (such as a grid with infinite rows in the data source), is actually container within a ScrollViewer. In this case, the ScrollViewer, being what it is, does NOT limit the size of its contents, so the infinitely-sized control will “explode” and will, by our algorithm, try to occupy an infinite size. Specifically in the case of a DevExpress WPF GridControl, the authors of that control know to detect that situation – and an exception is thrown, stating:</p>
<blockquote><p><span style="color: #808080;">DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled</span><br/>
<span style="color: #808080;">   Message=<span style="color: #000000;">“</span></span>By default, an infinite grid height is not allowed since all grid rows will be rendered and hence the grid will work very slowly. To fix this issue, you should place the grid into a container that will give a finite height to the grid, or you should manually specify the grid’s Height or MaxHeight. Note that you can also avoid this exception by setting the GridControl.AllowInfiniteGridSize static property to True, but in that case the grid will run slowly.”</p></blockquote>
<p>Problem is, sometimes we want to put that grid in a ScrollViewer so that when the screen is too small, the grid will assume some minimal size, and a scroll bar will be shown if the screen (or window) is smaller than the minimum. If the window is huge, what we want is to expand the grid to fill the available space in the window – as big as the window can be, with no limit. If someone is using the application on a 5000-inch screen, we want to use all that space. If someone is using a 1-inch screen, we want the grid to be 3 inches and show a scroll bar.</p>
<p>So, the solution seems simple enough: we can tell the ScrollViewer to have dual behavior:</p>
<ol>
<li>If the available screen size is smaller than some minimum, allow scrolling, and set the size available for the content to be that minimum size.</li>
<li>If the available screen size is larger than the minimum, behave like a regular container that gives its children only the space it has on the screen.</li>
</ol>
<p>For example, if we decide the content requires at least 100 pixels, if the ScrollViewer has 80 pixels available – make the content within the scrollable area exactly 100 pixels, and show scroll bars. If the size available for the ScrollViewer is 200 pixels (more than the minimum 100 pixels) – don’t allow scrolling, and let the contained UI content use up to 200 pixels. Here’s a WPF behavior for ScrollViewer that does exactly that:</p>
<pre>    public class ScrollViewerMaxSizeBehavior : Behavior&lt;ScrollViewer&gt;
    {
        public static readonly DependencyProperty MinContentHeightProperty = DependencyProperty.Register("MinContentHeight", typeof(int),
            typeof(ScrollViewerMaxSizeBehavior), new UIPropertyMetadata() { PropertyChangedCallback = MinSizeChanged } );
        public int MinContentHeight
        {
            get { return (int)GetValue(MinContentHeightProperty); }
            set { SetValue(MinContentHeightProperty, value); }
        }

        public static readonly DependencyProperty MinContentWidthProperty = DependencyProperty.Register("MinContentWidth", typeof(int),
            typeof(ScrollViewerMaxSizeBehavior), new UIPropertyMetadata() { PropertyChangedCallback = MinSizeChanged });
        public int MinContentWidth
        {
            get { return (int)GetValue(MinContentWidthProperty); }
            set { SetValue(MinContentWidthProperty, value); }
        }

        protected static void MinSizeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var self = d as ScrollViewerMaxSizeBehavior;
            if (null == self)
            {
                return;
            }
            self.Update();
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.SizeChanged += this.ParentSizeChanged;
            this.Update();
        }

        protected override void OnDetaching()
        {
            this.AssociatedObject.SizeChanged -= this.ParentSizeChanged;
            base.OnDetaching();
        }

        protected void ParentSizeChanged(Object sender, SizeChangedEventArgs e)
        {
            this.Update();
        }

        private void Update()
        {
            if (null == this.AssociatedObject)
            {
                return;
            }
            var content = this.AssociatedObject.Content as FrameworkElement;

            if ((0 &gt;= this.AssociatedObject.ActualHeight)
                || (0 &gt;= this.AssociatedObject.ActualWidth))
            {
                // The attached ScrollViewer was probably not laid out yet, or has zero size.
                this.AssociatedObject.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled;
                this.AssociatedObject.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
                return;
            }

            int minHeight = this.MinContentHeight;
            int minWidth = this.MinContentWidth;

            if ((minHeight &lt;= 0) || (minWidth &lt;= 0))
            {
                // Probably our attached properties were not initialized. By default we disable the scrolling completely,
                // to prevent exceptions from infinitely-sized objects within us.
                this.AssociatedObject.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled;
                this.AssociatedObject.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
                return;
            }

            this.AssociatedObject.SizeChanged -= this.ParentSizeChanged;

            if (this.AssociatedObject.ActualHeight &lt; minHeight)
            {
                this.AssociatedObject.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
                if (null != content)
                {
                    content.MaxHeight = minHeight - (content.Margin.Bottom + content.Margin.Top);
                }
            }
            else
            {
                this.AssociatedObject.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled;
                if (null != content)
                {
                    content.MaxHeight = Double.PositiveInfinity;
                }
            }

            if (this.AssociatedObject.ActualWidth &lt; minWidth)
            {
                this.AssociatedObject.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
                if (null != content)
                {
                    content.MaxWidth = minWidth - (content.Margin.Left + content.Margin.Right);
                }
            }
            else
            {
                this.AssociatedObject.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
                if (null != content)
                {
                    content.MaxWidth = Double.PositiveInfinity;
                }
            }

            this.AssociatedObject.SizeChanged += this.ParentSizeChanged;
        }
    }

An here's how to use it in a XAML file (assuming the above class was defined in a namespace known as "custom" within the XML namespace):
Somewhere at the top: xmlns:Interactivity="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
Then:

    &lt;ScrollViewer Style="{StaticResource AppHost_ScrollViewer}"&gt;
        &lt;Interactivity:Interaction.Behaviors&gt;
            &lt;custom:ScrollViewerMaxSizeBehavior MinContentWidth="600"
                                                MinContentHeight="500"/&gt;
        &lt;/Interactivity:Interaction.Behaviors&gt;

        &lt;!-- content --&gt;

    &lt;/ScrollViewer&gt;</pre>
<h3>Almost, but not quite</h3>
<p>Continuing the 100-pixel example – what happens if we have some <em>statically sized</em> content (no infinite sizes) that requires more than what we defined as a minimum? For example, what if instead of a dynamically-sizable grid we have content that requires 200 pixels, and the window size is 100 pixels? In this case, the previous solution is bad: it will not allow scrolling to see the full 200 pixels. So our dual-behavior needs to know, somehow, if the content within it can expand at all an infinite size (and therefore requires the dual behavior defined above to prevent explosion to infinite size). Because if the content has a <em>finite</em> size, we simply want the ScrollViewer to behave as usual and allow scrolling to see that maximum size.</p>
<h3>Conclusion – what’s missing in WPF (and possibly other UI frameworks)</h3>
<p>What I’d expect is that there would be some property on UI controls specifying whether or not this element can expand infinitely (in height, width, or both). If any node in the UI’s element containment tree has this “infinite size” property set, then the ScrollViewer that contains this tree must act using the dual behavior and must have a minimum size defined (smaller size means we allow scrolling and set the content exactly to the minimum size; bigger-than-minimum size means we don’t allow scrolling and give the content whatever space we have and no more). If the “infinite size” property, propagated to the ScrollViewer from the contained tree is <em>not</em> set, the ScrollViewer acts like a regular ScrollViewer – allowing the content to grow to whatever size it needs, and showing scroll bars if needed.</p>
<p>For now, since there is no such feature in WPF, I’ll be using the aforementioned ScrollViewer behavior with appropriately defined minimum sizes for those screens that need them – hard coded, ugly, but works.</p>
<br/>  <a href="http://feeds.wordpress.com/1.0/gocomments/noamlewis.wordpress.com/92/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/noamlewis.wordpress.com/92/"/></a> <a href="http://feeds.wordpress.com/1.0/godelicious/noamlewis.wordpress.com/92/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/noamlewis.wordpress.com/92/"/></a> <a href="http://feeds.wordpress.com/1.0/gofacebook/noamlewis.wordpress.com/92/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/noamlewis.wordpress.com/92/"/></a> <a href="http://feeds.wordpress.com/1.0/gotwitter/noamlewis.wordpress.com/92/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/noamlewis.wordpress.com/92/"/></a> <a href="http://feeds.wordpress.com/1.0/gostumble/noamlewis.wordpress.com/92/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/noamlewis.wordpress.com/92/"/></a> <a href="http://feeds.wordpress.com/1.0/godigg/noamlewis.wordpress.com/92/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/noamlewis.wordpress.com/92/"/></a> <a href="http://feeds.wordpress.com/1.0/goreddit/noamlewis.wordpress.com/92/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/noamlewis.wordpress.com/92/"/></a> <img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=noamlewis.wordpress.com&amp;blog=12721713&amp;post=92&amp;subd=noamlewis&amp;ref=&amp;feed=1" width="1"/></div>
    </content>
    <updated>2012-01-23T17:48:05Z</updated>
    <published>2012-01-23T17:48:05Z</published>
    <category scheme="http://noamlewis.wordpress.com" term="Uncategorized"/>
    <author>
      <name>sinelaw</name>
      <uri>http://noamlewis.wordpress.com</uri>
    </author>
    <source>
      <id>http://noamlewis.wordpress.com/feed/atom/</id>
      <link href="http://noamlewis.wordpress.com" rel="alternate" type="text/html"/>
      <link href="http://noamlewis.wordpress.com/feed/atom/" rel="self" type="application/atom+xml"/>
      <link href="http://noamlewis.wordpress.com/osd.xml" rel="search" type="application/opensearchdescription+xml"/>
      <link href="http://wordpress.com/opensearch.xml" rel="search" type="application/opensearchdescription+xml"/>
      <link href="http://noamlewis.wordpress.com/?pushpress=hub" rel="hub" type="text/html"/>
      <subtitle xml:lang="en">Haskell, FRP, and other technicalities</subtitle>
      <title xml:lang="en">Enough Blogging!</title>
      <updated>2012-01-23T17:48:10Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-301893373063372699.post-4620264616681706587</id>
    <link href="http://disciple-devel.blogspot.com/feeds/4620264616681706587/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://disciple-devel.blogspot.com/2012/01/new-disciple-core-language.html#comment-form" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/301893373063372699/posts/default/4620264616681706587" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/301893373063372699/posts/default/4620264616681706587" rel="self" type="application/atom+xml"/>
    <link href="http://disciple-devel.blogspot.com/2012/01/new-disciple-core-language.html" rel="alternate" type="text/html"/>
    <title>The new Disciple Core language</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">It's been a while since updates. The last one was in August, and after that I got distracted with ICFP. When I got back I spent more time doing Coq proofs, finishing with Progress and Preservation for a version of SystemF2 with mutable algebraic data. The proofs are <a href="http://code.ouroborus.net/ddc/ddc-head/proof/DDC/Language/SystemF2Store/">here</a>. All data is allocated into the store (heap), and there are primitive functions to update it. In this language you can, say, destructively update a list so that the tail points to different physical data. This language doesn't have effect typing, but after this proof I felt like I had crossed the line from "Coq-shy" to "Coq-sure".<br/><br/>In early November I read about ciu-equivalence, and how to prove contextual equivalence of program transformations. Thinking ahead, it felt like time to cleanup the sponginess in the existing DDC core language, because I'd need to do this before trying to formalise it. Although the plain calculus has a proper semantics and a hand-done soundness proof, the actual core language as used in the compiler also has some half-baked hacks. The reviewers of a previous paper had made suggestions about how to cleanup other aspects of the core calculus, and having Coqified all those languages, I now understand why it was good advice.<br/><br/>Cutting to the chase, I've redesigned the DDC core language and there is an interpreter that works well enough to evaluate simple recursive functions. Here is an example: <br/><pre>  letrec {<br/>   ack    [r1 r2 r3: %] <br/>          (m : Int r1) {!0 | Use r1 + Use r2 + Use r3}<br/>          (n : Int r2) { Read r1 + Read r2 + Alloc r3<br/>                       | Use r1  + Use r2  + Use r3}<br/>          : Int r3<br/>    = letregion r4 in<br/>      let zero = 0 [r4] () in<br/>      let one  = 1 [r4] () in<br/>      case eqInt [:r1 r4 r4:] m zero of {<br/>          1 -&gt; addInt [:r2 r4 r3:] n one;<br/>          _ -&gt; case eqInt [:r2 r4 r4:] n zero of {<br/>                  1 -&gt; ack [:r4 r4 r3:] <br/>                           (subInt [:r1 r4 r4:] m one) <br/>                           (1 [r4] ());<br/><br/>                  _ -&gt; ack [:r4 r4 r3:] <br/>                           (subInt [:r1 r4 r4:] m one)<br/>                           (ack [:r1 r4 r4:] m (subInt [:r2 r4 r4:] n one));<br/>          }<br/>    }<br/>  } in ack [:R0# R0# R0#:] (2 [R0#] ()) (3 [R0#] ());;<br/></pre>Here is another example that does destructive update of an integer:<br/><pre>  letregion r1 with {w1 : Mutable r1} in<br/>  let x : Int r1 = 0 [r1] () in<br/>  let _ : Unit   = updateInt [:r1 r1:] &lt; w1 &gt; x (2 [r1] ()) in<br/>  addInt [:r1 r1 R2#:] x (3 [r1] ());;<br/></pre>and one that suspends the allocation of an integer with lazy evaluation:<br/><pre>  letregion r1 with { w1 : Const r1; w2 : Lazy r1; w3 : Global r1 } in<br/>  let x : Int r1 lazy &lt; w2 &gt; <br/>     = purify &lt; alloc [r1] w1 &gt;  in<br/>       forget &lt; use [r1] w3 w1 &gt; in<br/>       2 [r1] () <br/>  in addInt [:r1 R0# R0#:] x (3 [R0#] ());;<br/></pre><br/>Note that this is an intermediate representation for a compiler, and has vastly more type information than a real user would want to write. The compiler will perform type inference on the source language, and automatically translate the user program to this lower level language.<br/><br/>The new DDC core language is described on the <a href="http://disciple.ouroborus.net/wiki/Language/Core">wiki</a> and so far I've been reasonably good at keeping the wiki up to date with what's implemented. <br/><br/>The main changes are:<br/><ul><li>Witnesses now exist in their own universe, at level 0 next to values. Both values and witnesses are classified by types, and types classified by kinds. This removes the dependent-kinding of the old language. The more I thought about it, the less fun formalising a dependently kinded language seemed to be.<br/><br/></li><li>I've removed the more-than constraints on effect and closure variables. The type inference algorithm I am using returns constraints on effect and closure variables, so I had added similar constraints to the core language. This was a bad idea because managing the additional subsumption judgements during core type checking is a headache. The new core language has no such constraints, and I think I know to process the output of the inferencer so I won't need them.<br/><br/></li><li>Introducing lazy evaluation is now done with the  <tt>let .. lazy</tt> binding form instead of a primitive suspend operator. This goes hand-in-hand with the <tt>purify</tt> and <tt>forget</tt> keywords that mask the effect and closure of their body respectively. These two keywords are akin to the type casts used by SystemFc and the GHC core language to support GADTs. I think it makes more sense to mask out the effect of an expression before suspending it, than to pass a witness as to why it's pure. The former style will still be used in the source program because that's how the type inferencer works, but the latter should be easier to work with in the core language.<br/></li></ul>Anyway, if you <tt>darcs get</tt> the DDC repo you can <tt>make bin/ddci-core</tt> to build the interpreter. Run the examples like <tt>bin/ddci-core test/ddci-core/30-Eval/30-Letrec/Test.dcx</tt>. It's not completely finished, but all the examples under the <tt>test/ddci-core</tt> directory run fine.<br/><br/>The interpreter should be done in another couple of weeks. After that it'll be time to split off the LLVM backend from the existing compiler so that we can compile core programs directly.<div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/301893373063372699-4620264616681706587?l=disciple-devel.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2012-01-23T06:20:20Z</updated>
    <published>2012-01-23T06:20:00Z</published>
    <author>
      <name>Ben Lippmeier</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/08287674468193351664</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-301893373063372699</id>
      <author>
        <name>Ben Lippmeier</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/08287674468193351664</uri>
      </author>
      <link href="http://disciple-devel.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/301893373063372699/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://disciple-devel.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">More info at the <a href="http://disciple.ouroborus.net">The Disciplined Disciple Compiler (DDC) Development Wiki</a>.<br/>
Easy tickets to get started with: <a href="http://disciple.ouroborus.net/report/9">on the trac</a>.</div>
      </subtitle>
      <title>Disciple Development</title>
      <updated>2012-02-02T11:32:33Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-3300386911011555799.post-8258406287870280745</id>
    <link href="http://happstack.blogspot.com/feeds/8258406287870280745/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://happstack.blogspot.com/2012/01/ann-happstack-server-651.html#comment-form" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/3300386911011555799/posts/default/8258406287870280745" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/3300386911011555799/posts/default/8258406287870280745" rel="self" type="application/atom+xml"/>
    <link href="http://happstack.blogspot.com/2012/01/ann-happstack-server-651.html" rel="alternate" type="text/html"/>
    <title>ANN: happstack-server 6.5.1</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">I am pleased to announce the release of happstack-server 6.5.1. Changes include:<br/><br/><br/><ul><li>support for https:// (aka, SSL/TLS) <a href="https://groups.google.com/group/happs/browse_thread/thread/d92c24a7a81adfe8">https://groups.google.com/group/happs/browse_thread/thread/d92c24a7a81adfe8</a></li><li>directory listings now sorted in alphabetical order</li><li>added Happstack class instances for ReaderT, WriterT, StateT, and RWST</li><li>happstack-server now compiles without producing any warnings</li><li>various code cleanup and formatting</li></ul><div>Discussion here: </div><div><a href="http://www.reddit.com/r/haskell/comments/os5kb/ann_happstackserver_651_https_aka_ssltls_support/">http://www.reddit.com/r/haskell/comments/os5kb/ann_happstackserver_651_https_aka_ssltls_support/</a></div><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/3300386911011555799-8258406287870280745?l=happstack.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2012-01-23T01:01:40Z</updated>
    <published>2012-01-23T01:00:00Z</published>
    <author>
      <name>Jeremy Shaw</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/18373967098081701148</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-3300386911011555799</id>
      <category term="hsx"/>
      <category term="type-safe"/>
      <category term="jmacro"/>
      <category term="persistence"/>
      <category term="happstack-lite"/>
      <category term="templating"/>
      <category term="routing"/>
      <category term="ANN"/>
      <category term="safecopy"/>
      <category term="web-routes"/>
      <category term="happstack"/>
      <category term="MACID"/>
      <category term="acid-state"/>
      <category term="database"/>
      <author>
        <name>Jeremy Shaw</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/18373967098081701148</uri>
      </author>
      <link href="http://happstack.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/3300386911011555799/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://happstack.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle>Happstack - A Haskell Web Framework</subtitle>
      <title>Happstack</title>
      <updated>2012-02-01T19:16:02Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-11295132.post-7973803066138768941</id>
    <link href="http://blog.sigfpe.com/feeds/7973803066138768941/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://www.blogger.com/comment.g?blogID=11295132&amp;postID=7973803066138768941" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/11295132/posts/default/7973803066138768941" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/11295132/posts/default/7973803066138768941" rel="self" type="application/atom+xml"/>
    <link href="http://blog.sigfpe.com/2012/01/some-parallels-between-classical-and.html" rel="alternate" type="text/html"/>
    <title>Some parallels between classical and quantum mechanics</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><b>Introduction</b><br/>This isn't really a blog post. More of something I wanted to interject in a discussion on Google plus but wouldn't fit in the text box.<br/><br/>I've always had trouble with the way the <a href="http://en.wikipedia.org/wiki/Legendre_transformation">Legendre transform</a> is introduced in classical mechanics. I know I'm not the only one. Many mathematicians and physicists have recognised that it seems to be plucked out of a hat like a rabbit and have even written papers to address this issue. But however much an author attempts to make it seem natural, it still looks like a rabbit to me.<br/><br/>So I have to ask myself, what would make me feel comfortable with the Legendre transform?<br/><br/>The Legendre transform is an analogue of the Fourier transform that uses a different semiring to the usual. I wrote <a href="http://blog.sigfpe.com/2005/10/quantum-mechanics-and-fourier-legendre.html">briefly</a> about this many years ago. So if we could write classical mechanics in a form that is analogous to another problem where I'd use a Fourier transform, I'd be happier. This is my attempt to do that.<br/><br/>When I wrote about <a href="http://blog.sigfpe.com/2011/06/another-elementary-way-to-approach.html">Fourier transforms</a> a little while back the intention was to immediately follow it with an analogous article about Legendre transforms. Unfortunately that's been postponed so I'm going to just assume you know that Legendre transforms can be used to compute <a href="http://en.wikipedia.org/wiki/Legendre_transformation#Infimal_convolution">inf-convolutions</a>. I'll state clearly what that means below, but I won't show any detail on the analogy with Fourier transforms.<br/><br/><b>Free classical particles</b><br/>Let's work in one dimension with a particle of mass <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=m" style="vertical-align: middle;"/> whose position at time <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t" style="vertical-align: middle;"/> is <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=x%28t%29" style="vertical-align: middle;"/>. The kinetic energy of this particle is given by <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=T%3d%5cfrac%7b1%7d%7b2%7dm%5cdot%7bx%7d%5e2" style="vertical-align: middle;"/>. Its Lagrangian is therefore <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=L%3d%5cfrac%7b1%7d%7b2%7dm%5cdot%7bx%7d%5e2-V%28x%29" style="vertical-align: middle;"/>.<br/><br/>The <a href="http://en.wikipedia.org/wiki/Action_%28physics%29">action</a> of our particle for the time from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f0" style="vertical-align: middle;"/> to <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f1" style="vertical-align: middle;"/> is therefore<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cdisplaystyle%7b%5cint%5f%7bt%5f0%7d%5e%7bt%5f1%7d%28%5cfrac%7b1%7d%7b2%7dm%5cdot%7bx%7d%5e2-V%28x%29%29dt%7d" style="vertical-align: middle;"/><br/></blockquote><br/>The particle motion is that which <a href="http://en.wikipedia.org/wiki/Principle_of_least_action">minimises</a> the action.<br/><br/>Suppose the position of the particle at time <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f0" style="vertical-align: middle;"/> is <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=x%5f0" style="vertical-align: middle;"/> and the position at time <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f1" style="vertical-align: middle;"/> is <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=x%5f1" style="vertical-align: middle;"/>. Then write <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cpsi%28t%5f0%2ct%5f1%2cx%5f0%2cx%5f1%29" style="vertical-align: middle;"/> for the action minimising path from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=x%5f0" style="vertical-align: middle;"/> to <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=x%5f1" style="vertical-align: middle;"/>. So<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cdisplaystyle%7b%5cpsi%28t%5f0%2cx%5f0%3bt%5f1%2cx%5f1%29+%3d+%5cmin%5fx%5cint%5f%7bt%5f0%7d%5e%7bt%5f1%7d%28%5cfrac%7b1%7d%7b2%7dm%5cdot%7bx%7d%5e2-V%28x%29%29dt%7d" style="vertical-align: middle;"/><br/></blockquote>where we're minimising over all paths <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=x" style="vertical-align: middle;"/> such that <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=x%28t%5fi%29%3dx%5fi" style="vertical-align: middle;"/>.<br/><br/>Now suppose our system evolves from time <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f0" style="vertical-align: middle;"/> to <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f2" style="vertical-align: middle;"/>. We can consider this to be two stages, one from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f0" style="vertical-align: middle;"/> to <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f1" style="vertical-align: middle;"/> followed by one from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f1" style="vertical-align: middle;"/> to <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f2" style="vertical-align: middle;"/>. Let <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cphi" style="vertical-align: middle;"/> be the minimised action analogous to <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cpsi" style="vertical-align: middle;"/> for the period <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f1" style="vertical-align: middle;"/> to <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f2" style="vertical-align: middle;"/>. The action from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f0" style="vertical-align: middle;"/> to <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f2" style="vertical-align: middle;"/> is the sum of the actions for the two subperiods. So the minimum total action for the period <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f0" style="vertical-align: middle;"/> to <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f2" style="vertical-align: middle;"/> is given by<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cdisplaystyle%7b%5cpsi%28t%5f0%2cx%5f0%3bt%5f2%2cx%5f2%29+%3d+%5cmin%5f%7bx%5f1%7d%28%5cpsi%28t%5f0%2cx%5f0%3bt%5f1%2cx%5f1%29%2b%5cpsi%28t%5f1%2cx%5f1%3bt%5f2%2cx%5f2%29%29%7d" style="vertical-align: middle;"/><br/></blockquote><br/>Let me simply that a little. I'll use <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cpsi%28t%2cx%29" style="vertical-align: middle;"/> where I previously used <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cpsi%28t%5f0%2cx%5f0%3bt%2cx%29" style="vertical-align: middle;"/> and <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cphi%28x%5f1%2cx%5f2%29" style="vertical-align: middle;"/> for <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cpsi%28t%5f1%2cx%5f1%3bt%5f2%2cx%5f2%29" style="vertical-align: middle;"/>. So that last equation becomes:<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cdisplaystyle%7b%5cpsi%28t%5f2%2cx%5f2%29%3d%5cmin%5f%7bx%5f1%7d%28%5cpsi%28t%5f1%2cx%5f1%29%2b%5cphi%28x%5f2-x%5f1%29%29%7d" style="vertical-align: middle;"/><br/></blockquote><br/>Now suppose <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cphi" style="vertical-align: middle;"/> is translation-independent in the sense that <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cphi%28x%2bs%2cx%27%2bs%29%3d%5cphi%28x%2cx%27%29" style="vertical-align: middle;"/>. So we can write <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cphi%28x%5f1%2cx%5f2%29%3d%5cphi%28x%5f2-x%5f1%29" style="vertical-align: middle;"/>. Then the minimum total action is given by<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cdisplaystyle%7b%5cpsi%28t%5f2%2cx%5f2%29%3d%5cmin%5f%7bx%5f1%7d%28%5cpsi%28t%5f1%2cx%5f1%29%2b%5cphi%28x%5f2-x%5f1%29%29%7d" style="vertical-align: middle;"/><br/></blockquote><br/>Infimal convolution is defined by<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cdisplaystyle%7b%28f%5codot+g%29%28x%29+%3d+%5cmin%5fs%28f%28s%29%2bg%28x-s%29%29%7d" style="vertical-align: middle;"/><br/></blockquote>so the minimum we seek is<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cdisplaystyle%7b%5cpsi%28t%5f2%2cx%5f2%29+%3d+%28%5cpsi%28t%5f1%2c%5ccdot%29%5codot%5cphi%29%29%28x%5f2%29%7d" style="vertical-align: middle;"/><br/></blockquote><br/>So now it's natural to use the Legendre transform. We have the inf-convolution theorem:<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%28f%5codot+g%29%5e%5cast%3df%5e%5cast%2bg%5e%5cast" style="vertical-align: middle;"/><br/></blockquote>where <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=f%5e%5cast" style="vertical-align: middle;"/> is the Legendre transform of <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=f" style="vertical-align: middle;"/> given by<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cdisplaystyle%7bf%5e%5cast%28p%29+%3d+%5csup%5fx%28px-f%28x%29%29%7d" style="vertical-align: middle;"/><br/></blockquote>and so <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cpsi%5e%5cast%28t%5f2%2cp%29+%3d+%5cpsi%5e%5cast%28t%5f1%2cp%29%2b%5cphi%5e%5cast%28p%29" style="vertical-align: middle;"/> (where we use <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cast" style="vertical-align: middle;"/> to represent Legendre transform with respect to the spatial variable).<br/><br/>Let's consider the case where from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f1" style="vertical-align: middle;"/> onwards the particle motion is free, so <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=V%3d0" style="vertical-align: middle;"/>. In this case we clearly have translation-invariance and so the time evolution is given by repeated inf-convolution with <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cphi" style="vertical-align: middle;"/> and in the "Legendre domain" this is nothing other than repeated addition of <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cphi%5e%5cast" style="vertical-align: middle;"/>.<br/><br/>Let's take a look at <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cphi" style="vertical-align: middle;"/>. We know that if a particle travels freely from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=x%5f1" style="vertical-align: middle;"/> to <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=x%5f2" style="vertical-align: middle;"/> over the period from <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f1" style="vertical-align: middle;"/> to <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f2" style="vertical-align: middle;"/> then it must have followed the minimum action path and we know, from basic mechanics, this is the path with constant velocity. So<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cdisplaystyle%7bT+%3d+%5cfrac%7b1%7d%7b2%7dm%28x%5f2-x%5f1%29%5e2%2f%28t%5f2-t%5f1%29%5e2%7d" style="vertical-align: middle;"/><br/></blockquote>and hence the action is given by<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cdisplaystyle%7b%5cphi%28s%29+%3d+%5cfrac%7b1%7d%7b2%7dms%5e2%2f%28t%5f2-t%5f1%29%7d" style="vertical-align: middle;"/><br/></blockquote>So the time evolution of <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cpsi" style="vertical-align: middle;"/> is given by repeated inf-convolution with a quadratic function. The time evolution of <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cpsi%5e%5cast" style="vertical-align: middle;"/> is therefore given by repeated addition of the Legendre transform of a quadratic function. It's not hard to prove that the Legendre transform of a quadratic function is also quadratic. In fact:<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cdisplaystyle%7b%5cphi%5e%5cast%28p%29+%3d+%5cfrac%7b1%7d%7b8%7dmp%5e2%28t%5f2-t%5f1%29%5e2%7d" style="vertical-align: middle;"/><br/></blockquote>Addition is easier to work with than inf-convolution so if we wish to understand the time evolution of the action function it's natural to work with this Legendre transformed function.<br/><br/>So that's it for classical mechanics in this post. I've tried to look at the evolution of a classical system in a way that makes the Legendre transform natural.<br/><br/><b>Free quantum particles</b><br/>Now I want to take a look at the evolution of a free quantum particle to show how similar it is to what I wrote above. In this case we have the Schrödinger equation<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cdisplaystyle%7bi%5chbar%5cfrac%7b%5cpartial%7d%7b%5cpartial+t%7d%5cpsi%28t%2cx%29+%3d+-%5cfrac%7b%5chbar%5e2%7d%7b2m%7d%5cfrac%7b%5cpartial%5e2%7d%7b%5cpartial+x%5e2%7d%5cpsi%28x%2ct%29%2bV%5cpsi%28t%2cx%29%7d" style="vertical-align: middle;"/><br/></blockquote>Let's suppose that from time <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=t%5f1" style="vertical-align: middle;"/> onwards the particle is free so <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=V%3d0" style="vertical-align: middle;"/>. Then we have<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cdisplaystyle%7bi%5chbar%5cfrac%7b%5cpartial%7d%7b%5cpartial+t%7d%5cpsi%28t%2cx%29+%3d+-%5cfrac%7b%5chbar%5e2%7d%7b2m%7d%5cfrac%7b%5cpartial%5e2%7d%7b%5cpartial+x%5e2%7d%5cpsi%28t%2cx%29" style="vertical-align: middle;"/><br/></blockquote>Now let's take the Fourier transform in the spatial variable. We get:<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cdisplaystyle%7bi%5chbar%5cfrac%7b%5cpartial%7d%7b%5cpartial+t%7d%5chat%7b%5cpsi%7d%28t%2ck%29+%3d+-%5cfrac%7b%5chbar%5e2%7d%7b2m%7d%28ik%29%5e2%5chat%7b%5cpsi%7d%28t%2ck%29" style="vertical-align: middle;"/><br/></blockquote>So<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cdisplaystyle%7b%5chat%7b%5cpsi%7d%28t%2ck%29+%3d+%5cexp%28%5cfrac%7bi%5chbar+k%5e2%28t-t%5f1%29%7d%7b2m%7d%29%5chat%7b%5cpsi%7d%28t%5f1%2ck%29" style="vertical-align: middle;"/><br/></blockquote>We can write this as<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cdisplaystyle%7b%5chat%7b%5cpsi%7d%28t%2ck%29+%3d+%5chat%7b%5cphi%7d%28k%29%5chat%7b%5cpsi%7d%28t%5f1%2ck%29" style="vertical-align: middle;"/><br/></blockquote>where<br/><blockquote><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5cphi%28x%29+%3d+%5cexp%28%5cfrac%7bix%5e2%7d%7b2%5chbar+m%7d%29" style="vertical-align: middle;"/><br/></blockquote>So the time evolution of the free quantum particle is given by repeated convolution with a Gaussian function which in the Fourier domain is repeated multiplication by a Gaussian. The classical section above is nothing but a <a href="http://ncatlab.org/nlab/show/tropical+semiring">tropical</a> version of this section.<br/><br/><b>Conclusion</b><br/>I doubt I've said anything original here. Classical mechanics is well known to be the limit of quantum mechanics as <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5chbar%5crightarrow+0" style="vertical-align: middle;"/> and it's well known that in this limit we find that occurrences of the semiring <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%28%5cmathbb%7bR%7d%2c%2b%2c%5ctimes%29" style="vertical-align: middle;"/> are replaced by the semiring <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%28%5cmathbb%7bR%7d%2c%5cmin%2c%2b%29" style="vertical-align: middle;"/>. But I've never seen an article that attempts to describe classical mechanics in terms of repeated inf-convolution even though this is close to Hamilton's formulation and I've never seen an article that shows the parallel with the Schrödinger equation in this way. I'm hoping someone will now be able to say to me "I've seen that before" and post a relevant link below.<br/><br/><b>Note</b><br/>I'm not sure how the above applies for a non-trivial potential <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=V" style="vertical-align: middle;"/>. I wrote this little Schrödinger <a href="http://homepage.mac.com/sigfpe/Harmonic/anharmonic.html">equation solver</a> a while back. As might be expected, it's inconvenient to use the Fourier domain to deal with the part of the evolution due to <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=V" style="vertical-align: middle;"/>. In order to simulate a time step of <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=dt" style="vertical-align: middle;"/> the code simulates <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=dt%2f2" style="vertical-align: middle;"/> in the Fourier domain assuming the particle is free and then spends <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=dt%2f2" style="vertical-align: middle;"/> solving for the <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=V" style="vertical-align: middle;"/>-dependent part in the spatial domain. So even in the presence of non-trivial <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=V" style="vertical-align: middle;"/> it can still be useful to work with a Fourier transform. Almost the same iteration could be used to numerically compute the action for the classical case.<div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/11295132-7973803066138768941?l=blog.sigfpe.com" width="1"/></div></div>
    </content>
    <updated>2012-01-22T00:34:54Z</updated>
    <published>2012-01-21T21:38:00Z</published>
    <author>
      <name>sigfpe</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/08096190433222340957</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-11295132</id>
      <category term="monad"/>
      <category term="mathematics"/>
      <category term="physics"/>
      <category term="optimisation"/>
      <category term="astronomy"/>
      <category term="self-reference"/>
      <category term="probability"/>
      <category term="comonads"/>
      <category term="haskell"/>
      <category term="types"/>
      <category term="programming"/>
      <category term="quantum"/>
      <author>
        <name>sigfpe</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/08096190433222340957</uri>
      </author>
      <link href="http://blog.sigfpe.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/11295132/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://blog.sigfpe.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <link href="http://www.blogger.com/feeds/11295132/posts/default?start-index=26&amp;max-results=25" rel="next" type="application/atom+xml"/>
      <title>A Neighborhood of Infinity</title>
      <updated>2012-02-07T22:05:28Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://chrisdone.com/posts/2012-01-22-ghc-upgrade.html</id>
    <link href="http://chrisdone.com/posts/2012-01-22-ghc-upgrade.html" rel="alternate" type="text/html"/>
    <title>Upgrading GHC</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>So this weekend I finally upgraded two large work projects from GHC 6.12.3! And I didn’t upgrade one up in some gradual nonsense, I jumped straight to GHC 7.2.2, the latest release, like a boss.</p><p>Why did I still have projects running on 6.12.3? GHC 6.12.3 is a two year old release, and the codebases I upgraded are also two years old. I have about 46 dependencies with specific constraints and some patched dependencies, which made the prospect of updating quite daunting. I didn’t really <em>need</em> to upgrade, the software I was writing worked.</p><p>Did I even try to uprade? Yes, I tried several times off-hand over the past months to upgrade my GHC but was met immediately with hard to grok Cabal complaints about version numbers. Not to mention some dependencies that just didn’t support the latest GHC. For a while I had genuinely thought it would be hopeless to upgrade these projects without tears.</p><p>Today I came back to it and decided that I’d start with an empty Cabal file and add dependencies incrementally until every one was satisfied, and then the project built. As far as GHC itself goes, separate from Cabal, I only had to add <code>BangPatterns</code> and <code>FlexibleInstances</code> to some files and it was happy.</p><p>Does this say anything about the stability of Haskell as a platform? I think so, a little. In the end it’s certainly easier for maintenance to keep up to date with the latest packages, and I think I will introduce this factor into the continuous integration system for my projects.</p><p>It also says that despite all the new stuff happening in Haskell, code is at least stable a few versions old. There were only a couple packages that I couldn’t use in GHC 6.12.3. It also says that GHC 6.12.3 was a very decent and stable release, having been using it in production for two years with no problems.</p><p>Now I’m quite excited about all the GHC features I’ve been missing out on that I’ll be able to start using. I have some reading to do, so I’ve opened up the release notes of 7.0.1, 7.0.2, 7.0.3, 7.0.4, 7.2.1, and 7.2.2, and <a href="http://www.haskell.org/pipermail/glasgow-haskell-users/2011-December/021310.html">the release notes of the upcoming 7.4</a>. I should also be able to try out the Scion package now, which is rather awesome.</p></div>
    </summary>
    <updated>2012-01-22T00:00:00Z</updated>
    <source>
      <id>http://chrisdone.com</id>
      <author>
        <name>Christopher Done</name>
      </author>
      <link href="http://chrisdone.com" rel="alternate" type="text/html"/>
      <link href="http://chrisdone.com/haskell.rss" rel="self" type="application/atom+xml"/>
      <subtitle>Chris Done's haskell posts</subtitle>
      <title>Chris Done's haskell posts</title>
      <updated>2012-02-10T03:22:23Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://joyridelabs.de/blog/?p=1179</id>
    <link href="http://joyridelabs.de/blog/?p=1179" rel="alternate" type="text/html"/>
    <link href="http://joyridelabs.de/blog/?p=1179#comments" rel="replies" type="text/html"/>
    <link href="http://joyridelabs.de/blog/?feed=atom&amp;p=1179" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">On Selling Nikki and the Robots’ Story Mode</title>
    <summary type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml"><p class="en"/><p>Episode 1 of the story mode is ready to be released and we are very excited! This will also mark the first public beta version.</p>

<p>We will start selling the story mode using a pay-what-you-want model, which is strongly inspired by the <a href="http://www.humblebundle.com/">Humble Indie Bundle</a> (which on the other hand was inspired by a <a href="http://2dboy.com/2009/10/19/birthday-sale-results/">World of Goo sale</a>). After one week we will then set a fixed minimum price.</p>

<p>When you buy the game, you pay for the game as it is, but will also get all further episodes and updates for free. With each further episode, however, the minimum price will increase for new buyers of the game. The sooner you buy, the less you pay, hooray! This is similar to the Alpha-Beta-1.0 price increments of <a href="http://web.archive.org/web/20101217223123/http://minecraft.net/prepurchase.jsp">Minecraft</a>.</p>
<p style="text-align: center;"><a href="http://joyridelabs.de/blog//wp-content/uploads/2012/01/vpp2n.jpg"><img alt="Joyride Labs Preorder Page Concept" class="aligncenter size-large wp-image-1190" height="512" src="http://joyridelabs.de/blog//wp-content/uploads/2012/01/vpp2n-423x1024.jpg" title="Joyride Labs Preorder Page Concept" width="212"/></a></p>

<p>Right now we are working hard on the presale website and we hope to be able to release Nikki and the Robots' story mode until mid February.</p>

<p><em>In the next post we will tell you some more details about episode 1, in which Nikki's great adventure begins to unfold.</em></p><p/></div>
    </summary>
    <content type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml"><p class="en"/><p>Episode 1 of the story mode is ready to be released and we are very excited! This will also mark the first public beta version.</p>

<p>We will start selling the story mode using a pay-what-you-want model, which is strongly inspired by the <a href="http://www.humblebundle.com/">Humble Indie Bundle</a> (which on the other hand was inspired by a <a href="http://2dboy.com/2009/10/19/birthday-sale-results/">World of Goo sale</a>). After one week we will then set a fixed minimum price.</p>

<p>When you buy the game, you pay for the game as it is, but will also get all further episodes and updates for free. With each further episode, however, the minimum price will increase for new buyers of the game. The sooner you buy, the less you pay, hooray! This is similar to the Alpha-Beta-1.0 price increments of <a href="http://web.archive.org/web/20101217223123/http://minecraft.net/prepurchase.jsp">Minecraft</a>.</p>
<p style="text-align: center;"><a href="http://joyridelabs.de/blog//wp-content/uploads/2012/01/vpp2n.jpg"><img alt="Joyride Labs Preorder Page Concept" class="aligncenter size-large wp-image-1190" height="512" src="http://joyridelabs.de/blog//wp-content/uploads/2012/01/vpp2n-423x1024.jpg" title="Joyride Labs Preorder Page Concept" width="212"/></a></p>

<p>Right now we are working hard on the presale website and we hope to be able to release Nikki and the Robots' story mode until mid February.</p>

<p><em>In the next post we will tell you some more details about episode 1, in which Nikki's great adventure begins to unfold.</em></p><p/></div>
    </content>
    <updated>2012-01-21T19:55:19Z</updated>
    <published>2012-01-21T19:53:53Z</published>
    <category scheme="http://joyridelabs.de/blog/" term="Uncategorized"/>
    <category scheme="http://joyridelabs.de/blog/" term="business"/>
    <category scheme="http://joyridelabs.de/blog/" term="indies"/>
    <category scheme="http://joyridelabs.de/blog/" term="mainstream"/>
    <category scheme="http://joyridelabs.de/blog/" term="nikki and the robots"/>
    <category scheme="http://joyridelabs.de/blog/" term="open source"/>
    <category scheme="http://joyridelabs.de/blog/" term="other"/>
    <category scheme="http://joyridelabs.de/blog/" term="planet-haskell"/>
    <category scheme="http://joyridelabs.de/blog/" term="press"/>
    <author>
      <name>Iwan</name>
    </author>
    <source>
      <id>http://joyridelabs.de/blog/?feed=atom</id>
      <link href="http://joyridelabs.de/blog/" rel="alternate" type="text/html"/>
      <link href="http://joyridelabs.de/blog/?feed=atom&amp;tag=planet-haskell" rel="self" type="application/atom+xml"/>
      <subtitle xml:lang="en">News from our Headquarters</subtitle>
      <title xml:lang="en">Joyride Laboratories » planet-haskell</title>
      <updated>2012-02-02T13:07:19Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-3734004713473160250.post-1067919966399482687</id>
    <link href="http://lambda-view.blogspot.com/feeds/1067919966399482687/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://lambda-view.blogspot.com/2012/01/talk-guided-tour-through-bytestring.html#comment-form" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/3734004713473160250/posts/default/1067919966399482687" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/3734004713473160250/posts/default/1067919966399482687" rel="self" type="application/atom+xml"/>
    <link href="http://lambda-view.blogspot.com/2012/01/talk-guided-tour-through-bytestring.html" rel="alternate" type="text/html"/>
    <title>Talk: A guided tour through the bytestring library</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">Yesterday, I held a talk about the <a href="http://hackage.haskell.org/package/bytestring">bytestring</a> library at the <a href="http://www.meetup.com/HaskellerZ/">Zurich HaskellerZ</a> meetup group. The goal of the talk was to enable the audience to write efficient code based on the bytestring library; i.e., explain enough about internals of the library and GHC such that they can judge the cost of the operations on bytestrings both in terms of time and space. The talk also covers the <a href="http://people.inf.ethz.ch/meiersi/downloads/private/bytestring-0.10.0.0-public/">new bytestring builder</a> (based on <a href="http://hackage.haskell.org/package/blaze-builder">blaze-builder</a>), which is currently under review for inclusion in the next release of the bytestring library.<br/><br/>Here are the <a href="http://meiersi.github.com/HaskellerZ/meetups/2012%2001%2019%20-%20The%20bytestring%20library/slides.html">slides</a> and their corresponding <a href="http://meiersi.github.com/HaskellerZ/meetups/2012%2001%2019%20-%20The%20bytestring%20library/handout.html">handout version</a> for interested readers.<div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/3734004713473160250-1067919966399482687?l=lambda-view.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2012-01-20T23:28:23Z</updated>
    <published>2012-01-20T23:26:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="haskell"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="bytestring"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="talk"/>
    <author>
      <name>Simon Meier</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/17873513558398372917</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-3734004713473160250</id>
      <category term="performance"/>
      <category term="bytestring"/>
      <category term="talk"/>
      <category term="blaze-builder"/>
      <category term="haskell"/>
      <author>
        <name>Simon Meier</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/17873513558398372917</uri>
      </author>
      <link href="http://lambda-view.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/3734004713473160250/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://lambda-view.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle>experience programming through a functional lens...</subtitle>
      <title>λ-view</title>
      <updated>2012-01-20T23:28:23Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://joaopizani.hopto.org/?p=1190</id>
    <link href="http://joaopizani.hopto.org/en/2012/01/haskell-kata-game-of-life/" rel="alternate" type="text/html"/>
    <title>Haskell Kata – Conway’s Game of Life</title>
    <summary>Hi everybody! Today I am going to write about another Code Kata experience I had using Haskell. This time the code didn't come directly from a Coding Dojo (live meeting with friends), but rather from an "enhancement" over the ...</summary>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p class="wp-flattr-button"/><p>Hi everybody! Today I am going to write about another <a href="http://codekata.pragprog.com">Code Kata</a> experience I had using Haskell. This time the code didn’t come directly from a Coding Dojo (live meeting with friends), but rather from an “enhancement” over the solution we wrote at a meeting.</p>
<p>In that Coding Dojo we wanted to solve the <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataGameOfLife">“Game Of Life”</a> problem. The goal was mainly to – given an initial configuration – evolve the world in one generation and print back this evolved state. For those of you who never heard about Conway’s Game of Life, its <a>article on Wikipedia</a> can be very clarifying.</p>
<p>So we did it, and we solved the problem, but – as always – I wanted very badly to try to solve the same problem using Haskell (instead of Python). At home, I coded it up in Haskell in around 30min, and the code was concise and elegant… In fact, this was so easy that I decided I needed some bigger challenge, something <strong>graphical</strong>, why not? Then I gave the awesome <a href="http://hackage.haskell.org/packages/archive/gloss/1.6.0.1/doc/html/Graphics-Gloss.html">Gloss</a> graphics library another chance, and I was AGAIN impressed with the results.<br/>
<span id="more-1190"/></p>
<p>So let’s start our Haskell Kata routine, by first describing the problem itself and then the beautiful Haskell solution…</p>
<h2>Problem Description</h2>
<p><em>(This problem description is blatantly copied from the correspondent Coding Dojo Wiki <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataGameOfLife">entry</a>, as of 2012-01-19)</em></p>
<p>This Kata is about calculating the next generation of Conway’s Game of Life, given any starting position. Take a look at <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">Wikipedia</a> for background.</p>
<p>You start with a two-dimensional grid of cells, where each cell is either alive or dead. In this version of the problem, the grid is finite, and no life can exist off the edges. When calculating the next generation of the grid, follow these rules:</p>
<ul>
<li>Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.</li>
<li>Any live cell with more than three live neighbours dies, as if by overcrowding.</li>
<li>Any live cell with two or three live neighbours lives on to the next generation.</li>
<li>Any dead cell with exactly three live neighbours becomes a live cell.</li>
</ul>
<p>You should write a program that can accept an arbitrary grid of cells, and will output a similar grid showing the next generation.</p>
<h3>Input and Output</h3>
<p>The input starting position is given through a text file that looks like this:</p>
<pre>........
....*...
...**...
........</pre>
<p>And the output could look like:</p>
<pre>........
...**...
...**...
........</pre>
<p>This format was chosen because it is very easily parsed in most languages. OBS: It is VERY, VERY easily parsed in Haskell :)</p>
<p> </p>
<h2>Proposed “solution” in Haskell</h2>
<p><strong>SPOILER ALERT: DO NOT KEEP READING if you want to try solving this problem for yourself.</strong></p>
<p>As I said in the beginning of the post, my code isn’t really a solution to the given problem, but rather an improvement over it. It improves a simple solution in two ways:</p>
<ol>
<li>It handles more than one generation. It is actually a live simulation</li>
<li>It has a graphical interface to display the simulation</li>
</ol>
<p>Even though the code is bigger (because of these enhancements) it is still very concise and readable, totaling some 150 lines of code (with lots of whitespace). And to keep it simple, we are going to start our tour of the solution by the module that deals with the “original” problem: we are going to look first at the functions to read and evolve the board for one generation. First of all, the parser for a starting position (imports omitted for brevity):</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="haskell"><pre class="de1">dead <span class="sy0">=</span> <span class="kw3">fmap</span> <span class="br0">(</span><span class="kw3">const</span> False<span class="br0">)</span> <span class="br0">(</span>char '<span class="sy0">.</span>'<span class="br0">)</span>
alive <span class="sy0">=</span> <span class="kw3">fmap</span> <span class="br0">(</span><span class="kw3">const</span> True<span class="br0">)</span> <span class="br0">(</span>char 'O'<span class="br0">)</span>
line <span class="sy0">=</span> many1 <span class="br0">(</span>dead  alive<span class="br0">)</span>
 
board ∷ Parser <span class="br0">[</span><span class="br0">[</span><span class="kw4">Bool</span><span class="br0">]</span><span class="br0">]</span>
board <span class="sy0">=</span> line `endBy1` newline
 
parseBoardFromFile ∷ FilePath → <span class="kw4">IO</span> <span class="br0">[</span><span class="br0">[</span><span class="kw4">Bool</span><span class="br0">]</span><span class="br0">]</span>
parseBoardFromFile filename <span class="sy0">=</span>
    <span class="kw1">do</span>  result ← parseFromFile board filename
        <span class="kw3">return</span> <span class="sy0">$</span> <span class="kw3">either</span> <span class="br0">(</span><span class="kw3">error</span> ∘ <span class="kw3">show</span><span class="br0">)</span> <span class="kw3">id</span> result</pre></div></div></div></div></div></div></div>


<p>Our parser was written using the easy-to-use, efficient and popular <a href="http://hackage.haskell.org/package/parsec-3.1.2">Parsec</a> library for Haskell, that allows us to describe a format to be recognized (a <strong>grammar</strong>) in Haskell itself, in a very readable and concise way. Parsec is a <strong>parser combinator</strong> library, which means that we build our “big” parser by combining smaller parsers, which are built by combining even smaller ones, and so on… until we reach the primitive parsers that come with Parsec like, for example, “char”, used to define the parser for a dead cell in the first line of the code above.</p>
<p>Indeed, the parsers “dead” (for a dead cell) and “alive” (for a live cell) are the most fundamental, and what they do is pretty simple: they <strong>map</strong> a dot or an upper-case ‘O’ to False or True, respectively. We can take a look at the type signatures of “char” and “fmap” if we want to know more precisely what they do:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="haskell"><pre class="de1"><span class="kw3">fmap</span> ∷ <span class="br0">(</span>a → b<span class="br0">)</span> → f a → f b
char ∷ <span class="kw4">Char</span> → Parser <span class="kw4">Char</span>
<span class="sy0">...</span>
<span class="kw3">map</span> ∷ <span class="br0">(</span>a → b<span class="br0">)</span> → <span class="br0">[</span>a<span class="br0">]</span> → <span class="br0">[</span>b<span class="br0">]</span></pre></div></div></div></div></div></div></div>


<p>First of all, let’s talk about “char”. The exact type of “char” (as in the <a href="http://hackage.haskell.org/packages/archive/parsec/3.1.2/doc/html/Text-Parsec-Char.html#v:char">Parsec documentation</a>) is more general and uses type classes. The type shown above, however, is a valid specialization of the general type, suiting our usage. You can see that “char” takes a character and gives us a <strong>Parser that recognizes</strong> that character. However, we want “dead” to be of type <em>Parser Bool</em>, that is, a parser that returns a boolean; so we need a function that converts <em>Parser Char</em> to <em>Parser Bool</em>… And that’s the point where <a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base-4.4.1.0/Control-Monad.html#v:fmap">“fmap”</a> comes to help us!</p>
<p>You can see that not only the name, but also the type of “fmap” is very similar to that of “map”. In fact, “fmap” is a generalization of “map”: while “map” works only over lists, “fmap” works over any container. Well, then “fmap” is applicable to our situation, that’s because anything of type <em>Parser a</em> is a monad, and any monad is a container (<em>the fancy word for container is <a href="http://learnyouahaskell.com/making-our-own-types-and-typeclasses#the-functor-typeclass">“Functor”</a></em>). The last interesting detail is the function that we map over (char ‘.’) and (char ‘O’): The usage of “const” means that <strong>we don’t care about what the Parser returns</strong>, as long as it succeeds, we return either a True or a False.</p>
<p>The remaining parser code is even simpler; the top-level function in the parser module (“parseBoardFromFile”) is the only one that still deserves some commentary:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="haskell"><pre class="de1">parseBoardFromFile ∷ FilePath → <span class="kw4">IO</span> <span class="br0">[</span><span class="br0">[</span><span class="kw4">Bool</span><span class="br0">]</span><span class="br0">]</span>
parseBoardFromFile filename <span class="sy0">=</span>
    <span class="kw1">do</span>  result ← parseFromFile board filename
        <span class="kw3">return</span> <span class="sy0">$</span> <span class="kw3">either</span> <span class="br0">(</span><span class="kw3">error</span> ∘ <span class="kw3">show</span><span class="br0">)</span> <span class="kw3">id</span> result</pre></div></div></div></div></div></div></div>


<p>This function takes a file name as input (<em>FilePath</em> is just a synonym for <em>String</em>) and performs some IO actions (reading the file and parsing its contents). As a result of these actions, it returns a matrix of booleans (that is, our <em>Board</em> \o/). The function <a href="http://hackage.haskell.org/packages/archive/parsec/3.1.2/doc/html/Text-Parsec-ByteString.html#v:parseFromFile">“parseFromFile”</a> comes from Parsec, and it does exactly what its name says, with a return type of <em>Either ParseError [[Bool]]</em>. Because “result” has this type, we use the <a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base-4.4.1.0/Data-Either.html#v:either">“either”</a> function in the next line. The “either” function is used whenever you need to <strong>decide what to do based on a value of type <em>Either</em></strong>. In our case, if the result is a correctly parsed matrix, we return it as-is (that’s what “id” does for us). But if it’s an erroneous parse, then we convert the ParseError to a string and terminate the program showing the error message (that’s what “(error ∘ show)” does for us).</p>
<p>Enough for parsing now, and on to what really matters: evolving a board one generation. We take care of this task in the Evolution module. The most important functions of this module are “evolve” and “eval”. “eval” is given a position on the board and returns whether the cell in that position should be dead or alive, based on its surroundings. “evolve” is given a board and just applies “eval” all over it to create the next-generation board. With one important consideration: it only looks at the inner cells in the board, i.e, all border cells are considered <strong>always dead</strong>. Here’s the code for “eval” and “evolve”:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="haskell"><pre class="de1">evolve ∷ Board → Board
evolve b <span class="sy0">=</span> dummyLine : newKernel <span class="sy0">++</span> <span class="br0">[</span>dummyLine<span class="br0">]</span>
    <span class="kw1">where</span>
        <span class="br0">(</span>ls<span class="sy0">,</span>cs<span class="br0">)</span> <span class="sy0">=</span> <span class="br0">(</span><span class="kw3">length</span> b<span class="sy0">,</span> <span class="kw3">length</span> <span class="sy0">$</span> <span class="kw3">head</span> b<span class="br0">)</span>
        <span class="br0">(</span>innerLs<span class="sy0">,</span>innerCs<span class="br0">)</span> <span class="sy0">=</span> <span class="br0">(</span><span class="br0">[</span><span class="nu0">1</span> <span class="sy0">..</span> ls<span class="sy0">-</span><span class="nu0">2</span><span class="br0">]</span><span class="sy0">,</span> <span class="br0">[</span><span class="nu0">1</span> <span class="sy0">..</span> cs<span class="sy0">-</span><span class="nu0">2</span><span class="br0">]</span><span class="br0">)</span>
        dummyLine <span class="sy0">=</span> replicate cs False
        dummyCel  <span class="sy0">=</span> False
        newKernel <span class="sy0">=</span> <span class="br0">[</span>dummyCel : <span class="br0">[</span>eval b l c <span class="sy0">|</span> c ← innerCs<span class="br0">]</span> <span class="sy0">++</span> <span class="br0">[</span>dummyCel<span class="br0">]</span>  <span class="sy0">|</span>  l ← innerLs<span class="br0">]</span>
 
eval ∷ Board → <span class="kw4">Int</span> → <span class="kw4">Int</span> → <span class="kw4">Bool</span>
eval b l c
    <span class="sy0">|</span> n &amp;lt; <span class="nu0">2</span> <span class="sy0">||</span> n &amp;gt; <span class="nu0">3</span>  <span class="sy0">=</span> False
    <span class="sy0">|</span> n <span class="sy0">==</span> <span class="nu0">3</span>          <span class="sy0">=</span> True
    <span class="sy0">|</span> <span class="kw3">otherwise</span>       <span class="sy0">=</span> b <span class="sy0">!!</span> l <span class="sy0">!!</span> c
        <span class="kw1">where</span> n <span class="sy0">=</span> aliveNeighbours b l c</pre></div></div></div></div></div></div></div>


<p>The function “aliveNeighbours” takes a board and a pair of coordinates, returning <strong>how many</strong> of the 8 surrounding cells are alive. Its definition is pretty boring and straightforward, so I won’t explain it – you’ll have to believe that it works :)</p>
<p>So, the code that we saw so far almost solves the original Kata problem – we only needed to add some pretty-printing of the board… BUT! But we are going to do something much nicer, much cooler: we are going to display our simulation in a graphical interface, like this:</p>
<div class="wp-caption aligncenter" style="width: 436px;"><img alt="" height="211" src="http://i.imgur.com/jCLp2.gif" title="Gosper Glider Gun" width="426"/><p class="wp-caption-text">The "Gosper glider gun" o/o/o/</p></div>
<p>Before getting too excited, I have to warn you: the module dealing with drawing the graphics is the largest one (It has around 50 lines of code). However, if you run the program for yourself and watch the AWESOME resulting simulation, you’ll realize that 50 lines is a <strong>very good mark :)</strong></p>
<p>Anyways, 50 lines is still too much to be embedded in a blog post, so I’ll only give you the highlights – namely, the functions “drawModel”, “layout” and “activate”. Here’s their code:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="haskell"><pre class="de1">drawModel ∷ Board → Picture
drawModel b <span class="sy0">=</span> <span class="br0">(</span>layoutY ∘ layoutX<span class="br0">)</span> <span class="sy0">$</span> activate b <span class="sy0">$</span> rawMatrix
    <span class="kw1">where</span>
        <span class="br0">(</span>l<span class="sy0">,</span>c<span class="br0">)</span> <span class="sy0">=</span> <span class="br0">(</span><span class="kw3">length</span> b<span class="sy0">,</span> <span class="kw3">length</span> <span class="sy0">$</span> <span class="kw3">head</span> b<span class="br0">)</span> 
        rawMatrix <span class="sy0">=</span> replicate l <span class="sy0">$</span> replicate c <span class="sy0">$</span> cell
        layoutX <span class="sy0">=</span> <span class="kw3">map</span> <span class="br0">(</span>pictures ∘ layout DirX<span class="br0">)</span>
        layoutY <span class="sy0">=</span> pictures ∘ layout DirY
 
layout ∷ LayoutDirection → <span class="br0">[</span>Picture<span class="br0">]</span> → <span class="br0">[</span>Picture<span class="br0">]</span>
layout dir pics <span class="sy0">=</span> <span class="br0">[</span>move dir middle i p <span class="sy0">|</span> <span class="br0">(</span>i<span class="sy0">,</span>p<span class="br0">)</span> ← <span class="kw3">zip</span> <span class="br0">[</span><span class="nu0">0</span><span class="sy0">..</span><span class="br0">(</span>n<span class="sy0">-</span><span class="nu0">1</span><span class="br0">)</span><span class="br0">]</span> pics<span class="br0">]</span>
    <span class="kw1">where</span>
        n <span class="sy0">=</span> <span class="kw3">length</span> pics
        middle <span class="sy0">=</span> <span class="kw3">fromIntegral</span> <span class="sy0">$</span> <span class="kw3">floor</span> <span class="br0">(</span><span class="kw3">fromIntegral</span> n <span class="sy0">/</span> <span class="nu0">2</span><span class="br0">)</span>
 
activate ∷ Board → <span class="br0">[</span><span class="br0">[</span>Picture<span class="br0">]</span><span class="br0">]</span> → <span class="br0">[</span><span class="br0">[</span>Picture<span class="br0">]</span><span class="br0">]</span>
activate board <span class="sy0">=</span> applyFunctionMatrix <span class="br0">(</span>paintersFromBoard board<span class="br0">)</span>
    <span class="kw1">where</span>
        paintersFromBoard <span class="sy0">=</span> <span class="kw3">map</span> <span class="br0">(</span><span class="kw3">map</span> painter<span class="br0">)</span>
        painter active <span class="sy0">=</span> <span class="kw1">if</span> active <span class="kw1">then</span> paintActive <span class="kw1">else</span> paintInactive</pre></div></div></div></div></div></div></div>


<p>Let’s begin with the easiest one: “activate” takes a matrix of pictures (all of them are squares) and assigns a color to each one, with the color depending on whether that position of the matrix is active or not in the underlying Game of Life board. The way in which we implemented “activate” is VERY typical in functional programming, and benefits largely from lazy evaluation. First, we apply “paintersFromBoard”, which has type:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="haskell"><pre class="de1">paintersFromBoard ∷ <span class="br0">[</span><span class="br0">[</span><span class="kw4">Bool</span><span class="br0">]</span><span class="br0">]</span> → <span class="br0">[</span><span class="br0">[</span>Picture → Picture<span class="br0">]</span><span class="br0">]</span></pre></div></div></div></div></div></div></div>


<p>It takes the board and transforms it into a <strong>matrix of functions</strong>. More specifically, each function in this matrix is a painter, transforming a picture into a new one by changing its color. Now we have two things to combine:</p>
<ol>
<li>A matrix of default-colored squares (by default they are all black)</li>
<li>A matrix of “painter functions”, one for each square</li>
</ol>
<p>To combine these, we use “applyFunctionMatrix” (not shown above). Its definition is very straightforward, but also very typical of functional programming languages. We define “applyFunctionMatrix” by “lifting” the usage of “applyFunctionList” to the outer list of the matrix (the list of lines). “applyFunctionList” is beautifully defined as follows:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="haskell"><pre class="de1">applyFunctionList ∷ <span class="br0">[</span><span class="br0">[</span>a → b<span class="br0">]</span><span class="br0">]</span> → <span class="br0">[</span><span class="br0">[</span>a<span class="br0">]</span><span class="br0">]</span> → <span class="br0">[</span><span class="br0">[</span>b<span class="br0">]</span><span class="br0">]</span>
applyFunctionList fs xs <span class="sy0">=</span> <span class="br0">[</span>f x <span class="sy0">|</span> <span class="br0">(</span>f<span class="sy0">,</span>x<span class="br0">)</span> ← <span class="kw3">zip</span> fs xs<span class="br0">]</span></pre></div></div></div></div></div></div></div>


<p>Continuing in the Drawing module, we reach “layout”. The purpose of this function is to – given a list of “unplaced” pictures (all overlapping each other) – spread them with some padding between each other so that they fill a horizontal or vertical line. We want the resulting “array” of pictures to be centered around the point where all overlapping pictures <strong>currently are</strong> – that’s why we calculate the “middle” index as being half of the list’s length. We then use “move” to displace each picture by “i” steps in direction “dir”. The “move” function knows the size of the cells, so we only need to pass it how many “steps” we want to displace a cell, and a pixel-exact translation will be done for us.</p>
<p>At last, the most important function in the drawing module – the core of the simulation: “drawModel”. Its type, <em>Board → Picture</em>, already tells us how much important it is. At each simulation step, the model is transformed by a call to “evolve”; then, our function “drawModel” is called by the <a href="http://hackage.haskell.org/packages/archive/gloss/1.6.0.1/doc/html/Graphics-Gloss-Interface-Simulate.html">Gloss Simulation Engine</a> to render to model into a Picture. The definition is a simple pipeline with the following steps:</p>
<ol>
<li>Create a l × c matrix of same-sized squares – by default they are all black and placed at (0,0)</li>
<li>Paint the squares according to the model</li>
<li>Place them – equally spaced – in a nice grid</li>
</ol>
<p>Ladies and gentlemen, having understood how to do a simulation step (“evolve”) and how to display the model (“drawModel”), we are almost DONE. I am only going to show you how the <a href="http://hackage.haskell.org/packages/archive/gloss/1.6.0.1/doc/html/Graphics-Gloss-Interface-Simulate.html#v:simulate">“simulate”</a> function from Gloss connects these pieces together. Our main function is basically just a call to “simulate”, like this:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="haskell"><pre class="de1">main <span class="sy0">=</span> 
    <span class="kw1">do</span>  args ← getArgs
        <span class="kw1">let</span> fps <span class="sy0">=</span> <span class="kw3">read</span> <span class="br0">(</span><span class="kw3">head</span> args<span class="br0">)</span>
        <span class="co1">-- reads input here</span>
        simulate display bg fps initial drawModel <span class="br0">(</span>\<span class="sy0">_</span> <span class="sy0">_</span> → evolve<span class="br0">)</span>
 
bg <span class="sy0">=</span> greyN <span class="nu0">0.95</span>
display <span class="sy0">=</span> InWindow <span class="st0">"Conway's Game of Life"</span> windowSize windowPosition</pre></div></div></div></div></div></div></div>


<p>The <a>“simulate”</a> function takes 6 parameters, and while it might seem too much, they all actually make sense:</p>
<ol>
<li><strong>display:</strong> defines how gloss is going to show the simulation – the size and position of the window, etc.</li>
<li><strong>bg:</strong> background color for the drawing area</li>
<li><strong>fps:</strong> how many simulation steps happen in one second of real time</li>
<li><strong>initial:</strong> the initial model (that we read from the file)</li>
<li><strong>drawModel:</strong> a function that transforms the model into a <em>Picture</em></li>
<li><strong>step function:</strong> a function to advance the model one iteration. We use the lambda to ignore some parameters that are irrelevant for us</li>
</ol>
<p>THAT’S IT! TADA! Now we are done. As always, you can download the <em>cabalized</em> package with the source code <a href="http://joaopizani.hopto.org/wp-content/uploads/2012/01/GlossGameOfLife.tar.gz">GlossGameOfLife</a>, build and run it as follows:</p>
<pre>$ tar xzf GlossGameOfLife.tar.gz
$ cd GlossGameOfLife
$ cabal-dev install</pre>
<p>Have fun!</p>
 <p><a href="http://joaopizani.hopto.org/?flattrss_redirect&amp;id=1190&amp;md5=11a17b0e7b24ae18e99440831c3ed821" target="_blank" title="Flattr"><img alt="flattr this!" src="http://joaopizani.hopto.org/wp-content/plugins/flattr/img/flattr-badge-large.png"/></a></p></div>
    </content>
    <updated>2012-01-20T19:42:11Z</updated>
    <category term="Computa&#xE7;&#xE3;o"/>
    <category term="Haskell"/>
    <category term="game of life"/>
    <category term="gloss"/>
    <category term="haskell kata"/>
    <category term="kata"/>
    <author>
      <name>João Paulo</name>
    </author>
    <source>
      <id>http://joaopizani.hopto.org</id>
      <link href="http://joaopizani.hopto.org/category/haskell/feed/" rel="self" type="application/atom+xml"/>
      <link href="http://joaopizani.hopto.org" rel="alternate" type="text/html"/>
      <subtitle>Pensamentos aleatórios… Linux, Computação, Música, Política…</subtitle>
      <title>Experimento imaginário » Haskell</title>
      <updated>2012-01-25T20:22:39Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://leepike.wordpress.com/?p=513</id>
    <link href="http://leepike.wordpress.com/2012/01/19/whos-afraid-of-software/" rel="alternate" type="text/html"/>
    <link href="http://leepike.wordpress.com/2012/01/19/whos-afraid-of-software/#comments" rel="replies" type="text/html"/>
    <link href="http://leepike.wordpress.com/2012/01/19/whos-afraid-of-software/feed/atom/" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">Who’s Afraid of Software?</title>
    <summary type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml">Who’s afraid of software?  I mean viscerally, stomach-knotting afraid.  Afraid like you might be when you come across a snake or a bear, or when you are mugged.  Do you obsess about a phishing attack each time you open your email?  Do you worry there’s an eavesdropper when you join the open wifi access point [...]<img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=leepike.wordpress.com&amp;blog=7358124&amp;post=513&amp;subd=leepike&amp;ref=&amp;feed=1" width="1"/></div>
    </summary>
    <content type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml"><p>Who’s afraid of software?  I mean viscerally, stomach-knotting afraid.  Afraid like you might be when you come across a snake or a bear, or when you are mugged.  Do you obsess about a phishing attack each time you open your email?  Do you worry there’s an eavesdropper when you join the open wifi access point in a coffee shop?  Do you worry your software will fail in your modern automobile or aircraft?</p>
<p>I listened to a <a href="http://www.freakonomics.com/2011/11/23/the-truth-is-out-there%E2%80%A6isn%E2%80%99t-it-a-new-freakonomics-radio-podcast/">Freakonomics podcast</a> about risk, uncertainty, and beliefs.  One point made during the show was that our fears are shaped by evolution—to our ancestors, it made sense to be afraid of threatening animals.  In modern life, however, our fears don’t match risks—we’d be much better off being afraid of cheeseburgers, as pointed out in the show.  Some people are afraid of modern risks.  I know people afraid of cancer, for example.</p>
<p>That got me thinking about fearing software.  Software is certainly among the most complex artifacts created by humans.  Modern <a href="http://spectrum.ieee.org/green-tech/advanced-cars/this-car-runs-on-code">cars contain 100+ million lines of code</a>.  Nearly every day there is a story about a large corporation being hacked and of <a href="http://en.wikipedia.org/wiki/Iran%E2%80%93U.S._RQ-170_incident">cyber-warfare</a> between nations.</p>
<p>My question is serious—I really do wonder if people are genuinely afraid of software.  I work in the area of software assurance, and while I take precautions against viruses, phishing attacks, etc., I don’t particularly worry about software failures, even when my life might depend on it.  This is despite issues just last year like <a href="http://www.telegraph.co.uk/motoring/8841996/Jaguar-recalls-cars-after-cruise-control-fault.html">this</a> and <a href="http://blogs.computerworld.com/15547/toyotas_lesson_software_can_be_unsafe_at_any_speed">this</a> in automotive software.  I get to see a somewhat how the sausage is made, and in general, we only exercise a small fraction of the state-space of deployed software in validation and in actual usage.  There are legitimate risks, but there seems to be very little fear.</p>
<p>Perhaps like a medical doctors stereotypically neglecting their own health, I don’t worry day-to-day about software assurance despite working in the field.  But it seems nobody else really fears software, either.</p>
<p>In the podcast, the topic of polarizing claims, like global warming, is discussed.  Outside of academic circles, one’s view on the risks of software are not so polarizing—your views on the topic won’t cause your friends or colleagues to disparage you (indeed, if anything, the main risk is likely boring others in discussing the topic!).  I wonder just what the “global warming” of software might be in the future.</p>
<br/>  <a href="http://feeds.wordpress.com/1.0/gocomments/leepike.wordpress.com/513/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/leepike.wordpress.com/513/"/></a> <a href="http://feeds.wordpress.com/1.0/godelicious/leepike.wordpress.com/513/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/leepike.wordpress.com/513/"/></a> <a href="http://feeds.wordpress.com/1.0/gofacebook/leepike.wordpress.com/513/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/leepike.wordpress.com/513/"/></a> <a href="http://feeds.wordpress.com/1.0/gotwitter/leepike.wordpress.com/513/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/leepike.wordpress.com/513/"/></a> <a href="http://feeds.wordpress.com/1.0/gostumble/leepike.wordpress.com/513/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/leepike.wordpress.com/513/"/></a> <a href="http://feeds.wordpress.com/1.0/godigg/leepike.wordpress.com/513/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/leepike.wordpress.com/513/"/></a> <a href="http://feeds.wordpress.com/1.0/goreddit/leepike.wordpress.com/513/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/leepike.wordpress.com/513/"/></a> <img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=leepike.wordpress.com&amp;blog=7358124&amp;post=513&amp;subd=leepike&amp;ref=&amp;feed=1" width="1"/></div>
    </content>
    <updated>2012-01-20T06:46:03Z</updated>
    <published>2012-01-20T06:46:03Z</published>
    <category scheme="http://leepike.wordpress.com" term="Software"/>
    <category scheme="http://leepike.wordpress.com" term="fear"/>
    <category scheme="http://leepike.wordpress.com" term="risk"/>
    <author>
      <name>Lee Pike</name>
      <uri>http://www.cs.indiana.edu/~lepike/</uri>
    </author>
    <source>
      <id>http://leepike.wordpress.com/feed/atom/</id>
      <link href="http://leepike.wordpress.com" rel="alternate" type="text/html"/>
      <link href="http://leepike.wordpress.com/feed/atom/" rel="self" type="application/atom+xml"/>
      <link href="http://leepike.wordpress.com/osd.xml" rel="search" type="application/opensearchdescription+xml"/>
      <link href="http://wordpress.com/opensearch.xml" rel="search" type="application/opensearchdescription+xml"/>
      <link href="http://leepike.wordpress.com/?pushpress=hub" rel="hub" type="text/html"/>
      <subtitle xml:lang="en">Thoughts on safe and secure embedded computer systems</subtitle>
      <title xml:lang="en">A Critical Systems Blog</title>
      <updated>2012-02-01T07:30:48Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-2267747408703654731.post-8137870764380768166</id>
    <link href="http://pchiusano.blogspot.com/feeds/8137870764380768166/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://www.blogger.com/comment.g?blogID=2267747408703654731&amp;postID=8137870764380768166" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/2267747408703654731/posts/default/8137870764380768166" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/2267747408703654731/posts/default/8137870764380768166" rel="self" type="application/atom+xml"/>
    <link href="http://pchiusano.blogspot.com/2012/01/possible-projects-for-boston-haskell.html" rel="alternate" type="text/html"/>
    <title>Possible projects for Boston Haskell Hackathon: smarter evaluation strategies and refactoring combinators</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>This weekend I'm going to be participating in the <a href="http://www.haskell.org/haskellwiki/Hac_Boston">Boston Haskell hackathon</a>. I'm very excited about it and I have a couple idea for projects to work on. If any of these sound interesting or you are thinking of something similar, I'm looking for people to collaborate with! Send me an email or come talk to me in person! I think I'm going to get there sometime in the late afternoon to early evening on Friday and I'll be around all weekend.</p><h2 id="evaluation-strategies-for-haskell-that-dont-leak-space">Evaluation strategies for Haskell that don't leak space</h2><p>The first project is doing some research / prototyping of an alternate evaluation strategy with the same termination properties as normal order evaluation, but with much easier reasoning about space usage. For lack of a better name, I'm calling it <em>specializing, strictness-propagating evaluation</em>. In this model, calling a function is something like two communicating coroutines. When calling a function, the callee begins evaluating its body, yielding control back to the caller when it needs its first argument, and also indicating whether that argument should be strict or lazily passed, using whatever information is available at runtime. Subsequent arguments work similarly. As a result, functions are automatically specialized as arguments are passed, and we do not construct thunks if they are going to be consumed strictly by a subsequent callee. This can be implemented efficiently using just two call stacks, and there are various optimizations to the scheme. It is intended to augment, not replace, the existing static strictness analysis and argument passing.</p><p>Here's an example working through this for the <code>if</code> function, which let's assume has the following implementation:</p><pre><code>foldl f z l = case l of <br/>  [] -&gt; z<br/>  h:t -&gt; foldl t f (f z h)<br/></code></pre><p>I'm also going to assume we've done some static strictness analysis to determine that all branches evaluate <code>z</code> and that therefore the <code>h:t</code> branch evaluates <code>f</code> (since all branches evaluate <code>z</code> and in the <code>h:t</code> case, <code>f</code> appears at the head of an expression passed as <code>z</code>). Suppose we call this with <code>foldl (+) 0 [1,2,3,4]</code>.</p><ol style=""><li>Caller pushes <code>foldl</code> onto the call stack. <code>foldl</code> begins evaluating with no arguments. It gets as far as the <code>case l</code>. It will then request <code>l</code> strictly, since it is about to evaluated it anyway.</li><li>To request the argument, <code>foldl</code> pops its currently running frame from the call stack and pushes it onto the <em>save stack</em>. It then resumes the caller now at the top of the call stack with an argument of <code>strict</code>.</li><li>The caller passes the argument as requested - if the caller were itself receiving these arguments as function parameters, it would propagate the strictness request of <code>foldl</code> to <em>its</em> caller.</li><li>To resume <code>foldl</code>, it pops <code>foldl</code> from the save stack and pushes it onto the call stack, giving it the (strictly evaluated) list it requested.</li><li>Now we hit the interesting case: inside the <code>h:t</code> branch, we know that <code>z</code> is strict (this is known statically). We also know that <code>f</code> can now be evaluated, so we request this argument strictly from our caller. With <code>f</code> now evaluated, we can propagate its stricness information. We know we will be evaluating <code>f z h</code> - what we did not know until runtime was that <code>f</code> was plus (let's just say it was <code>+</code> specialized to <code>Int</code>), and therefore static SA has no choice but to pass <code>f z h</code> as a thunk. We now know that <code>f</code> is strict in both its arguments, so the call to <code>f z h</code> means we can fully evaluate <code>z</code> (which we do by requesting <code>z</code> strictly from our caller), <code>h</code>, and then <code>f z h</code>.</li></ol><p>Each step of the iteration works similarly and <code>foldl</code> ends up running in constant space. I'm handwaving a lot here, but in general I want an evaluation order that is totally predictable in its space usage - values are immediately forced as soon as their consuming functions are known at runtime. The consuming functions tell us if an argument will ultimately be forced so we find out sooner rather than building up enormous thunks.</p><p>This needs some serious whiteboarding, but assuming it is at all sensible, here's what I propose doing:</p><ul><li>Come up with an instruction set for this evaluation model, and write a simple interpreter for it</li><li>Write a compiler for a toy functional language to this instruction set, including the basic static analysis needed to kickstart the dynamic analysis</li><li>Try writing some programs with it</li></ul><p>Some other interesting ideas - I wonder if there's some way to embed this evaluation model in GHC itself.</p><h2 id="a-code-database-for-haskell-and-refactoring-combinators">A code database for Haskell and refactoring combinators</h2><p>The other project I'm interested in working on is a code database for Haskell, and a <a href="http://en.wikipedia.org/wiki/Datalog">Datalog</a> interpreter to go with it. Using this database and the datalog query language, I then want to implement a set of <em>refactoring combinators</em>. A "refactoring" is simply a <em>compilation-preserving</em> function from one code database to another. I've started tinkering with a set of combinators that individually preserve compilation and can be composed to allow arbitrary code transformations. I wrote up some ideas for that <a href="http://pchiusano.blogspot.com/2011/12/future-of-programming.html">here</a>:</p><blockquote><p>... Refactoring times in this new model will go from weeks or months to hours, and writing code to transform a codebase will become a separate but critical skill, distinct from the usual act of programming. That is, programmers do not simply conceive of a refactoring (which is often quite simple to express to another programmer), then begin a tedious, manual and error-prone process of text munging to implement it. Instead, the programmer conceives of a refactoring, then conceives of a code transforming program to implement the refactoring, then applies this transformation to the code database, all in the span of a few hours.</p></blockquote><blockquote><p>... First, I am not advocating for datalog syntax. I don't care about that. The key functionality enabled by datalog over and above the relational algebra is the ability to express transitive closure and mutual recursion guaranteed to terminate. Together these features enable many of the common queries we'd like to express in transforming and querying our codebases. For instance, here is a hypothetical query to find all references to a given function id, fid. Don't worry if the syntax looks alien or doesn't make sense. The key is more that this query is just a few lines of code to express, and it can be reused and built upon.</p></blockquote><blockquote><pre><code>-- propagate reference to containing apply<br/>refs(Id) :- apps(Id, fid, _). <br/>refs(Id) :- apps(Id, _, fid).<br/>refs(Id) :- refs(X), apps(Id,X,_).<br/>refs(Id) :- refs(X), apps(Id,_,X).<br/>-- any lambda whose body is or contains fid<br/>-- is considered to reference fid<br/>return(Id) :- lambdas(Id,_,Id1), refs(Id1).<br/>return(Id) :- lambdas(Id,_,fid).<br/></code></pre></blockquote><p>Much of the analysis required to implement refactorings has this sort of "transitive-closure" feel to it - you need to do something to the "direct" callers, then do some transformation for their callers as necessary, and so on.</p><p>Here's what I propose for this project:</p><ul><li>Implement datalog, possibly backed by just in-memory data structures, or maybe tied to something like SQLite. Or if there's an existing free datalog interpreter and backend for it somewhere, let's see if we can use that.</li><li>Come up with the normalized datalog representation for the Haskell AST and type information - besides just the AST I think you'll need to know all the type information. Is there some way to use the GHC API to get the type of all expressions in the</li><li>Implement or steal a Haskell parser, and write code to translate this to the normalized datalog representation. As a proof of concept, take some existing Haskell project and "code-database-ify" it.</li><li>Come up with a good set of refactoring combinators. Implement them using datalog. As a proof of concept, use the combinators to express some nontrivial refactoring (like - make this value monadic rather than pure, and propagate the change in calling convention to all direct and indirect callers as needed - this is exactly the sort of refactoring that is trivial to describe to another Haskell programmer, and is totally mechanical, but is still done via a tedious process of text munging)</li></ul><p>If all this is too much, I propose not doing this for Haskell but instead for a toy functional language with a very simple AST and type system.</p><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/2267747408703654731-8137870764380768166?l=pchiusano.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2012-01-20T01:07:54Z</updated>
    <published>2012-01-19T15:57:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="haskell"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="programming"/>
    <author>
      <name>Paul Chiusano</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/04844651950877109501</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-2267747408703654731</id>
      <category term="mathematics"/>
      <category term="economics"/>
      <category term="scala"/>
      <category term="health"/>
      <category term="haskell"/>
      <category term="politics"/>
      <category term="programming"/>
      <author>
        <name>Paul Chiusano</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/04844651950877109501</uri>
      </author>
      <link href="http://pchiusano.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/2267747408703654731/posts/default/-/haskell" rel="self" type="application/atom+xml"/>
      <link href="http://pchiusano.blogspot.com/search/label/haskell" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle>(Stuff worth thinking about)</subtitle>
      <title>Prettt-tty, pretty, pretty good!</title>
      <updated>2012-01-27T08:48:12Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://patternsinfp.wordpress.com/?p=227</id>
    <link href="http://patternsinfp.wordpress.com/2012/01/19/comprehensions/" rel="alternate" type="text/html"/>
    <link href="http://patternsinfp.wordpress.com/2012/01/19/comprehensions/#comments" rel="replies" type="text/html"/>
    <link href="http://patternsinfp.wordpress.com/2012/01/19/comprehensions/feed/atom/" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">Comprehensions</title>
    <summary type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml">Prompted by some recent work I’ve been doing on reasoning about monadic computations, I’ve been looking back at the work from the 1990s by Phil Trinder, Limsoon Wong, Leonidas Fegaras, Torsten Grust, and others, on monad comprehensions as a framework … <a href="http://patternsinfp.wordpress.com/2012/01/19/comprehensions/">Continue reading <span class="meta-nav">→</span></a><img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=patternsinfp.wordpress.com&amp;blog=15593982&amp;post=227&amp;subd=patternsinfp&amp;ref=&amp;feed=1" width="1"/></div>
    </summary>
    <content type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml"><p>
 Prompted by some recent work I’ve been doing on <a href="http://www.cs.ox.ac.uk/publications/publication4877-abstract.html">reasoning about monadic computations</a>, I’ve been looking back at the work from the 1990s by Phil Trinder, Limsoon Wong, Leonidas Fegaras, Torsten Grust, and others, on monad comprehensions as a framework for database queries. </p>
<p>
The idea goes back to <a href="http://patternsinfp.wordpress.com/2011/02/15/universal-properties-and-galois-connections/">the adjunction between extension and intension</a> in set theory—you can define a set by its <em>extension</em>, that is by listing its elements: </p>
<blockquote><p>
<img alt="\displaystyle  \{ 1, 9, 25, 49, 81 \} " class="latex" src="http://s0.wp.com/latex.php?latex=%5Cdisplaystyle++%5C%7B+1%2C+9%2C+25%2C+49%2C+81+%5C%7D+&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="\displaystyle  \{ 1, 9, 25, 49, 81 \} "/>
</p></blockquote>
<p> or by its <em>intension</em>, that is by characterizing those elements: </p>
<blockquote><p>
<img alt="\displaystyle  \{ n^2 \mid 0 &lt; n &lt; 10 \land n \equiv 1 (\mathop{mod} 2) \} " class="latex" src="http://s0.wp.com/latex.php?latex=%5Cdisplaystyle++%5C%7B+n%5E2+%5Cmid+0+%3C+n+%3C+10+%5Cland+n+%5Cequiv+1+%28%5Cmathop%7Bmod%7D+2%29+%5C%7D+&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="\displaystyle  \{ n^2 \mid 0 &lt; n &lt; 10 \land n \equiv 1 (\mathop{mod} 2) \} "/>
</p></blockquote>
<p> Expressions in the latter form are called <em>set comprehensions</em>. They inspired a programming notation in the <a href="http://en.wikipedia.org/wiki/SETL">SETL</a> language from NYU, and have become widely known through list comprehensions in languages like Haskell. The structure needed of sets or of lists to make this work is roughly that of a <em>monad</em>, and Phil Wadler showed how to <a href="http://dx.doi.org/10.1017/S0960129500001560">generalize comprehensions to arbitrary monads</a>, which led to the “<b>do</b>” notation in Haskell. Around the same time, Phil Trinder showed that <a href="http://www.cs.ox.ac.uk/publications/publication3861-abstract.html">comprehensions make a convenient database query language</a>. The comprehension notation has been extended to cover other important aspects of database queries, particularly <a href="http://dx.doi.org/10.1007/BFb0026993">aggregation</a> and <a href="http://dx.doi.org/10.1145/1291201.1291209">grouping</a>. Monads and aggregations have very nice algebraic structure, which leads to a useful body of laws to support database query optimization.</p>
<p/><h2> List comprehensions </h2>
<p>
Just as a warm-up, here is a reminder about Haskell’s list comprehensions. </p>
<blockquote><p>
<img alt="\displaystyle  [ 2 \times a + b \mid a \leftarrow [1,2,3] , b \leftarrow [4,5,6] , b \mathbin{\underline{\smash{\mathit{mod}}}} a == 0 ] " class="latex" src="http://s0.wp.com/latex.php?latex=%5Cdisplaystyle++%5B+2+%5Ctimes+a+%2B+b+%5Cmid+a+%5Cleftarrow+%5B1%2C2%2C3%5D+%2C+b+%5Cleftarrow+%5B4%2C5%2C6%5D+%2C+b+%5Cmathbin%7B%5Cunderline%7B%5Csmash%7B%5Cmathit%7Bmod%7D%7D%7D%7D+a+%3D%3D+0+%5D+&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="\displaystyle  [ 2 \times a + b \mid a \leftarrow [1,2,3] , b \leftarrow [4,5,6] , b \mathbin{\underline{\smash{\mathit{mod}}}} a == 0 ] "/>
</p></blockquote>
<p> This (rather concocted) example yields the list of all values of the expression <img alt="{2 \times a + b}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B2+%5Ctimes+a+%2B+b%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{2 \times a + b}"/> as <img alt="{a}" class="latex" src="http://s0.wp.com/latex.php?latex=%7Ba%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{a}"/> is drawn from <img alt="{[1,2,3]}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5B1%2C2%2C3%5D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{[1,2,3]}"/> and <img alt="{b}" class="latex" src="http://s0.wp.com/latex.php?latex=%7Bb%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{b}"/> from <img alt="{[4,5,6]}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5B4%2C5%2C6%5D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{[4,5,6]}"/> and such that <img alt="{b}" class="latex" src="http://s0.wp.com/latex.php?latex=%7Bb%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{b}"/> is divisible by <img alt="{a}" class="latex" src="http://s0.wp.com/latex.php?latex=%7Ba%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{a}"/>, namely <img alt="{[6,7,8,8,10,12]}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5B6%2C7%2C8%2C8%2C10%2C12%5D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{[6,7,8,8,10,12]}"/>.</p>
<p>
To the left of the vertical bar is the <em>term</em> (an expression). To the right is a comma-separated sequence of <em>qualifiers</em>, each of which is either a <em>generator</em> (of the form <img alt="{a \leftarrow x}" class="latex" src="http://s0.wp.com/latex.php?latex=%7Ba+%5Cleftarrow+x%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{a \leftarrow x}"/>, with a variable <img alt="{a}" class="latex" src="http://s0.wp.com/latex.php?latex=%7Ba%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{a}"/> and a list expression <img alt="{x}" class="latex" src="http://s0.wp.com/latex.php?latex=%7Bx%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{x}"/>) or a <em>filter</em> (a boolean expression). The scope of a variable introduced by a generator extends to all subsequent generators and to the term. Note that, in contrast to the mathematical inspiration, bound variables need to be generated from some existing list.</p>
<p>
The semantics of list comprehensions is defined by translation; see for example Phil Wadler’s Chapter 7 of <a href="http://research.microsoft.com/en-us/um/people/simonpj/papers/slpj-book-1987/">The Implementation of Functional Programming Languages</a>. It can be expressed equationally as follows: </p>
<blockquote><p>
<img alt="\displaystyle  \begin{array}{lcl} [ e \mid \epsilon ] &amp;=&amp; [e] \\ {} [ e \mid b ] &amp;=&amp; \mathbf{if}\;b\;\mathbf{then}\;[ e ]\;\mathbf{else}\;[\,] \\ {} [ e \mid a \leftarrow x ] &amp;=&amp; \mathit{map}\,(\lambda a \mathbin{.} e)\,x \\ {} [ e \mid q, q' ] &amp;=&amp; \mathit{concat}\,[ [ e \mid q' ] \mid q ] \end{array} " class="latex" src="http://s0.wp.com/latex.php?latex=%5Cdisplaystyle++%5Cbegin%7Barray%7D%7Blcl%7D+%5B+e+%5Cmid+%5Cepsilon+%5D+%26%3D%26+%5Be%5D+%5C%5C+%7B%7D+%5B+e+%5Cmid+b+%5D+%26%3D%26+%5Cmathbf%7Bif%7D%5C%3Bb%5C%3B%5Cmathbf%7Bthen%7D%5C%3B%5B+e+%5D%5C%3B%5Cmathbf%7Belse%7D%5C%3B%5B%5C%2C%5D+%5C%5C+%7B%7D+%5B+e+%5Cmid+a+%5Cleftarrow+x+%5D+%26%3D%26+%5Cmathit%7Bmap%7D%5C%2C%28%5Clambda+a+%5Cmathbin%7B.%7D+e%29%5C%2Cx+%5C%5C+%7B%7D+%5B+e+%5Cmid+q%2C+q%27+%5D+%26%3D%26+%5Cmathit%7Bconcat%7D%5C%2C%5B+%5B+e+%5Cmid+q%27+%5D+%5Cmid+q+%5D+%5Cend%7Barray%7D+&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="\displaystyle  \begin{array}{lcl} [ e \mid \epsilon ] &amp;=&amp; [e] \\ {} [ e \mid b ] &amp;=&amp; \mathbf{if}\;b\;\mathbf{then}\;[ e ]\;\mathbf{else}\;[\,] \\ {} [ e \mid a \leftarrow x ] &amp;=&amp; \mathit{map}\,(\lambda a \mathbin{.} e)\,x \\ {} [ e \mid q, q' ] &amp;=&amp; \mathit{concat}\,[ [ e \mid q' ] \mid q ] \end{array} "/>
</p></blockquote>
<p> (Here, <img alt="{\epsilon}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5Cepsilon%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{\epsilon}"/> denotes the empty sequence of qualifiers. It’s not allowed in Haskell, but it is helpful in simplifying the translation.)</p>
<p>
Applying this translation to the example at the start of the section gives </p>
<blockquote><p>
<img alt="\displaystyle  \begin{array}{ll} &amp; [ 2 \times a + b \mid a \leftarrow [1,2,3] , b \leftarrow [4,5,6] , b \mathbin{\underline{\smash{\mathit{mod}}}} a == 0 ] \\ = &amp; \mathit{concat}\,(\mathit{map}\,(\lambda a \mathbin{.} \mathit{concat}\,(\mathit{map}\,(\lambda b \mathbin{.} \mathbf{if}\;b \mathbin{\underline{\smash{\mathit{mod}}}} a == 0\;\mathbf{then}\;[2 \times a + b]\;\mathbf{else}\;[\,])\,[4,5,6]))\,[1,2,3]) \\ = &amp; [6,7,8,8,10,12] \end{array} " class="latex" src="http://s0.wp.com/latex.php?latex=%5Cdisplaystyle++%5Cbegin%7Barray%7D%7Bll%7D+%26+%5B+2+%5Ctimes+a+%2B+b+%5Cmid+a+%5Cleftarrow+%5B1%2C2%2C3%5D+%2C+b+%5Cleftarrow+%5B4%2C5%2C6%5D+%2C+b+%5Cmathbin%7B%5Cunderline%7B%5Csmash%7B%5Cmathit%7Bmod%7D%7D%7D%7D+a+%3D%3D+0+%5D+%5C%5C+%3D+%26+%5Cmathit%7Bconcat%7D%5C%2C%28%5Cmathit%7Bmap%7D%5C%2C%28%5Clambda+a+%5Cmathbin%7B.%7D+%5Cmathit%7Bconcat%7D%5C%2C%28%5Cmathit%7Bmap%7D%5C%2C%28%5Clambda+b+%5Cmathbin%7B.%7D+%5Cmathbf%7Bif%7D%5C%3Bb+%5Cmathbin%7B%5Cunderline%7B%5Csmash%7B%5Cmathit%7Bmod%7D%7D%7D%7D+a+%3D%3D+0%5C%3B%5Cmathbf%7Bthen%7D%5C%3B%5B2+%5Ctimes+a+%2B+b%5D%5C%3B%5Cmathbf%7Belse%7D%5C%3B%5B%5C%2C%5D%29%5C%2C%5B4%2C5%2C6%5D%29%29%5C%2C%5B1%2C2%2C3%5D%29+%5C%5C+%3D+%26+%5B6%2C7%2C8%2C8%2C10%2C12%5D+%5Cend%7Barray%7D+&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="\displaystyle  \begin{array}{ll} &amp; [ 2 \times a + b \mid a \leftarrow [1,2,3] , b \leftarrow [4,5,6] , b \mathbin{\underline{\smash{\mathit{mod}}}} a == 0 ] \\ = &amp; \mathit{concat}\,(\mathit{map}\,(\lambda a \mathbin{.} \mathit{concat}\,(\mathit{map}\,(\lambda b \mathbin{.} \mathbf{if}\;b \mathbin{\underline{\smash{\mathit{mod}}}} a == 0\;\mathbf{then}\;[2 \times a + b]\;\mathbf{else}\;[\,])\,[4,5,6]))\,[1,2,3]) \\ = &amp; [6,7,8,8,10,12] \end{array} "/>
</p></blockquote>
<p> More generally, a generator may match against a pattern rather than just a variable. In that case, it may bind multiple (or indeed no) variables at once; moreover, the match may fail, in which case it is discarded. This is handled by modifying the translation for generators to use a function defined by pattern-matching, rather than a straight lambda-abstraction: </p>
<blockquote><p>
<img alt="\displaystyle  [ e \mid p \leftarrow x ] = \mathit{concat}\,(\mathit{map}\,(\lambda a \mathbin{.} \mathbf{case}\;a\;\mathbf{of}\;p \rightarrow [ e ] \;;\; \_ \rightarrow [\,])\,x) " class="latex" src="http://s0.wp.com/latex.php?latex=%5Cdisplaystyle++%5B+e+%5Cmid+p+%5Cleftarrow+x+%5D+%3D+%5Cmathit%7Bconcat%7D%5C%2C%28%5Cmathit%7Bmap%7D%5C%2C%28%5Clambda+a+%5Cmathbin%7B.%7D+%5Cmathbf%7Bcase%7D%5C%3Ba%5C%3B%5Cmathbf%7Bof%7D%5C%3Bp+%5Crightarrow+%5B+e+%5D+%5C%3B%3B%5C%3B+%5C_+%5Crightarrow+%5B%5C%2C%5D%29%5C%2Cx%29+&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="\displaystyle  [ e \mid p \leftarrow x ] = \mathit{concat}\,(\mathit{map}\,(\lambda a \mathbin{.} \mathbf{case}\;a\;\mathbf{of}\;p \rightarrow [ e ] \;;\; \_ \rightarrow [\,])\,x) "/>
</p></blockquote>
<p> or, more perspicuously, </p>
<blockquote><p>
<img alt="\displaystyle  [ e \mid p \leftarrow x ] = \mathbf{let}\;h\,p = [ e ] ; h\,\_ = [\,]\;\mathbf{in}\; \mathit{concat}\,(\mathit{map}\,h\,x) " class="latex" src="http://s0.wp.com/latex.php?latex=%5Cdisplaystyle++%5B+e+%5Cmid+p+%5Cleftarrow+x+%5D+%3D+%5Cmathbf%7Blet%7D%5C%3Bh%5C%2Cp+%3D+%5B+e+%5D+%3B+h%5C%2C%5C_+%3D+%5B%5C%2C%5D%5C%3B%5Cmathbf%7Bin%7D%5C%3B+%5Cmathit%7Bconcat%7D%5C%2C%28%5Cmathit%7Bmap%7D%5C%2Ch%5C%2Cx%29+&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="\displaystyle  [ e \mid p \leftarrow x ] = \mathbf{let}\;h\,p = [ e ] ; h\,\_ = [\,]\;\mathbf{in}\; \mathit{concat}\,(\mathit{map}\,h\,x) "/>
</p></blockquote>
<p/><h2> Monad comprehensions </h2>
<p>
It is clear from the above translation that the necessary ingredients for list comprehensions are <img alt="{\mathit{map}}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5Cmathit%7Bmap%7D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{\mathit{map}}"/>, singletons, <img alt="{\mathit{concat}}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5Cmathit%7Bconcat%7D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{\mathit{concat}}"/>, and the empty list. The first three are the operations arising from lists as a functor and a monad, which suggests that the same translation might be applicable to other monads too. But the fourth ingredient, the empty list, does not come from the functor and monad structures; that requires an extra assumption: </p>
<blockquote><p>
<img alt="\displaystyle  \begin{array}{ll} \mathbf{class}\;\mathit{Monad}\,m \Rightarrow \mathit{MonadZero}\,m\;\mathbf{where} \\ \quad \mathit{mzero} :: m\,a \end{array} " class="latex" src="http://s0.wp.com/latex.php?latex=%5Cdisplaystyle++%5Cbegin%7Barray%7D%7Bll%7D+%5Cmathbf%7Bclass%7D%5C%3B%5Cmathit%7BMonad%7D%5C%2Cm+%5CRightarrow+%5Cmathit%7BMonadZero%7D%5C%2Cm%5C%3B%5Cmathbf%7Bwhere%7D+%5C%5C+%5Cquad+%5Cmathit%7Bmzero%7D+%3A%3A+m%5C%2Ca+%5Cend%7Barray%7D+&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="\displaystyle  \begin{array}{ll} \mathbf{class}\;\mathit{Monad}\,m \Rightarrow \mathit{MonadZero}\,m\;\mathbf{where} \\ \quad \mathit{mzero} :: m\,a \end{array} "/>
</p></blockquote>
<p> Then the translation for list comprehensions can be generalized to other monads: </p>
<blockquote><p>
<img alt="\displaystyle  \begin{array}{lcl} [ e \mid \epsilon ] &amp;=&amp; \mathit{return}\,e \\ {} [ e \mid b ] &amp;=&amp; \mathbf{if}\;b\;\mathbf{then}\;\mathit{return}\,e\;\mathbf{else}\;\mathit{mzero} \\ {} [ e \mid p \leftarrow m ] &amp;=&amp; \mathbf{let}\;h\,p = \mathit{return}\,e ; h\,\_ = \mathit{mzero}\;\mathbf{in}\; \mathit{join}\,(\mathit{map}\,h\,m) \\ {} [ e \mid q, q' ] &amp;=&amp; \mathit{join}\,[ [ e \mid q' ] \mid q ] \end{array} " class="latex" src="http://s0.wp.com/latex.php?latex=%5Cdisplaystyle++%5Cbegin%7Barray%7D%7Blcl%7D+%5B+e+%5Cmid+%5Cepsilon+%5D+%26%3D%26+%5Cmathit%7Breturn%7D%5C%2Ce+%5C%5C+%7B%7D+%5B+e+%5Cmid+b+%5D+%26%3D%26+%5Cmathbf%7Bif%7D%5C%3Bb%5C%3B%5Cmathbf%7Bthen%7D%5C%3B%5Cmathit%7Breturn%7D%5C%2Ce%5C%3B%5Cmathbf%7Belse%7D%5C%3B%5Cmathit%7Bmzero%7D+%5C%5C+%7B%7D+%5B+e+%5Cmid+p+%5Cleftarrow+m+%5D+%26%3D%26+%5Cmathbf%7Blet%7D%5C%3Bh%5C%2Cp+%3D+%5Cmathit%7Breturn%7D%5C%2Ce+%3B+h%5C%2C%5C_+%3D+%5Cmathit%7Bmzero%7D%5C%3B%5Cmathbf%7Bin%7D%5C%3B+%5Cmathit%7Bjoin%7D%5C%2C%28%5Cmathit%7Bmap%7D%5C%2Ch%5C%2Cm%29+%5C%5C+%7B%7D+%5B+e+%5Cmid+q%2C+q%27+%5D+%26%3D%26+%5Cmathit%7Bjoin%7D%5C%2C%5B+%5B+e+%5Cmid+q%27+%5D+%5Cmid+q+%5D+%5Cend%7Barray%7D+&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="\displaystyle  \begin{array}{lcl} [ e \mid \epsilon ] &amp;=&amp; \mathit{return}\,e \\ {} [ e \mid b ] &amp;=&amp; \mathbf{if}\;b\;\mathbf{then}\;\mathit{return}\,e\;\mathbf{else}\;\mathit{mzero} \\ {} [ e \mid p \leftarrow m ] &amp;=&amp; \mathbf{let}\;h\,p = \mathit{return}\,e ; h\,\_ = \mathit{mzero}\;\mathbf{in}\; \mathit{join}\,(\mathit{map}\,h\,m) \\ {} [ e \mid q, q' ] &amp;=&amp; \mathit{join}\,[ [ e \mid q' ] \mid q ] \end{array} "/>
</p></blockquote>
<p> (so <img alt="{[ e \mid \epsilon ] = [ e \mid \mathit{True} ]}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5B+e+%5Cmid+%5Cepsilon+%5D+%3D+%5B+e+%5Cmid+%5Cmathit%7BTrue%7D+%5D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{[ e \mid \epsilon ] = [ e \mid \mathit{True} ]}"/>). The actual monad to be used is implicit; if we want to be explicit, we could use a subscript, as in “<img alt="{[ e \mid q ]_\mathsf{List}}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5B+e+%5Cmid+q+%5D_%5Cmathsf%7BList%7D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{[ e \mid q ]_\mathsf{List}}"/>“.</p>
<p>
This translation is different from the one used in the Haskell language specification, which to my mind is a little awkward: the empty list crops up in two different ways in the translation of list comprehensions—for filters, and for generators with patterns—and these are generalized in two different ways to other monads (to the <img alt="{\mathit{mzero}}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5Cmathit%7Bmzero%7D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{\mathit{mzero}}"/> method of the <img alt="{\mathit{MonadPlus}}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5Cmathit%7BMonadPlus%7D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{\mathit{MonadPlus}}"/> class in the first case, and the <img alt="{\mathit{fail}}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5Cmathit%7Bfail%7D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{\mathit{fail}}"/> method of the <img alt="{\mathit{Monad}}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5Cmathit%7BMonad%7D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{\mathit{Monad}}"/> class in the second). I think it is neater to have a monad subclass <img alt="{\mathit{MonadZero}}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5Cmathit%7BMonadZero%7D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{\mathit{MonadZero}}"/> with a single method subsuming both these operators. Of course, this does mean that the translation forces a monad comprehension with filters or possibly failing generators to be interpreted in a monad in the <img alt="{\mathit{MonadZero}}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5Cmathit%7BMonadZero%7D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{\mathit{MonadZero}}"/> subclass rather than just <img alt="{\mathit{Monad}}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5Cmathit%7BMonad%7D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{\mathit{Monad}}"/>—the type class constraints that are generated depend on the features used in the comprehension. (Perhaps this translation was tried in earlier versions of the language specification, and found wanting?)</p>
<p>
Taking this approach gives basically the monad comprehension notation from Wadler’s <a href="http://dx.doi.org/10.1017/S0960129500001560">Comprehending Monads</a> paper; it loosely corresponds to Haskell’s <b>do</b> notation, except that the term is to the left of a vertical bar rather than at the end, and that filters are just boolean expressions rather than introduced using <img alt="{\mathit{guard}}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5Cmathit%7Bguard%7D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{\mathit{guard}}"/>. </p>
<p>
We might impose the law that <img alt="{\mathit{mzero}}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5Cmathit%7Bmzero%7D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{\mathit{mzero}}"/> is a “left” zero of composition, in the sense </p>
<blockquote><p>
<img alt="\displaystyle  \mathit{join}\,\mathit{mzero} = \mathit{mzero} " class="latex" src="http://s0.wp.com/latex.php?latex=%5Cdisplaystyle++%5Cmathit%7Bjoin%7D%5C%2C%5Cmathit%7Bmzero%7D+%3D+%5Cmathit%7Bmzero%7D+&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="\displaystyle  \mathit{join}\,\mathit{mzero} = \mathit{mzero} "/>
</p></blockquote>
<p> or, in terms of comprehensions, </p>
<blockquote><p>
<img alt="\displaystyle  [ e \mid a \leftarrow \mathit{mzero} ] = \mathit{mzero} " class="latex" src="http://s0.wp.com/latex.php?latex=%5Cdisplaystyle++%5B+e+%5Cmid+a+%5Cleftarrow+%5Cmathit%7Bmzero%7D+%5D+%3D+%5Cmathit%7Bmzero%7D+&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="\displaystyle  [ e \mid a \leftarrow \mathit{mzero} ] = \mathit{mzero} "/>
</p></blockquote>
<p> Informally, this means that any failing steps of the computation cleanly cut off subsequent branches. Conversely, we do not require that <img alt="{\mathit{mzero}}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%5Cmathit%7Bmzero%7D%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{\mathit{mzero}}"/> is a “right” zero too: </p>
<blockquote><p>
<img alt="\displaystyle  \mathit{join}\,(\mathit{map}\,(\lambda a \mathbin{.} \mathit{mzero})\,m) \ne \mathit{mzero} \quad\mbox{(in general)} " class="latex" src="http://s0.wp.com/latex.php?latex=%5Cdisplaystyle++%5Cmathit%7Bjoin%7D%5C%2C%28%5Cmathit%7Bmap%7D%5C%2C%28%5Clambda+a+%5Cmathbin%7B.%7D+%5Cmathit%7Bmzero%7D%29%5C%2Cm%29+%5Cne+%5Cmathit%7Bmzero%7D+%5Cquad%5Cmbox%7B%28in+general%29%7D+&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="\displaystyle  \mathit{join}\,(\mathit{map}\,(\lambda a \mathbin{.} \mathit{mzero})\,m) \ne \mathit{mzero} \quad\mbox{(in general)} "/>
</p></blockquote>
<p> This would have the consequence that a failing step also cleanly erases any effects from earlier parts of the computation, which is too strong a requirement for many monads—particularly those of the “launch missiles now” variety. (The names “left-” and “right zero” make more sense when the equations are expressed in terms of the usual Haskell bind operator <img alt="{(\gg\!=)}" class="latex" src="http://s0.wp.com/latex.php?latex=%7B%28%5Cgg%5C%21%3D%29%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{(\gg\!=)}"/>, which is a kind of sequential composition.)</p>
<p/><h2> Ringads and collection classes </h2>
<p>
One more ingredient is needed in order to characterize monads that correspond to “collection classes” such as sets and lists, and that is an analogue of set union or list append. It’s not difficult to see that this is inexpressible in terms of the operations introduced so far: given only collections <img alt="{m}" class="latex" src="http://s0.wp.com/latex.php?latex=%7Bm%7D&amp;bg=ffffff&amp;fg=000000&amp;s=0" title="{m}"/> of a
