Skip to content

Instantly share code, notes, and snippets.

@excitablesnowball
Created June 27, 2014 03:59
Show Gist options
  • Save excitablesnowball/9f64bc41e11ed0780e42 to your computer and use it in GitHub Desktop.
Save excitablesnowball/9f64bc41e11ed0780e42 to your computer and use it in GitHub Desktop.
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Chris Done's home page feed.</title>
<link>http://chrisdone.com</link>
<description><![CDATA[Chris Done's home page feed.]]></description>
<atom:link href="http://chrisdone.com/rss.xml" rel="self"
type="application/rss+xml" />
<lastBuildDate>Thu, 29 May 2014 00:00:00 UT</lastBuildDate>
<item>
<title>An alternative Haskell home page</title>
<link>http://chrisdone.com/posts/haskell-lang</link>
<description><![CDATA[<p>I started a couple months back an alternative home page for Haskell. It is a work in progress, but as I work on it every so often I push changes to it.</p>
<h2 id="whats-wrong-with-haskell.org">What’s wrong with haskell.org?</h2>
<p>haskell.org isn’t doing a satisfactory job for me as a place to impress people with Haskell and to guide them into using it.</p>
<ul>
<li>Its design is broken or just strangely put together and it’s not responsive.<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup></li>
<li>There are too many links on one page which indicates indecision about priorities and a lack of user story or particular target audience. Who’s this site targeting? Where are they supposed to go next? Is it answering the right questions?</li>
<li>Also, the uncoordinated effort of the wiki <a href="http://stackoverflow.com/questions/23848648/text-html-vs-blaze-html">misleads people</a> and pages begin to bitrot. There are too many to vet.</li>
</ul>
<h2 id="why-not-fix-haskell.org">Why not fix haskell.org?</h2>
<p>The current home page is historically resistant to change, technologically and socially. My relationship to haskell.org over the years has been one of stonewalling when requesting access, of slow replies, and of bike-shedding and nitpicking when proposing designs. A camel is a horse designed by committee and haskell.org is such a horse.</p>
<h2 id="so-your-plan-is">So your plan is?</h2>
<p>The plan goes like this:</p>
<ul>
<li>The first part of the plan was to survey existing programming language web sites.</li>
<li>Decide on an audience.</li>
<li>Decide on a theme.</li>
<li>Decide on user stories.</li>
<li>Implement.</li>
<li>Yay, shiny web site.</li>
</ul>
<h2 id="what-do-all-language-sites-have-and-what-should-they-all-have">What do all language sites have and what should they all have?</h2>
<p>I looked at the following web sites:</p>
<ul>
<li><a href="http://fsharp.org/">http://fsharp.org/</a></li>
<li><a href="http://ruby-lang.org/">http://ruby-lang.org/</a></li>
<li><a href="https://www.python.org/">https://www.python.org/</a></li>
<li><a href="http://www.rust-lang.org/">http://www.rust-lang.org/</a></li>
<li><a href="http://ocaml.org/">http://ocaml.org/</a></li>
<li><a href="http://golang.org/">http://golang.org/</a></li>
<li><a href="http://www.perl.org/">http://www.perl.org/</a></li>
<li><a href="http://scala-lang.org/">http://scala-lang.org/</a></li>
<li><a href="http://clojure.org/">http://clojure.org/</a></li>
</ul>
<p>There are good points and bad points for each one, but I came up with a set of things that are common among all, and a couple additional points I came up with:</p>
<ul>
<li>A theme</li>
<li>Logo</li>
<li>Menu
<ul>
<li>Download</li>
<li>Community</li>
<li>Documentation</li>
<li>News</li>
</ul></li>
<li>Visual things
<ul>
<li>Opening paragraph</li>
<li>Code sample</li>
<li>Thumbnails of videos</li>
<li>Pictures of community stuff; human beings</li>
<li>Screenshots</li>
<li>Selling points</li>
<li>News</li>
<li>Twitter/feeds</li>
<li>Supporters / sponsoring companies</li>
</ul></li>
<li>Other links
<ul>
<li>Application areas / success stories</li>
<li>Language options (locale; Japanese, German, etc.)</li>
</ul></li>
</ul>
<h2 id="existing-crop-of-language-home-pages">Existing crop of language home pages</h2>
<p>If you’re interested in my review of each home page, here’s what I wrote:</p>
<ul>
<li>F#’s is boring, it has no character, features no code samples. But it does have a bunch of company backing logos.</li>
<li>Ruby’s is among the best. It has character. It has two navigations, which is bad,<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup> but otherwise it’s perfect. Otherwise, my only criticism is that it overemphasizes news which most new people don’t care about and which Rubyists get via other sources.</li>
<li>Python’s, like Ruby’s, is good. It has character. It has code samples. But it’s worse than Ruby in that it has four areas of navigation. The top bar, the second bar, the third call to action section, and finally the footer. Each of which has a different subset of total places of interest. Again, it uses space presenting news items. However, I particularly like the section which shows Web Programming, GUI Development, etc. and then next to each the library one would use to accomplish that task. That’s very practical and speaks positively about the language and community.</li>
<li>OCaml’s is not bad either. It has a deserty theme giving it its own character. It suffers from link overload, which implies it might’ve been copying Haskell’s or Python’s home pages.</li>
<li>Go’s home page is notable for its embedded try feature, something which I’ve wanted Haskell’s home page to have for a long time. It’s also got a very simple and straight-forward navigation. The logo/mascot is in there, giving the whole page a bit of fun character, too. While not much to look at, unresponsive to device, clearly written by a pragmatist systems person, it has a lot going for it and is in my mind among the best I’ve looked at.</li>
<li>For Perl’s homepage, I’ll echo similar complaints as before. Link overload. It’s a rather lazy way to make a home page. Let’s throw in as many links as we can and hope people read it all and by chance find what they’re looking for. Oh and to fill out the page, let’s add recent uploads (who cares?) and news items (again, who cares?). Finally, it has no character whatsoever. It has the awful O’Reilly pen drawing of a random animal that’s supposed to embody the character of the language, but is meaningless. I probably dislike this one the most, a close tie with F#’s.</li>
<li>Scala’s is very trendy and pretty. It’s got a lot of events and training info which, along with the header mountains, gives it a very communal and active fresh feel. Again, echoing the praise of Go’s page, it has very simple navigation. One navigation at the top, and then two big buttons for the most common tasks. After that, like Python’s home page, there’s a good review of features of the language that make this language more interesting than the next language. I give credit to this page for visual inspiration.</li>
<li>Clojure suffers a little bit from linkitis, too. It has three menus and then a page full of links. It has zero code samples on the first page you land on. But it is clean and has a certain character to it.</li>
</ul>
<p>Generally, I’m not sure why sites bother with search boxes. Unless they’re implementing code-aware searches, Google will be faster and more accurate every time. As Joel Spolsky says of his StackOverflow, Google is the user interface to SO.</p>
<p>Regarding linkitis, I will quote <a href="http://en.wikipedia.org/wiki/Don&#39;t_Make_Me_Think">Don’t Make Me Think</a> that a user will happily click three links to narrow down what they want, than to have to think and search around a page to find what they want, if they have the patience for it.</p>
<h2 id="the-audience">The audience</h2>
<p>The audience is newbies. People who use Haskell don’t go to haskell.org. They go to Hackage, or they google search and find wiki entries, or the GHC manual. A home page shouldn’t cater to Haskellers, it should cater to would-be Haskellers.</p>
<p>Naysayers for an attractive home page say things like “we don’t want superficial people joining the community” (as if they could just learn Haskell on a whim!), but forget that people live insular lives. There are millions of people out there who’ve never heard of Haskell. If a random web user stumbles upon it and is taken by the look of it, what are they going to do with it? Share it. How did you first hear of Haskell? I was told about it by a friend.</p>
<p>To decide on the kinds of things I want to see on a landing page when I first look at a language I’m unfamiliar with I ask a bunch of common questions. I’ve condensed them all in the user stories section.</p>
<h2 id="the-theme">The theme</h2>
<p>I’ve always liked the purple and green of the old Haskell logo. I don’t know why gray/sky blue ended up being used for the new logo. So I decided I’d keep that purple theme and made some mockups. Purple is <a href="http://en.wikipedia.org/wiki/Purple#Vanity.2C_extravagance.2C_individualism">a cool color</a>.</p>
<h2 id="user-stories">User stories</h2>
<p>The user stories I’ve identified have been encoded in the main navigation:</p>
<ul>
<li>A user just wants to try Haskell. They scroll to ‘Try it’ and, well, try it. There can be links to further sites like Try Haskell, School of Haskell, Code Pad, Lambdabot, services like that.</li>
<li>A user wants to download Haskell. They click ‘Downloads’. What particular file they want to download doesn’t matter. It could be GHC, it could be the Haskell Platform, it could be some packages. If they want to download something, they go to Downloads.</li>
<li>A user wants to interact with/find community. They click ‘Community’. On that page is a list of various community places of interest, which may itself be expanded with videos and things like that.</li>
<li>A user wants to get information. They click ‘Documentation’. That means books, reports, papers, tutorials.</li>
<li>A user wants to catch up with what’s new in general, with Haskell. They click ‘News’ and there can be an RSS feed available on that page. Haskell News is mostly suitable to this task.</li>
</ul>
<h2 id="ahoy-ye-olde-mockup">Ahoy, ye olde mockup!</h2>
<p>I synthesized all this together into <a href="http://chrisdone.com/comp.png">a comp in Inkscape</a>.</p>
<p>I think it answers the following questions:</p>
<ul>
<li>Any particular brand/logo? [header]</li>
<li>In a few words, what is this thing? [header]</li>
<li>What does it look like? I want to see code immediately. [header]</li>
<li>Can I try it right now? [try haskell section]</li>
<li>I’m still interested. Is anyone using this thing? [community &amp; videos, events section]</li>
<li>What are the selling points, over, say, ML or C#? [features section]</li>
<li>Where do I download stuff/find community/docs/news? [the main menu at the top]</li>
</ul>
<p>I made a mockup for the subsite, but that’s uninteresting.</p>
<h2 id="implementation">Implementation</h2>
<p>I’ve implemented a starting prototype here at <a href="http://haskell-lang.org/">haskell-lang.org</a>. At the time of writing it doesn’t yet fully flesh out all the things planned in the mockup.</p>
<p>There are a few half-done pages in the navigation, fleshed out just enough to satisfy my plan and to motivate for further work.</p>
<p>Here’s a quick comparison of the two sites now:</p>
<p>To illustrate, here’re the sites on various devices:</p>
<ul>
<li><a href="http://ami.responsivedesign.is/?url=http%3A%2F%2Fhaskell.org">haskell.org</a></li>
<li><a href="http://ami.responsivedesign.is/?url=http%3A%2F%2Fhaskell-lang.org">haskell-lang.org</a></li>
</ul>
<p>I’ve also made a little page to render wiki pages from haskell.org. There is a simple request sent to haskell.org for <code>/wiki/*</code> pages, it parses the Wiki syntax with pandoc and renders it to HTML, at least for the pages that MediaWiki is kind enough to serve. Example: <a href="http://www.haskell.org/haskellwiki/Handling_errors_in_Haskell">Handling errors in Haskell</a></p>
<p>Here is <a href="http://haskell-lang.org/wiki/Handling_errors_in_Haskell">the above wiki page</a> with a cleaned up presentation.</p>
<p>Note that MediaWiki is a bit stunted in the data it exposes for use. Some pages just aren’t available, others produce invalid XML, etc. This is why the wiki is not exposed in the navigation.</p>
<p>I’m not sure about exposing the wiki directly, but rather some selected vetted pages, perhaps.</p>
<h2 id="going-forward">Going forward</h2>
<p>I still have to:</p>
<ul>
<li><del>Fill in the Try support</del></li>
<li><del>The features copy</del></li>
<li>Examples for each of said features</li>
<li><del>A list of video thumbnails to appear under the community banner (as in the comp)</del></li>
<li>Upcoming/past events</li>
<li>At least 5 examples for the header code</li>
<li><del>Add books &amp; manuals to the Documentation tab</del></li>
</ul>
<p>I’m happy with the look and feel and organization. Now is the matter of filling it with useful things. That’ll take about a month, by weekend/spare-time development. Once that’s done, it will be ready to link to newbies. I’ll have a link to be proud of when people bring up Haskell.</p>
<p>I could solicit the community for contributions via pull requests. It depends on people approving of the project and my approach. So if you’re reading this and you accept my design and organization<sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup> and would like to contribute content (content pages are written in markdown), then pull requests to <a href="http://github.com/chrisdone/hl">the github repo</a> would be most handy. I will merge your changes and redeploy with relative speed.</p>
<p>In particular, content in wanting which is not straight-forward for me to produce:</p>
<ul>
<li>About 5 examples of concise, short Haskell code which can sit in the header. Ideally, each example can be clicked and it will take you to a markdown page under an Examples hierarchy that explains how the code works.</li>
<li>The features section needs to be filled out with content. I’m not entirely sure that the headers are decent, but I’m pretty sure they’re a good start.<sup><a href="#fn4" class="footnoteRef" id="fnref4">4</a></sup> Pages for each of those which contain example code of real problems that are solved are needed.</li>
</ul>
<p>I won’t be able to actively work on this for a few days, but I can do bits and bobs here and there on the weekend and I always have time to merge straight-forward changes.</p>
<p>Questions/comments, feel free to email me: <script type="text/javascript">
<!--
h='&#x67;&#x6d;&#x61;&#x69;&#108;&#46;&#x63;&#x6f;&#x6d;';a='&#64;';n='&#x63;&#104;&#114;&#x69;&#x73;&#100;&#x6f;&#110;&#x65;';e=n+a+h;
document.write('<a h'+'ref'+'="ma'+'ilto'+':'+e+'">'+'<code>'+e+'</code>'+'<\/'+'a'+'>');
// -->
</script><noscript>&#x63;&#104;&#114;&#x69;&#x73;&#100;&#x6f;&#110;&#x65;&#32;&#x61;&#116;&#32;&#x67;&#x6d;&#x61;&#x69;&#108;&#32;&#100;&#x6f;&#116;&#32;&#x63;&#x6f;&#x6d;</noscript> Put a note in the email if you wish to be CC’d with other people in the discussion.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>When I open haskell.org on my phone, I see the tablet-sized layout with tiny text. The layout goes wonky on the tablet version.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>Having two navigations leads to <a href="http://en.wikipedia.org/wiki/The_Paradox_of_Choice">arbitrary choice.</a><a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>That means that you won’t nitpick design decisions, bike shed about the theme, organization, choice of picture in the landing page, etc.<a href="#fnref3">↩</a></p></li>
<li id="fn4"><p>Maybe type-classes and monads might be of interest because both where pioneered by Haskell and, at least in their native support, are both peculiar to Haskell.<a href="#fnref4">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Thu, 29 May 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/haskell-lang</guid>
</item>
<item>
<title>Haskell-mode documentation</title>
<link>http://chrisdone.com/posts/haskell-mode-docs</link>
<description><![CDATA[<p><em>tl;dr: <a href="https://github.com/haskell/haskell-mode/wiki">The haskell-mode manual</a></em></p>
<h2 id="background">Background</h2>
<p>So I’ve been using and adding to haskell-mode in Emacs for about 5-6 years now. All the while, I’ve pretty much documented none of it. Much of all the other features that I use written by other people are also not discoverable, either.</p>
<p>From the results of the <a href="https://docs.google.com/forms/d/1FzWbzGm6odYWxJZcU3GFHlS3lVFTBOI1-M1c87CjOFg/viewanalytics">haskell-mode survey</a>, it was clear that people wanted documentation, and that much of the features we asked about, people weren’t even aware existed.</p>
<p>Keeping with the spirit of Emacs, it’s better to write a decent manual and then let users customize and pick and choose as needed.</p>
<h2 id="lets-write-some-docs">Let’s write some docs!</h2>
<p>Herbert made a start on <a href="https://github.com/haskell/haskell-mode/blob/master/haskell-mode.texi">a texinfo manual</a>, which I thoroughly approved of. Until I started trying to add to it. The texinfo format is a big and unfamiliar format. I got bored of trying to figure it out and decided if <em>I</em> would be discouraged from writing docs, so would anyone else who didn’t even write the features.</p>
<p>On the other hand, the wikis on Github projects are written in Markdown. Pretty much everyone knows Markdown. And you can work with it as a Git repository. So I set to work down that route.</p>
<h2 id="enter-the-haskell-mode-manual">Enter the haskell-mode manual</h2>
<p>Here’s about a day’s worth of work:</p>
<p><a href="https://github.com/haskell/haskell-mode/wiki">The haskell-mode manual</a></p>
<p>I’ve more things to add and flesh out, but this is pretty much all the things I could think of from the top of my head. I’ll keep adding to it as and when I think of things. Hope it’s useful!</p>]]></description>
<pubDate>Sat, 10 May 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/haskell-mode-docs</guid>
</item>
<item>
<title>Presentations update</title>
<link>http://chrisdone.com/posts/presentations-update</link>
<description><![CDATA[<p>Just a small update. I took 15 mins and updated the haskell-mode printer a bit so that everything is indented by default, and lists are expanded as <code>[1,2,…]</code> rather than <code>1:(2:…)</code>.</p>
<p><a href="https://www.youtube.com/watch?v=oJhIvHtflbI">Video demonstration!</a></p>
<p>Andrew Gibiansky contacted me about getting a front-end added for <a href="https://github.com/gibiansky/IHaskell">IHaskell</a>, which would be lovely! I designed the <a href="https://github.com/chrisdone/present">present</a> package specifically aimed at working on Emacs or the browser or wherever. So I sent him back an excessively long email about how to integrate it.</p>
<p>It might also be worth adding to tryhaskell, too. It’d be rather easy and helpful to newbies.</p>
<p>Also, update to the loeb example:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; <span class="fu">:</span>present loeb (map (\i l <span class="ot">-&gt;</span> <span class="dt">Node</span> i (map (fmap (<span class="fu">+</span><span class="dv">1</span>)) l)) [<span class="dv">1</span><span class="fu">..</span><span class="dv">3</span>])
[<span class="dt">Node</span>
<span class="dv">1</span>
[<span class="dt">Tree</span> <span class="dt">Integer</span>
,<span class="dt">Node</span>
<span class="dv">3</span>
[<span class="dt">Node</span>
<span class="dv">3</span>
[<span class="dt">Tree</span> <span class="dt">Integer</span>
,<span class="dt">Tree</span> <span class="dt">Integer</span>
,<span class="dt">Node</span>
<span class="dv">6</span>
[<span class="dt">Node</span>
<span class="dv">5</span>
[<span class="dt">Node</span>
<span class="dv">6</span>
[<span class="dt">Tree</span> <span class="dt">Integer</span>
,[<span class="dt">Tree</span> <span class="dt">Integer</span>]]
,[<span class="dt">Tree</span> <span class="dt">Integer</span>]]
,[<span class="dt">Tree</span> <span class="dt">Integer</span>]]]
,[<span class="dt">Tree</span> <span class="dt">Integer</span>]]
,<span class="dt">Tree</span> <span class="dt">Integer</span>]
,<span class="dt">Tree</span> <span class="dt">Integer</span>
,<span class="dt">Tree</span> <span class="dt">Integer</span>]</code></pre>
<p>You can really drill down into those structures!</p>]]></description>
<pubDate>Wed, 30 Apr 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/presentations-update</guid>
</item>
<item>
<title>The Identity monad trick</title>
<link>http://chrisdone.com/posts/identity-monad</link>
<description><![CDATA[<p><em><strong>Update:</strong> Got the link! <a href="http://blog.sigfpe.com/2007/04/trivial-monad.html">The Trivial Monad</a>. Thanks, John. Naturally, all interesting Haskell things eventually lead back to Dan Piponi.</em></p>
<p>I heard about this from John Wiegley a while ago, but every time I recall it, I can’t remember how it goes, so I thought I’d write it down for myself. I think there’s a paper about it, but I can’t find it. Hopefully I’m recalling it correctly.</p>
<p>The Identity monad trick: Let’s say I want to expose an API that lets you work with a data structure. I want you to be able to keep hold of that data structure and pass it back into my library, and I’ll give it back to you later and we can go back and forth.</p>
<p><strong>But</strong> I don’t want you to actually <em>give you</em> the data structure freely so you can go and give it to your friends. So instead I force you into the Identity monad, via a newtype wrapper that only <em>I</em> can unpack.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">newtype</span> <span class="dt">Secret</span> a <span class="fu">=</span> <span class="dt">Secret</span> {<span class="ot"> unSecret ::</span> <span class="dt">Identity</span> a }
<span class="kw">deriving</span> (<span class="dt">Monad</span>,<span class="dt">Functor</span>,<span class="dt">Applicative</span>)</code></pre>
<p>And I have some function exposing it like:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">getSecret ::</span> <span class="dt">Foo</span> <span class="ot">-&gt;</span> <span class="dt">Secret</span> <span class="dt">Text</span></code></pre>
<p>Here, use that. What can you do with it? You can’t extract the value out, you can only compose it with more functor or monad stuff:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">fmap (map T.toUpper) (getSecret foo)</code></pre>
<p>Or:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">do</span> text <span class="ot">&lt;-</span> getSecret foo
<span class="kw">if</span> all T.isUpper text
<span class="kw">then</span> return (T.reverse text)
<span class="kw">else</span> return text</code></pre>
<p>Note that the whole type of this expression is <code>Secret Text</code>. You still don’t have the secret, you’ve got a computation over it.</p>
<p>You’ve used the value, but it never escaped<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup> the actual Identity monad. It’s like I’m giving you the value, but I’m also not giving you the value.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>As always, there’s a difference between “secure against your own stupidity” and “secure against attackers.” For the former, this is satisfied.</p>
<p>For the latter, bottom complicates it, so you should force it in the IO monad and catch any exceptions e.g.</p>
<p><code>extract :: Secret a -&gt; IO (Maybe a)</code></p>
<p>This prevents people from using</p>
<p><code>(v &gt;&gt;= \a -&gt; error (&quot;The value is &quot; ++ show a))</code></p>
<p>To try to get around it.</p>
<p><code>unsafePerformIO</code> and other non-standard Haskell can get around it, but if you’re defending against developers, you probably have control over the environment, so you can just white-list the imports and extensions and there’s nothing they can do. This is what tryhaskell (via mueval) does.<a href="#fnref1">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Tue, 29 Apr 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/identity-monad</guid>
</item>
<item>
<title>The printer Haskell deserves</title>
<link>http://chrisdone.com/posts/the-printer-haskell-deserves</link>
<description><![CDATA[<p>Friday night project ahoy!</p>
<h2 id="problem">Problem</h2>
<p>I was working with haskell-names the other day. Its data types are nice enough, but are rather unweildly to read in the REPL when debugging and inspecting. This got me thinking about inspection and printers for Haskell data structures again.</p>
<p>I’ve made several approaches for to haskell-mode in the past.</p>
<ul>
<li>One which requires parsing the output of Show with Haskell and then printing that to s-expressions for Emacs to consume. This is generally unreliable and hacky.</li>
<li>Then I settled with making the REPL just syntax highlight the output. That generally works flawlessly and is an okay solution.</li>
<li>Then I really wanted collapsing support again, so I implemented one based on Emacs’s awareness of expression boundaries (of ( ) and { } and &quot; &quot; etc.). Simple. Kind of reliable.</li>
</ul>
<p>Today I implement yet another one, but this one I like best. I’ve always wanted to have a Haskell printer that can evaluate on demand, piece-wise, taking care not to evaluate the whole structure too eagerly. I should be able to type <code>[1..]</code> into my REPL and not be spammed by numbers, but rather to expand it at my leisure.</p>
<h2 id="implementation">Implementation</h2>
<p>My plan was to use the <a href="http://chrisdone/posts/data-typeable">Data.Data API</a> to traverse data structures breadth-first, display to the user something like <code>Just …</code> and then allow the user to continue evaluating on request by clicking the <code>…</code> slot.</p>
<p>I chatted with <a href="https://github.com/mgsloan">Michael Sloan</a> about it and we came up with a simple experimental design and thought it would be a nice idea. We hypothesized a nice class-based way to provide custom presenters for your types, so that e.g. a <code>Diagram</code> could be rendered as a bitmap inline with the rest of the data structure, but that needs more thinking about.</p>
<p>I’ve implemented a basic version of it in the <a href="http://hackage.haskell.org/package/present-0.0.0">present</a> package (a la “presentations” in <a href="http://bauhh.dyndns.org:8000/clim-spec/23-1.html#_1125">CLIM</a>) and implemented a usable front-end for it in Emacs. There’s some information about the implementation <a href="https://github.com/chrisdone/present">in the README</a> which you can read on Github.</p>
<h2 id="result">Result</h2>
<p>Yes! It works. <a href="http://youtu.be/4rcPfZveGZc">Here is a demonstration video.</a> Concept proven. This is definitely my favourite way so far. I will probably write a simple algorithm in Emacs to format things on separate lines, which would make it much easier to read, and I want to make strings expand to fill the screen width, but no further. But this is already an improvement.</p>
<p>I’ll trial it for a while, if I end up using it more often than not, I’ll make the option to make :present implicit for all REPL evaluations.</p>
<h2 id="example">Example</h2>
<p>For kicks, here’s the output for</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">loeb (map (\i l <span class="ot">-&gt;</span> <span class="dt">Node</span> i (map (fmap (<span class="fu">+</span><span class="dv">1</span>)) l)) [<span class="dv">1</span><span class="fu">..</span><span class="dv">3</span>])</code></pre>
<p>Normally you would get:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">[<span class="dt">Node</span> {rootLabel <span class="fu">=</span> <span class="dv">1</span>, subForest <span class="fu">=</span> [<span class="dt">Node</span> {rootLabel <span class="fu">=</span> <span class="dv">2</span>, subForest <span class="fu">=</span>
[<span class="dt">Node</span> {rootLabel <span class="fu">=</span> <span class="dv">3</span>, subForest <span class="fu">=</span> [<span class="dt">Node</span> {rootLabel <span class="fu">=</span> <span class="dv">4</span>, subForest <span class="fu">=</span>
[<span class="dt">Node</span> {rootLabel <span class="fu">=</span> <span class="dv">5</span>, subForest <span class="fu">=</span> [<span class="dt">Node</span> {rootLabel <span class="fu">=</span> <span class="dv">6</span>, subForest <span class="fu">=</span>
[<span class="dt">Node</span> {rootLabel <span class="fu">=</span> <span class="dv">7</span>, subForest <span class="fu">=</span> [<span class="dt">Node</span> {rootLabel <span class="fu">=</span> <span class="dv">8</span>, subForest <span class="fu">=</span></code></pre>
<p>Ad infinitum! With presentation, you get:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; <span class="fu">:</span>present loeb (map (\i l <span class="ot">-&gt;</span> <span class="dt">Node</span> i (map (fmap (<span class="fu">+</span><span class="dv">1</span>)) l)) [<span class="dv">1</span><span class="fu">..</span><span class="dv">3</span>])
<span class="dt">Tree</span> <span class="dt">Integer</span><span class="fu">:</span>[<span class="dt">Tree</span> <span class="dt">Integer</span>]</code></pre>
<p>If you click <code>Tree Integer</code> on the left, you get:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">(<span class="dt">Node</span> <span class="dv">1</span> [<span class="dt">Tree</span> <span class="dt">Integer</span>])<span class="fu">:</span>[<span class="dt">Tree</span> <span class="dt">Integer</span>]</code></pre>
<p>Click the new one on the left:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">(<span class="dt">Node</span> <span class="dv">1</span> (<span class="dt">Tree</span> <span class="dt">Integer</span><span class="fu">:</span>[<span class="dt">Tree</span> <span class="dt">Integer</span>]))<span class="fu">:</span>[<span class="dt">Tree</span> <span class="dt">Integer</span>]</code></pre>
<p>Et cetera:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">(<span class="dt">Node</span> <span class="dv">1</span> ((<span class="dt">Node</span> <span class="dv">2</span> [<span class="dt">Tree</span> <span class="dt">Integer</span>])<span class="fu">:</span>[<span class="dt">Tree</span> <span class="dt">Integer</span>]))<span class="fu">:</span>
((<span class="dt">Node</span> <span class="dv">2</span> [<span class="dt">Tree</span> <span class="dt">Integer</span>])<span class="fu">:</span>[<span class="dt">Tree</span> <span class="dt">Integer</span>])</code></pre>
<p>In other words, every <code>[Tree Integer]</code> is a placeholder that you can click to get more output.</p>]]></description>
<pubDate>Sat, 26 Apr 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/the-printer-haskell-deserves</guid>
</item>
<item>
<title>Prescience</title>
<link>http://chrisdone.com/posts/prescience</link>
<description><![CDATA[<img src="/images/idris.png">
<style>body{text-align: center}</style>
]]></description>
<pubDate>Fri, 25 Apr 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/prescience</guid>
</item>
<item>
<title>Typeable and Data in Haskell</title>
<link>http://chrisdone.com/posts/data-typeable</link>
<description><![CDATA[<p><a href="hackage.haskell.org/package/base-4.6.0.1/docs/Data-Typeable.html">Data.Typeable</a> and <a href="http://hackage.haskell.org/package/base-4.6.0.1/docs/Data-Data.html">Data.Data</a> are rather mysterious. Starting out as a Haskell newbie you see them once in a while and wonder what use they are. Their Haddock pages are pretty opaque and scary in places. Here’s a quick rundown I thought I’d write to get people up to speed nice and quick so that they can start using it.<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup></p>
<p>It’s really rather beautiful as a way to do generic programming in Haskell. The general approach is that you don’t know what data types are being given to you, but you want to work upon them almost as if you did. The technique is simple when broken down.</p>
<h2 id="requirements">Requirements</h2>
<p>First, there is a class exported by each module. The class <code>Typeable</code> and the class <code>Data</code>. Your data types have to be instances of these if you want to use the generic programming methods on them.</p>
<p>Happily, we don’t have to write these instances ourselves (and in GHC 7.8 it is actually not possible to do so): GHC provides the extension <code>DeriveDataTypeable</code>, which you can enable by adding <code>{-# LANGUAGE DeriveDataTypeable #-}</code> to the top of your file, or providing <code>-XDeriveDataTypeable</code> to <code>ghc</code>.</p>
<p>Now you can derive instances of both:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">X</span> <span class="fu">=</span> <span class="dt">X</span>
<span class="kw">deriving</span> (<span class="dt">Data</span>,<span class="dt">Typeable</span>)</code></pre>
<p>Now we can start doing generic operations upon <code>X</code>.</p>
<h2 id="the-typeable-class">The Typeable class</h2>
<p>As a simple starter, we can trivially print the type of any instance of <code>Typeable</code>. What are some existing instances of <code>Typeable</code>? Let’s ask GHCi:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; <span class="fu">:</span>i <span class="dt">Typeable</span>
<span class="kw">class</span> <span class="dt">Typeable</span> a <span class="kw">where</span><span class="ot"> typeOf ::</span> a <span class="ot">-&gt;</span> <span class="dt">TypeRep</span>
<span class="kw">instance</span> [overlap ok] (<span class="dt">Typeable1</span> s, <span class="dt">Typeable</span> a) <span class="ot">=&gt;</span> <span class="dt">Typeable</span> (s a)
<span class="kw">instance</span> [overlap ok] <span class="dt">Typeable</span> <span class="dt">TypeRep</span>
<span class="kw">instance</span> [overlap ok] <span class="dt">Typeable</span> <span class="dt">TyCon</span>
<span class="kw">instance</span> [overlap ok] <span class="dt">Typeable</span> <span class="dt">Ordering</span>
<span class="kw">instance</span> [overlap ok] <span class="dt">Typeable</span> <span class="dt">Integer</span>
<span class="kw">instance</span> [overlap ok] <span class="dt">Typeable</span> <span class="dt">Int</span>
<span class="kw">instance</span> [overlap ok] <span class="dt">Typeable</span> <span class="dt">Float</span>
<span class="kw">instance</span> [overlap ok] <span class="dt">Typeable</span> <span class="dt">Double</span>
<span class="kw">instance</span> [overlap ok] <span class="dt">Typeable</span> <span class="dt">Char</span>
<span class="kw">instance</span> [overlap ok] <span class="dt">Typeable</span> <span class="dt">Bool</span>
<span class="kw">instance</span> [overlap ok] <span class="dt">Typeable</span> ()</code></pre>
<p>That’s the basic Prelude types and the Typeable library’s own types.</p>
<p>There’s only one method in the <code>Typeable</code> class:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">typeOf ::</span> a <span class="ot">-&gt;</span> <span class="dt">TypeRep</span></code></pre>
<p>The <code>TypeRep</code> value has some useful normal instances:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; <span class="fu">:</span>i <span class="dt">TypeRep</span>
<span class="kw">instance</span> [overlap ok] <span class="dt">Eq</span> <span class="dt">TypeRep</span>
<span class="kw">instance</span> [overlap ok] <span class="dt">Ord</span> <span class="dt">TypeRep</span>
<span class="kw">instance</span> [overlap ok] <span class="dt">Show</span> <span class="dt">TypeRep</span>
<span class="kw">instance</span> [overlap ok] <span class="dt">Typeable</span> <span class="dt">TypeRep</span></code></pre>
<h2 id="use-case-1-print-the-type-of-something">Use-case 1: Print the type of something</h2>
<p>So we can use this function on a <code>Char</code> value, for example, and GHCi can print it:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; <span class="fu">:</span>t typeOf <span class="ch">&#39;a&#39;</span>
typeOf <span class="ch">&#39;a&#39;</span><span class="ot"> ::</span> <span class="dt">TypeRep</span>
λ&gt; typeOf <span class="ch">&#39;a&#39;</span>
<span class="dt">Char</span></code></pre>
<p>This is mostly useful for debugging, but can also be useful when writing generic encoders or any tool which needs an identifier to be associated with some generic value.</p>
<h2 id="use-case-2-compare-the-types-of-two-things">Use-case 2: Compare the types of two things</h2>
<p>We can also compare two type representations:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; typeOf <span class="ch">&#39;a&#39;</span> <span class="fu">==</span> typeOf <span class="ch">&#39;b&#39;</span>
<span class="dt">True</span>
λ&gt; typeOf <span class="ch">&#39;a&#39;</span> <span class="fu">==</span> typeOf ()
<span class="dt">False</span></code></pre>
<p>Any code which needs to allow any old type to be passed into it, but which has some interest in sometimes enforcing or triggering on a specific type can use this to compare them.</p>
<h2 id="use-case-3-reifying-from-generic-to-concrete">Use-case 3: Reifying from generic to concrete</h2>
<p>A common thing to need to do is when given a generic value, is to sometimes, if the type is right, actually work with the value as the concrete type, not a polymorphic type. For example, a printing function:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">char ::</span> <span class="dt">Typeable</span> a <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">String</span></code></pre>
<p>The specification for this function is: if given an <code>Char</code>, return its string representation, otherwise, return <code>&quot;unknown&quot;</code>. To do this, we need a function that will convert from a polymorphic value to a concrete one:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">cast ::</span> (<span class="dt">Typeable</span> a, <span class="dt">Typeable</span> b) <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> b</code></pre>
<p>This function from <code>Data.Typeable</code> will do just that. Now we can implement <code>char</code>:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; <span class="kw">let</span> char x <span class="fu">=</span> <span class="kw">case</span> cast x <span class="kw">of</span>
<span class="dt">Just</span> (<span class="ot">x ::</span> <span class="dt">Char</span>) <span class="ot">-&gt;</span> show x
<span class="dt">Nothing</span> <span class="ot">-&gt;</span> <span class="st">&quot;unknown&quot;</span>
λ&gt; char <span class="ch">&#39;a&#39;</span>
<span class="st">&quot;&#39;a&#39;&quot;</span>
λ&gt; char <span class="dv">5</span>
<span class="st">&quot;unknown&quot;</span>
λ&gt; char ()
<span class="st">&quot;unknown&quot;</span></code></pre>
<h2 id="the-data-class">The Data class</h2>
<p>That’s more or less where the interesting practical applications of the <code>Typeable</code> class ends. But it becomes more interesting once you have that, the <code>Data</code> class can take advantage of it. The <code>Data</code> class is much more interesting. The point is to be able to look into a data type’s constructors, its fields and traverse across or fold over them. Let’s take a look at the class.</p>
<p>Again, there are some basic instances provided:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">instance</span> <span class="dt">Data</span> a <span class="ot">=&gt;</span> <span class="dt">Data</span> [a]
<span class="kw">instance</span> <span class="dt">Data</span> <span class="dt">Ordering</span>
<span class="kw">instance</span> <span class="dt">Data</span> a <span class="ot">=&gt;</span> <span class="dt">Data</span> (<span class="dt">Maybe</span> a)
<span class="kw">instance</span> <span class="dt">Data</span> <span class="dt">Integer</span>
<span class="kw">instance</span> <span class="dt">Data</span> <span class="dt">Int</span>
<span class="kw">instance</span> <span class="dt">Data</span> <span class="dt">Float</span>
<span class="kw">instance</span> (<span class="dt">Data</span> a, <span class="dt">Data</span> b) <span class="ot">=&gt;</span> <span class="dt">Data</span> (<span class="dt">Either</span> a b)
<span class="kw">instance</span> <span class="dt">Data</span> <span class="dt">Double</span>
<span class="kw">instance</span> <span class="dt">Data</span> <span class="dt">Char</span>
<span class="kw">instance</span> <span class="dt">Data</span> <span class="dt">Bool</span></code></pre>
<p>It’s a rather big class, so I’ll just cover some methods that demonstrate the key use-cases.</p>
<h2 id="use-case-1-get-the-data-type">Use-case 1: Get the data type</h2>
<p>Similar to the <code>TypeRep</code>, you can use <code>dataTypeOf</code> to get a unique representation of a data type:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">dataTypeOf ::</span> <span class="dt">Data</span> a <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">DataType</span></code></pre>
<p>For example:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; dataTypeOf (<span class="dt">Just</span> <span class="ch">&#39;a&#39;</span>)
<span class="dt">DataType</span> {tycon <span class="fu">=</span> <span class="st">&quot;Prelude.Maybe&quot;</span>, datarep <span class="fu">=</span> <span class="dt">AlgRep</span> [<span class="dt">Nothing</span>,<span class="dt">Just</span>]}</code></pre>
<p>There aren’t any other interesting instances for this type, but we’ll look at uses for this type later. Representations (so-called <code>FooRep</code>) tend to be references from which you can reify into more concrete values.</p>
<h2 id="use-case-2-inspecting-a-data-type">Use-case 2: Inspecting a data type</h2>
<p>The most common thing to want to do is to get a list of constructors that a type contains. So, the <code>Maybe</code> type contains two.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; <span class="fu">:</span>t dataTypeConstrs
<span class="ot">dataTypeConstrs ::</span> <span class="dt">DataType</span> <span class="ot">-&gt;</span> [<span class="dt">Constr</span>]
λ&gt; dataTypeConstrs (dataTypeOf (<span class="dt">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> ()))
[<span class="dt">Nothing</span>,<span class="dt">Just</span>]</code></pre>
<p>We’ll look at what we can do with constructors later.</p>
<p>It’s also surprisingly common to want to see what the constructor is at a particular index. We could write this function ourself, but there’s already one provided:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; indexConstr (dataTypeOf (<span class="dt">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> ())) <span class="dv">2</span>
<span class="dt">Just</span></code></pre>
<p>Sometimes you want to know whether a data type is algebraic (in other words, does it have constructors and is it not one of the built-in types like Int/Float/etc)?</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; isAlgType (dataTypeOf (<span class="dt">Just</span> <span class="ch">&#39;a&#39;</span>))
<span class="dt">True</span>
λ&gt; isAlgType (dataTypeOf <span class="ch">&#39;a&#39;</span>)
<span class="dt">False</span></code></pre>
<div class="figure">
<img src="http://i.imgur.com/7ud0ezn.gif" /><p class="caption"></p>
</div>
<h2 id="use-case-3-get-the-constructor-of-a-value">Use-case 3: Get the constructor of a value</h2>
<p>We have the method</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">toConstr ::</span> a <span class="ot">-&gt;</span> <span class="dt">Constr</span></code></pre>
<p>Which given any instance of <code>Data</code> will yield a constructor.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; <span class="fu">:</span>i <span class="dt">Constr</span>
<span class="kw">data</span> <span class="dt">Constr</span>
<span class="kw">instance</span> <span class="dt">Eq</span> <span class="dt">Constr</span>
<span class="kw">instance</span> <span class="dt">Show</span> <span class="dt">Constr</span></code></pre>
<p>You can’t do much with a constructor as-is, but compare and print it:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; toConstr (<span class="dt">Just</span> <span class="ch">&#39;a&#39;</span>)
<span class="dt">Just</span>
λ&gt; toConstr (<span class="dt">Just</span> <span class="ch">&#39;a&#39;</span>) <span class="fu">==</span> toConstr (<span class="dt">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Char</span>)
<span class="dt">False</span></code></pre>
<p>However, those operations by themselves can be useful.</p>
<p>By the way, we can also get back the <code>DataRep</code> of a constructor:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; constrType (toConstr (<span class="dt">Just</span> <span class="ch">&#39;a&#39;</span>))
<span class="dt">DataType</span> {tycon <span class="fu">=</span> <span class="st">&quot;Prelude.Maybe&quot;</span>, datarep <span class="fu">=</span> <span class="dt">AlgRep</span> [<span class="dt">Nothing</span>,<span class="dt">Just</span>]}</code></pre>
<h2 id="use-case-4-get-fields-of-a-constructor">Use-case 4: Get fields of a constructor</h2>
<p>Another typical thing to want to do is to use the field names of a constructor. So for example:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; <span class="kw">data</span> <span class="dt">X</span> <span class="fu">=</span> <span class="dt">X</span> {<span class="ot"> foo ::</span> <span class="dt">Int</span>,<span class="ot"> bar ::</span> <span class="dt">Char</span> } <span class="kw">deriving</span> (<span class="dt">Typeable</span>,<span class="dt">Data</span>)
λ&gt; toConstr (<span class="dt">X</span> <span class="dv">0</span> <span class="ch">&#39;a&#39;</span>)
<span class="dt">X</span>
λ&gt; constrFields (toConstr (<span class="dt">X</span> <span class="dv">0</span> <span class="ch">&#39;a&#39;</span>))
[<span class="st">&quot;foo&quot;</span>,<span class="st">&quot;bar&quot;</span>]</code></pre>
<p>It’s a good use-case for serializing and debugging.</p>
<h2 id="use-case-5-make-a-real-value-from-its-constructor">Use-case 5: Make a real value from its constructor</h2>
<p>It’s actually possible to produce a value from its constructor. We have this function</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">fromConstr ::</span> <span class="dt">Data</span> a <span class="ot">=&gt;</span> <span class="dt">Constr</span> <span class="ot">-&gt;</span> a</code></pre>
<p>Example:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; fromConstr (toConstr (<span class="dt">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> ()))<span class="ot"> ::</span> <span class="dt">Maybe</span> ()
<span class="dt">Nothing</span></code></pre>
<p>But what do you do when the constructor has fields? No sweat. We have this function:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">fromConstrB ::</span> forall a<span class="fu">.</span> <span class="dt">Data</span> a
<span class="ot">=&gt;</span> (forall d<span class="fu">.</span> <span class="dt">Data</span> d <span class="ot">=&gt;</span> d) <span class="ot">-&gt;</span> <span class="dt">Constr</span> <span class="ot">-&gt;</span> a</code></pre>
<div class="figure">
<img src="http://i.imgur.com/vs9AG.gif" /><p class="caption"></p>
</div>
<p>Haskell beginners: Don’t fear the rank-N type. What it’s saying is merely that the <code>fromConstrB</code> function determines what the type of <code>d</code> will be by itself, by looking at <code>Constr</code>. It’s not provided externally by the caller, as it would be if the <code>forall d.</code> were at the same level as the <code>a</code>. Think of it like scope. <code>let a = d in let d = …</code> doesn’t make sense: the <code>d</code> is in a lower scope. That means we can’t just write:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">fromConstrB (<span class="dv">5</span><span class="ot"> ::</span> <span class="dt">Int</span>) (toConstr (<span class="dt">Just</span> <span class="dv">1</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>))<span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span></code></pre>
<p>The <code>Int</code> cannot unify with the <code>d</code> because the quantification is one level lower. It basically doesn’t exist outside of the <code>(forall d. Data d =&gt; d)</code> (nor can it escape). That’s okay, though. There is a type-class constraint which lets us be generic. We already have a function producing a value of that type:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; <span class="fu">:</span>t fromConstr (toConstr (<span class="dv">1</span><span class="ot"> ::</span> <span class="dt">Int</span>))
fromConstr (toConstr (<span class="dv">1</span><span class="ot"> ::</span> <span class="dt">Int</span>))<span class="ot"> ::</span> <span class="dt">Data</span> a <span class="ot">=&gt;</span> a</code></pre>
<p>So we can just use that:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; fromConstrB (fromConstr (toConstr (<span class="dv">1</span><span class="ot"> ::</span> <span class="dt">Int</span>)))
(toConstr (<span class="dt">Just</span> <span class="dv">1</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>))<span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>
<span class="dt">Just</span> <span class="dv">1</span></code></pre>
<p>Tada! But wait… What if there’re <em>more</em> fields? How do we provide more than one, and of different types?</p>
<p>Enter <code>fromConstrM</code>:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">fromConstrM ::</span> forall m a<span class="fu">.</span> (<span class="dt">Monad</span> m, <span class="dt">Data</span> a)
<span class="ot">=&gt;</span> (forall d<span class="fu">.</span> <span class="dt">Data</span> d <span class="ot">=&gt;</span> m d) <span class="ot">-&gt;</span> <span class="dt">Constr</span> <span class="ot">-&gt;</span> m a</code></pre>
<p>Because it’s monadic we can use a state monad to keep an index! Observe:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; <span class="fu">:</span>t execState
<span class="ot">execState ::</span> <span class="dt">State</span> s a <span class="ot">-&gt;</span> s <span class="ot">-&gt;</span> s
λ&gt; <span class="fu">:</span>t execState (modify (<span class="fu">+</span><span class="dv">1</span>))
execState (modify (<span class="fu">+</span><span class="dv">1</span>))<span class="ot"> ::</span> <span class="dt">Num</span> s <span class="ot">=&gt;</span> s <span class="ot">-&gt;</span> s
λ&gt; <span class="fu">:</span>t execState (forM_ [<span class="dv">1</span><span class="fu">..</span><span class="dv">5</span>] (const (modify (<span class="fu">+</span><span class="dv">1</span>))))
execState (forM_ [<span class="dv">1</span><span class="fu">..</span><span class="dv">5</span>] (const (modify (<span class="fu">+</span><span class="dv">1</span>))))<span class="ot"> ::</span> <span class="dt">Num</span> s <span class="ot">=&gt;</span> s<span class="ot">-&gt;</span> s
λ&gt; execState (forM_ [<span class="dv">1</span><span class="fu">..</span><span class="dv">5</span>] (const (modify (<span class="fu">+</span><span class="dv">1</span>)))) <span class="dv">5</span>
<span class="dv">10</span></code></pre>
<p>Let’s put this to use with <code>fromConstrM</code>:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; evalState
(fromConstrM
(<span class="kw">do</span> i <span class="ot">&lt;-</span> get
modify (<span class="fu">+</span><span class="dv">1</span>)
return
(<span class="kw">case</span> i <span class="kw">of</span>
<span class="dv">0</span> <span class="ot">-&gt;</span> fromConstr (toConstr (<span class="dv">5</span><span class="ot">::</span><span class="dt">Int</span>))
<span class="dv">1</span> <span class="ot">-&gt;</span> fromConstr (toConstr <span class="ch">&#39;b&#39;</span>)))
(toConstr (<span class="dt">Foo</span> <span class="dv">4</span> <span class="ch">&#39;a&#39;</span>)))
<span class="dv">0</span><span class="ot"> ::</span> <span class="dt">Foo</span>
<span class="dt">Foo</span> <span class="dv">5</span> <span class="ch">&#39;b&#39;</span>
λ&gt;</code></pre>
<p>In other words, keep an index starting at 0. Increase it each iteration that <code>fromConstrM</code> does. When we’re at index 0, return an <code>Int</code>, when we’re at index 1, return a <code>Char</code>. Easy! Right?</p>
<div class="figure">
<img src="http://i.imgur.com/HfAq4.gif" /><p class="caption"></p>
</div>
<h2 id="use-case-6-mapping-over-data-structures-generically">Use-case 6: mapping over data structures generically</h2>
<p>A common thing to want is to map over a value in a structure-preserving way, but changing its values. For that we have <code>gmapT</code>:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">gmapT ::</span> forall a<span class="fu">.</span> <span class="dt">Data</span> a
<span class="ot">=&gt;</span> (forall b<span class="fu">.</span> <span class="dt">Data</span> b <span class="ot">=&gt;</span> b <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> a</code></pre>
<p>Similar to <code>fromConstr*</code>, there is a rank-n type <code>b</code> that refers to each type in the constructor of type <code>a</code>. It’s easy enough to use:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; gmapT
(\d <span class="ot">-&gt;</span>
<span class="kw">case</span> cast d <span class="kw">of</span>
<span class="dt">Nothing</span> <span class="ot">-&gt;</span> d
<span class="dt">Just</span> x <span class="ot">-&gt;</span>
fromJust (cast (<span class="kw">if</span> isUpper x <span class="kw">then</span> <span class="ch">&#39;!&#39;</span> <span class="kw">else</span> x)))
(<span class="dt">Foo</span> <span class="dv">4</span> <span class="ch">&#39;a&#39;</span>)
<span class="dt">Foo</span> <span class="dv">4</span> <span class="ch">&#39;a&#39;</span>
λ&gt; gmapT
(\d <span class="ot">-&gt;</span>
<span class="kw">case</span> cast d <span class="kw">of</span>
<span class="dt">Nothing</span> <span class="ot">-&gt;</span> d
<span class="dt">Just</span> x <span class="ot">-&gt;</span>
fromJust (cast (<span class="kw">if</span> isUpper x <span class="kw">then</span> <span class="ch">&#39;!&#39;</span> <span class="kw">else</span> x)))
(<span class="dt">Foo</span> <span class="dv">4</span> <span class="ch">&#39;A&#39;</span>)
<span class="dt">Foo</span> <span class="dv">4</span> <span class="ch">&#39;!&#39;</span></code></pre>
<p>Here I’m doing a little check on any field in the constructor of type <code>Char</code> and if it’s upper case, replacing it with <code>!</code>, otherwise leaving it as-is. The first trick is to use the <code>cast</code> function we used earlier to reify the generic <code>d</code> into something real (<code>Char</code>). The second trick is to cast our concrete <code>Char</code> back into a generic <code>d</code> type.</p>
<p>Just like <code>fromConstrM</code> earlier, if you want to operate on exact indices of the constructor rather than going by type, you can use <code>gmapM</code> and use a state monad to do the same thing as we did before.</p>
<h2 id="use-case-7-generating-from-data-structures-generically">Use-case 7: generating from data structures generically</h2>
<p>Another slightly different use-case is to walk over the values of a data structure, collecting the result. You can do this with <code>gmapM</code> and a state monad or a writer, but there’s a handy function already to do this:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">gmapQ ::</span> forall a<span class="fu">.</span> <span class="dt">Data</span> a <span class="ot">=&gt;</span> (forall d<span class="fu">.</span> <span class="dt">Data</span> d <span class="ot">=&gt;</span> d <span class="ot">-&gt;</span> u) <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> [u]</code></pre>
<p>Trivial example:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; gmapQ (\d <span class="ot">-&gt;</span> toConstr d) (<span class="dt">Foo</span> <span class="dv">5</span> <span class="ch">&#39;a&#39;</span>)
[<span class="dv">5</span>,<span class="ch">&#39;a&#39;</span>]</code></pre>
<p>A more useful example can be found in <a href="https://github.com/chrisdone/structured-haskell-mode/blob/18c011978acfca30bac800d0ac0e9e31e653c440/src/Main.hs#L96">structured-haskell-mode</a> which walks over the Haskell syntax tree and collects source spans into a flat list. Another decent example is in <a href="https://github.com/chrisdone/present/blob/master/src/Present.hs#L75">the present package</a>. There’s also an example in <a href="https://github.com/faylang/fay/blob/master/src/Fay/Convert.hs#L54">Fay</a> to encode types to JSON with a specific Fay-runtime-specific encoding.</p>
<h2 id="printer-example">Printer example</h2>
<p>Here’s a trivial (not very good, but something I wrote once) generic printer:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">gshows ::</span> <span class="dt">Data</span> a <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">ShowS</span>
gshows <span class="fu">=</span> render <span class="ot">`extQ`</span> (shows<span class="ot"> ::</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">ShowS</span>) <span class="kw">where</span>
render t
<span class="fu">|</span> isTuple <span class="fu">=</span> showChar <span class="ch">&#39;(&#39;</span>
<span class="fu">.</span> drop <span class="dv">1</span>
<span class="fu">.</span> commaSlots
<span class="fu">.</span> showChar <span class="ch">&#39;)&#39;</span>
<span class="fu">|</span> isNull <span class="fu">=</span> showString <span class="st">&quot;[]&quot;</span>
<span class="fu">|</span> isList <span class="fu">=</span> showChar <span class="ch">&#39;[&#39;</span>
<span class="fu">.</span> drop <span class="dv">1</span>
<span class="fu">.</span> listSlots
<span class="fu">.</span> showChar <span class="ch">&#39;]&#39;</span>
<span class="fu">|</span> otherwise <span class="fu">=</span> showChar <span class="ch">&#39;(&#39;</span>
<span class="fu">.</span> constructor
<span class="fu">.</span> slots
<span class="fu">.</span> showChar <span class="ch">&#39;)&#39;</span>
<span class="kw">where</span> constructor <span class="fu">=</span> showString <span class="fu">.</span> showConstr <span class="fu">.</span> toConstr <span class="fu">$</span> t
slots <span class="fu">=</span> foldr (<span class="fu">.</span>) id <span class="fu">.</span> gmapQ ((showChar <span class="ch">&#39; &#39;</span> <span class="fu">.</span>) <span class="fu">.</span> gshows) <span class="fu">$</span> t
commaSlots <span class="fu">=</span> foldr (<span class="fu">.</span>) id <span class="fu">.</span> gmapQ ((showChar <span class="ch">&#39;,&#39;</span> <span class="fu">.</span>) <span class="fu">.</span> gshows) <span class="fu">$</span> t
listSlots <span class="fu">=</span> foldr (<span class="fu">.</span>) id <span class="fu">.</span> init <span class="fu">.</span> gmapQ ((showChar <span class="ch">&#39;,&#39;</span> <span class="fu">.</span>) <span class="fu">.</span> gshows) <span class="fu">$</span> t
isTuple <span class="fu">=</span> all (<span class="fu">==</span><span class="ch">&#39;,&#39;</span>) (filter (not <span class="fu">.</span> flip elem <span class="st">&quot;()&quot;</span>) (constructor <span class="st">&quot;&quot;</span>))
isNull <span class="fu">=</span> null (filter (not <span class="fu">.</span> flip elem <span class="st">&quot;[]&quot;</span>) (constructor <span class="st">&quot;&quot;</span>))
isList <span class="fu">=</span> constructor <span class="st">&quot;&quot;</span> <span class="fu">==</span> <span class="st">&quot;(:)&quot;</span></code></pre>
<p>I wrote it because the GHC API doesn’t have <code>Show</code> instances for most of its data types, so it’s rather hard to actually inspect <em>any</em> data types that you’re working with in the REPL. It has instances for pretty printing, but pretty printing confuses presentation with data.</p>
<p>Example:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; <span class="kw">data</span> <span class="dt">Foo</span> <span class="fu">=</span> <span class="dt">Foo</span> <span class="dt">Char</span> <span class="dt">Int</span> <span class="kw">deriving</span> (<span class="dt">Data</span>,<span class="dt">Typeable</span>)
λ&gt; gshow ([<span class="dt">Just</span> <span class="dv">2</span>],<span class="ch">&#39;c&#39;</span>,<span class="dt">Foo</span> <span class="ch">&#39;a&#39;</span> <span class="dv">5</span>)
<span class="st">&quot;([(Just (2))],(&#39;c&#39;),(Foo (&#39;a&#39;) (5)))&quot;</span></code></pre>
<p>Note: no <code>Show</code> instance for <code>Foo</code>.</p>
<h2 id="summary">Summary</h2>
<p>We’ve briefly covered how to query types, how to cast them, how to walk over them or generate from them. There’re other things one can do, but those are the main things. The real trick is understanding how to make the types work and that comes with a bit of experience. Fiddle around with the concepts above and you should gain an intution for what is possible with this library. See also: <a href="http://hackage.haskell.org/package/syb-0.4.1/docs/Data-Generics-Aliases.html">Data.Generics.Aliases</a>.</p>
<p>Hope it helps!</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>I’ll migrate this to the HaskellWiki when it doesn’t look so, uh, shall we say, unattractive.<a href="#fnref1">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Tue, 22 Apr 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/data-typeable</guid>
</item>
<item>
<title>12 Years a Slave</title>
<link>http://chrisdone.com/posts/12-years-a-slave</link>
<description><![CDATA[<p>Wow. I just watched it. I’ll be thinking about this film for a long time.</p>
<p>Naturally, I immediately jumped onto Wikipedia to find when slavery was abolished in the US. In 1865 the U.S. abolished slavery with the Thirteenth Amendment to the Constitution.</p>
<p>It goes to show how ineffectual Quenten Tarantino is. Django wasn’t daring, it wasn’t harrowing, it was one big joke, a big revenge genre exploitation movie. But Tarantino himself saw it as bringing slavary to the foyer (as if no one else has been doing so).</p>
<p>Chiwetel Ejiofor is stunning. At one point in the film he looks directly at the camera for a long time. He looks right into your eyes. Wonderful scene.</p>
<p>Michael Fassbender is brilliant and convincing as this lascivious power mad drunk with no conscience. There’s a tense scene between him and Chiwetel, stood in the dark with lamplight only that is perfect.</p>
<p>Brad Pitt kind of sticks out like a sore thumb, but I didn’t mind his part. He lectures a bit but it wasn’t too contrived. I didn’t find Benedict Cumberbatch’s accent too convincing. Sarah Paulson was quite hard to read, which I liked. Her character is conniving.</p>
<p>I was struck in the first few minutes by footage of a paddle steamer. The paddles on the paddle wheel are red and they’re splashing through the ocean continuously. There is a bunch of visual metaphor in the movie like that.</p>
<p>I was also struck by a scene where a slave runs to his master and hugs him, and they walk away arm in arm. That kind of relationship in the age of slavery is almost more eye opening than all the violence put upon Lupita Nyong’o’s character. Slaves are so happy to be with their master in servitude, than the unknown hell that awaits them elsewhere in America.</p>
<p>At one point I realised it kind of reminded me of The Pianist.</p>
<p>There was one line in the movie that floored me, said by the wife of a slavemaster to a distraught and crying slave who’d been separated from her children, with the faintest air of pity,</p>
<p>“Your children will soon be forgotten.”</p>]]></description>
<pubDate>Sun, 13 Apr 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/12-years-a-slave</guid>
</item>
<item>
<title>Beers</title>
<link>http://chrisdone.com/posts/beers</link>
<description><![CDATA[<p>Thought I’d make a page of all the beers I’ve been trying. A beerlog. A bleeg! I’ll update this specific page when I try new beers from now on.</p>
<h2 id="chimay-bleue">Chimay Bleue</h2>
<p><a href="http://www.ratebeer.com/beer/chimay-bleue-blue--grande-reserve/53/">Link on ratebeer</a></p>
<p>This is a delicious beer! Chocolately texture, very rich tastes and pleasant aftertaste. High alcohol content but you don’t notice it.</p>
<ul>
<li>Enjoyed: ✓</li>
<li>Would drink again: ✓</li>
<li>Would recommend: ✓</li>
</ul>
<h2 id="la-trappe-blond">La Trappe Blond</h2>
<p><a href="http://www.ratebeer.com/beer/la-trappe-blond/10380/">Link on ratebeer</a></p>
<p>I love this beer. Very fruity. Big bottle, good for an evening. I’ve had this a couple times now.</p>
<ul>
<li>Enjoyed: ✓</li>
<li>Would drink again: ✓</li>
<li>Would recommend: ✓</li>
</ul>
<h2 id="la-chouffe">La Chouffe</h2>
<p><a href="http://www.ratebeer.com/beer/la-chouffe/1614/">Link on ratebeer</a></p>
<p>This is one tasty beverage. Not fruity, almost meaty to me. It goes well with some pasta ragù di carne. I’ve had this twice and loved it each time. Not so many beers have such a full, unique taste. Comes in a large bottle a la Trappe Blond, good for an evening beer.</p>
<ul>
<li>Enjoyed: ✓</li>
<li>Would drink again: ✓</li>
<li>Would recommend: ✓</li>
</ul>
<h2 id="aecht-schlenkerla-rauchbier-märzen">Aecht Schlenkerla Rauchbier Märzen</h2>
<p><a href="http://www.ratebeer.com/beer/aecht-schlenkerla-rauchbier-marzen/1269/">Link on ratebeer</a></p>
<p>Hated it! It’s an interesting beer with a definite smokey taste, but I simply don’t like this type of beer, I discovered while drinking it.</p>
<ul>
<li>Enjoyed: ✗</li>
<li>Would drink again: ✗</li>
<li>Would recommend: If you like smoked beers.</li>
</ul>
<h2 id="leffe-radieuse">Leffe Radieuse</h2>
<p><a href="http://www.ratebeer.com/beer/leffe-radieuse/2512/">Link on ratebeer</a></p>
<p>This beer surprised me with how quality it was. It’s high alocoholic content, at 8.5%, but the bottle is small, and actually you cannot really taste the alcohol, it’s very fruity and has character. It’s suitable to drink one bottle with a glass of water and something savoury to eat. It’s rather sweet and does not go well with sweet foods.</p>
<ul>
<li>Enjoyed: ✓</li>
<li>Would drink again: ✓</li>
<li>Would recommend: ✓</li>
</ul>
<h2 id="aldaris-dūmaku">Aldaris Dūmaku</h2>
<p><a href="http://www.ratebeer.com/beer/aldaris-d363maku/123608/">Link on ratebeer</a></p>
<p>An award-winning Latvian unfiltered beer which has a tasty texture; put it in the freezer for a short while and get it out when the bottle has a sheen of condensation over it. Lovely!</p>
<ul>
<li>Enjoyed: ✓</li>
<li>Would drink again: ✓</li>
<li>Would recommend: If you like slightly bitter beers.</li>
</ul>]]></description>
<pubDate>Fri, 11 Apr 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/beers</guid>
</item>
<item>
<title>Haskell structured diffs</title>
<link>http://chrisdone.com/posts/haskell-diff</link>
<description><![CDATA[<p>Project-request: someone please implement a program that will diff Haskell in a cleverer way than lines.</p>
<p>In an effort to reign in my incessant work on Haskell tooling<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup>, I’m outlining a tool that I’d personally like and welcome people to implement it. Otherwise it serves as a motivating problem description for the next time I come around to it myself with free time.</p>
<p>Before anyone emails me saying “lines/words are simple, other things are hard, that’s why it’s not been done yet. People undervalue the simple solution …” with a long lecture, spare me!</p>
<h2 id="the-concrete-diff">The concrete diff</h2>
<p>The concrete diff is the line-based, and sometimes character-based, diff that we all know and love. There’s no reason to throw this away. You will need to keep this as an optional backend for when you are unable to parse a Haskell file.</p>
<p>Pros: simple to implement. You produce the necessary lines to delete and insert to create the change from A to B.</p>
<p>Cons: doesn’t know about syntactic redundancy where some changes don’t mean anything, and where the actual important change occurs. For example:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">main <span class="fu">=</span> <span class="kw">do</span> putStrLn <span class="st">&quot;Write your name!&quot;</span>
name <span class="ot">&lt;-</span> getLine
print name</code></pre>
<p>Now you change this to:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">main <span class="fu">=</span> <span class="kw">do</span> args <span class="ot">&lt;-</span> getArgs
<span class="kw">case</span> args <span class="kw">of</span>
[] <span class="ot">-&gt;</span> <span class="kw">do</span> putStrLn <span class="st">&quot;Write your name!&quot;</span>
name <span class="ot">&lt;-</span> getLine
print name
_ <span class="ot">-&gt;</span> runWithArgs args</code></pre>
<p>The diff will look like this:</p>
<pre class="sourceCode diff"><code class="sourceCode diff"><span class="dt">@@ -5,3 +5,6 @@ module Main where</span>
<span class="st">-main = do putStrLn &quot;Write your name!&quot;</span>
<span class="st">- name &lt;- getLine</span>
<span class="st">- print name</span>
<span class="ot">+main = do args &lt;- getArgs</span>
<span class="ot">+ case args of</span>
<span class="ot">+ [] -&gt; do putStrLn &quot;Write your name!&quot;</span>
<span class="ot">+ name &lt;- getLine</span>
<span class="ot">+ print name</span>
<span class="ot">+ _ -&gt; runWithArgs args</span></code></pre>
<p>But it’s clear to observe that this is not the change we made in spirit, it’s just one line-based way to achieve it. In actual fact, our <code>do putStrLn …</code> was moved into a <code>case</code>, un-changed. At this size, it’s not a big deal. When the code is more interesting, it’s important to know what was really changed, and what remains the same.</p>
<h2 id="the-abstract-syntax-diff">The abstract syntax diff</h2>
<p>Enter the syntactic diff. We show the difference between two syntactic trees. How this is to be achieved in a readable way is the rub, but here are some ideas.</p>
<p>Take our example above, one approach can be to label nodes.</p>
<p>Before:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">¹{main <span class="fu">=</span> ²{<span class="kw">do</span> putStrLn <span class="st">&quot;Write your name!&quot;</span>
name <span class="ot">&lt;-</span> getLine
print name}}</code></pre>
<p>After:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">¹{main <span class="fu">=</span> <span class="kw">do</span> args <span class="ot">&lt;-</span> getArgs
<span class="kw">case</span> args <span class="kw">of</span>
[] <span class="ot">-&gt;</span> ²{<span class="kw">do</span> putStrLn <span class="st">&quot;Write your name!&quot;</span>
name <span class="ot">&lt;-</span> getLine
print name}
_ <span class="ot">-&gt;</span> runWithArgs args}</code></pre>
<p>Now, at least at a superficial glance, you don’t even need this explained to you. You can see exactly what has happened: The code before has changed to the code after, but we can see that node<sub>2</sub> has just moved to inside the case.</p>
<p>Where the trickiness arises is taking this to its logical conclusion and applying it generally. What’s displayed if you also change the string in the <code>putStrLn</code>? Good question. Here’s an idea:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">¹{main <span class="fu">=</span> ²{<span class="kw">do</span> putStrLn <span class="fu">-</span>{<span class="st">&quot;Write your name!&quot;</span>}
name <span class="ot">&lt;-</span> getLine
print name}}</code></pre>
<p>Because the node <code>&quot;Write your name&quot;</code> has now been lost, we don’t need to reference it any longer. So one way to show that it has been removed could be to put <code>-{…}</code>. And then to show what replaced it, put in <code>+{…}</code>, a la classic diffs:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">¹{main <span class="fu">=</span> <span class="fu">+</span>{<span class="kw">do</span> args <span class="ot">&lt;-</span> getArgs
<span class="kw">case</span> args <span class="kw">of</span>
[] <span class="ot">-&gt;</span> ²{<span class="kw">do</span> putStrLn <span class="fu">+</span>{<span class="st">&quot;Write your name!&quot;</span>}
name <span class="ot">&lt;-</span> getLine
print name}
_ <span class="ot">-&gt;</span> runWithArgs args}}</code></pre>
<p>In reality this rule would insert more <code>-{…}</code> and <code>+{…}</code> than I’ve written here, but I’m writing these examples manually so take them with a grain of salt. Let’s take it further and say that the string has actually been moved. Then we should indeed give it a number to reference it later:</p>
<p>Before:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">¹{main <span class="fu">=</span> ²{<span class="kw">do</span> putStrLn ³{<span class="st">&quot;Write your name!&quot;</span>}
name <span class="ot">&lt;-</span> getLine
print name}}</code></pre>
<p>After:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">¹{main <span class="fu">=</span> <span class="fu">+</span>{<span class="kw">do</span> args <span class="ot">&lt;-</span> getArgs
<span class="kw">case</span> args <span class="kw">of</span>
[] <span class="ot">-&gt;</span> ²{<span class="kw">do</span> putStrLn <span class="fu">+</span>{greeting}
name <span class="ot">&lt;-</span> getLine
print name}
_ <span class="ot">-&gt;</span> runWithArgs args}
<span class="fu">+</span>{<span class="kw">where</span> greeting <span class="fu">=</span> ³{<span class="st">&quot;Write your name!&quot;</span>}}}</code></pre>
<p>Again, I don’t think anybody is going to find this confusing. The node<sub>3</sub> has moved into a <code>where</code> clause, which has been named <code>greeting</code> and referenced in place of its original place.</p>
<p>Am I making obvious sense, here? It’s not a particularly novel display, it states what happened syntactically, precisely. With a UI, you could expand/collapse nodes in a nested fashion or “explode” all the pieces into a flat list of numbered or +’d or -’d nodes, or just narrow down to one specific interesting expression, like</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">²{<span class="kw">do</span> putStrLn <span class="fu">+</span>{greeting}
name <span class="ot">&lt;-</span> getLine
print name}</code></pre>
<p>If you’re sufficiently nerd-sniped to find this interesting and do-able, then I invite you to go ahead and give it a go. I’d love to see a prototype. I don’t plan on implementing this in the near or distant future, so we won’t be toe stepping.</p>
<h2 id="the-reduced-semantic-diff">The reduced semantic diff</h2>
<p>If you’re still reading by this point, let me try to entice you with ambitious ideas. Take the above approach, everything we just laid out, but let’s put an additional step in there: instead of diffing Haskell’s abstract syntax tree, diff the Core.</p>
<p>If you compile the below with GHC,</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">main <span class="fu">=</span> <span class="kw">case</span> <span class="dt">Just</span> () <span class="kw">of</span>
<span class="dt">Just</span> () <span class="ot">-&gt;</span> print <span class="st">&quot;Hey!&quot;</span></code></pre>
<p>The external core is:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="fu">%</span><span class="kw">module</span> main<span class="fu">:</span><span class="dt">Main</span>
main<span class="fu">:</span><span class="ot">main5 ::</span> (<span class="dt">ZMZN</span> <span class="dt">Char</span>) <span class="fu">=</span> unpackCStringzh (<span class="st">&quot;Hey!&quot;</span><span class="ot">::</span><span class="dt">Addrzh</span>);
main<span class="fu">:</span><span class="ot">main4 ::</span> (<span class="dt">ZMZN</span> <span class="dt">Char</span>) <span class="fu">=</span> <span class="dt">ZC</span> <span class="fu">@</span> <span class="dt">Char</span> base<span class="fu">:</span>zdfShowChar1 (<span class="dt">ZMZN</span> <span class="fu">@</span> <span class="dt">Char</span>);
main<span class="fu">:</span><span class="ot">main3 ::</span> (<span class="dt">ZMZN</span> <span class="dt">Char</span>) <span class="fu">=</span> base<span class="fu">:</span>showLitString main<span class="fu">:</span>main5 main<span class="fu">:</span>main4;
main<span class="fu">:</span><span class="ot">main2 ::</span> (<span class="dt">ZMZN</span> <span class="dt">Char</span>) <span class="fu">=</span> <span class="dt">ZC</span> <span class="fu">@</span> <span class="dt">Char</span> base<span class="fu">:</span>zdfShowChar1 main<span class="fu">:</span>main3;
main<span class="fu">:</span><span class="ot">main1 ::</span> (<span class="dt">Statezh</span> <span class="dt">RealWorld</span>) <span class="ot">-&gt;</span> (<span class="dt">Z2H</span> ((<span class="dt">Statezh</span> <span class="dt">RealWorld</span>)) <span class="dt">Z0T</span>) <span class="fu">=</span>
\ (<span class="ot">etaB1::</span>(<span class="dt">Statezh</span> <span class="dt">RealWorld</span>)) <span class="ot">-&gt;</span>
base<span class="fu">:</span>hPutStr2 base<span class="fu">:</span>stdout main<span class="fu">:</span>main2 <span class="dt">True</span> etaB1;
main<span class="fu">:</span><span class="ot">main ::</span> (<span class="dt">IO</span> <span class="dt">Z0T</span>) <span class="fu">=</span> <span class="fu">%</span>cast (main<span class="fu">:</span>main1) (<span class="fu">%</span>sym ((<span class="dt">NTCoZCIO</span> <span class="dt">Z0T</span>)));
main<span class="fu">:</span><span class="ot">main6 ::</span> (<span class="dt">Statezh</span> <span class="dt">RealWorld</span>) <span class="ot">-&gt;</span> (<span class="dt">Z2H</span> ((<span class="dt">Statezh</span> <span class="dt">RealWorld</span>)) <span class="dt">Z0T</span>) <span class="fu">=</span>
\ (<span class="ot">etaXb::</span>(<span class="dt">Statezh</span> <span class="dt">RealWorld</span>)) <span class="ot">-&gt;</span>
base<span class="fu">:</span>runMainIO1 <span class="fu">@</span> <span class="dt">Z0T</span> (<span class="fu">%</span>cast (main<span class="fu">:</span>main1) (<span class="fu">%</span>sym ((<span class="dt">NTCoZCIO</span> <span class="dt">Z0T</span>))))
etaXb;
main<span class="fu">:</span><span class="dt">ZCmain</span><span class="ot"> ::</span> (<span class="dt">IO</span> <span class="dt">Z0T</span>) <span class="fu">=</span> <span class="fu">%</span>cast (main<span class="fu">:</span>main6) (<span class="fu">%</span>sym ((<span class="dt">NTCoZCIO</span> <span class="dt">Z0T</span>)));</code></pre>
<p>You can see that the pointless <code>case</code> has been removed. This is the bread and butter of Core simplification. But if I remove the case myself, the Core is exactly the same. This is redundant semantic content, which is why GHC removed it.</p>
<p>If someone made a change like this in a real codebase which removed some redundant <em>semantic</em> content, not just syntactical redundancy, your diff could show it like that. In other words, nothing important semantically actually happened here.</p>
<p>In fact, if I refactored a bunch of code, re-organized a bit, does my next colleague really want to read through all the syntax tree just to see the crux of what changed? Sometimes, but not always. Sometimes, they just want to see the precise thing that will change at runtime.</p>
<p>It might actually be insane, with big blow ups in code difference for minute high-level changes, or it might be great for teams caring about performance. Difficult to know until you try it. You can also do a source-mapping back to the original Haskell source, for a more interesting display.</p>
<p>If you want to implement this, I would love to see any results.</p>
<h2 id="the-typed-diff">The typed diff</h2>
<p>Okay, you’re still reading so you’re pretty easily nerd sniped. Let’s continue with the ideas. Another type of difference between two sources is the types of expressions in there. Consider:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">main <span class="fu">=</span> <span class="kw">let</span> x <span class="fu">=</span> [<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>]
<span class="kw">in</span> print (x <span class="fu">&lt;&gt;</span> x)</code></pre>
<p>Now you change the code to:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">main <span class="fu">=</span> <span class="kw">let</span> x <span class="fu">=</span> myFancyMonoid
<span class="kw">in</span> print (x <span class="fu">&lt;&gt;</span> x)</code></pre>
<p>Our structural diff laid out earlier will show this:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">main <span class="fu">=</span> <span class="kw">let</span> x <span class="fu">=</span> <span class="fu">-</span>{[<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>]}
<span class="kw">in</span> print (x <span class="fu">&lt;&gt;</span> x)</code></pre>
<p>After:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">main <span class="fu">=</span> <span class="kw">let</span> x <span class="fu">=</span> <span class="fu">+</span>{myFancyMonoid}
<span class="kw">in</span> print (x <span class="fu">&lt;&gt;</span> x)</code></pre>
<p>But actually, more things have changed here. As a result of the different monoid instance, the <code>print (x &lt;&gt; x)</code> will do something different. Maybe it’s a <code>*</code> rather than <code>+</code>, maybe it’s a number, whatever. Maybe that expression is used in a more interesting way than merely printing it. What’s the real diff?</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">main <span class="fu">=</span> <span class="kw">let</span> {<span class="ot">x::</span>[<span class="dt">Integer</span>]} <span class="fu">=</span> <span class="fu">-</span>{[<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>]}
<span class="kw">in</span> print {{(x <span class="fu">&lt;&gt;</span> x)}<span class="ot">::</span>[<span class="dt">Integer</span>]}</code></pre>
<p>After:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">main <span class="fu">=</span> <span class="kw">let</span> {<span class="ot">x::</span><span class="dt">MyFancyMonoid</span>} <span class="fu">=</span> <span class="fu">+</span>{myFancyMonoid}
<span class="kw">in</span> print {(x <span class="fu">&lt;&gt;</span> x)}<span class="ot">::</span><span class="dt">MyFancyMonoid</span>}</code></pre>
<p>Or something like that. I’m being hand-wavey in the display, here. The real difference is that we’ve changed the type of <code>x</code>. It’s an important change, which has semantic meaning. My ideas are more vague here. I haven’t thought through many scenarios of how to represent this. But one thing is clear: a diff of types can actually be useful and interesting.</p>
<h2 id="the-editing-diff">The editing diff</h2>
<p>The diffs above are all examples of “cold” diffs. Calculating the difference between two files as-is. If you’re in a structured editor like <a href="http://peaker.github.io/lamdu/">Lamdu</a>, then you don’t have to do cold diffs and figure out and guess at what happened. You know exactly what happened. This node was raised here, this variable was renamed there, etc. But if you want to work on that, you pretty much have to work on Lamdu.</p>
<h2 id="summary">Summary</h2>
<p>In summary I’ve intentionally listed increasingly more wacky diff ideas, from the familiar to the fairly novel. My general approach to tooling is progressive: start with the simplest working implementation then step up. Structured-haskell-mode is an example of this. It’s no Lamdu, and it’s no vanilla text-based mode. It’s a stepping stone inbetween. The impedance to try SHM is lower.</p>
<p>In the same way, maybe we can start with the abstract syntax diff, let people become acclimatized to it, let it stabilize, get it integrated into things like Git, and then work our way up from there.</p>
<p>If nobody bothers trying out these ideas, I’ll probably end up doing them myself eventually, but I thought I’d put the suggestion out there first.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>In favour of writing programs that concern themselves with things other than Haskell for once!<a href="#fnref1">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Tue, 01 Apr 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/haskell-diff</guid>
</item>
<item>
<title>One step forward, two steps back</title>
<link>http://chrisdone.com/posts/one-step-forward-two-steps-back</link>
<description><![CDATA[<p>The issue is that programming languages don’t go forward, they move sideways or diagonally, or sometimes backwards.</p>
<p>A new car comes out, and it has some cool feature: Hey, it has road surface detection and changes the steering accordingly! But it should also come with all the old stuff that you come to expect. Comfy seats, seatbelts, airconditioner, heated windows, wipers, proximity detection, power steering, cruise control, etc.</p>
<p>With new programming languages, what you tend to get is a chassis, engine and steering wheel, and the road surface detection.</p>
<p>Here is a list of cool ideas that have been discovered and implemented in programming languages, but which do not in their whole make up any existing language:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Design_by_contract">Contracts</a></li>
<li><a href="http://en.wikipedia.org/wiki/Pattern_matching">Pattern matching</a></li>
<li><a href="http://c2.com/cgi/wiki?SyntacticAbstraction">Syntactic abstraction</a><sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup></li>
<li><a href="http://en.wikipedia.org/wiki/Type_system">Static types</a></li>
<li><a href="http://en.wikipedia.org/wiki/Type_inference">Type inference</a></li>
<li><a href="http://en.wikipedia.org/wiki/Dependent_type">Dependent types</a></li>
<li><a href="http://en.wikipedia.org/wiki/Standard_ML#Module_system">Parametrized modules</a></li>
<li><a href="http://www.haskell.org/ghc/docs/7.0.4/html/users_guide/type-class-extensions.html#overloaded-strings">Overloaded literals</a><sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup></li>
<li><a href="http://en.wikipedia.org/wiki/Immutable_object">Fundamental immutability</a></li>
<li><a href="http://en.wikipedia.org/wiki/Purely_functional">Purity</a></li>
<li><a href="http://en.wikipedia.org/wiki/Interpreter_%28computing%29">Interpreter</a></li>
<li><a href="http://en.wikipedia.org/wiki/Closure_%28computer_programming%29">Closures</a></li>
<li><a href="http://en.wikipedia.org/wiki/Multiple_dispatch">Multiple dispatch</a></li>
<li><a href="http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29">Inheritance</a></li>
<li><a href="http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29">Garbage collection</a></li>
<li><a href="http://en.wikipedia.org/wiki/Debugger">A debugger</a></li>
<li><a href="http://en.wikipedia.org/wiki/Concurrency_%28computer_science%29">Well-supported concurrency</a></li>
<li><a href="http://en.wikipedia.org/wiki/Parallel_computing">Parallelism</a></li>
<li><a href="http://en.wikipedia.org/wiki/Scope_%28computer_science%29#Dynamic_scoping">Dynamic scope</a><sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup></li>
<li><a href="http://en.wikipedia.org/wiki/Hot_swapping">Dynamic code update</a><sup><a href="#fn4" class="footnoteRef" id="fnref4">4</a></sup></li>
<li><a href="http://en.wikipedia.org/wiki/Smalltalk#Image-based_persistence">Image-based persistent</a></li>
<li>Infinite-sized integers and rationals</li>
<li><a href="http://en.wikipedia.org/wiki/Exception_handling">Exceptions</a></li>
<li><a href="http://en.wikipedia.org/wiki/Nullable_type">Explicit null</a></li>
<li><a href="http://www.haskell.org/tutorial/classes.html">Generic equality</a></li>
<li><a href="http://www.gigamonkeys.com/book/beyond-exception-handling-conditions-and-restarts.html">Restarts</a></li>
<li>A comprehensive platform / library set (e.g. Java, .NET)</li>
<li><a href="http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop">REPL/interaction mode</a></li>
<li><a href="http://common-lisp.net/project/slime/">Compiler—IDE integration</a></li>
<li>Interoperability (with C, Java, JavaScript, CLR)</li>
<li><a href="http://en.wikipedia.org/wiki/Domain-specific_language">Support domain-specific languages</a></li>
<li><a href="http://en.wikipedia.org/wiki/Proof_assistant">Proofs</a></li>
<li><a href="http://en.wikipedia.org/wiki/Erlang_%28programming_language%29#Concurrency_and_distribution_orientation">Distribution</a></li>
<li>A compiler that compiles to machine code, either via static compilation, JIT compilation, or third-party engines</li>
<li><a href="http://en.wikipedia.org/wiki/Tacit_programming">Tacit programming</a></li>
<li><a href="http://chrisdone.com/posts/value-polymorphism">Value polymorphism</a></li>
</ul>
<p>The moral is, if you’re inventing a new general purpose programming language and you have some clue that it’s going to be adopted, I implore you to thoroughly explore all of the features above within the existing languages that do them well, and think about adding it to your language.</p>
<p>As a follow-up post I might make a matrix of the top, say, 30, general purpose programming languages and all the features that they tick off.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Also known as quotation, quasiquotes, macros, templating, mixins, etc.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>So, numbers, strings, vectors, patterns, etc.<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>Preferablly static. Also known as implicit parameters, contexts, etc.<a href="#fnref3">↩</a></p></li>
<li id="fn4"><p>Also known as “hot-swapping”, “live update”, “plugins”, etc.<a href="#fnref4">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Sun, 30 Mar 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/one-step-forward-two-steps-back</guid>
</item>
<item>
<title>Emacs support for debugging Haskell</title>
<link>http://chrisdone.com/posts/ghci-debugger</link>
<description><![CDATA[<p>One odd thing about the Haskell community is that we don’t use debuggers. We don’t even use stack traces. I think for several reasons:</p>
<ol style="list-style-type: decimal">
<li>Haskell code goes wrong less often.</li>
<li>Due to that, people are content with once in a while sticking in printf statements.</li>
<li>Lazy evaluation is known to make debugging tricky.</li>
<li>Haskell has no decent editor support for debugging.</li>
</ol>
<p>It’s at least my experience that when my Haskell code goes wrong, I don’t fret too much because I put my code into small functions. If something’s not working as expected then I run that function in GHCi with typical inputs and check that the result is as desired.</p>
<p>If I’m in a codebase that makes it hard to do that, then I’ll insert some <code>error</code> or <code>trace</code> calls and re-run the whole program.</p>
<p>It’s also my experience that I don’t care about GHCi’s debugging support if I have to manually set breakpoints myself and step through things manually. Who wants to bother doing that? It’s like running git commands manually instead of using magit.</p>
<p>So, I thought, as an experiment, I’d whip up a simple magit-like interface to GHCi’s debugging facilities, based upon my (limited) understanding from the manual and the tutorials about it, which should help me answer the following questions:</p>
<ol style="list-style-type: decimal">
<li>Is GHCi’s debugger any good? I.e. it’s useful, not quirky or obtuse.</li>
<li>Is it practical? I.e. it works on real project code.</li>
<li>Is lazy evaluation as problematic as suspected for real code?</li>
<li>Does Haskell lend itself to debugging with GHCi enough that I’d reach for it as part of my problem-solving workflow?</li>
</ol>
<p>By removing the “it’s hard to use” impedance from the debugger, that puts me in a good position to evaluate the above questions. Is it that we as a community are missing out on sweet tooling because we just don’t have a convenient way to use it?</p>
<p><a href="https://www.youtube.com/watch?v=WAtEmoVN30E">Here is a video</a> demonstrating a trivial usage of it, i.e. the one that I’ve been testing with. I was too lazy to commentate it, but you can pause the video to see the display. I just set a breakpoint on <code>fib</code> and step into the <code>main</code> function and keep stepping until evaluation is complete. At one point I go to the REPL to inspect the local binding <code>x</code> and then go back to stepping.</p>
<p>In the display you can see the current expression being evaluated, and the values of the local bindings and their types below. I think there’s room for in-place expansion of values, here. But I need to experiment with more interesting data structures.</p>
<p>I invite overenthusiastic early adopters to try pulling from the haskell-mode repo to play around with it and patch up obvious deficiencies. You have to be using haskell-interactive-mode’s REPL, <code>(require 'haskell-debug)</code> and then run <code>M-x haskell-debug</code> from a Haskell file or the REPL, like I do in the video. The rest should be fairly obvious from the buffer’s helpful messages. But if it doesn’t work as you expected because I don’t know the first thing about how debuggers are supposed to be used, don’t blame me. Just fix it.</p>
<p>I’m completely ambivalent about whether a debugger is really useful, I’ve never really used one properly. So I’ll try to use it to solve some problems—once I can find some decent use-cases—and report back in a few weeks. For science!</p>]]></description>
<pubDate>Sun, 23 Mar 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/ghci-debugger</guid>
</item>
<item>
<title>On Death</title>
<link>http://chrisdone.com/posts/on-death</link>
<description><![CDATA[<p>I quite like listening to Alan Watts talks while doing things around the house.</p>
<p>But one point I’d like to touch upon is that I don’t quite take Alan’s views on death as readily as his other views.</p>
<p>The recent movement of philosophy about transhumanism is at odds with the classical religions of the last thousand years, because they all deal with death in terms of acceptance. They say, don’t commit suicide, going on living is fun and you should explore. But then they say “but death comes to us all sooner or later, so don’t fear it when it comes.” I consider this a contradiction.</p>
<p>Consider the recent tale of the <a href="http://www.nickbostrom.com/fable/dragon.html">Dragon Tyrant</a>. The dragon in the story represents death. The town that the dragon terrorizes and from which demands are made for human sacrifices serving as meals for the dragon, over time, come to accept the dragon as a fact of life. People who point out the fact that the dragon is obviously bad are seen as trouble makers and youths. After so many generations, the dragon is just how things are, and the sooner you come to terms with it, the better.</p>
<p>If and when technology arises for us to either “upload” to some limitless quantum computer, or more likely in the coming century to apply therapies to extend life to the point that they can be extended and rejuvenated indefinitely, religions will have to re-think their views on what it means to be alive and the role death plays in life.</p>
<p>Is almost all ancient theology dealing with death by trying to justify it as if it has a good purpose, when really they had no choice other than to frame it so, because they lacked the technology to have it any other way? Life and death is yin and yang, black and white, they say. You can’t have one without the other. Poetic, but true?</p>]]></description>
<pubDate>Fri, 21 Mar 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/on-death</guid>
</item>
<item>
<title>My favourite comedians and funnymen</title>
<link>http://chrisdone.com/posts/favourite-comedians</link>
<description><![CDATA[<p>Here’s a list of my favourite comedians in alphabetical order. It’s a disparate mix of people who have either made me giggle until I cried, or that tickled me with clever bits, or made me see the world a little bit differently and I thought they were something special. They’re all appealing in different ways. In all cases, I come back to their sets fairly often. It’s mostly a mix of American and British comedians.</p>
<p>I’ll be filling out the descriptions and adding more people as and when I get the time. One has to view their videos to get into each headspace individually, so it will take a while to finish writing this page.</p>
<h2 id="armando-ianucci">Armando Ianucci</h2>
<p><a href="https://www.youtube.com/watch?v=ZQ12DDe4ag0">YouTube clip</a>. TBA.</p>
<h2 id="bill-bailey">Bill Bailey</h2>
<p>A English comedian, his self-described part-troll part-hippy appearance, gait and old-woodland-in-olde-England-tale-like jokes and stream-of-consciousness and geeky absurdist ramblings combined with down to earth London speech has tickled me to the point of tears. His musical talent is also used fantastically well. I tend to groan when comedians try to combine music with their comedy, but for Bill it’s understated rather than taking centerstage. He’s mostly clean, liberal and generally insightful, and very English. A YouTube sample of his comedy can be seen on his, in my opinion, best stand-up gig, <a href="https://www.youtube.com/watch?v=ggOa9aSG-Ow">Part Troll</a>.</p>
<h2 id="bill-burr">Bill Burr</h2>
<p>In stark contrast to the previous Bill, an expletive sweary confessional-style American comedian with unsavoury views on women and an unhealthy preoccupation with sports, all that I can forgive for his delivery and Boston-area accent and quips. What I like most about Bill is the way he expresses himself, his impressions and delivery. He’s also a great raconteur. He walks the line between going too far with his contrarian views and reigning them in, often skipping over the line. But sometimes there’s some insight in all that ignorance and anger. A YouTube sample, demonstrating all I’ve described, can be found here <a href="https://www.youtube.com/watch?v=AlvvCYUDHrQ">here</a>.</p>
<h2 id="billy-connolly">Billy Connolly</h2>
<p>Billy is a raspy-voiced Scottish comedian who’s made me cry laughing many times. He is an outstanding raconteur. One of if not the best. He can tell anecdotes all day. Even the most mundane event when told by him has a funny streak to it. He started out telling jokes, but quickly his comedy became about his wacky views, his great stories and observations. His stories wind and go in and out of digressions like silly string. Very expletive and vulgar, coming from the docks of Glasgow, after all, but in a good way. Very Scottish, too! He’s also one to openly talk about how much he likes other comedians during his show, which is quite rare among top stand-up comedians, because he joyfuly celebrates all things funny. A YouTube sample of his funny-and-serious comedy can be found <a href="https://www.youtube.com/watch?v=kj7PP1UZ7k8&amp;t=2m39s">here</a>, time-skipped to the start of an anecdote.</p>
<h2 id="bill-hicks">Bill Hicks</h2>
<p>Bill Hicks was an American comedian who was incredibly passionate about his work, his views and his material. He was loud, aggressive, shouty, animated, in-your-face and entirely sincere. His comedy was always rooted in insight, whether political, religious or personal. Often his material was politically topical, and philosophical. I’ve cried laughing at some of his material, and looked on in awe at his sweating expressive rage with other material. It’s hard to over-state the strength of his convictions in his stand-up and interviews. Despite all his ranting and dismay at hypocrisy he perceived in the world, in the end his act always had a positive message. I’ve never seen another comedian like him. His whole shows can be found on YouTube now. The best demonstration of his don’t-know-wether-to-laugh-or-serious is <a href="https://www.youtube.com/watch?v=xRkA6zugNMQ">his bit on music of the time</a>.</p>
<h2 id="chris-morris">Chris Morris</h2>
<p>Chris Morris is an English satirist best known for his programme Brass Eye in the 90’s. It’s frankly an oustanding and overlooked piece of work, and his other work, including many shorts that you can find on YouTube, are just wonderful. Everything he has done has been bitingly satirical, ironic, absurd and hilariously clever. From mocking the public media of the time and their representations of drug culture, crime, the pedophile witch hunts of the early 2000’s, of perceptions of gay people and AIDS, to absurd scenes and tickling puns. Very British in humour, if there is such a categorization. Many people (including most Brits) simply don’t “get it”. Most if not all of the “guest” stars on his show were unaware of being shown up with false charities and organizations and being made to say ridiculous things, without even questioning it. It’s hard to describe without going into more paragraphs how stuningly good and unique Morris’s work is. Almost every scene has me shouting “brilliant!” A sample of Brass Eye can be found on YouTube <a href="https://www.youtube.com/watch?v=mPrCsfd1E64">here</a>.</p>
<h2 id="eddie-izzard">Eddie Izzard</h2>
<p>TBA.</p>
<h2 id="eddie-murphy">Eddie Murphy</h2>
<p>TBA.</p>
<h2 id="karl-pilkington">Karl Pilkington</h2>
<p>TBA.</p>
<h2 id="louis-ck">Louis CK</h2>
<p>TBA.</p>
<h2 id="lee-evans">Lee Evans</h2>
<p>TBA.</p>
<h2 id="noel-fielding">Noel Fielding</h2>
<p>TBA.</p>
<h2 id="patrice-oneal">Patrice O’Neal</h2>
<p>TBA.</p>
<h2 id="peter-kay">Peter Kay</h2>
<p>TBA.</p>
<h2 id="peter-cook">Peter Cook</h2>
<p>TBA.</p>
<h2 id="peter-sellars">Peter Sellars</h2>
<p>TBA.</p>
<h2 id="ricky-gervais">Ricky Gervais</h2>
<p>TBA.</p>
<h2 id="steven-wright">Steven Wright</h2>
<p>TBA.</p>
<h2 id="stewart-lee">Stewart Lee</h2>
<p>TBA.</p>
<h2 id="tim-vine">Tim Vine</h2>
<p>TBA.</p>]]></description>
<pubDate>Wed, 19 Mar 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/favourite-comedians</guid>
</item>
<item>
<title>Reloading running code in GHCi</title>
<link>http://chrisdone.com/posts/ghci-reload</link>
<description><![CDATA[<p>Something I’ve been using over the past couple weeks in a personal Yesod web site is a way to reload the code while the server is still running in GHCi. I saw in <a href="http://www.yesodweb.com/blog/2014/03/gsoc-proposals">Greg Weber’s</a> blog post about a “reload mode” for web servers and thought I’d share my approach. GHCi already supports reloading of code, it just doesn’t know it.</p>
<p>The problem with doing this in GHCi is always that the <code>:load</code> and <code>:reload</code> commands will clear out any bindings made in the REPL. This means that even if you start your web server in a separate thread—and it will stay running between reloads—you have no way to <em>update</em> or <em>talk</em> to it directly.</p>
<p>That’s why I wrote a package called <a href="http://hackage.haskell.org/package/foreign-store">foreign-store</a>. Its purpose is to make a stable pointer to some Haskell value and store it at an index, and then keep hold of it in C. Later, it can provide that stable pointer by that index. That’s its whole purpose. Because the C code is unaffected by GHCi’s reloads, the pointers are retained, and they are not garbage collected, because that is the point of a stable pointer.</p>
<p>Now, with that created, it’s possible to run a web server, keep hold of the thread id, reload some code in GHCi, kill that thread and restart it. Another option is to keep an <code>IORef</code> of the web handler itself, and then update the <code>IORef</code> instead. In my use of it so far, this has worked flawlessly.</p>
<p>I made <a href="https://github.com/chrisdone/ghci-reload-demo">a demo project</a> with a README explaining the (simple) approach. The short of it is that I can make some change to a Haskell module in my web project, hit a key (F12), and instantaneously see the browser page refresh with the new update. This is pretty much optimal for me.</p>
<p>It doesn’t end at web servers, of course. Any kind of long-running program that you would like to keep running while developing is fair game. For example, an IRC server. Why not run the server and also inspect the innards of its state while it’s running, and also update the message handler? I’ve done this with my <a href="https://github.com/chrisdone/hulk">Hulk</a> IRC server before. You can inspect the data structures, query the types of things, etc. all from the REPL.<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup></p>
<p>If you want to get really funky, you can try using the continuation monad to implement <a href="http://www.gigamonkeys.com/book/beyond-exception-handling-conditions-and-restarts.html">Common Lisp’s restarts.</a> Restarts are especially handy for when you’re running some long IO process and it bails out. You want to be able to correct the code and the continue from where you left off. Restarts let you do that.</p>
<p>I shouldn’t have to tell anyone this but just in case: <em>don’t use this in production</em>.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Of course, there aren’t many of us Haskellers who live in the REPL like Smalltalkers and Lispers do. Many Haskellers never even launch GHCi while developing.<a href="#fnref1">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Sun, 16 Mar 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/ghci-reload</guid>
</item>
<item>
<title>Attempto Controlled English</title>
<link>http://chrisdone.com/posts/attempto-controlled-english</link>
<description><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Attempto_Controlled_English">Attempto Controlled English</a> is a formally defined unambiguous language which is a subset of the English language. It’s pretty sweet.</p>
<p>I’ve known about it for some time, but I never fiddled with it because the standard implementation setup is rather elaborate. I wanted a nice, simple package in Haskell which would define a parser and a printer only, much like haskell-src-exts does. That way I can use ACE to parse some simple English for all sorts of purposes<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup>, with a simple familiar API that I can peruse on Hackage. Partly it’s also a good learning experience.</p>
<p>So I went through the paper The Syntax of Attempto Controlled English to see whether it was comprehensive enough to write a parsec parser out of. It was! I first wrote a <a href="https://github.com/chrisdone/ace/blob/master/src/ACE/Tokenizer.hs">tokenizer</a> in with Attoparsec and <a href="https://github.com/chrisdone/ace/blob/master/test/Main.hs#L39">wrote some tests</a>. From those tokens I produced a set of <a href="https://github.com/chrisdone/ace/blob/master/src/ACE/Combinators.hs">combinators</a> for Parsec, then I wrote a <a href="https://github.com/chrisdone/ace/blob/master/src/ACE/Parsers.hs">parser</a>. While writing the parser I produced a set of <a href="https://github.com/chrisdone/ace/blob/master/test/Main.hs#L67">test-cases</a> for each grammar production. Finally, I wrote a <a href="https://github.com/chrisdone/ace/blob/master/src/ACE/Pretty.hs">pretty printer</a>, and <a href="https://github.com/chrisdone/ace/blob/master/test/Main.hs#L599">wrote some tests</a> to check that <code>print . parse . print . parse = id</code>.</p>
<p>Newbies to Haskell parsing might find it an interesting use-case because it tokenizes with <a href="http://hackage.haskell.org/package/attoparsec">Attoparsec</a> (from Text) and then parses its own token type (<a href="http://hackage.haskell.org/package/ace-0.3/docs/ACE-Types-Tokens.html">Token</a>) with <a href="http://hackage.haskell.org/package/parsec">Parsec</a>. A common difficulty is to avoid parsing from <code>String</code> in Parsec, which most tutorials use as their demonstration.</p>
<p>The Hackage package is <a href="http://hackage.haskell.org/package/ace">here</a>. I find the documentation interesting to browse. I tried to include helpful examples for the production rules. You shouldn’t have to know syntax theory to use this library.</p>
<p>Here is an ACE sample. We can parse the sentence “a &lt;noun&gt; &lt;intrans-verb&gt;” like this:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; parsed specification <span class="st">&quot;a &lt;noun&gt; &lt;intrans-verb&gt;.&quot;</span>
<span class="dt">Right</span> (<span class="dt">Specification</span> (<span class="dt">SentenceCoord</span> (<span class="dt">SentenceCoord_1</span> (<span class="dt">SentenceCoord_2</span>
(<span class="dt">SentenceCoord_3</span> (<span class="dt">TopicalizedSentenceComposite</span> (<span class="dt">CompositeSentence</span>
(<span class="dt">Sentence</span> (<span class="dt">NPCoordUnmarked</span> (<span class="dt">UnmarkedNPCoord</span> (<span class="dt">NP</span> (<span class="dt">SpecifyDeterminer</span> <span class="dt">A</span>)
(<span class="dt">N&#39;</span> <span class="dt">Nothing</span> (<span class="dt">N</span> <span class="st">&quot;&lt;noun&gt;&quot;</span>) <span class="dt">Nothing</span> <span class="dt">Nothing</span> <span class="dt">Nothing</span>)) <span class="dt">Nothing</span>))
(<span class="dt">VPCoordVP</span> (<span class="dt">VP</span> (<span class="dt">V&#39;</span> <span class="dt">Nothing</span> (<span class="dt">ComplVIV</span> (<span class="dt">IntransitiveV</span> <span class="st">&quot;&lt;intrans-verb&gt;&quot;</span>))
[])))))) <span class="dt">Nothing</span>) <span class="dt">Nothing</span>) <span class="dt">Nothing</span>) <span class="dt">Nothing</span>) <span class="dt">Nothing</span>)</code></pre>
<p>Anything to do with vocabulary is written as <code>&lt;foo&gt;</code>. The parser actually takes <a href="http://hackage.haskell.org/package/ace-0.3/docs/ACE-Parsers.html#t:ACEParser">a record of parsers</a> so that you can provide your own parsers for each type of word. These words are not of interest to the grammar, and your particular domain might support different types of words.</p>
<p>If we pretty print the parsed phrase, we get:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; fmap pretty (parsed specification <span class="st">&quot;a &lt;noun&gt; &lt;intrans-verb&gt;.&quot;</span>)
<span class="dt">Right</span> <span class="st">&quot;a &lt;noun&gt; &lt;intrans-verb&gt;.&quot;</span></code></pre>
<p>I.e. we get back what we put in. I also wrote a HTML printer. A more complicated sentence demonstrates the output:</p>
<blockquote>
<p>for each &lt;noun&gt; &lt;var&gt; if a &lt;noun&gt; that &lt;trans-verb&gt; some &lt;noun&gt; and &lt;proper-name&gt;’s &lt;noun&gt; &lt;trans-verb&gt; 2 &lt;noun&gt; then some &lt;noun&gt; &lt;intrans-verb&gt; and some &lt;noun&gt; &lt;distrans-verb&gt; a &lt;intrans-adj&gt; &lt;noun&gt; &lt;proper-name&gt;’s &lt;noun&gt; &lt;adverb&gt;.</p>
</blockquote>
<p>Can be printed with</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">fmap (renderHtml <span class="fu">.</span> toMarkup) <span class="fu">.</span> parsed specification</code></pre>
<p>and the output is:</p>
<blockquote><p>
<span title="specification" class="ace-specification"><span title="sentence-or" class="ace-sentence-or"><span title="sentence-and" class="ace-sentence-and"><span title="sentence-or" class="ace-sentence-or"><span title="sentence-and" class="ace-sentence-and"><span title="universal-topic" class="ace-universal-topic"><span title="universal-quantor" class="ace-universal-quantor"><span title="universal-quantor" class="ace-universal-quantor">for each</span></span> <span title="n_" class="ace-n_"><span title="n" class="ace-n">&lt;noun&gt;</span> <span title="appos-coord" class="ace-appos-coord"><span title="apposition" class="ace-apposition"><span title="variable" class="ace-variable">&lt;var&gt;</span></span></span></span></span> <span title="sentence-or" class="ace-sentence-or"><span title="sentence-and" class="ace-sentence-and"><span title="sentence-or" class="ace-sentence-or"><span title="sentence-and" class="ace-sentence-and"><span title="conditional" class="ace-conditional"><span title="if-if" class="ace-if-if">if </span><span title="sentence-or" class="ace-sentence-or"><span title="sentence-and" class="ace-sentence-and"><span title="sentence-or" class="ace-sentence-or"><span title="sentence-and" class="ace-sentence-and"><span title="sentence" class="ace-sentence"><span title="npcoord" class="ace-npcoord"><span title="np" class="ace-np"><span title="specifier" class="ace-specifier"><span title="determiner" class="ace-determiner">a</span></span> <span title="n_" class="ace-n_"><span title="n" class="ace-n">&lt;noun&gt;</span> <span title="relative-clause-coord" class="ace-relative-clause-coord"><span title="relative-clause" class="ace-relative-clause"><span title="relative-clause-that" class="ace-relative-clause-that">that </span><span title="vp-coord" class="ace-vp-coord"><span title="vp" class="ace-vp"><span title="v_" class="ace-v_"><span title="compl-v" class="ace-compl-v"><span title="transitive-v" class="ace-transitive-v">&lt;trans-verb&gt;</span> <span title="npcoord" class="ace-npcoord"><span title="np" class="ace-np"><span title="specifier" class="ace-specifier"><span title="determiner" class="ace-determiner">some</span></span> <span title="n_" class="ace-n_"><span title="n" class="ace-n">&lt;noun&gt;</span></span></span><span title="unmarked-npcoord-and" class="ace-unmarked-npcoord-and"> and </span><span title="np" class="ace-np"><span title="specifier" class="ace-specifier"><span title="possessive-np-coord" class="ace-possessive-np-coord"><span title="proper-name" class="ace-proper-name">&lt;proper-name&gt;</span><span title="genitive-tail" class="ace-genitive-tail"><span title="genitive-tail" class="ace-genitive-tail"><span title="saxon-genitive-marker" class="ace-saxon-genitive-marker">'s</span></span></span></span></span> <span title="n_" class="ace-n_"><span title="n" class="ace-n">&lt;noun&gt;</span></span></span></span></span></span></span></span></span></span></span></span></span> <span title="vp-coord" class="ace-vp-coord"><span title="vp" class="ace-vp"><span title="v_" class="ace-v_"><span title="compl-v" class="ace-compl-v"><span title="transitive-v" class="ace-transitive-v">&lt;trans-verb&gt;</span> <span title="npcoord" class="ace-npcoord"><span title="np" class="ace-np"><span title="specifier" class="ace-specifier"><span title="number-p" class="ace-number-p">2</span></span> <span title="n_" class="ace-n_"><span title="n" class="ace-n">&lt;noun&gt;</span></span></span></span></span></span></span></span></span></span></span></span></span><span title="if-then" class="ace-if-then"> then </span><span title="sentence-or" class="ace-sentence-or"><span title="sentence-and" class="ace-sentence-and"><span title="sentence-or" class="ace-sentence-or"><span title="sentence-and" class="ace-sentence-and"><span title="sentence" class="ace-sentence"><span title="npcoord" class="ace-npcoord"><span title="np" class="ace-np"><span title="specifier" class="ace-specifier"><span title="determiner" class="ace-determiner">some</span></span> <span title="n_" class="ace-n_"><span title="n" class="ace-n">&lt;noun&gt;</span></span></span></span> <span title="vp-coord" class="ace-vp-coord"><span title="vp" class="ace-vp"><span title="v_" class="ace-v_"><span title="compl-v" class="ace-compl-v"><span title="intransitive-v" class="ace-intransitive-v">&lt;intrans-verb&gt;</span></span></span></span></span></span><span title="sentence-op" class="ace-sentence-op"> and </span><span title="sentence-and" class="ace-sentence-and"><span title="sentence" class="ace-sentence"><span title="npcoord" class="ace-npcoord"><span title="np" class="ace-np"><span title="specifier" class="ace-specifier"><span title="determiner" class="ace-determiner">some</span></span> <span title="n_" class="ace-n_"><span title="n" class="ace-n">&lt;noun&gt;</span></span></span></span> <span title="vp-coord" class="ace-vp-coord"><span title="vp" class="ace-vp"><span title="v_" class="ace-v_"><span title="compl-v" class="ace-compl-v"><span title="distransitive-v" class="ace-distransitive-v">&lt;distrans-verb&gt;</span> <span title="npcoord" class="ace-npcoord"><span title="np" class="ace-np"><span title="specifier" class="ace-specifier"><span title="determiner" class="ace-determiner">a</span></span> <span title="n_" class="ace-n_"><span title="adjective-coord" class="ace-adjective-coord"><span title="intransitive-adjective" class="ace-intransitive-adjective">&lt;intrans-adj&gt;</span></span> <span title="n" class="ace-n">&lt;noun&gt;</span></span></span></span> <span title="npcoord" class="ace-npcoord"><span title="np" class="ace-np"><span title="specifier" class="ace-specifier"><span title="possessive-np-coord" class="ace-possessive-np-coord"><span title="proper-name" class="ace-proper-name">&lt;proper-name&gt;</span><span title="genitive-tail" class="ace-genitive-tail"><span title="genitive-tail" class="ace-genitive-tail"><span title="saxon-genitive-marker" class="ace-saxon-genitive-marker">'s</span></span></span></span></span> <span title="n_" class="ace-n_"><span title="n" class="ace-n">&lt;noun&gt;</span></span></span></span></span> <span title="v-modifier" class="ace-v-modifier"><span title="adverb-coord" class="ace-adverb-coord"><span title="adverb" class="ace-adverb">&lt;adverb&gt;</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span><span title="period" class="ace-period">.</span></span>
</p></blockquote>
<p>The colors and parenthesizing embellishments are just to demonstrate what can be done. I’m not sure this output would actually be readable in reality.</p>
<p>This is a good start. I’m going to leave it for now and come back to it later. The next steps are: (1) write more tests, (2) add feature restrictions and related type information in the AST, (3) add a couple sample vocabularies, (4) implement the interrogative (useful for query programs) and imperative moods (useful for writing instructions, e.g. text-based games).</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Specifically, I want to use this to experiment with translating it to logic-language databases and queries, and from that produce interactive tutorials, and perhaps experiment with a MUD-like game that utilizes it.<a href="#fnref1">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Mon, 24 Feb 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/attempto-controlled-english</guid>
</item>
<item>
<title>Emacs, Notmuch and Offlineimap</title>
<link>http://chrisdone.com/posts/emacs-mail</link>
<description><![CDATA[<p>I kind of hate writing in anything other than Emacs. Especially email. Writing email in Emacs with <code>message-mode</code> is lovely. I get all my editing facilities and any key bindings that I want. More than that, generally managing my mail in Emacs rather than relying on what’s available in the GMail UI is desirable.</p>
<p>So I moved my email reading to Emacs. Here’s how I did it.</p>
<h1 id="offlineimap">Offlineimap</h1>
<p>First, I installed offlineimap. Second, I made a <code>~/.offlineimaprc</code> configuration file:</p>
<pre class="sourceCode python"><code class="sourceCode python">[general]
accounts = ChrisGmail
[Account ChrisGmail]
localrepository = Local
remoterepository = ChrisDoneGmail
[Repository Local]
<span class="dt">type</span> = Maildir
localfolders = ~/Mail
[Repository ChrisDoneGmail]
<span class="dt">type</span> = Gmail
maxconnections=<span class="dv">1</span>
remoteuser = chrisdone@gmail.com
realdelete=no
folderfilter =
<span class="kw">lambda</span> foldername:
foldername in [<span class="st">&#39;[Google Mail]/All Mail&#39;</span>,
<span class="co">&#39;[Google Mail]/Sent Mail&#39;</span>]
nametrans =
<span class="kw">lambda</span> foldername:
re.sub(<span class="st">&#39;^\[Google Mail\]/All Mail$&#39;</span>, <span class="st">&#39;all&#39;</span>,
re.sub(<span class="st">&#39;^\[Google Mail\]/Sent Mail$&#39;</span>, <span class="st">&#39;sent&#39;</span>,
foldername))
sslcacertfile = /etc/ssl/certs/ca-certificates.crt
remotepass = &lt;my password here&gt;</code></pre>
<p><em>Note: if you’re copy-pasting this file, you will need to put the <code>folderfilter</code> and <code>nametrans</code> on one line. Python doesn’t like multi-line lambdas.</em></p>
<p>I ran</p>
<pre><code>$ offlineimap</code></pre>
<p>I let that run for 10 hours to download all 19K messages from my 8~ year old GMail account.</p>
<h1 id="notmuch">Notmuch</h1>
<p>To index, tag and search that mail, I installed Notmuch. I configured it using <code>notmuch config</code> and followed the guide.</p>
<p>My current configuration (<code>~/.notmuch-config</code>) contains:</p>
<pre><code>[database]
path=/home/chris/Mail
[new]
tags=unread;inbox
ignore=
[search]
exclude_tags=deleted;spam</code></pre>
<p>I ran</p>
<pre><code>$ notmuch new</code></pre>
<p>to import all new mail from my database, which was the 19K messages. I think that took about 5 minutes.</p>
<h1 id="post-sync-hook">Post-sync hook</h1>
<p>Rather than manually running <code>offlineimap</code> and <code>notmuch new</code> all the time, instead you can put</p>
<pre><code>autorefresh = 1</code></pre>
<p>under your <code>[Account]</code> setting in <code>.offlineimaprc</code>. That will make Offlineimap run in one continuous process. I run it in screen for now, but I will probably add it as a system script when I’m feeling masochistic.</p>
<p>Another thing you can add to the <code>[Account]</code> section is a <code>postsynchook</code>:</p>
<pre><code>postsynchook = /usr/bin/offlineimap-postsync</code></pre>
<p>That path points to my post-sync script. It contains:</p>
<pre><code>notmuch new</code></pre>
<p>And then a bunch of tagging commands.</p>
<h1 id="tagging">Tagging</h1>
<p>In GMail I would organize everything with filters and tags. I like this approach, so I took the same with Notmuch. First, mailing lists skip the inbox and are tagged. For example:</p>
<pre><code>notmuch tag -inbox +ghc-devs to:ghc-devs@haskell.org tag:inbox
notmuch tag -inbox +ghc-users to:glasgow-haskell-users@haskell.org tag:inbox
notmuch tag -inbox +haskell-cafe to:haskell-cafe@haskell.org tag:inbox
notmuch tag -inbox +haskell-beginners to:beginners@haskell.org tag:inbox</code></pre>
<p>In other words, “remove the <code>inbox</code> tag, and add the <code>ghc-devs</code> tag for all messages addressed to <code>ghc-devs@haskell.org</code> in my inbox.”</p>
<p>When I receive an electric bill I tag it and flag it:</p>
<pre><code>notmuch tag +flagged +bill from:serviziweb@trenta.it tag:inbox</code></pre>
<p>I also have some inbox skipping filters from lists or people I don’t have interest in seeing in my inbox.</p>
<p>Then I have 69 deletion filters on various mailing lists I never signed up for and am unable to unsubscribe from.</p>
<p>In all I have about 130 filters. I copied them from my GMail account and ran some keyboard macros to conver them to Notmuch’s tagging style.</p>
<h1 id="emacs">Emacs</h1>
<p>Once you have Notmuch setup, you can use notmuch.el and it works out of the box for reading and searching mail. The mode has some strange choices for its defaults, so I copied <a href="https://github.com/chrisdone/notmuch">the repo</a> with full intention for patching it heavily in the future, and I made some further configurations <a href="https://github.com/chrisdone/chrisdone-emacs/blob/master/config/notmuch.el">in a separate file</a>.</p>
<p>The mode is pretty self-explanatory, it just has very silly keybindings. Otherwise it works very well.</p>
<h1 id="sending-email">Sending email</h1>
<p>One thing that doesn’t work out of the box is sending mail. For this I configured my mail user agent:</p>
<pre><code>(setq mail-user-agent &#39;message-user-agent)</code></pre>
<p>Set my default sending details:</p>
<pre><code>(setq user-mail-address &quot;chrisdone@gmail.com&quot;
user-full-name &quot;Chris Done&quot;)</code></pre>
<p>Configured the SMTP server info for GMail:</p>
<pre><code>(setq smtpmail-stream-type &#39;ssl
smtpmail-smtp-server &quot;smtp.gmail.com&quot;
smtpmail-smtp-service 465)</code></pre>
<p>Then I made a <code>~/.authinfo</code> file and put in:</p>
<pre><code>machine smtp.gmail.com login chrisdone port 465 password &quot;&lt;password here&gt;&quot;</code></pre>
<h1 id="suave-desktop-panel">Suave desktop panel</h1>
<p>I also <a href="https://github.com/chrisdone/chrisdone-xmonad/blob/b097b98ac044fc1cfa0f2bccd9abe9803b6ac8c4/src/XMonad/Suave/Window.hs#L69">added the current inbox status to my Suave XMonad desktop panel</a>. There’s a screenshot <a href="http://chrisdone.com/suave-1.png">here</a>. The inbox display is in the centre.</p>
<h1 id="summary">Summary</h1>
<p>In summary I moved the client part of my GMail use from the GMail web client to Emacs. Now I can read and write mail completely in Emacs, and I can see when new mail has arrived in my panel.</p>]]></description>
<pubDate>Sat, 08 Feb 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/emacs-mail</guid>
</item>
<item>
<title>Life Goes As You Are in the Eighties</title>
<link>http://chrisdone.com/posts/life-comes-as-eighties</link>
<description><![CDATA[<p>Listen to the following songs:</p>
<ul>
<li>Nirvana - Come as You Are (1992)</li>
<li>Killing Joke - Eighties (1984)</li>
<li>The Damned - Life Goes On (1982)</li>
</ul>
<p>Well, bugger me.</p>]]></description>
<pubDate>Fri, 07 Feb 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/life-comes-as-eighties</guid>
</item>
<item>
<title>structured-haskell-mode screencast</title>
<link>http://chrisdone.com/posts/structured-haskell-mode-screencasts</link>
<description><![CDATA[<p>I’ve created a series of videos explaining structured-haskell-mode; how it works and the feature-set <a href="https://www.youtube.com/watch?v=-QMBVMMmaCU&amp;list=PLlzKKtH5TyE-R-k86na3bLSNaKflFNRZr">here</a>. While the <a href="https://github.com/chrisdone/structured-haskell-mode">Github repository’s README</a> shows a series of animations showing off the features, I’ve observed that this, while pretty and impressive, isn’t particularly useful to explain to people the intended use of SHM and what to expect. People really need to see features in context with explanation. This set of videos explains all the features and keybindings.</p>]]></description>
<pubDate>Sun, 19 Jan 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/structured-haskell-mode-screencasts</guid>
</item>
<item>
<title>Atmospheric piano experiments</title>
<link>http://chrisdone.com/posts/piano-experiments</link>
<description><![CDATA[<p>Over the past year I experimented with composing a few simple piano pieces, inspired by atmospheres that conjure up images of wet spring mornings, misty mountains and caves, rainy building entrances, eerie uncanniness, with simple but effective compositions, by people like <a href="https://www.youtube.com/watch?v=SqUwDI_bV-U">Thomas Newman</a>, <a href="https://www.youtube.com/watch?v=omK5H4_giSo">Yann Tiersen</a> or <a href="https://www.youtube.com/watch?v=vt0g6mDasA8">Kate Bush</a>. Here are the pieces I composed and my motivations and interpretations of their meaning.</p>
<p>
<img
src="http://static.tumblr.com/4aa2d12cad2b611779826ebb25800842/ru5taba/qkYmlp26w/tumblr_static_misty_forest.jpg"
style="width:40em">
</p>
<p>
<em>A picture to set the atmosphere of the pieces in this page</em>
</p>
<p>If I were to make an album based on such a conceit, of a journey through various kinds of atmospheres and feelings, the first piece would undoubtedly be <a href="https://soundcloud.com/chrisdone/this-world-is-not-what-it">This World is Not What It Seems</a>, a track that sets a tone of warm simplicity but not without a light breeze of the uncertain and dubious. Generally, I am happy with this piece in its entirey. I could build upon this, extend it, or add instruments (a bass violin wouldn’t go amiss).</p>
<p>An entirely separate piece, but on the same theme could appear during a more disturbing and dramatic piece of the journey, and that piece is <a href="https://soundcloud.com/chrisdone/a-short-dream">The Nightmare</a>. A fairly stereotypical cadence and intentional conflicting tones, gives impressions of sinister unnaturalness, a clockwork order brought to beings or objects things that should be gone. I could expand on this, too.</p>
<p>A bittersweet and melancholic yet wistfully romantic piece is <a href="https://soundcloud.com/chrisdone/a-chance-meeting-1">A Chance Meeting</a> which I made to give a feel of fleetingness, passing moments inbetween daily drudgery—a stranger passes you by, you want to spark up a conversion—but do you? I’m generally happy with this as a full piece. I wouldn’t want to expand it.</p>
<p>I piece that I’m particularly proud of for such a short and uncomplicated sample is <a href="https://soundcloud.com/chrisdone/creepy">Man on the Stairway</a>, which was inspired from the short two liner poem: “Yesterday upon the stair / I met a man who wasn’t there / He wasn’t there again today / Oh, how I wish he’d go away” The melody (if one can call it that) conjures feelings of confusion and fear—to me—and I like the unconventional and unpredictable structure it takes. It doesn’t want to be pinned down, but it is catchy. It makes you both want to escape from it and also stay within it, like a scary story. I could definitely expand upon this.</p>
<p>The minute collection of ideas named <a href="https://soundcloud.com/chrisdone/happy-dream">Happy Dream</a> is a few peices. The first a blatant, but more playful and happy version of <a href="https://www.youtube.com/watch?v=CGeAMVK75T4">the introduction to American Psycho</a>, followed by a very childlike patter, and then at the end an a racey skipping movement that could certainly be expanded. I wouldn’t mind expand this into a whole track, though the conception draws largely from imitating common “happy” piano tropes.</p>
<p><a href="https://soundcloud.com/chrisdone/wool-wip">The final piece</a> I did was inspired by the science fiction novel, Wool. I’ve compressed what I would like to make a thirty minute track into about two minutes. It would consist of three parts, the atmospheric calm-before-the-storm, the central dramatic point, followed by a quiet period, ending in a dramatic stereotypical last-stand style patter. I’m not entirely happy with the execution of the latter two parts, but I like the theme I’ve created in the first part. I could apply that as a general melody for a whole soundtrack, I think.</p>
<p>For future pieces I would rather like to have a proper MIDI keyboard for composing more complex and layered pieces, as at the moment I’m confined to a small portion of the keyboard. Overall, I’m quite pleased with the melodies and atmospheres created above, and I’m looking forward to getting a proper keyboard to really flesh out more ideas and experiments.</p>]]></description>
<pubDate>Sun, 19 Jan 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/piano-experiments</guid>
</item>
<item>
<title>Musings on philosophy</title>
<link>http://chrisdone.com/posts/musings-on-philosophy</link>
<description><![CDATA[<p>I tend not to write anything on philosophy because I tend not to have any original thoughts that haven’t been discussed ad naseum since the dawn of man. However, I thought that I would start writing on my general position, the parts of philosophy that interest me, and that appeal to my sensibilities and experience. In this instance, I cover theism and the oneness of everything.</p>
<p>I don’t believe in an Abrahamic god.<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup> I don’t have faith in an Abrahamic god. The question itself is not interesting to me, now that I am not a child, nor do I designate any weight to Pascal’s wager,<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup> owing partly to the theoretical articulation of Bertrand Russell’s teapot.<sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup> Due to Parkinson’s Law of Trivality,<sup><a href="#fn4" class="footnoteRef" id="fnref4">4</a></sup> and western religious entrenchment, the topic of the monotheistic, patriarchal, king-of-the-universe, god takes the lion’s share of amateur debate and writing of the whole Venn diagram of philosophical discourse. It is as uninteresting as it is popular and I’m glad to dispose of it in this paragraph.</p>
<p>Essentially, my approach and outlook on life is an existential one, or, what I’d dub, “positive nihilism”. I don’t believe that there is absolute truth, purpose or meaning to anything, nor do I wish I did. On the other hand, contrary to the general impression of nihilism, I believe that I define what’s important or meaningful to me by my own choosing, and that is existentialism. I balance this playfully with the anti-rationalist approach that life is better lived and experience than conceptualised<sup><a href="#fn5" class="footnoteRef" id="fnref5">5</a></sup>. Generally speaking, I will take what I like and what works for me, and discard the rest.</p>
<p>Now that I’ve described the general nexus parameters from which I’m coming at philosophy, will I say that my previous paragraph follows nicely onto a general theme that I see and that appeals to me across the board in philosophy, which is the notion of oneness, of energy and action and fluidity and cyclism and flow and play and relativism, as opposed to things, solidity, identity, ego, absolutism, idolitry, certainty.</p>
<p>Even in Christian literature there is the notion of the Cloud of Unknowing<sup><a href="#fn6" class="footnoteRef" id="fnref6">6</a></sup>, an anonymous work of Christian mysticism from the 14th century, which claims that an image of god gets in the way of the real thing. An image can only ever be something imposed by your own experience, and that is something that is filtered and distorted.</p>
<p>The same theme comes from practically atheist circles of the 60’s LSD movement, with trippers like Timothy Leary popularizing the notion of ego-death, that the drug-enabled crumbling of the self, which is a walled garden in one small patch of reality, and that direct experience of reality is one that very profoundly indicates a continuous, unbroken oneness of all things.</p>
<p>Aldous Huxley, more eloquently, has written The Doors of Perception, and finally Island, his novel-come-treatise on his interpretation of the Vedanta and its complementary relationship with shamanic drugs like Mescaline. In Island, Huxley takes his protagonist on a trip that transcends Nirvana—his mind evaporating into the ether—to here-and-now consciousness, that one should not merely disappear into bliss, but experience reality as directly as possible.<sup><a href="#fn7" class="footnoteRef" id="fnref7">7</a></sup><sup><a href="#fn8" class="footnoteRef" id="fnref8">8</a></sup></p>
<p>As popularly known, Buddhist meditation is predicated upon the assumption that through focus and mindfulness one can break down the barrier of me-ness and the self, at least temporarily, to experience reality through a direct feed, it is said, “not thinking, analyzing, just observing.” Something which is very hard to do; to observe anything without attaching inherent meaning. This is called the “unconditioned state.”<sup><a href="#fn9" class="footnoteRef" id="fnref9">9</a></sup></p>
<p>There is also a scientific angle, which is that the universe evolved the human brain in order to observe itself. In other words, we <em>are</em> the universe, looking at itself. We aren’t some separate entities, we are the universe, reflecting upon the nature of itself. It’s not, me and the universe, it’s: me, the universe. In this sense, if there is a so-called “energy force” god, some “necessary being” which exists as merely some quantum effect, or string configuration, we are it.</p>
<p>Finally, speaking from personal experience, I have once experienced a glimpse of what I would consider related. It was early in the morning, around four, and I went for a walk. The sun had not started rising, and I was walking past some trees in a small woods. In this brief period of ten minutes from the start of the road to the end, a lifetime of contemplation about nothing occurred. I suddenly noticed the shape of the trees. I’d seen trees my whole life, but this time, I saw them for the first time. Like a baby sees the world. I saw the amazing fractal shape of the branches reaching out across the sky. I felt nothing but joy and love and hope for the whole world and the future in this moment where I thought of nothing and marveled at existence.</p>
<p>In the same way, I related this to a friend some time afterwards, and he recounted a story to me in which he’d been out for the night, and came home to find that he was locked out of the house. So he went to his car and sat in the back seat. He said that it was probably the best night of his life. I asked why, and what did he do? And he replied that he did absolutely nothing, he simply sat there, in absolute wonder and contentment, at his situation and surroundings. I understood this completely. The typical state of waking human moments is dissatisfaction, of discontent; suffering. To escape this, even briefly, is a gift.</p>
<p>I sometimes wonder whether this kind of experience has happened to most people and whether most would understand this brief encounter with bliss, whatever shape it takes, and even for a few minutes. In closing, I give a lot of weight to the notion of the oneness of everything. It’ll probably crop up in future writings, which will deal on a less grand scale and more on personal, interpersonal, and societal grounds.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>That’s an intentional lower-case. The practice of upper-casing “god” is an embellishing practice to which I need not adhere.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>“Given the possibility that God actually does exist and assuming the infinite gain or loss associated with belief in God or with unbelief, a rational person should live as though God exists and seek to believe in God. If God does not actually exist, such a person will have only a finite loss (some pleasures, luxury, etc.).” <a href="http://en.wikipedia.org/wiki/Pascal%27s_Wager">Pascal’s Wager</a><a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>“I ought to call myself an agnostic; but, for all practical purposes, I am an atheist. I do not think the existence of the Christian God any more probable than the existence of the Gods of Olympus or Valhalla. To take another illustration: nobody can prove that there is not between the Earth and Mars a china teapot revolving in an elliptical orbit, but nobody thinks this sufficiently likely to be taken into account in practice. I think the Christian God just as unlikely.” <a href="http://en.wikipedia.org/wiki/Russell%27s_teapot">Russell’s teapot</a><a href="#fnref3">↩</a></p></li>
<li id="fn4"><p>“The time spent on any item of the agenda will be in inverse proportion to the sum [of money] involved.” A reactor is used because it is so vastly expensive and complicated that an average person cannot understand it, so one assumes that those that work on it understand it. On the other hand, everyone can visualize a cheap, simple bicycle shed, so planning one can result in endless discussions because everyone involved wants to add a touch and show personal contribution. <a href="http://en.wikipedia.org/wiki/Parkinson%27s_law_of_triviality">Parkinson’s law of triviality</a><a href="#fnref4">↩</a></p></li>
<li id="fn5"><p>“Life is better lived than conceptualized. This writing can be less demanding should I allow myself to indulge in the usual manipulating game of role creation. Fortunately for me, my self-knowledge has transcended that and I’ve come to understand that life is best to be lived — not to be conceptualized. If you have to think, you still do not understand.” — Bruce Lee<a href="#fnref5">↩</a></p></li>
<li id="fn6"><p>“The highest form of contemplative prayer, was that in which all concept of god has been left behind. And this is the surpeme act of faith. So that you no longer need an image, because this gets in the way of reality.” — Alan Watts<a href="#fnref6">↩</a></p></li>
<li id="fn7"><p>“If you’re a Tantrik, you don’t renounce the world or deny its value; you don’t try to escape into a Nirvana apart from life, as the monks of the Southern School do. No, you accept the world, and you make use of it; you make use of everything you do, of everything that happens to you, of all the things you see and hear and taste and touch, as so many means to your liberation from the prison of yourself.”<a href="#fnref7">↩</a></p></li>
<li id="fn8"><p>Behind his closed eyelids an ocean of luminous bliss poured upwards like an inverted cataract. Poured upwards from union into completer union, from impersonality into a yet more absolute transcendence of selfhood. “God-the-Fourteenth-of-July,” he repeated and, from the heart of the cataract, gave vent to a final chuckle of recognition and understanding. “What about the fifteenth of July?” Susila questioned. “What about the morning after?” “There isn’t any morning after.” She shook her head. “It sounds suspiciously like Nirvana.” “What’s wrong with that?” “Pure Spirit, one hundred percent proof—that’s a drink that only the most hardened contemplation guzzlers indulge in. <a href="http://en.wikipedia.org/wiki/Bodhisattva">Bodhisattvas</a> dilute their Nirvana with equal parts of love and work.” “This is better,” Will insisted. “You mean, it’s more delicious. That’s why it’s such an enormous temptation. The only temptation that God could succumb to. The fruit of the ignorance of good and evil. What heavenly lusciousness, what a supermango! God had been stuffing Him self with it for billions of years. Then all of a sudden, up comes Homo sapiens, out pops the knowledge of good and evil. God had to switch to a much less palatable brand of fruit. You’ve just eaten a slice of the original supermango, so you can sympathize with Him.” — <a href="http://www.huxley.net/island/aldoushuxley-island.html">Island</a><a href="#fnref8">↩</a></p></li>
<li id="fn9"><p>“To arrive at the experiential realization of the truths it is necessary to take up the practice of meditation…. At the climax of such contemplation the mental eye … shifts its focus to the unconditioned state, Nibbana” — <a href="http://en.wikipedia.org/wiki/Kamala%C5%9B%C4%ABla">Kamalashila</a><a href="#fnref9">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Sun, 19 Jan 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/musings-on-philosophy</guid>
</item>
<item>
<title>2014: Blackout</title>
<link>http://chrisdone.com/posts/blackout</link>
<description><![CDATA[<p>Sometimes, you see something that makes you re-evaluate your habits. You realise your habits don’t give you much entertainment, learnings or happiness. You think about other activities that are better for your personal development, your perspective and your education. You think more about the things you would like to learn, the places you would like to travel to, performances and gatherings you’d like to experience. You think about applying discipline to separate your work from your free time. Maybe your free time should be applied more carefully. Sometimes, you need catharsis and change.</p>
<p>Perhaps 2014 will be the year of online silence. Silence from myself, and silence from outside. Time to learn, reflect, grow. I will write an update post in January of 2015 about this topic, and I will continue writing blog posts, working on my open source projects, and reading and responding to email. If you want to contact me, send me an email. Otherwise, consider this a complete Internet blackout.</p>]]></description>
<pubDate>Mon, 13 Jan 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/blackout</guid>
</item>
<item>
<title>Pure IO monad and Try Haskell</title>
<link>http://chrisdone.com/posts/pure-io-tryhaskell</link>
<description><![CDATA[<p><strong>tl;dr: <a href="http://tryhaskell.org/">Try Haskell</a> now has simple I/O built on a pure IO monad.</strong></p>
<p>I wrote Try Haskell in 2010. I didn’t really update the codebase since. It was rather poor, but had generally been stable enough. Last week I finally set some time aside to rewrite it from scratch (barring the tutorial part). In doing so I gave it a fresh design, rewrote the backend and stopped using my patched version of mueval (faster, but less stable).</p>
<p>Aside from reproducing the functionality, I afterwards added a new piece of functionality: typing in a function name (or composition of functions) will simply show the generalized type of that expression. This removes the need for an explicit <code>:t</code> and is more friendly to newbies who would rather see something useful than an error.<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup></p>
<p>After that, Bob Ippolito requested that some simple IO operations be made available, like <code>getLine</code>, <code>putStrLn</code>, etc. People have requested this in the past, but it seemed more complicated back then. This time, it seemed rather easy to support simple input/output. The console library already supports continued prompts, so the question became simply how to do safe IO.</p>
<p>As Haskellers worth their salt know, the IO monad is not special. Examples of a monad ADT for newbies are available<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup><sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup>, and we know that pre-monad Haskell IO was modelled as a request/response system<sup><a href="#fn4" class="footnoteRef" id="fnref4">4</a></sup> before it got updated in Haskell 1.3<sup><a href="#fn5" class="footnoteRef" id="fnref5">5</a></sup> Fuelled by the nerdiness factor of this, and that it was the weekend, I rose to the challenge. I knew it wouldn’t be hard, but it would be fun with a real use-case (Try Haskell’s REPL).</p>
<p>My constraints were that it shouldn’t be a continuation-based library, because I cannot have any state in Try Haskell. The server evaluates an expression and returns the result. No other context is kept, no process kept open, and it should return immediately. Given that it’s rather hard to serialize closures, but rather easy to serialize a list of inputs and outputs (aka responses/requests), I thought I’d go that route.</p>
<p>In the end I settled on an <code>ErrorT</code> monad over a <code>State</code> monad containing <code>Input</code> and an <code>Output</code>. The inputs would be stdin lines as <code>[String]</code>. The outputs would be stdout lines and either a final value, or an interrupt.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">runIO ::</span> <span class="dt">Input</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> a <span class="ot">-&gt;</span> (<span class="dt">Either</span> <span class="dt">Interrupt</span> a, <span class="dt">Output</span>)</code></pre>
<p>Whenever the expression being evaluated runs <code>getLine</code>, it reads from the <code>Input</code> state and pops that line of text off the stack. When <code>getLine</code> tries to read something and the stack is empty, it throws an error (of the <code>ErrorT</code> monad), returning the interrupt <code>InterruptStdin</code>. For example, here is a return value:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; runIO (<span class="dt">Input</span> mempty mempty) (return ())
(<span class="dt">Right</span> ()
,<span class="dt">Output</span> {outputStdout <span class="fu">=</span> [], outputFiles <span class="fu">=</span> fromList []})</code></pre>
<p>Here is an interrupt:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; runIO (<span class="dt">Input</span> mempty mempty) (putStrLn <span class="st">&quot;Name:&quot;</span> <span class="fu">&gt;&gt;</span> getLine)
(<span class="dt">Left</span> <span class="dt">InterruptStdin</span>
,<span class="dt">Output</span> {outputStdout <span class="fu">=</span> [<span class="st">&quot;Name:\n&quot;</span>],outputFiles <span class="fu">=</span> fromList []})</code></pre>
<p>As a user of the library it is now my part of the dance to get some input from the user and then re-call<sup><a href="#fn6" class="footnoteRef" id="fnref6">6</a></sup> the same function with more stdin input:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; runIO (<span class="dt">Input</span> [<span class="st">&quot;Chris&quot;</span>] mempty) (putStrLn <span class="st">&quot;Name:&quot;</span> <span class="fu">&gt;&gt;</span> getLine)
(<span class="dt">Right</span> <span class="st">&quot;Chris&quot;</span>
,<span class="dt">Output</span> {outputStdout <span class="fu">=</span> [<span class="st">&quot;Name:\n&quot;</span>],outputFiles <span class="fu">=</span> fromList []})</code></pre>
<p>I also implemented trivial exceptions:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; runIO (<span class="dt">Input</span> [<span class="st">&quot;Chris&quot;</span>] mempty) (throw (<span class="dt">UserError</span> <span class="st">&quot;Woo!&quot;</span>))
(<span class="dt">Left</span> (<span class="dt">InterruptException</span> (<span class="dt">UserError</span> <span class="st">&quot;Woo!&quot;</span>))
,<span class="dt">Output</span> {outputStdout <span class="fu">=</span> [],outputFiles <span class="fu">=</span> fromList []})</code></pre>
<p>After that, it was only a matter of time before I implemented some simple file IO operations:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ&gt; runIO (<span class="dt">Input</span> [<span class="st">&quot;Chris&quot;</span>]
(M.fromList [(<span class="st">&quot;/foo.txt&quot;</span>,<span class="st">&quot;Hello, World!&quot;</span>)]))
(readFile <span class="st">&quot;/foo.txt&quot;</span>)
(<span class="dt">Right</span> <span class="st">&quot;Hello, World!&quot;</span>
,<span class="dt">Output</span> {outputStdout <span class="fu">=</span> []
,outputFiles <span class="fu">=</span> fromList [(<span class="st">&quot;/foo.txt&quot;</span>,<span class="st">&quot;Hello, World!&quot;</span>)]})</code></pre>
<p>That resulted in the library <a href="https://hackage.haskell.org/package/pure-io/docs/PureIO.html">pure-io</a> which <a href="http://ircbrowse.net/browse/haskell?id=17223900&amp;timestamp=1389386757#t1389386757">some</a> thought was a joke. It supports enough of the subset of IO operations for, I think, a newbie to at least feel like they’re doing some realistic I/O. So I added it to <a href="http://tryhaskell.org/">Try Haskell!</a> You can now run interactive commands and write/save/list files. Any file system operations you do will be saved in your browser’s local storage.</p>
<p>It’s really a rather nice referentially transparent IO service. Even if you run <code>forever (getLine &gt;&gt;= putStrLn) :: IO ()</code>, it will run forever, but the server can be restarted inbetween. No state is stored on the server at all, it’s all in the client. All the client has to do is pass it back and forth when it communicates with the server.</p>
<p>I’d recommend Haskell intermediates (perhaps not newbies) to implement their own IO monad as a free monad, or as an mtl transformer, partly for the geeky fun of it, and partly for the insights.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Like “No instance for <code>(Show (a0 -&gt; a0))</code> arising from a use of …” which is frankly a useless message to print in a REPL and it’s strange that this is GHCi’s default behaviour.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>Johan Kiviniemi demonstrates <a href="https://gist.github.com/ion1/7154691">an alternative monad implementation</a> as an ADT that you interpret.<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>Russell O’Connor also talks about implementing IO as a free monad <a href="http://r6.ca/blog/20110520T220201Z.html">here</a>.<a href="#fnref3">↩</a></p></li>
<li id="fn4"><p><a href="http://stackoverflow.com/questions/17002119/haskell-pre-monadic-i-o">Request/response example API on StackOverflow</a>. All shuffling between an actual interface and the user is left to someone else to deal with.<a href="#fnref4">↩</a></p></li>
<li id="fn5"><p>“Monadic I/O has already become the de-facto standard in the various Haskell systems. We have chosen a fairly conservative, but extensible basic design (an IO monad with error handling),” in <a href="http://www.haskell.org/definition/from12to13.html#monad">the changes list</a>.<a href="#fnref5">↩</a></p></li>
<li id="fn6"><p>Yes, that means running the same computation every time from scratch, like a transaction.<a href="#fnref6">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Sun, 12 Jan 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/pure-io-tryhaskell</guid>
</item>
<item>
<title>Dijkstra on Haskell and Java</title>
<link>http://chrisdone.com/posts/dijkstra-haskell-java</link>
<description><![CDATA[<p>In 2001, Edsger W. Dijkstra wrote a letter to the Budget Council of The University of Texas. A <a href="http://www.cs.utexas.edu/users/EWD/OtherDocs/To%20the%20Budget%20Council%20concerning%20Haskell.pdf">PDF is available here</a>, I’ve typed it up so that everyone can read it. Sadly, <a href="http://www.cs.utexas.edu/undergraduate-program/courses/312-introduction-programming">the curriculum was changed to Java</a>. Relatedly, the algorithmic language Scheme was replaced by Python in MIT’s The Structure and Interpretation of Computer Programs version <a href="http://student.mit.edu/catalog/search.cgi?search=6.01">6.01</a>.</p>
<h2 id="to-the-members-of-the-budget-council">To the members of the Budget Council</h2>
<p>I write to you because of a rumor of efforts to replace the introductory programming course of our undergraduate curriculum the functional programming language Haskell by the imperative language Java, and because I think that in this case the Budget Council has to take responsibility lest the decision be taken at the wrong level.</p>
<p>You see, it is no minor matter. Colleagues from outside the state (still!) often wonder how I can survive in a place like Austin, Texas, automatically assuming that Texas’s solid conservatism guarantees equally solid mediocrity. My usual answer is something like “Don’t worry. The CS Department is quite an enlightened place, for instance for introductory programming we introduce our freshmen to Haskell”; they react first almost with disbelief, and then with envy —usually it turns out that their undergraduate curriculum has not recovered from the transition from Pascal to something like C++ or Java.</p>
<p>A very practical reason for preferring functional programming in a freshman course is that most students already have a certain familiarity with imperative programming. Facing them with the novelty of functional programming immediately drives home the message that there is more to programming than they thought. And quickly they will observe that functional programming elegantly admits solutions that are very hard (or impossible) to formulate with the programming vehicle of their high school days.</p>
<p>A fundamental reason for the preference is that functional programs are much more readily appreciated as mathematical objects than imperative ones, so that you can teach what rigorous reasoning about programs amounts to. The additional advantage of functional programming with “lazy evaluation” is that it provides an environment that discourages operational reasoning<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup><sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup>.</p>
<p>Finally, in the specific comparison of Haskell versus Java, Haskell, though not perfect, is of a quality that is several orders of magnitude higher than Java, which is a mess (and needed an extensive advertizing campaign and aggressive salesmanship for its commercial acceptance). It is bad enough that, on the whole, industry accepts designs of well-identified lousiness as “de facto” standards. Personally I think that the University should keep the healthier alternatives alive.</p>
<p>It is not only the violin that shapes the violinist, we are all shaped by the tools we train ourselves to use, and in this respect programming languages have a devious influence: they shape our thinking habits. This circumstance makes the choice of first programming language so important. One would like to use the introductory course as a means of creating a culture that can serve as a basis for computing science curriculum, rather than be forced to start with a lot of unlearning (if that is possible at all: what has become our past, forever remains so). The choice implies a grave responsibility towards our undergraduate students, and that is why it can not be left to a random chairman of something but has to be done by the Budget Council. This is not something that can be left to the civil servants or the politicians; here statesmen are needed.</p>
<p>Austin, 12 April 2001</p>
<p>Edsger W. Dijkstra</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p><a href="http://www.cs.utexas.edu/~EWD/transcriptions/EWD10xx/EWD1036.html">On the cruelty of really teaching computing science</a><a href="#fnref1">↩</a></p></li>
<li id="fn2"><p><a href="http://www.cs.utexas.edu/~EWD/transcriptions/EWD10xx/EWD1012.html">Real mathematicians don’t prove</a><a href="#fnref2">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Wed, 08 Jan 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/dijkstra-haskell-java</guid>
</item>
<item>
<title>Control of My Data</title>
<link>http://chrisdone.com/posts/control-of-my-data</link>
<description><![CDATA[<p>A new standard I was discovering for myself in 2012 was that maybe <em>I</em> should be in complete control of data about me. In this case, <a href="http://chrisdone.com/posts/lastfm">the context was Last.fm</a>. In 2013, I applied that discontent to some real effort and pulled all my data from Last.fm into a database that <em>I</em> control, presented on <a href="http://chrisdone.com/music">a simple web app</a> that <em>I</em> control.</p>
<p>The same way, it occurs to me that I should start importing from all the services that I contribute data to regularly and for which the data collected is actually useful in some sense. Cthulhu knows I have the space for’t. The ones off the top of my head are:</p>
<ul>
<li>GMail</li>
<li>GoodReads</li>
<li>Twitter</li>
<li>Google+</li>
<li>Reddit</li>
<li>YouTube</li>
<li>My bank web site</li>
</ul>
<p>For GMail, I actually have no local copy of my email going back to 2007. Six years worth of email is important data, for finding references, for security and for interesting statistical analysis. In fact, the reasons I’m still using GMail are few these days. I regularly just cannot find the email I’m looking for. I don’t like its composing mode, at all. It’s slow. In fact, I think the only reason I use it these days is for the service of hosting my emails in a reliable place.</p>
<p>GoodReads, like Last.fm, is a place where I’ve submitted things I like in a regular format. The usefulness of that requires little elaboration.</p>
<p>Twitter, Google+ and Reddit contain lots of references to materials, and finding <em>anything</em> on these web sites is horrendous. They are not made to be searched like an archive, they’re made to only show the latest stuff, understandably. Having a complete indexed archive of my few years worth of these three web sites would be very handy. Not to mention the possible statistical analysis.</p>
<p>My bank history should be very useful to analyze expenditure, profit, bills, etc.</p>
<p>By comparison, Github is a service which archives. That’s its one main job. I can pull data from it at any time and generate data. However, it’s still worth pulling data from my activity feed.</p>
<p>Probably the rules should be:</p>
<ul>
<li>If the service provides no means of exporting, <em>do not use it</em>.</li>
<li>If the service misrepresents your data and does not allow you to fix it, even if it exports, <em>do not use it</em>.</li>
<li>If the service provides a means of exporting or feed importing, then do so, regularly.</li>
</ul>
<p>My bank web site regrettably does not allow an automatic login procedure, it requires a physical manual step. However, I can import weekly with a manual step for login followed by automatic import.</p>
<p>Really, the main benefit to all these services, to me, is that they are reliable (insofar as they still exist), they don’t lose data, that is all managed for you. I need to learn how to setup secure and reliable replication of data like this that I want to endure over time. I have my dedicated host, but that could malfunction at any time. I should utilize dropbox (encrypted), my local storage and other backup services.</p>]]></description>
<pubDate>Wed, 01 Jan 2014 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/control-of-my-data</guid>
</item>
<item>
<title>Emacs users are like Terry Pratchett’s Igors</title>
<link>http://chrisdone.com/posts/emacs-users-are-like-igor</link>
<description><![CDATA[<p>Within the constraints of the Emacs environment, there are no limits. Emacs is built upon this principle; the Lisp principle. Make some small kernel of features. A substrate. Take care to make this substrate programmable (in any language, Emacs chooses Lisp), and then build the system upon it. Let users worry about future features. Some 359,000 lines of C code comprise its kernel, and 1,637,000 lines of Emacs Lisp take the rest of it.<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup></p>
<p>Similarly, the nature of The <a href="http://www.winestockwebdesign.com/Essays/Lisp_Curse.html">Lisp Curse</a> is that what can be written to express any given problem is so arbitrary and free, that you are spoiled for choice, and every programmer re-invents solutions to the same problems, uncaring about sharing a common language with the world outside. The core problem is that Lisp makes programmers selfish. Giving programmers so much flexibility is inviting the alienation of other programmers; Lispers think: how can I express this problem best, for me?</p>
<p>That phenomenon is not a problem for Emacs. Work environments are a very personal thing. They exist to serve only one person: you. Me-me-me is a winning attitude when dealing with your environment. Maybe in the real world, out there, where you have to share programs with other people, where other people will see or even use your efforts, you have to care or take consideration about other people. Not in your environment. Not in your Emacs. It is your virtual home for at least nine hours of the day, every day.</p>
<p>My road to Emacs love developed slowly. I first came to it due to Common Lisp. I knew enough Lisp to get by, copy-pasting example snippets, configuring just enough to edit my environment. It felt a little bit barebones compared to the IDEs I’d used before it. Little did I know the world of functionality and configuration waiting beneath my feet.</p>
<p>Eventually I started patching some things here and there, writing my own hooks, little things like that. I used Emacs for a long time, just becoming proficient as a user with the keybindings and window management, before I ever wrote any Elisp. It hadn’t occured to me that writing any Elisp would ever be of interest to me. I would often shaft my .emacs configuration, and everything would break, and I wouldn’t quite know why.</p>
<p>Finally, I wrote my first mode. I think it was a mode for ASP. It wasn’t very good, and I didn’t fully understand everything that was going on. But it gave me some key insights. This thing isn’t just an editor, it’s really an environment all the way down. I can configure <em>everything</em> about this mode. And the mode consists of a bunch of functions and variables. It’s all code.</p>
<p>After that, it was really a sky-rocket of productivity. Eventually I would write Elisp casually in between programming on work projects. I would notice that a way of working was repetitive, or that Emacs behaved in a way I just didn’t quite like, or I simply thought of a nice thing that I could add. I’d happily spend anywhere from 30 seconds to half an hour writing some functionality to extend my editing facilities.</p>
<p>And it was extended for good. That amazed me, and still does. My problems are only problems for as long as I don’t notice them. Once I do, I write some Elisp to solve it, and then it’s never a problem again. In typical editors and IDEs, I simply wouldn’t even think of fixing such things, never mind actually putting my work to one side for a minute, solving them, and then going back to work again.</p>
<p>I’ve now written a lot of Elisp to support my development, especially with respect to Haskell. Many times, for many months at a time, over the years, I’ve been working on an experimental feature, or feature set, mode, what-have-you, and it’s been very spotty. Mostly working, but breaking a lot, interrupting my work, but with me persevering, pushing through, until that work becomes stable and quite robust through sheer usage and battle testing.</p>
<p>When working recently it occured to me that a lot of the functionality I depend on presently in Emacs for work is built upon my own work. I use the session/interactive-mode work for interacting with Cabal and GHCi, I use structured-haskell-mode in conjunction with that, and then atop that I use god-mode, my own Emacs input method. At one time or another in the past they have all been unusable, or flaky as hell. SHM still has a few growing pains, but is basically there.</p>
<p>This really reminds me of Terry Pratchett’s <a href="http://en.wikipedia.org/wiki/Igor_%28Discworld%29">Igor</a> clan. I discovered this amiable race in The Fifth Elephant. Igors are a people inspired from the typical hunchbacked Igor archetype, but in Discworld, they are also self-modifiers. Their bodies consist of mixed and matched and patched and swapped body parts among other members of their clan, of scars and self-adjustements. They are infinitely self-improving, self-experimenting. They might end up with a botched job and have to hobble around for a few days, but in the end it’s always fixable.</p>
<p>And they lisp.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Though, while Elisp is Emacs’s programmability language of choice, the particular language doesn’t matter much. It could be Python, JavaScript, Haskell, whatever. The key is: if most of your feature set is written in your editor’s programming language, then that editor is very programmable.<a href="#fnref1">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Wed, 25 Dec 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/emacs-users-are-like-igor</guid>
</item>
<item>
<title>structured-haskell-mode</title>
<link>http://chrisdone.com/posts/structured-haskell-mode</link>
<description><![CDATA[<p>For about 2 months I’ve been working on and off on an Emacs package called <a href="https://github.com/chrisdone/structured-haskell-mode">structured-haskell-mode.</a><sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup> A full explanation and demo of the features is available on the Github page. In summary, it is a mode that offers <a href="https://www.youtube.com/watch?v=D6h5dFyyUX0">paredit-mode</a><sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup> abilities for Haskell code.</p>
<p>I’ve been keeping it to myself in a private Github repo, hoping to finish fleshing out the feature set<sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup> and smooth over stability issues. In the end I decided I’d put it out there, because the base functionality is quite reliable and enough to get work done better. It does actually change how you work.</p>
<p>The key features that enable new ways of working are:</p>
<ol style="list-style-type: decimal">
<li>Cutting and pasting actually preserves the indentation of the particular syntactic node. One doesn’t have to think or care about “re-indenting” or worry about how much nesting is happening for fear of having to clean it up later. It’s so trivial now.</li>
<li>Typing characters or removing them will “bring along” dependent node source, meaning that re-indentation is handled automatically. This means that you can use a nice consistent Lisp style<sup><a href="#fn4" class="footnoteRef" id="fnref4">4</a></sup> without caring about how you’re going to have to manually re-indent it whenever you make changes.</li>
<li>You now don’t have to think about indentation. You think about nesting level. To go to the right place, you use the <code>)</code> keybinding to go further outwards in the node layers, and hit <code>C-j</code> to start a new sibling at that node level. There is no “tab cycle”. This style is 100% reliable.</li>
<li>Context-awareness is useful. In strings, the quote character is escaped. When hitting <code>C-j</code> in a list (of values, or types in a record, or a list of constructors in a data declaration), it can automatically add delimiter characters properly indented and spaced out. Something you don’t want to have to care about doing yourself.</li>
<li>Parentheses are actually good. The Haskell tendency to abuse <code>$</code> to avoid having to manage parentheses is symptomatic of having crappy editing facilities. Managing parentheses in Haskell code is a pain, because editors don’t know about things like Haskell’s case expressions, or lambdas, or patterns, or whatever, and re-indentation is a nightmare inside parentheses. Not in this mode. Parentheses make editing a triviality rather than a chore.</li>
</ol>
<p>The overarching theme to this whole library is to remove redundancy in your work. Stop thinking so much about layout and syntactic debt<sup><a href="#fn5" class="footnoteRef" id="fnref5">5</a></sup> and appealing to the status quo<sup><a href="#fn6" class="footnoteRef" id="fnref6">6</a></sup>, and start just thinking about the real work you’re doing, which is plugging together programming constructs.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>It is actually a rewrite of a package I wrote six months ago of the same name. That package was stable, but the code was not favourable and there were some kinks to be ironed out. The new version uses Emacs markers so structured operations fail less often.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>Emacs users who’ve written their share of Elisp will know that paredit-mode is among the most enjoyable editing experiences out there. Strangers to this editing experience are simply missing out on the cream of the crop.<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>Stealing ideas from paredit-mode (e.g. slurping, barfing, convoluting) and coming up with my own ideas, such as operand manipulation, automagic re-indentation.<a href="#fnref3">↩</a></p></li>
<li id="fn4"><p>Lisp style is:</p>
<pre><code>foo bar
mu
(zot bar
bob)</code></pre>
<a href="#fnref4">↩</a></li>
<li id="fn5"><p>Syntactic debt is the energy and time you spend later on for making decisions or choices now. Feel like you’re nesting your function too deep? Better stop now or you’ll pay for it later because you’ll have to come back and collapse it down to fit within 80/120 columns! That’s a real problem when your editor sucks. When you have much better control over your code, things like that are a non-issue. Just write the code, worry about layout when you’re done. Lispers know this.<a href="#fnref5">↩</a></p></li>
<li id="fn6"><p>The status quo has to debunked incrementally, I think. The next thing to sort out is diffs. People waste their time making their code more friendly to diff engines that only know about lines. Diffs should be smart enough to know better. Expect further development in this area.<a href="#fnref6">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Mon, 09 Dec 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/structured-haskell-mode</guid>
</item>
<item>
<title>Recording simple GIFs for demos</title>
<link>http://chrisdone.com/posts/recording-small-gifs</link>
<description><![CDATA[<p>Sometimes you might like to record little GIF animations of your screen to demonstrate an Emacs feature you did (hey, some of you might…). For example, <a href="https://github.com/chrisdone/structured-haskell-mode#features">these</a>. I made a wee F9 keybinding for Emacs to run this:</p>
<pre class="lisp"><code>(defun screenshot-frame ()
&quot;Take a screenshot of 400x200 pixels of the Emacs frame.&quot;
(interactive)
(shell-command-to-string
(concat &quot;sleep 1; &quot;
&quot;import -window 0x3c000a3 &quot;
&quot;-crop 400x200+13+0 +repage /tmp/frames/`date +%s`.png&quot;)))</code></pre>
<p>Replace the window id with the window id of your target window, which you can get with <code>xwininfo -display :0</code>.</p>
<p>I would execute <code>screenshot-frame</code> after running a command or pressing a key (it sounds painful but it’s not, and it allows you to make mistakes). The <code>sleep</code> call is to ensure that the buffer has finished updating. I also disabled <code>blink-cursor-mode</code>. Then to preview the animation so far I would use</p>
<pre><code>animate -delay 35 /tmp/frames/*.png</code></pre>
<p>If some frames were redundant I’d remove them. And then finally to write out a .gif I’d use</p>
<pre><code>convert -delay 35 /tmp/frames/*.png out.gif</code></pre>
<p>I found the whole thing quite convenient!</p>]]></description>
<pubDate>Mon, 09 Dec 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/recording-small-gifs</guid>
</item>
<item>
<title>My Emacs configuration</title>
<link>http://chrisdone.com/posts/dot-emacs</link>
<description><![CDATA[<p>Here’s how to use <a href="https://github.com/chrisdone/chrisdone-emacs">my Emacs configuration</a>, which is optimized for Haskell development.</p>
<h2 id="requirements">Requirements</h2>
<p>You need:</p>
<ul>
<li>Emacs</li>
<li>Git</li>
<li>hasktags</li>
</ul>
<p>Everything else is either in my repo or pulled from git submodules.</p>
<h2 id="downloading">Downloading</h2>
<p>Clone it from github, pull the submodules and setup the Haskell-specific tools.</p>
<pre><code>$ git clone https://github.com/chrisdone/chrisdone-emacs.git
$ git submodule init
$ git submodule update
$ cd packages/haskell-mode; make; cd ../..
$ cd packages/structured-haskell-mode; cabal install
$ cabal install hasktags</code></pre>
<h2 id="tweaks">Tweaks</h2>
<p>There are some strange things about my configuration that some users might not like:</p>
<ul>
<li>You probably want to comment out <a href="https://github.com/chrisdone/chrisdone-emacs/blob/master/init.el#L62">this line</a> about <a href="http://chrisdone.com/posts/god-mode"><code>god-mode</code></a><sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup>.</li>
<li>If you like arrow keys for code navigation, remove <a href="https://github.com/chrisdone/chrisdone-emacs/blob/master/config/global.el#L145">these lines</a>.<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup></li>
<li>If you don’t like the dark theme, comment out <code>(zenburn)</code> on <a href="https://github.com/chrisdone/chrisdone-emacs/blob/master/init.el#L61">this line</a>.</li>
<li>Keybindings that are different or additional to normal Emacs are <a href="https://github.com/chrisdone/chrisdone-emacs/blob/master/config/global.el#L133">here</a>.</li>
<li>My haskell-specific keybindings are <a href="https://github.com/chrisdone/chrisdone-emacs/blob/master/config/haskell.el#L84">here</a>.</li>
</ul>
<p>Open a .hs file in a project and run C-` to start GHCi. Things should be mostly self-explanatory from there. Look at the keybindings and play around.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>That enables a strange input style like Vim to avoid having to hit Ctrl.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>I use <code>C-n/C-p/C-f/C-b</code> for navigation, which in <code>god-mode</code> is <code>npfb</code>.<a href="#fnref2">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Mon, 09 Dec 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/dot-emacs</guid>
</item>
<item>
<title>Making GHCi scale better and faster</title>
<link>http://chrisdone.com/posts/making-ghci-fast</link>
<description><![CDATA[<p>A common complaint with GHCi is that it doesn’t scale well when the size of the project gets bigger. Once you hit 20, 30, 50, or 150 modules, it stops being fun anymore and you start wishing you didn’t have to wait for it to load.</p>
<p>I recommend enabling <code>-fobject-code</code>. You can enable this by running</p>
<pre><code>$ ghci -fobject-code</code></pre>
<p>Or by setting it in the REPL:</p>
<pre><code>:set -fobject-code</code></pre>
<p>If you want it on all the time, you can put the above line in a <code>.ghci</code> file either in your home directory or in the directory of your project.</p>
<p>This makes GHCi compile everything once and then use incremental recompilation thereafter. You’ll find that you can load 100-module projects and work with them just fine in this way.</p>
<p>After that, you may notice that loading some modules gives less type information and general metadata than before. For that, re-enable byte-compilation temporarily with <code>-fbyte-code</code> (<code>:set -fbyte-code</code>) and <code>:load</code> that module again, you now have fast recompilation with complete information, too.</p>
<p>Another tip is to use <code>-fno-code</code> to have <em>really</em> fast compilation. This also works in combination with <code>-fobject-code</code>. But I’d recommend using this only for type checking, not for getting useful warnings (like pattern match inexhaustiveness). So I would combine it with <code>-fobject-code</code> in the same way as above with <code>-fbyte-code</code>, and then once you’re done hacking, re-enable <code>-fobject-code</code> and rebuild everything.</p>]]></description>
<pubDate>Wed, 20 Nov 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/making-ghci-fast</guid>
</item>
<item>
<title>Twitter waterflow problem and loeb</title>
<link>http://chrisdone.com/posts/twitter-problem-loeb</link>
<description><![CDATA[<style>
.g b{background:#888;color:#eee}
.g i{background:#ccc;color:#888}
.g a{background:#1a6e8e;color:#1a6e8e;}
.g u{background:#8f4e8b;color:#fff;text-decoration:none;}
.g s{background:#397460;color:#fff;text-decoration:none;}
.g b,.g i,.g a,.g u,.g s {padding:0.2em;display:block;border-radius:0.1em;width:1em;height:1em;float:left;margin:0.1em;line-height:1em;text-align:center;font-weight:normal;text-shadow:none;}
.g em{clear:both;display:block}
</style>
<h2 id="the-waterflow-problem">The Waterflow Problem</h2>
<p>I recently saw <em><a href="http://qandwhat.apps.runkite.com/i-failed-a-twitter-interview/">I Failed a Twitter Interview</a></em> which features the following cute problem. Consider the following picture:</p>
<div class="g">
<i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <b>7</b> <b>7</b> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <b></b> <b></b> <b>6</b> <em></em> <i></i> <b>5</b> <i></i> <i></i> <i></i> <i></i> <b></b> <b></b> <b></b> <em></em> <i></i> <b></b> <i></i> <i></i> <i></i> <b>4</b> <b></b> <b></b> <b></b> <em></em> <i></i> <b></b> <i></i> <i></i> <b>3</b> <b></b> <b></b> <b></b> <b></b> <em></em> <b>2</b> <b></b> <i></i> <b>2</b> <b></b> <b></b> <b></b> <b></b> <b></b> <em></em> <b></b> <b></b> <b>1</b> <b></b> <b></b> <b></b> <b></b> <b></b> <b></b> <em></em>
</div>
<p><strong><em>Fig. 1</em></strong></p>
<p>In <em>Fig. 1</em>, we have walls of different heights. Such pictures are represented by an array of integers, where the value at each index is the height of the wall. <em>Fig. 1</em> is represented with an array as <code>[2,5,1,2,3,4,7,7,6]</code>.</p>
<p>Now imagine it rains. How much water is going to be accumulated in puddles between walls? For example, if it rains in <em>Fig 1</em>, the following puddle will be formed:</p>
<div class="g">
<i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <b>7</b> <b>7</b> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <b></b> <b></b> <b>6</b> <em></em> <i></i> <b>5</b> <a></a> <a></a> <a></a> <a></a> <b></b> <b></b> <b></b> <em></em> <i></i> <b></b> <a></a> <a></a> <a></a> <b>4</b> <b></b> <b></b> <b></b> <em></em> <i></i> <b></b> <a></a> <a></a> <b>3</b> <b></b> <b></b> <b></b> <b></b> <em></em> <b>2</b> <b></b> <a></a> <b>2</b> <b></b> <b></b> <b></b> <b></b> <b></b> <em></em> <b></b> <b></b> <b>1</b> <b></b> <b></b> <b></b> <b></b> <b></b> <b></b> <em></em>
</div>
<p><strong><em>Fig. 2</em></strong></p>
<p>No puddles are formed at edges of the wall, water is considered to simply run off the edge.</p>
<p>We count volume in square blocks of 1×1. Thus, we are left with a puddle between column 1 and column 6 and the volume is 10.</p>
<p>Write a program to return the volume for any array.</p>
<h2 id="my-reaction">My Reaction</h2>
<p>I thought, this looks like a spreadsheet problem, and closed the page, to get on with my work. Last thing I need right now is nerd sniping.</p>
<p>A week or so later I saw <em><a href="http://philipnilsson.github.io/Badness10k/articles/waterflow/">A functional solution to Twitter’s waterflow problem</a></em> which presented a rather concise and beautiful approach to solving the problem. I present it here, in the style that I prefer:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">water ::</span> [<span class="dt">Int</span>] <span class="ot">-&gt;</span> <span class="dt">Int</span>
water h <span class="fu">=</span>
sum (zipWith (<span class="fu">-</span>)
(zipWith min
(scanl1 max h)
(scanr1 max h))
h)</code></pre>
<p>This is the second fastest algorithm in this page, clocking in at a mean 2.624748 ms for a random list of 10000 elements. See <a href="#benchmarks">Benchmarks</a> for more details.</p>
<p>An efficient algorithm can be achieved with a trivial rewrite of Michael Kozakov’s <a href="https://gist.github.com/mkozakov/59af0fd5bddbed1a0399">Java solution</a> is:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">{-# LANGUAGE BangPatterns #-}</span>
<span class="ot">{-# LANGUAGE ViewPatterns #-}</span>
<span class="kw">import</span> <span class="kw">qualified</span> Data.Vector <span class="kw">as</span> V
<span class="kw">import</span> Data.Vector ((!),Vector)
<span class="ot">water ::</span> <span class="dt">Vector</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span>
water land <span class="fu">=</span> go <span class="dv">0</span> <span class="dv">0</span> (V.length land <span class="fu">-</span> <span class="dv">1</span>) <span class="dv">0</span> <span class="dv">0</span> <span class="kw">where</span>
go <span class="fu">!</span>volume <span class="fu">!</span>left <span class="fu">!</span>right
(extend left <span class="ot">-&gt;</span> leftMax)
(extend right <span class="ot">-&gt;</span> rightMax)
<span class="fu">|</span> left <span class="fu">&lt;</span> right <span class="fu">=</span>
<span class="kw">if</span> leftMax <span class="fu">&gt;=</span> rightMax
<span class="kw">then</span> go (volume <span class="fu">+</span> rightMax <span class="fu">-</span> land<span class="fu">!</span>right)
left (right <span class="fu">-</span> <span class="dv">1</span>) leftMax rightMax
<span class="kw">else</span> go (volume <span class="fu">+</span> leftMax <span class="fu">-</span> land<span class="fu">!</span>left)
(left <span class="fu">+</span> <span class="dv">1</span>) right leftMax rightMax
<span class="fu">|</span> otherwise <span class="fu">=</span> volume
extend i d <span class="fu">=</span> <span class="kw">if</span> land<span class="fu">!</span>i <span class="fu">&gt;</span> d <span class="kw">then</span> land<span class="fu">!</span>i <span class="kw">else</span> d</code></pre>
<p>This is expectedly the fastest algorithm in this page, clocking in at a mean of 128.2953 us for a random vector of 10000 elements.</p>
<p>But I still thought my spreadsheet idea was feasible.</p>
<h2 id="my-approach">My approach</h2>
<p>In a similar way to Philip Nilsson, I can define the problem as it comes intuitively to me. As I saw it in my head, the problem can be broken down into “what is the volume that a given column will hold?” That can be written like this:</p>
<blockquote>
<p>volume<sub>0</sub> = 0</p>
<p>volume<sub>|S|-1</sub> = 0</p>
<p>volume<sub>i</sub> = min(left<sub>i-1</sub>,right<sub>i+1</sub>)−height<sub>i</sub></p>
</blockquote>
<p>Where <i>left</i> and <i>right</i> are the peak heights to the left or right:</p>
<blockquote>
<p>left<sub>0</sub> = height<sub>0</sub></p>
<p>left<sub>i</sub> = max(height<sub>i</sub>,left<sub>i-1</sub>)</p>
<p>right<sub>|S|-1</sub> = height<sub>|S|-1</sub></p>
<p>right<sub>i</sub> = max(height<sub>i</sub>,right<sub>i+1</sub>)</p>
</blockquote>
<p>That’s all.</p>
<h2 id="a-visual-example">A visual example</h2>
<p>An example of <code>i</code> is:</p>
<div class="g">
<i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <b>7</b> <b>7</b> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <b></b> <b></b> <b>6</b> <em></em> <i></i> <b>5</b> <i></i> <i></i> <i></i> <i></i> <b></b> <b></b> <b></b> <em></em> <i></i> <b></b> <i></i> <i></i> <i></i> <b>4</b> <b></b> <b></b> <b></b> <em></em> <i></i> <b></b> <i></i> <i></i> <b>3</b> <b></b> <b></b> <b></b> <b></b> <em></em> <b>2</b> <b></b> <i></i> <u>2</u> <b></b> <b></b> <b></b> <b></b> <b></b> <em></em> <b></b> <b></b> <b>1</b> <u></u> <b></b> <b></b> <b></b> <b></b> <b></b> <em></em>
</div>
<p>We spread out in both directions to find the “peak” of the columns:</p>
<div class="g">
<i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <s>7</s> <b>7</b> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <s></s> <b></b> <b>6</b> <em></em> <i></i> <s>5</s> <i></i> <i></i> <i></i> <i></i> <s></s> <b></b> <b></b> <em></em> <i></i> <s></s> <i></i> <i></i> <i></i> <b>4</b> <s></s> <b></b> <b></b> <em></em> <i></i> <s></s> <i></i> <i></i> <b>3</b> <b></b> <s></s> <b></b> <b></b> <em></em> <b>2</b> <s></s> <i></i> <u>2</u> <b></b> <b></b> <s></s> <b></b> <b></b> <em></em> <b></b> <s></s> <b>1</b> <u></u> <b></b> <b></b> <s></s> <b></b> <b></b> <em></em>
</div>
<p>How do we do that? We simply define the volume of a column to be in terms of our immediate neighbors to the left and to the right:</p>
<div class="g">
<i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <b>7</b> <b>7</b> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <b></b> <b></b> <b>6</b> <em></em> <i></i> <b>5</b> <i></i> <i></i> <i></i> <i></i> <b></b> <b></b> <b></b> <em></em> <i></i> <b></b> <i></i> <i></i> <i></i> <b>4</b> <b></b> <b></b> <b></b> <em></em> <i></i> <b></b> <i></i> <i></i> <s>3</s> <b></b> <b></b> <b></b> <b></b> <em></em> <b>2</b> <b></b> <i></i> <u>2</u> <s></s> <b></b> <b></b> <b></b> <b></b> <em></em> <b></b> <b></b> <s>1</s> <u></u> <s></s> <b></b> <b></b> <b></b> <b></b> <em></em> <i></i> <i></i> <i>A</i> <i>X</i> <i>B</i> <i></i> <i></i> <i></i> <i></i> <em></em>
</div>
<p>X is defined in terms of A and B. A and B are, in turn, are defined in terms of their immediate neighbors. Until we reach the ends:</p>
<div class="g">
<i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <b>7</b> <b>7</b> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <b></b> <b></b> <s>6</s> <em></em> <i></i> <b>5</b> <i></i> <i></i> <i></i> <i></i> <b></b> <b></b> <s></s> <em></em> <i></i> <b></b> <i></i> <i></i> <i></i> <b>4</b> <b></b> <b></b> <s></s> <em></em> <i></i> <b></b> <i></i> <i></i> <b>3</b> <b></b> <b></b> <b></b> <s></s> <em></em> <s>2</s> <b></b> <i></i> <u>2</u> <b></b> <b></b> <b></b> <b></b> <s></s> <em></em> <s></s> <b></b> <b>1</b> <u></u> <b></b> <b></b> <b></b> <b></b> <s></s> <em></em> <i>A</i> <i>X</i> <i></i> <i></i> <i></i> <i></i> <i></i> <i>Y</i> <i>B</i> <em></em>
</div>
<p>The ends of the wall are the only ones who only have <em>one side</em> defined in terms of their single neighbor, which makes complete sense. Their volume is always <code>0</code>. It’s impossible to have a puddle on the edge. A’s “right” will be defined in terms of X, and B’s “left” will be defined in terms of Y.</p>
<p>But how does this approach avoid infinite cycles? Easy. Each column in the spreadsheet contains three values:</p>
<ol style="list-style-type: decimal">
<li>The peak to the left.</li>
<li>The peak to the right.</li>
<li>My volume.</li>
</ol>
<p>A and B below depend upon eachother, but for different slots. A depends on the value of B’s “right” peak value, and B depends on the value of A’s “left” value:</p>
<div class="g">
<i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <b>7</b> <b>7</b> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <b></b> <b></b> <b>6</b> <em></em> <i></i> <b>5</b> <i></i> <i></i> <i></i> <i></i> <b></b> <b></b> <b></b> <em></em> <i></i> <b></b> <i></i> <i></i> <i></i> <b>4</b> <b></b> <b></b> <b></b> <em></em> <i></i> <b></b> <i></i> <i></i> <s>3</s> <b></b> <b></b> <b></b> <b></b> <em></em> <b>2</b> <b></b> <i></i> <u>2</u> <s></s> <b></b> <b></b> <b></b> <b></b> <em></em> <b></b> <b></b> <b>1</b> <u></u> <s></s> <b></b> <b></b> <b></b> <b></b> <em></em> <i></i> <i></i> <i></i> <i>A</i> <i>B</i> <i></i> <i></i> <i></i> <i></i> <em></em>
</div>
<p>The <em>height</em> of the column’s peak will be the smallest of the two peaks on either side:</p>
<div class="g">
<i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <b>7</b> <b>7</b> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <b></b> <b></b> <b>6</b> <em></em> <i></i> <s>5</s> <i></i> <a></a> <i></i> <i></i> <s></s> <b></b> <b></b> <em></em> <i></i> <s></s> <i></i> <i></i> <i></i> <b>4</b> <s></s> <b></b> <b></b> <em></em> <i></i> <s></s> <i></i> <i></i> <b>3</b> <b></b> <s></s> <b></b> <b></b> <em></em> <b>2</b> <s></s> <i></i> <u>2</u> <b></b> <b></b> <s></s> <b></b> <b></b> <em></em> <b></b> <s></s> <b>1</b> <u></u> <b></b> <b></b> <s></s> <b></b> <b></b> <em></em>
</div>
<p>And then the <em>volume</em> of the column is simply the height of the peak minus the column’s height:</p>
<div class="g">
<i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <b>7</b> <b>7</b> <i></i> <em></em> <i></i> <i></i> <i></i> <i></i> <i></i> <i></i> <b></b> <b></b> <b>6</b> <em></em> <i></i> <s>5</s> <i></i> <a></a> <i></i> <i></i> <s></s> <b></b> <b></b> <em></em> <i></i> <s></s> <i></i> <a></a> <i></i> <b>4</b> <s></s> <b></b> <b></b> <em></em> <i></i> <s></s> <i></i> <a></a> <b>3</b> <b></b> <s></s> <b></b> <b></b> <em></em> <b>2</b> <s></s> <i></i> <u>2</u> <b></b> <b></b> <s></s> <b></b> <b></b> <em></em> <b></b> <s></s> <b>1</b> <u></u> <b></b> <b></b> <s></s> <b></b> <b></b> <em></em>
</div>
<h2 id="enter-loeb">Enter loeb</h2>
<p>I first heard about <code>loeb</code> from Dan Piponi’s <a href="http://blog.sigfpe.com/2006/11/from-l-theorem-to-spreadsheet.html">From Löb’s Theorem to Spreadsheet Evaluation</a> some years back, and ever since I’ve been wanting to use it for a real problem. It lets you easily define a spreadsheet generator by mapping over a functor containing functions. To each function in the container, the container itself is passed to that function.</p>
<p>Here’s <code>loeb</code>:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">loeb ::</span> <span class="dt">Functor</span> f <span class="ot">=&gt;</span> f (f b <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> f b
loeb x <span class="fu">=</span> fmap (\f <span class="ot">-&gt;</span> f (loeb x)) x</code></pre>
<p>(Note, there is a <a href="#update-on-loeb">more efficient version here</a>.)</p>
<p>So as described in the elaboration of how I saw the problem in my head, the solution takes the vector of numbers, generates a spreadsheet of triples, defined in terms of their neighbors—exept edges—and then simply makes a sum total of the third value, the volumes.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">import</span> Control.Lens
<span class="kw">import</span> <span class="kw">qualified</span> Data.Vector <span class="kw">as</span> V
<span class="kw">import</span> Data.Vector ((!),Vector)
<span class="ot">water ::</span> <span class="dt">Vector</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span>
water <span class="fu">=</span> V.sum <span class="fu">.</span> V.map (view _3) <span class="fu">.</span> loeb <span class="fu">.</span> V.imap cell <span class="kw">where</span>
cell i x xs
<span class="fu">|</span> i <span class="fu">==</span> <span class="dv">0</span> <span class="fu">=</span> edge _2
<span class="fu">|</span> i <span class="fu">==</span> V.length xs <span class="fu">-</span> <span class="dv">1</span> <span class="fu">=</span> edge _1
<span class="fu">|</span> otherwise <span class="fu">=</span> col i x xs
<span class="kw">where</span> edge ln <span class="fu">=</span> set l (view l (col i x xs)) (x,x,<span class="dv">0</span>)
<span class="kw">where</span> l r <span class="fu">=</span> cloneLens ln r
col i x xs <span class="fu">=</span> (l,r,min l r <span class="fu">-</span> x)
<span class="kw">where</span> l <span class="fu">=</span> neighbor _1 (<span class="fu">-</span>)
r <span class="fu">=</span> neighbor _2 (<span class="fu">+</span>)
neighbor l o <span class="fu">=</span> max x (view l (xs <span class="fu">!</span> (i <span class="ot">`o`</span> <span class="dv">1</span>)))</code></pre>
<p>It’s not the most efficient algorithm—it relies on laziness in an almost perverse way, but I like that I was able to express exactly what occured to me. And <code>loeb</code> is suave. It clocks in at a mean of 3.512758 ms for a vector of 10000 random elements. That’s not too bad, compared to the <code>scanr</code>/<code>scanl</code>.</p>
<p>This is was also my first use of <a href="http://hackage.haskell.org/package/lens">lens</a>, so that was fun. The <code>cloneLens</code> are required because you can’t pass in an arbitrary lens and then use it both as a setter and a getter, the type becomes fixed on one or the other, making it not really a <em>lens</em> anymore. I find that pretty disappointing. But otherwise the lenses made the code simpler.</p>
<h2 id="update-with-comonads-pointed-lists">Update with comonads &amp; pointed lists</h2>
<p>Michael Zuser pointed out another cool insight from <em><a href="http://blog.sigfpe.com/2007/02/comonads-and-reading-from-future.html?showComment=1171056660000#c2284986681058924897">Comonads and reading from the future</a></em> (Dan Piponi’s blog is a treasure trove!) that while <code>loeb</code> lets you look at the <em>whole</em> container, giving you <em>absolute</em> references, the equivalent corecursive fix (below <code>wfix</code>) on a comonad gives you <em>relative</em> references. Michael demonstrates below using Jeff Wheeler’s <a href="http://hackage.haskell.org/package/pointedlist-0.4.0.3/docs/Data-List-PointedList.html">pointed list</a> library and Edward Kmett’s <a href="http://hackage.haskell.org/package/comonad">comonad</a> library:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">import</span> Control.Comonad
<span class="kw">import</span> Control.Lens
<span class="kw">import</span> Data.List.PointedList (PointedList)
<span class="kw">import</span> <span class="kw">qualified</span> Data.List.PointedList <span class="kw">as</span> PE
<span class="kw">import</span> Data.Maybe
<span class="kw">instance</span> <span class="dt">Comonad</span> <span class="dt">PointedList</span> <span class="kw">where</span>
extend <span class="fu">=</span> PE.contextMap
extract <span class="fu">=</span> <span class="dt">PE</span><span class="fu">.</span>_focus
<span class="ot">water ::</span> [<span class="dt">Int</span>] <span class="ot">-&gt;</span> <span class="dt">Int</span>
water <span class="fu">=</span> view _2 <span class="fu">.</span> wfix <span class="fu">.</span> fmap go <span class="fu">.</span> fromMaybe (PE.singleton <span class="dv">0</span>) <span class="fu">.</span> PE.fromList
<span class="kw">where</span>
go height context <span class="fu">=</span> (lMax, total, rMax)
<span class="kw">where</span>
get f <span class="fu">=</span> maybe (height, <span class="dv">0</span>, height) <span class="dt">PE</span><span class="fu">.</span>_focus <span class="fu">$</span> f context
(prevLMax, _, _) <span class="fu">=</span> get PE.previous
(_ , prevTotal, prevRMax) <span class="fu">=</span> get PE.next
lMax <span class="fu">=</span> max height prevLMax
rMax <span class="fu">=</span> max height prevRMax
total <span class="fu">=</span> prevTotal <span class="fu">+</span> min lMax rMax <span class="fu">-</span> height</code></pre>
<p>I think if I’d’ve heard of this before, this solution would’ve come to mind instead, it seems entirely natural!</p>
<p>Sadly, this is the slowest algorithm on the page. I’m not sure how to optimize it to be better.</p>
<h2 id="update-on-lens">Update on lens</h2>
<p>Russell O’Connor gave me some hints for reducing the lens verbiage. First, eta-reducing the locally defined lens <code>l</code> in my code removes the need for the <code>NoMonomorphismRestriction</code> extension, so I’ve removed that. Second, a rank-N type can also be used, but then the type signature is rather large and I’m unable to reduce it presently without reading more of the lens library.</p>
<h2 id="update-on-loeb">Update on loeb</h2>
<p>On re-reading the comments for <em><a href="http://blog.sigfpe.com/2006/11/from-l-theorem-to-spreadsheet.html">From Löb’s Theorem to Spreadsheet Evaluation</a></em> I noticed Edward Kmett pointed out we can get better laziness sharing with the following definition of loeb:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">loeb ::</span> <span class="dt">Functor</span> f <span class="ot">=&gt;</span> f (f b <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> f b
loeb x <span class="fu">=</span> xs
<span class="kw">where</span> xs <span class="fu">=</span> fmap (<span class="fu">$</span> xs) x</code></pre>
<p>For my particular <code>water</code> function, this doesn’t make much of a difference, but there is a difference. See the next section.</p>
<h2 id="time-travelling-solution">Time travelling solution</h2>
<p>Michael Zuser demonstrated a time travelling solution based on <a href="http://hackage.haskell.org/package/tardis-0.3.0.0/docs/Control-Monad-Tardis.html">the Tardis monad</a>:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">import</span> Control.Monad
<span class="kw">import</span> Control.Monad.Tardis
<span class="ot">water ::</span> [<span class="dt">Int</span>] <span class="ot">-&gt;</span> <span class="dt">Int</span>
water <span class="fu">=</span> flip evalTardis (minBound, minBound) <span class="fu">.</span> foldM go <span class="dv">0</span>
<span class="kw">where</span>
go total height <span class="fu">=</span> <span class="kw">do</span>
modifyForwards <span class="fu">$</span> max height
leftmax <span class="ot">&lt;-</span> getPast
rightmax <span class="ot">&lt;-</span> getFuture
modifyBackwards <span class="fu">$</span> max height
return <span class="fu">$</span> total <span class="fu">+</span> min leftmax rightmax <span class="fu">-</span> height</code></pre>
<h2 id="fastest">Fastest</h2>
<p>Sami Hangaslammi submitted this fast version (clocks in at 33.80864 us):</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">import</span> Data.Array
<span class="ot">waterVolume ::</span> <span class="dt">Array</span> <span class="dt">Int</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span>
waterVolume arr <span class="fu">=</span> go <span class="dv">0</span> minB maxB <span class="kw">where</span>
(minB,maxB) <span class="fu">=</span> bounds arr
go <span class="fu">!</span>acc lpos rpos
<span class="fu">|</span> lpos <span class="fu">&gt;=</span> rpos <span class="fu">=</span> acc
<span class="fu">|</span> leftHeight <span class="fu">&lt;</span> rightHeight <span class="fu">=</span>
segment leftHeight <span class="dv">1</span> acc lpos contLeft
<span class="fu">|</span> otherwise <span class="fu">=</span>
segment rightHeight (<span class="fu">-</span><span class="dv">1</span>) acc rpos contRight
<span class="kw">where</span>
leftHeight <span class="fu">=</span> arr <span class="fu">!</span> lpos
rightHeight <span class="fu">=</span> arr <span class="fu">!</span> rpos
contLeft acc&#39; pos&#39; <span class="fu">=</span> go acc&#39; pos&#39; rpos
contRight acc&#39; pos&#39; <span class="fu">=</span> go acc&#39; lpos pos&#39;
segment limit move <span class="fu">!</span>acc&#39; <span class="fu">!</span>pos cont
<span class="fu">|</span> delta <span class="fu">&lt;=</span> <span class="dv">0</span> <span class="fu">=</span> cont acc&#39; pos&#39;
<span class="fu">|</span> otherwise <span class="fu">=</span> segment limit move (acc&#39; <span class="fu">+</span> delta) pos&#39; cont
<span class="kw">where</span>
delta <span class="fu">=</span> limit <span class="fu">-</span> arr <span class="fu">!</span> pos&#39;
pos&#39; <span class="fu">=</span> pos <span class="fu">+</span> move</code></pre>
<p>Changing the data structure to a vector brings this down to 26.79492 us.</p>
<h2 id="benchmarks">Benchmarks</h2>
<p>Here are benchmarks for all versions presented in this page.</p>
<pre><code>benchmarking water/10000
mean: 2.624748 ms, lb 2.619731 ms, ub 2.630364 ms, ci 0.950
std dev: 85.45235 us, lb 78.33856 us, ub 103.2333 us, ci 0.950
found 54 outliers among 1000 samples (5.4%)
51 (5.1%) high mild
3 (0.3%) high severe
variance introduced by outliers: 79.838%
variance is severely inflated by outliers
benchmarking water_loeb/10000
mean: 3.512758 ms, lb 3.508533 ms, ub 3.517332 ms, ci 0.950
std dev: 70.77688 us, lb 65.88087 us, ub 76.97691 us, ci 0.950
found 38 outliers among 1000 samples (3.8%)
24 (2.4%) high mild
14 (1.4%) high severe
variance introduced by outliers: 59.949%
variance is severely inflated by outliers
benchmarking water_loeb&#39;/10000
mean: 3.511872 ms, lb 3.507492 ms, ub 3.516778 ms, ci 0.950
std dev: 74.34813 us, lb 67.99334 us, ub 84.56183 us, ci 0.950
found 43 outliers among 1000 samples (4.3%)
34 (3.4%) high mild
9 (0.9%) high severe
variance introduced by outliers: 62.285%
variance is severely inflated by outliers
benchmarking water_onepass/10000
mean: 128.2953 us, lb 128.1194 us, ub 128.4774 us, ci 0.950
std dev: 2.864153 us, lb 2.713756 us, ub 3.043611 us, ci 0.950
found 18 outliers among 1000 samples (1.8%)
17 (1.7%) high mild
1 (0.1%) high severe
variance introduced by outliers: 64.826%
variance is severely inflated by outliers
benchmarking water_array/10000
mean: 33.80864 us, lb 33.76067 us, ub 33.86597 us, ci 0.950
std dev: 844.9932 ns, lb 731.3158 ns, ub 1.218807 us, ci 0.950
found 29 outliers among 1000 samples (2.9%)
27 (2.7%) high mild
2 (0.2%) high severe
variance introduced by outliers: 69.836%
variance is severely inflated by outliers
benchmarking water_vector/10000
mean: 26.79492 us, lb 26.75906 us, ub 26.83274 us, ci 0.950
std dev: 595.1865 ns, lb 559.8929 ns, ub 652.5076 ns, ci 0.950
found 21 outliers among 1000 samples (2.1%)
18 (1.8%) high mild
3 (0.3%) high severe
variance introduced by outliers: 64.525%
variance is severely inflated by outliers
benchmarking water_comonad/10000
collecting 1000 samples, 1 iterations each, in estimated 28315.44 s
benchmarking water_tardis/10000
collecting 1000 samples, 1 iterations each, in estimated 28.98788 s</code></pre>
<p>I never bothered waiting around for the comonad or the time traveller ones to complete. They’re slow, let’s say that.</p>
<p><a href="http://lpaste.net/95686">Here’s the source code</a> to the benchmarks, let me know if I made a mistake in the benchmark setup.</p>]]></description>
<pubDate>Thu, 14 Nov 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/twitter-problem-loeb</guid>
</item>
<item>
<title>God-mode for Emacs</title>
<link>http://chrisdone.com/posts/god-mode</link>
<description><![CDATA[<p>A month ago I blogged about ways to reduce strenuous key presses in my Emacs use. I <a href="/posts/emacs-key-analysis">analyzed my runs of chords in Emacs</a>, then <a href="/posts/speculations-on-exclusive-editing">speculated</a> on the merits of <a href="http://chrisdone.com/posts/modal-editors">exclusive vs mixed editing</a>. Since then I wrote an Emacs mode called <a href="https://github.com/chrisdone/god-mode/">god-mode</a>. It’s a mode that you toggle in and out of, and when you’re in it, all keys are implicitly prefixed with <code>C-</code> (among other helpful shortcuts). Over all, it’s been a resounding success. A couple other people, including the author of multiple mark mode, contributed some patches. I’ve been using it for a month and have been very satisfied.</p>
<p>For those interested in the keymapping as of writing, you can <a href="#the-keymapping">skip to that section below.</a></p>
<h2 id="compared-with-vim">Compared with Vim</h2>
<p>Coming back to the examples I came up with in <a href="(/posts/speculations-on-exclusive-editing)">speculations on exclusive editing</a>, God-mode is on par with Vim. In fact, it’s the same or fewer key presses for each one:</p>
<pre><code>Vim: bbDi (5)
Emacs: gb.ki (5)
Vim: db.i (4)
Emacs: g←.i (4)
Vim: ?r↲lDi (8)
Emacs: rr↲ki (5)</code></pre>
<p>That’s not bad. I grant that my Vim fu is weak, so probably there are shorter ways to write the Vim examples. But at any rate Emacs is doing well here.</p>
<h2 id="evaluation-after-one-month">Evaluation After One Month</h2>
<p>I’ve been using this in my Emacs turned on by default for one month. I knew I was going to stick with it after a week or so of use, it was already ingrained into how I use Emacs. Now, when I access a remote Emacs on a server or whatnot, I find that I reach for the Caps Lock key (my toggler key) in order to do an involved editing operation, only to find that it’s not there! Oh, no! I’ll have to use Ctrl for all these dull commands…</p>
<p>In typical usage, it’s a 50-50. When I’m writing code, I tend to work in normal Emacs mode. When I’m editing, I work almost exclusively in God-mode. Cutting (<code>w</code>), copying (<code>gw</code>), moving (<code>k</code>, <code>gk</code>, <code>Gk</code>, <code>y</code>), navigating (<code>ga</code>, <code>gf</code>, etc.), reindenting, slurping, buffer switching (<code>z</code>), running commands (<code>cc</code>, <code>ci</code>, <code>ct</code>, etc), moving around (<code>e</code>, <code>a</code>, <code>f</code>, <code>b</code>, etc.), searching (<code>s</code>, <code>r</code>), replacing (<code>t</code>), saving (<code>xs</code>). All those things I do from god mode.</p>
<p>I’ve also noticed that the more tired I get with my hands towards the end of the day, the more I tend to stick in god-mode. That gives me extra mileage to finish those last things.</p>
<h2 id="retaining-god-mode-exclusively">Retaining God Mode Exclusively</h2>
<p>In fact in some modes it’s possible to remain entirely in God mode. In CSS mode, for example, I’m able to produce out the following:</p>
<pre><code>.foo {
display: none;
}</code></pre>
<p>by typing</p>
<pre><code>{ .foo ↲ : d ↲ ↲</code></pre>
<p>What happens there is that <code>{</code> prompts me for a rule and inserts <code>{ }</code> and puts my cursor inside it. Then <code>:</code> prompts for a property name, which is completed with ido-mode. Then it prompts for a value. In the case of the <code>display</code> property, it knows there’s only a list of values available for it, and it prompts for a choice of <code>none</code>, <code>block</code>, etc. I hit <code>↲</code> to choose the default.</p>
<p>If I want to edit a property/value pair, I hit <code>;</code> and it prompts me for the value with the input containing the existing value.</p>
<p>The more one is able to stay in God mode, the more the speed and convenience benefits.</p>
<h2 id="the-keymapping">The Keymapping</h2>
<p>(This is described in the README, but including here for posterity.)</p>
<p>God-mode defines the following mapping:</p>
<ul>
<li><p>All commands are assumed to be <code>C-&lt;something&gt;</code> unless otherwise indicated. Examples:</p></li>
<li><code>a</code> → <code>C-a</code></li>
<li><code>s</code> → <code>C-s</code></li>
<li><code>akny</code> → <code>C-a C-k C-n C-y</code></li>
<li><code>xs</code> → <code>C-x C-s</code></li>
<li><p><code>x s</code> → <code>C-x s</code></p></li>
</ul>
<p>Note the use of space to produce <code>C-x s</code>.</p>
<ul>
<li><p><code>g</code> is a special key to indicate <code>M-&lt;something&gt;</code>. This means that there is no way to write <code>C-g</code> in this mode, you must therefore type <code>C-g</code> directly. Examples:</p></li>
<li><code>gf</code> → <code>M-f</code></li>
<li><p><code>gx</code> → <code>M-x</code></p></li>
<li><p><code>G</code> is a special key to indicate <code>C-M-&lt;something&gt;</code>. Example:</p></li>
<li><p><code>Gx</code> → <code>C-M-x</code></p></li>
<li><p>Digit arguments:</p></li>
<li><p><code>12f</code> → <code>M-12 C-f</code></p></li>
<li><p>Repetition:</p></li>
<li><p><code>gfzz</code> → <code>M-f M-f M-f</code></p></li>
<li><p>Universal boolean argument:</p></li>
<li><p><code>uco</code> → <code>C-u C-c C-o</code></p></li>
<li><p>There is a key (default <code>i</code> - think <em>insert</em>) to disable God mode, similar to Vim’s i.</p></li>
</ul>]]></description>
<pubDate>Sat, 21 Sep 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/god-mode</guid>
</item>
<item>
<title>Functional Programming is Hard?</title>
<link>http://chrisdone.com/posts/functional-programming-is-hard</link>
<description><![CDATA[<p>Just a reminder to those who think imperative object oriented style is inherently easier to understand for humans, and that functional programming languages are really hard, if you look at any class of complete programming newbies trying to learn a modern language like Java or C++, you quickly realise this is false. Here’s an email I received a few years ago from a friend who was taking programming at college, verbatim:</p>
<blockquote>
<p>Encapsulation, Inheritance, Class, Object</p>
<p>I have to define what these mean in terms of programming yet every time I research them I come across information I don’t understand. If you could lend me a hand or point me in the right direction of something a bit easier to understand that’d be great.</p>
<p>Just need some one to explain the terms in a simple manner, I don’t get why every time you research something they try to explain it in the most complex terms possible.</p>
</blockquote>]]></description>
<pubDate>Sat, 21 Sep 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/functional-programming-is-hard</guid>
</item>
<item>
<title>Goodbye, Last.fm</title>
<link>http://chrisdone.com/posts/goodbye-lastfm</link>
<description><![CDATA[<p><em>tl;dr: I replaced my dependence on Last.fm with my own service <a href="http://chrisdone.com/music">http://chrisdone.com/music</a>.</em></p>
<p>In my <a href="/posts/lastfm">last post</a> (admittedly, a year ago) I talked about how Last.fm had served me well enough over the years, but that I’d grown tired of not having full access to my data in order to make corrections. The final straw yesterday was that I have two Last.fm profiles; one from years back, and one for the past few years. In total I have 6 years worth of music listening information that I wanted to merge into one. Last.fm said no, you cannot do this. For a data aggregation service, that’s bonkers. Sod it.</p>
<p>I used <a href="https://github.com/encukou/lastscrape-gui/blob/master/lastexport.py">lastexport.py</a> which was written by the <a href="http://libre.fm/">libre.fm</a> guys. I downloaded everything from both of my profiles into an 11MB CSV (tab-separated) file, I also downloaded my loved tracks. This gave me the only information I cared about from Last.fm. I don’t need Last.fm anymore.</p>
<p>I tried to use the <a href="http://hackage.haskell.org/package/cassava">cassava</a> library to parse the CSV but it failed to parse and threw ridiculous 11MB error messages. I tried out <a href="http://hackage.haskell.org/package/csv-conduit">csv-conduit</a> and it parsed it first time. The APIs are similar, so I didn’t care which one worked. I imported my data into a PostgreSQL database. As of writing there are 83,238 listens recorded.</p>
<p>I then wrote a trivial web server with the <a href="http://hackage.haskell.org/package/scotty">scotty library</a>. It’s not that much more trivial than <a href="http://hackage.haskell.org/package/snap">snap</a>, but it has a low dependency foot-print and doesn’t require doing ByteString conversion to get anything done. I made a simple handler to accept track submissions that would record into the database.</p>
<p>I made a simple greasemonkey script for <a href="http://grooveshark.com">Grooveshark</a> (which is pretty much all I use right now to play music) that would submit tracks every 30 seconds to my local server. I’ll probably make a script for YouTube, too, because I sometimes listen to music on there. Grooveshark supports “favouriting” tracks, which I also added a hook for—when a track is favourited, it submits it to my server as “loved”. Like Last.fm, I don’t care about what Grooveshark stores.</p>
<p>I added to the web server a little summary page, then I installed it on my Hetzner dedicated host under chrisdone.com, <a href="http://chrisdone.com/music">here</a>.</p>
<p>I merged “The Prodigy” and “Prodigy” into one artist, because “Prodigy” is some rapper that I don’t like nor have ever listened to. This brought The Prodigy up to my most listened-to artist, which is accurate.</p>
<p>Job done, back to listening to music and hacking on important things. Goodbye, Last.fm.</p>]]></description>
<pubDate>Sun, 15 Sep 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/goodbye-lastfm</guid>
</item>
<item>
<title>CamelCase vs under_scores vs hyphenated-words</title>
<link>http://chrisdone.com/posts/camelcase-vs-underscores-vs-hyphens</link>
<description><![CDATA[<h2 id="snake-case-do_and_go">Snake-case: <code>do_and_go</code></h2>
<ul>
<li>2 key presses per new component</li>
<li>Chords involved: 1</li>
<li>Doesn’t use standard English compounding character</li>
<li>Marginally aesthetically pleasing, but not normal typography</li>
</ul>
<h2 id="camel-case-doandgo">Camel-case: <code>doAndGo</code></h2>
<ul>
<li>2 key presses per new component</li>
<li>Chords involved: n where n is the first character of the next component</li>
<li>Non-standard upper-case</li>
<li>Not aesthetically pleasing, like a camel’s back</li>
</ul>
<h2 id="lisp-case-do-and-go">Lisp-case: <code>do-and-go</code></h2>
<ul>
<li>1 key press per new component</li>
<li>Chords involved: 0</li>
<li>Uses standard English compounding character: <code>-</code> (think: “type-class”, “camel-case”, “five-point”, “computer-generated”)</li>
<li>Aesthetically pleasing, consistent height and separation</li>
</ul>]]></description>
<pubDate>Fri, 30 Aug 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/camelcase-vs-underscores-vs-hyphens</guid>
</item>
<item>
<title>Speculations on exclusive vs mixed editing</title>
<link>http://chrisdone.com/posts/speculations-on-exclusive-editing</link>
<description><![CDATA[<p>I covered what exclusive vs mixed editing means in <a href="/posts/modal-editors">another page</a>.</p>
<p>I think it depends on what you’re doing. If you’re writing stuff e.g. in insertion mode, the mode switching in vim becomes a pain because every time you want a command you have to switch to normal mode and then switch back again. E.g. consider the following (where <code>|</code> indicates the cursor):</p>
<pre><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit|</code></pre>
<p>If I’m writing this sentence and I realise the last two words are bad and should be another word, in Vim I might run the following to go backwards two words and delete to the end of the line:</p>
<p><code>C-c b b D i</code> — 7 key presses to do the operation</p>
<p>In Emacs I would run</p>
<p><code>M-b-b C-k</code> — 5 key presses</p>
<p>Or in Vim I might run the following to just delete the last two words:</p>
<p><code>C-c d b . i</code> — 6 key presses</p>
<p>which in Emacs is</p>
<p><code>M-&lt;backspace&gt;-&lt;backspace&gt;</code> — 3 key presses</p>
<p>Or I might instead search to the “r” character and then delete from there:</p>
<p><code>C-c ? r RET l D i</code> — 10 key presses</p>
<p>which in Emacs is</p>
<p><code>C-r r RET C-f-k</code> — 7 key presses</p>
<p>It’s just an example and the gains or losses will vary depending on the example. But Emacs’s default keybindings optimize the writing case where you are inserting and editing with equal fervor, whereas Vim’s mutal exclusion optimizes the editing mode, and I’m told leaves a lot to be desired for insertion mode.</p>
<p>What I’ve been considering, and was <a href="/posts/emacs-key-analysis">the point of my other page</a>, is to gather some real data on how often I am doing these C-/M- commands and for how much. Looking at the data, it turns out that I only do about 2.3 unique commands at one time, so <code>C-c b b i</code> in Vim is not a gain over M-b-b.</p>
<p>On the other hand there are some commands that I repeat a lot (probably <code>C-f</code>/<code>C-b</code>/<code>C-n</code>/<code>C-p</code> for navigation that I can probably combat by making repetition slow, encouraging me to use search more), and some editing commands that are too costly to type but also common, and so ought to be rebound. It’s not yet clear that mutually exclusive editing is a big win in the general case, but I am quite serious about trying it for editing Haskell and Lisp code, where there are slightly longer runs of commands.</p>]]></description>
<pubDate>Thu, 08 Aug 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/speculations-on-exclusive-editing</guid>
</item>
<item>
<title>Modal Editing: exclusive vs mixed</title>
<link>http://chrisdone.com/posts/modal-editors</link>
<description><![CDATA[<p>First I should clarify what I mean by exclusive vs mixed editing:</p>
<ul>
<li><em>Exclusive</em>: In Vim you can only insert or edit, those are two different modes.</li>
<li><em>Mixed</em>: In Emacs and most other editors, insertion and editing are done without switching modes.</li>
</ul>
<p>Now we can say what a mode is. Modal editing means that the effects of your key presses depend on the mode currently activated. From that we can say that both Emacs and Vim are modal editors:</p>
<p>Vim only has three modes as far as I know:</p>
<ul>
<li>Insertion mode</li>
<li>“Normal” mode (editing)</li>
<li>Last line mode</li>
</ul>
<p>Emacs has hundreds of modes:</p>
<ul>
<li>Mini-buffer mode</li>
<li>Text mode</li>
<li>Lisp mode</li>
<li>Dired mode</li>
<li>Magit mode</li>
<li>Shell mode</li>
<li>etc.</li>
</ul>
<p>In light of this, calling Vim “modal” as if it’s the only editor that does this confuses matters. The real difference is the exclusion.</p>]]></description>
<pubDate>Thu, 08 Aug 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/modal-editors</guid>
</item>
<item>
<title>Analysis of Emacs keys pressed</title>
<link>http://chrisdone.com/posts/emacs-key-analysis</link>
<description><![CDATA[<p>Here’s the deal: Emacs keybindings make my fingers hurt. I don’t think I ever experienced RSI before I started using Emacs. I guess I’ve been using Emacs for about 6 years. I’m very efficient with it. I can edit almost as fast as I can think, my fingers never need to take a break. But that efficiency comes at a steep price, I feel.</p>
<p>I hypothesize that chords are to blame, and that I would be happier and less achey if I used a modal set of keybindings, like in Vim, in which every key binding is a single character. Not all the keybindings (e.g. <code>$</code>) are a single key press, but most are.</p>
<p>I’ve tried <code>evil-mode</code>, and it’s pretty poor. It doesn’t provide a proper mapping to Emacs; hitting <code>$</code> doesn’t actually execute <code>move-end-of-line</code>, it executes <code>evil-end-of-line</code>, which does not integrate with existing modes well at all. It’s catering to Vimers, but it’s not good for Emacs power users.</p>
<p>I suspect that I would like to have a global modal switcher that will make <code>C-</code> and <code>M-</code> implicit somehow, so that <code>a SPC e w</code> is equivalent to typing <code>C-a C-SPC C-e C-w</code>. Before sitting down to develop such a system, tackle the problem of how to start and exit the mode, and how to deal with the meta key, I thought I would collect some statistics. (And actually there are systems like sticky keys or chords for Emacs for tackling stuff like this, so it’s not a scary, new area.)</p>
<p>What I wanted to prove (or collect evidence for) was:</p>
<ul>
<li>I waste a lot of energy on <code>C-</code> and <code>M-</code> commands.</li>
<li>Said commands happen in clusters, which would justify a modal switcher.</li>
</ul>
<p>I already had <a href="http://lpaste.net/91637">a trivial script</a> to print key presses for screencasts, so I modified that to also store the time and mode in the buffer, and I opened a <code>keys.log</code> file to which I would save the key presses for a day.</p>
<p>I then whipped up a <a href="http://lpaste.net/91638">script</a> to read in those statistics and print out a summary, to (hopefully) provide evidence for the above claims.</p>
<p>The output is the following:</p>
<blockquote>
<p>Recording start/end: 2013-08-07 09:52:23 UTC/2013-08-08 07:54:23 UTC</p>
<p>Time spent: 22 hours (not 100% activity)</p>
<p>Total key presses: 29687</p>
<p>Commands (including character presses): 22657</p>
<p>Single-key commands: 16457</p>
<p>C- or M- commands: 6200 (27.36%)</p>
<p>Runs of (consecutively) unique C-/M- clusters: min/max/avg/stddev: 1/45/2.25/2.52</p>
<p>Runs of non-unique C-/M- clusters: min/max/avg/stddev: 1/189/3.35/7.04</p>
<p>Key presses used on C-/M- commands: 13230 (44.56%)</p>
<p>Runs of C-f/C-n/C-p/C-b: min/max/avg/stddev: 1/39/2.96/4.63</p>
<p>Key presses used on C-f/C-b/C-n/C-p: 4572 (15.40% of all key presses, 34.56% of C-/M- command key presses)</p>
</blockquote>
<pre><code>Top commands used:
1 | 750 | C-n
2 | 716 | C-p
3 | 355 | C-f
4 | 341 | C-/
5 | 335 | C-b
6 | 259 | M-DEL
7 | 248 | C-z
8 | 245 | M-b
9 | 231 | C-e
10 | 221 | M-p
11 | 193 | C-d
12 | 189 | M-f
13 | 157 | C-s
14 | 145 | C-M-u
15 | 142 | C-g
16 | 136 | C-a
17 | 117 | C-y
18 | 109 | C-x C-s
19 | 107 | M-
20 | 92 | C-SPC</code></pre>
<p>Terms:</p>
<ul>
<li><em>Unique</em>: <code>C-SPC C-a C-w</code> – this would cut the text from the point to the start of the line, that’s a unique cluster.</li>
<li><em>Non-unique</em>: <code>C-f C-f C-f</code> – move forward three times, that’s a non-unique cluster.</li>
</ul>
<p>For unique clusters, I’m doing 2.26 commands per cluster. So if I used sticky keys, or a modal switcher, it would not be a gain. E.g. <code>C f f C</code> vs <code>C-f C-f</code> is no gain, it’s actually more presses due to having to hit C again.</p>
<p>But in terms of non-unique clusters, there’s a gain at 3.44 commands per cluster. That means <code>C f f f C</code> vs <code>C-f C-f C-f</code>, which is one key less pressed. If I’m pressing <code>9218</code> keys for <code>C-</code>/<code>M-</code> commands, there might be a 20% decrease in key presses.</p>
<p>I’d love to see a similar analysis done of Vim. How often do Vim users switch from insert mode to normal or presentation mode? I will continue recording my keys for the next couple of days.</p>
<p>Very interesting is how much I use navigation functions. In reaction to this, I’m disabling those keybindings and switching to arrow keys. And I’ve found <code>M-e</code>, a more convenient binding for <code>C-M-u</code>. I will also stop using <code>C-d</code> and use <code>DEL</code>.</p>
<p><a href="/posts/speculations-on-exclusive-editing">Follow-up page →</a></p>]]></description>
<pubDate>Wed, 07 Aug 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/emacs-key-analysis</guid>
</item>
<item>
<title>Comparison: Esqueleto from a HaskellDB perspective</title>
<link>http://chrisdone.com/posts/esqueleto-haskelldb</link>
<description><![CDATA[<p>Esqueleto looks pretty good, I’m considering using it as a modern replacement for HaskellDB. From what I’ve been able to gather, it’s different in the following ways:</p>
<ul>
<li>Seems to be a monad, but I’m not sure in what flavour</li>
<li>Doesn’t have an extensible record system (instead you use tuples)</li>
</ul>
<p>But does have the other good stuff of HaskellDB:</p>
<ul>
<li>Efficient joins</li>
<li>Can query things like COUNT(*)</li>
<li>Can do projection (good for not pulling the whole row into memory just to get one field)</li>
<li>Can be extended with functions and values (e.g. postgresql’s date/time functions, full text support, etc.)</li>
<li>It’s based on persistent so I presume it can do enums</li>
</ul>
<p>And something that HaskellDB doesn’t do:</p>
<ul>
<li>Using proper data types, so pattern matching can be used and such, rather than the HList approach in HDB</li>
</ul>
<p>As an <a href="http://chrisdone.com/posts/haskelldb-tutorial">avid haskellDB user</a>, I’m serious about switching to esqueleto, so I sent the differences that I garnered above to Felipe Lessa to document somewhere, so that the next Haskeller doesn’t have to figure out the difference.</p>
<p><strong>Update:</strong> Felipe got back to me, linked me <a href="http://blog.felipe.lessa.nom.br/?p=68">this</a>, I’ll summarize that and the above I wrote in a pull request for the package description later today.</p>]]></description>
<pubDate>Mon, 05 Aug 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/esqueleto-haskelldb</guid>
</item>
<item>
<title>Haskell Home Page: Food for Thought</title>
<link>http://chrisdone.com/posts/haskell-homepage-thoughts</link>
<description><![CDATA[<p><strong>Update</strong>: It seems that we are in agreement on the theme. I’ve begun <a href="http://www.haskell.org/haskellwiki/Brand">a HaskellWiki page</a> prescribing the brand, and guides of how to migrate or design existing sites in this theme.</p>
<p>There are points that need to be agreed upon by the community:</p>
<ul>
<li>The palette</li>
<li>The target audience</li>
</ul>
<h2 id="palette-theme">Palette &amp; Theme</h2>
<p>We used to have a palette of green and purple:</p>
<ul>
<li><a href="http://www.haskell.org/haskell-symposium/Images/HaskellLogo.gif">Old logo</a> — old palette</li>
<li><a href="http://haskellwebnews.files.wordpress.com/2009/12/haskell-logo-variation.png?w=500">New logo</a> — old palette</li>
<li><a href="http://www.haskell.org/wikiupload/7/7d/Platform.png">Haskell Platform logo</a> — subdued old palette</li>
</ul>
<p>Now we have randomness:</p>
<ul>
<li><a href="http://www.haskell.org/wikistatic/haskellwiki_logo.png">New logo, haskell.org</a> — grey palette</li>
<li><a href="http://www.haskell.org/platform/">New logo, haskell.org/platform</a> — blue palette</li>
</ul>
<p>Haskell sites have no consistent common palette or theme:</p>
<ul>
<li><a href="http://www.haskell.org/haskellwiki/Haskell">Haskell.org</a> — grey, blue and orange</li>
<li><a href="http://hackage.haskell.org/packages/archive/lens/3.9.0.2/doc/html/Control-Exception-Lens.html">Haddock</a> — grey, blue and orange</li>
<li><a href="http://hackage.haskell.org/packages/hackage.html">Hackage</a> — no particular palette</li>
<li><a href="http://lpaste.net/">λ Paste</a> — old palette</li>
<li><a href="http://tryhaskell.org/">Try Haskell</a> — old palette</li>
<li><a href="http://haskellnews.org/">Haskell News</a> — bootstrap palette</li>
<li><a href="http://www.haskell.org/onlinereport/haskell2010/">Language report</a> — zero palette</li>
<li><a href="http://www.haskell.org/hoogle/">Hoogle</a> — purple</li>
<li><a href="http://holumbus.fh-wedel.de/hayoo/hayoo.html">Hayoo</a> — google</li>
<li><a href="http://planet.haskell.org/">Planet Haskell</a> — no particular theme</li>
<li><a href="http://haskellers.com/">Haskellers</a> — red and blue</li>
</ul>
<h2 id="audience">Audience</h2>
<p>The target audience can be:</p>
<ul>
<li>Existing Haskell users</li>
<li>Programmers interested in Haskell</li>
<li>Businesses interested in Haskell</li>
</ul>
<p>Our existing sites target:</p>
<ul>
<li>Haskell.org — programmers interested in Haskell</li>
<li>Haddock — our haddocks mostly target experiences Haskellers, with little tutorial or example in the general</li>
<li>Hackage — seems to target Haskell newbies who’ve never heard of Cabal</li>
<li>λ Paste — general functional programmers wanting to paste something</li>
<li>Try Haskell — complete Haskell newbies</li>
<li>Haskell News — anyone interested in Haskell</li>
<li>Language report — unclear, anyone?</li>
<li>Hoogle — people who are new to Hoogle, but already know Haskell</li>
<li>Hayoo — general Haskellers</li>
<li>Planet Haskell — anyone interested in Haskell</li>
<li>Haskellers — business</li>
<li>FP Complete — business</li>
</ul>
<h2 id="next-steps">Next steps</h2>
<p>The next steps are:</p>
<ul>
<li>Decide on a theme</li>
<li>Use that theme across the board</li>
<li>Consolidate the audiences and make clear navigation paths between the subsites</li>
<li>Make haskell.org sell itself better to the audience we decide it should aim at</li>
</ul>
<p>Here is Bootstrap (which serves as a very good template for testing themes), re-themed with whatever I’ve been able to garner—which sopvop says is called Ocean—as being a theme (colors, some borders and heading font) from haskell.org:</p>
<ul>
<li><a href="http://tryhaskell.org/ocean/">Ocean</a></li>
</ul>
<p><a href="http://tryhaskell.org/haskell-font/">Here is an icon font for Haskell.</a></p>
<h2 id="layout">Layout</h2>
<p>The layout of the page is something that can come later and follow naturally from the two points outlined above.</p>]]></description>
<pubDate>Sat, 03 Aug 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/haskell-homepage-thoughts</guid>
</item>
<item>
<title>Haskell News</title>
<link>http://chrisdone.com/posts/haskell-news</link>
<description><![CDATA[<p>As a consumer of Haskell content I neither have the time nor inclination to follow haskell-cafe and other various mailing lists, the reddits, the google+ community, planet haskell, hackage releases, twitter, youtube and whatever other submission places I haven’t heard of.</p>
<p>I wrote this <a href="http://www.haskell.org/pipermail/haskell-cafe/2013-February/104898.html">to Haskell-Cafe</a> four months ago. Only one person responded, which was <a href="http://www.haskell.org/pipermail/haskell-cafe/2013-February/104899.html">Daniel Díaz Casanueva</a>, the producer of <a href="http://contemplatecode.blogspot.it/">Haskell Weekly News</a>. Naturally this would be a great resource for him, as it would summarize everything of the past few days in one place.</p>
<p>Shortly after this post I went ahead and implemented <a href="http://haskellnews.org/">Haskell News</a> for which you can find <a href="https://github.com/chrisdone/haskellnews/">the source code here on GitHub</a>.</p>
<p>It has two views: grouped and mixed. Grouped lists all the items according to their source, and mixed lists everything in a flat stream. The mixed view polls for updates every ten minutes, so that users can leave it open in a tab a la Twitter. There is also <a href="http://haskellnews.org/feed">an RSS feed</a>, because I heard you like feeds, so I put a feed in your feed so you can subscribe while you subscribe.</p>
<p>The sources, as of writing, are:</p>
<ul>
<li>Reddit: /r/haskell and /r/programming posts containing the word “haskell”</li>
<li>Haskell-Cafe</li>
<li>Stack Overflow: questions tagged “haskell”</li>
<li>Pastes: pastes made to the #haskell channel</li>
<li>GitHub: updates for projects that contain Haskell code</li>
<li>Planet Haskell</li>
<li>Google+: posts to the Haskell community</li>
<li>Twitter: posts tagged “#haskell” or containing “Haskell”</li>
<li>Hackage</li>
<li>IRC Quotes: things that have been @remember’d in the #haskell channel</li>
<li>Vimeo: various Haskell related feeds</li>
<li>HaskellWiki: updates to the wiki</li>
</ul>
<p>I think this paints a fairly comprehensive picture of the Haskell community’s public activities. Certainly, if you want Haskell news, here is the best place online to go.</p>
<p>All the feeds are updated every ten minutes. All of the feeds are taken from RSS or Atom feeds, with the exception of three, which I scraped with tagsoup:</p>
<ul>
<li>Google+, which provides no RSS feed (but they do provide an API, which I could look into if I had nothing better to do)</li>
<li>Twitter, which no longer provides an RSS feed (but they do provide an API, which I could look into if I had nothing better to do)</li>
<li>Github, which does not provide an RSS feed for language-specific project updates (I don’t know if they have an API, nor care too much)</li>
</ul>
<p>All feed items are stored in a database forever. There are currently 17k entries from 4 months of running. Feeds are unparseable for the feed library from time to time.</p>]]></description>
<pubDate>Fri, 26 Jul 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/haskell-news</guid>
</item>
<item>
<title>IRC Browse</title>
<link>http://chrisdone.com/posts/ircbrowse</link>
<description><![CDATA[<p>Haven’t blogged in a while, had some time to write now.</p>
<p>Since I last blogged, I made <a href="http://ircbrowse.net/">IRC Browse.</a> It’s a service which allows you to browse the IRC logs of the #haskell and #lisp channels of Freenode. The logs come from <a href="tunes.org/~nef/logs/">tunes</a>, and, for <a href="http://ircbrowse.net/browse/haskell">Haskell</a>, they go back to 2001. I like IRC. I don’t go on it that frequently anymore, but I like to read the logs and I see it for the useful communication and coordination tool it is. I’ve always wanted a trivial way to view and share IRC logs as a service, so I made one. The source code is <a href="https://github.com/chrisdone/ircbrowse">here</a>.</p>
<p>It boasts these features:</p>
<ul>
<li><a href="http://ircbrowse.net/">A simple summary</a> of statistics on the home page</li>
<li><a href="http://ircbrowse.net/browse/haskell">Browsing, page by page</a>, all the logs</li>
<li><a href="http://ircbrowse.net/browse/haskell?q=chrisdone">Searching</a> the logs</li>
<li><a href="http://ircbrowse.net/nick/chrisdone">Viewing a statistics profile</a> of a particular person</li>
</ul>
<p>It’s written in Haskell, using Snap, PostgreSQL for the database, and Sphinx for search. It’s fast.</p>
<p>I made it ages ago, really, but thought it worth blogging about once.</p>
<h2 id="the-irc-summary">The IRC summary</h2>
<p>The IRC summary is generated upon request, and reveals some possibly interesting insights into channel activity and the top contributors.</p>
<p>Of interest the most is the activity by year, which indicates that 2009 was the apex of the IRC channel’s activity, which has since dwindled, and appears to be continuing to dwindle: despite sustained activity, conversation generally is decreasing.</p>
<p>There are various hypotheses put forth for this. I speculate that</p>
<ul>
<li>People have been moving to other channels, such as #haskell-lens, #haskell-blah, etc.</li>
<li>People are able to read reliable books that are now well publicized in contrast to in the past</li>
<li>Some very active people have moved on</li>
</ul>
<h2 id="browsing">Browsing</h2>
<p>This is where the name “IRC Browse” comes from. There used to be a service at ircbrowse.com, a few years back, providing a similar browsing service. I asked the author of that old site whether I could use the name ircbrowse.net, and they approved and wished me luck.</p>
<p>One thing that bugged me about the old IRC Browse was the speed. It was god-awfully slow. It would take ages just to display one page of logs. What I wanted was to have a log browsing service that would be <em>instantaneous</em> and snappy.</p>
<p>After some learning with PostgreSQL, I discovered some ways to make paginating 26 million rows of a table quite fast. Simply using <code>OFFSET</code>/<code>LIMIT</code> is far too slow—takes about one second to retrieve a result. I couldn’t simply query on the IDs, because there isn’t just one channel, or one pagination type. So I created a separate table to store paging indexes. For every row of the “event” table, I created a corresponding, ordered, row in the index table. After that, it was snappy.</p>
<p>Another thing I discovered is that my pgsql-simple library was a little sluggish. The pages would retrieve in, say, 50ms, rather than, say, 2ms. So I switched the library to postgresql-simple and got the extremely snappy responsiveness that I wanted.</p>
<h2 id="searching">Searching</h2>
<p>For searching I learned how to use the tool called Sphinx. It takes in a configuration and a database, and then populates a search index. From that search index, it provides very fast full text search.</p>
<p>I couldn’t get the Sphinx library to work with the version of Sphinx I was using at the time. I made a trivial wrapper to the command line program instead. That worked. At some point I will replace this with use of the Haskell sphinx library.</p>
<p>Another optimization I can do is split the indexes into #haskell and #lisp.</p>
<h2 id="profiles">Profiles</h2>
<p>Profiles give a nice way to tell when someone probably goes to sleep and is probably available. It also tells whether someone has been active lately. If they haven’t been active lately, you can check their complete history by year, and if you see it dwindling, perhaps they’re not on the IRC anymore.</p>
<p>There are also quotes @remember’d by lambdabot, which can be fun to read.</p>
<h2 id="importation">Importation</h2>
<p>Importing the logs happens daily, at 10:30 UTC time. One day I might update this so that it connects to the IRC directly and updates the logs in real time. But I’m not sure it’s worth it.</p>
<h2 id="other-stuff">Other stuff</h2>
<p>I also did a social graph thing, but it’s not that good and I will probably remove it. There’s a word cloud, which looks pretty enough, I’ll keep that.</p>]]></description>
<pubDate>Tue, 23 Jul 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/ircbrowse</guid>
</item>
<item>
<title>Because linguistics</title>
<link>http://chrisdone.com/posts/because-linguistics</link>
<description><![CDATA[<p>I read <a href="http://www.theatlantic.com/technology/archive/2013/11/english-has-a-new-preposition-because-internet/281601/">this post</a> about the Internet joke construct “because <reason>”. And subsequently the Hacker News comments <a href="https://news.ycombinator.com/item?id=6765099">below it</a>. It mildly irks me, the lack of understanding about the context of this joke. People wrongly think it’s:</p>
<ul>
<li>Laziness on the part of the writer.</li>
<li>Brevity on the part of the writer.</li>
<li>Non-ironic on the part of the witer.</li>
</ul>
<p>The whole point of is to act like a child or someone with no thoughts to back them up. The lack of words <em>imitate your lack of thoughts</em>. It’s a non-sequitur to silence anyone capable of rational inquiry.</p>
<ul>
<li>The government covered this up, because… ALIENS. [I’m grasping at straws because I have no other explanation.]</li>
<li>Your article is wrong because reasons. [I disagree but I don’t have/can’t be bothered thinking up reasons.]</li>
<li>This <em>because</em> construction is now a valid construction because LINGUISTICS. [I’m an article about a word’s usage and I’m blindly citing “linguists” as the reasons.]</li>
</ul>
<p>The whole point is that it’s ungramatical and without structure. It bugs me a little bit that so-called linguists try to follow this stuff but almost always seem to miss the actual sense.</p>
<p>It’s the same as, “do want”, “do not want”, “not sure if want”. These are <em>intentionally</em> ungrammatical. They’re not lazy or brief. They’re ironically mocking someone without the education or ability to string a grammatical sentence together.</p>]]></description>
<pubDate>Fri, 08 Feb 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/because-linguistics</guid>
</item>
<item>
<title>A Clockwork Orange</title>
<link>http://chrisdone.com/posts/a-clockwork-orange</link>
<description><![CDATA[<p>Kubrick took the American version of the book, missing the last chapter (chapter 21 — get it?) of the original, in which Alex has an epiphany and grows weary of ultraviolence after seeing one of his old droogs in love and matured in a local cafe. The American publishers thought ending on Alex having learned nothing and remaining evil would appeal to an American audience more.</p>
<p>Burgess complained about this, Kubrick thought the last chapter was “extra”, because he hadn’t read that version, and thought it was “inconsistent with the rest of the book”. Which is funny, because the whole point of the book is that the youth of the nation are reckless, violent brutes and then become older, grow up, only to be hounded on by their own children. It’s the cycle. Coming of age. If you leave that out, all you have is a guy who likes to assault and rape people for no reason or point. What have you learnt in watching it? That bad people are always bad? Great.</p>
<p>I also don’t remember a bunch of scenes from the book, e.g. the scenes of Alex’s interaction with prison in-mates (e.g after beating his would-be-rapist to death he’s sent for the therapy). I don’t think it was done even close to page-per-page. Just dribs and drabs of material that Kubrick used to make a movie out of in his own vision. It’s a great movie, don’t get me wrong. But it’s clearly not by the book. In Burgress’s words:</p>
<blockquote>
<p>[A Clockwork Orange] became known as the raw material for a film which seemed to glorify sex and violence. The film made it easy for readers of the book to misunderstand what it was about, and the misunderstanding will pursue me until I die. I should not have written the book because of this danger of misinterpretation.</p>
</blockquote>]]></description>
<pubDate>Fri, 08 Feb 2013 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/a-clockwork-orange</guid>
</item>
<item>
<title>Updated my blog's Hakyll</title>
<link>http://chrisdone.com/posts/upgraded-hakyll</link>
<description><![CDATA[<p>Had some free time this week, updated my blog to the latest Hakyll as I’ve needed to update it for nearly a year. Eventually I was unable to recompile it and was stuck keeping hold of a year old binary!</p>
<p>New repo is <a href="https://github.com/chrisdone/chrisdone-homepage">here.</a> Got a nice Cabal file, easy to install with cabal-dev.</p>
<p>I’ve tweaked it slightly by not following the date-in-the-filename convention, and updated the sorting using <a href="https://github.com/chrisdone/chrisdone-homepage/blob/8026113374e327e8ed1b3ec468ceed5e4c08171e/src/Main.hs#L88">a field in the posts.</a></p>]]></description>
<pubDate>Tue, 25 Dec 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/upgraded-hakyll</guid>
</item>
<item>
<title>Lockhart's Lament</title>
<link>http://chrisdone.com/posts/lockharts-lament</link>
<description><![CDATA[<p>Oh. My. God. What a fantastic paper! A Mathematician’s Lament by Paul Lockhart. I have never been so moved and compelled by a text on mathematics in my life.</p>
<p>I found it, by chance, looking on my rarely-used Macbook, and sat down to read…</p>
<p>It was like reading a synthesis of all the thoughts I’ve ever had about a subject but had never verbalised. Ever had that? When reading something is like <em>remembering</em>?</p>
<p>I won’t paraphrase what’s written in it. You can go read it yourself. You should. I should think that <em>all</em> mathematicians, and anyone in the field of education should have read this by now.</p>
<h2 id="another-brick-in-the-wall">Another Brick in the Wall</h2>
<p>Lockhart writes of the poor sod subjected to this every day. I was one of those students. I suppose many reading this will be, too, right?</p>
<p>I was given the UK-equivalent of the K-12 education program. The “ladder myth”, as Lockhart puts it so well. Right from childhood from 5, to the end of high school at age 15. From the mid-90s to the mid-00s.</p>
<p>If you were to generate a montage from my memory of maths education, it would go something like this:</p>
<p>The screen ripples and a smattering of voices and sights are heard. The monotonous “one-times-seven-is-seven, two-times-seven-is fourteen, …”, followed by, “to do long division you draw two lines like this…”, “repeat after me, the square on the hypoteneuse is equal to the sum of the squares on the other two sides,” we repeat, “the square on the …”, and “SOH-CAH-TOA, this is all you need to remember …”, and every couple years, “you’re going to need this on the exam, so pay attention …”</p>
<p>Monotonous, boring, stressful.</p>
<h2 id="youll-be-sent-to-cleaning-asking-questions-like-that">You’ll be sent to cleaning asking questions like that…</h2>
<p>There are a few times that I remember, when, despite it, I had some sparks of curiosity.</p>
<p>One example that I distinctly remember, which made an impression on me, was that I suddenly wanted to know how to calculate the area of a sphere. It just proposed itself and wanted to be answered.</p>
<p>At the end of class I asked something like, “How do you work out the area of a sphere? I mean, it’s not πDh, I think that’s a cylinder, I don’t know how to make it shrink like a sphere…” (Look, I had no mathematical intuition <em>whatsoever</em>!) He turned to me with an uncertain look, and told me that it was too advanced, and not in this level of curriculum. That was the answer. I remember walking away for lunch, dejected. My rare spark of curiousity put down.</p>
<p>It kills me that with a more capable teacher I would’ve learned something that day. I can’t fathom the kind of intuition I would have now if I’d’ve been taught from primary school by someone like Lockhart.</p>
<h2 id="on-confidence">On confidence</h2>
<p>My experience with art and programming is the opposite. Those are two things that I’ve always loved, and subjects that I took by choice.</p>
<p>Every step of the way was figured out by experimentation, exploring. I had never read a drawing or programming manual, nothing about algorithms, or even syntax. I just tried things and looked at examples. I sweated, got confused, pushed through, and learned how to be stubborn for the rewards that came after it. I had gained <em>confidence</em> for art and programming. Whatever it was, I’m sure I could figure it out.</p>
<p>With maths, I have <em>never</em> had such confidence. I still don’t. Even the mention of maths puts a sinking feeling in my stomach. Maths is like some trauma I’ve experienced, and I can only handle it in small doses. When I approach something unfamiliar, my brain shuts down. I don’t have that confident spark like I do with art or programming, I have fear and doubt and confusion. I don’t feel that if I sit and bash my head against it that I’ll persevere. I’ll just fail.</p>
<p>I’m not alone. This is the doctrine described in Lockhart’s fantastic paper.</p>
<h2 id="self-expression">Self-expression</h2>
<p>One art teacher once gave me a profound peace of advice, it was something like this:</p>
<blockquote>
<p>Next time you sketch something, Chris, I don’t want you to use a rubber. And I want you to go wild, go crazy with it, don’t care about it being neat. Do a few instead of just one. See what you come up with.</p>
</blockquote>
<p>In other words, to express myself. Draw what you feel. Do something new, individual to you.</p>
<p>I high school we were taught with LOGO. What a great time that was! Spending an hour trying to figure out how do draw pretty things. Think of anything you want to see. Then struggle for half an hour. Then see it! <em>That</em> is how you introduce people to programming.</p>
<h2 id="as-a-career-skill">As a career skill</h2>
<p>Lockhart addresses the inevitable criticism that careers demand certain expertise:</p>
<blockquote>
<p>SIMPLICIO: Fair enough. But what about those students who are interested in pursuing a career in science or engineering? Don’t they need the training that the traditional curriculum provides? Isn’t that why we teach mathematics in school?</p>
<p>SALVIATI: How many students taking literature classes will one day be writers? That is not why we teach literature, nor why students take it. We teach to enlighten everyone, not to train only the future professionals. In any case, the most valuable skill for a scientist or engineer is being able to think creatively and independently. The last thing anyone needs is to be trained.</p>
</blockquote>
<p>D’accord! I cannot speak for mathematicians, or people in physics or other “applied maths”. But I can speak for programming. Every skill I have now that I use in my job, I gained myself. Like so many programmers. We’re often entirely self-taught.</p>
<h2 id="not-just-maths">Not just maths</h2>
<p>In fact, programming education suffers from the same problems, it’s boring, uncontextualised, incompetently taught, career-focused. With the exception of a few universities, and LOGO class. I went through college and my degree bored out of my wits. I think you tend not to notice the awful state of programming education because it’s not mandatory, taught in schools since primary school. As in the paper:</p>
<blockquote>
<p>There is surely no more reliable way to kill enthusiasm and interest in a subject than to make it a mandatory part of the school curriculum. Include it as a major component of standardized testing and you virtually guarantee that the education establishment will suck the life out of it. School boards do not understand what math is, neither do educators, textbook authors, publishing companies, and sadly, neither do most ofthe problem is so enormous, I hardly know where to begin.</p>
</blockquote>
<h2 id="conclusion">Conclusion</h2>
<p>Finally, ending on the most important message: mathematics is art. Programming is art. Painting is art. Poetry is art. They <em>cannot</em> be ruined like this. We have a lot to think about regarding education. We also have a lot to answer for to Logic, a field which could be taught from primary school, which would bring us inconceivable benefits. But that’s for another write-up.</p>
<h2 id="funny-bits">Funny bits</h2>
<p>Here’re some funny bits that tickled me from the paper.</p>
<blockquote>
<p>Does any middle school algebra teacher have the slightest clue why he is asking his students to rephrase “the number x lies between three and seven” as |x - 5| &lt; 2 ? Do these hopelessly inept textbook authors really believe they are helping students by preparing them for a possible day, years hence, when they might be operating within the context of a higher-dimensional geometry or an abstract metric space?</p>
</blockquote>
<p>And Bertrand Russell, the legend:</p>
<blockquote>
<p>English teachers know that spelling and pronunciation are best learned in a context of reading and writing. History teachers know that names and dates are uninteresting when removed from the unfolding backstory of events. Why does mathematics education remain stuck in the nineteenth century? Compare your own experience of learning algebra with Bertrand Russell’s recollection: “I was made to learn by heart: ‘The square of the sum of two numbers is equal to the sum of their squares increased by twice their product.’ I had not the vaguest idea what this meant and when I could not remember the words, my tutor threw the book at my head, which did not stimulate my intellect in any way.”</p>
</blockquote>]]></description>
<pubDate>Sun, 11 Nov 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/lockharts-lament</guid>
</item>
<item>
<title>Sky dive</title>
<link>http://chrisdone.com/posts/skydive</link>
<description><![CDATA[<p>Last week I read the title of a TED talk that read, “Before I die I want to…” And I thought about that question, and the first thing that came to mind was to sky dive. It’s the thing that I’ve always wanted to try, but have always been too scared to do.</p>
<p>Yesterday I went for a sky dive.</p>
<p>It was everything I hoped it would be. The instructors were confident, friendly and warm. During the flight upwards, I felt, “maybe this wasn’t such a good idea”. And with that feeling, I knew it was a fantastic idea. To do what frightens me! Leaning out of the plane, every fibre of my body said “er, no, I don’t think so” but away I went, I clung onto thin air and let fate take its course, and soaked in the rush of falling at 200 kilometers per hour.</p>
<p>After a full minute of that, I and the instructor appreciated the gorgeous view as we glided around with the opened parachute. It was a perfect, blue-sky day.</p>
<p>Best decision I’ve made in a long time!</p>]]></description>
<pubDate>Sat, 15 Sep 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/skydive</guid>
</item>
<item>
<title>Riva del Garda</title>
<link>http://chrisdone.com/posts/riva</link>
<description><![CDATA[<p>Last Sunday I visited <a href="http://en.wikipedia.org/wiki/Riva_del_Garda">Riva del Garda</a> (“shore of the lake”) for the first time. It’s surprising that I never went, I just “never got around to it”.</p>
<p>It is of course wordlessly beautiful. The color of the water is a deep blue and it shimmers with turquoise and sunshine. I went on a perfect day, the sun was hot—sunbathable, and I did—and the sky was blue.</p>
<p>It’s a little touristy, of course, and it’s funny to hear English people trying to pronounce Italian ice creams and such, they make absolutely zero effort to do it in an Italian accent, it makes me laugh.</p>
<p>I went and sunbathed for a wee while by the waves and I haven’t been so comfortable in public like that before.</p>
<p>This time I went by bus, but next time I will go by bike. It’s about 25 miles away, and there is a path to ride which follows the river.</p>]]></description>
<pubDate>Sat, 15 Sep 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/riva</guid>
</item>
<item>
<title>No Reddit, no Twitter, no Google+</title>
<link>http://chrisdone.com/posts/no-social</link>
<description><![CDATA[<p>For some reason, I don’t actually remember why, one day two weeks back, I felt that I’d had enough of social network web sites. Speculating, it was probably that I’d found myself in a trivial discussion about minutae of some things that didn’t matter at all. Actually, on second thoughts, I think I just read a page of reddit or twitter and realised I didn’t care about any of the topics, at all.</p>
<p>At any rate, since then, I added these to my <code>/etc/hosts</code>:</p>
<pre><code>192.0.0.1 reddit.com
192.0.0.1 twitter.com
192.0.0.1 plus.google.com</code></pre>
<p>Also, no IRC.</p>
<p>And I must say my life has improved since. I’ve gone out more and done more things in the past two weeks than I have in months. I get more done at work, I read or tidy up instead of aimlessly checking all the social network sites.</p>
<p>It’s surprising how often I open a new tab in Chrome to /r/haskell, almost automatically. Any seconds of time that I have to wait for something, my hands just open it up. But now that page never loads, and I close the tab, and think about something else.</p>
<p>I’ve since commented these out for about 5 minutes to post a couple things, but immediately re-enabled them. I think this was a good idea.</p>]]></description>
<pubDate>Sat, 15 Sep 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/no-social</guid>
</item>
<item>
<title>Movies at Let's Movie</title>
<link>http://chrisdone.com/posts/movies</link>
<description><![CDATA[<p>There is a movie club called <a href="http://letsmovie.it">Let’s Movie</a> which I attend sometimes and watch movies in Italian (dubbed, naturally) at one of the local cinemas. Some movies I saw recently are as follows.</p>
<h2 id="le-premier-homme">Le Premier Homme</h2>
<p>This was a movie about the war and cultural segregation of the local arabic and French occupation at the time in Algeria. It’s also a semi-autobiographical story by Albert Camus. As always, I didn’t understand much of it, due to being in Italian, but I gathered a strong emphasis on childhood and love for his mother. I don’t have much to say about it. It didn’t make a strong impression on me, I expect half because of the language barrier, and half because the story was not particularly familiar to me.</p>
<h2 id="quijote">Quijote</h2>
<p>This was a movie by Mimmo Paladino, an Italian director. It had no narrative or particular themes, more of an artistic movie that referenced other more original artwork than itself. I think the audience enjoyed it rather a lot more than me. Again, the language barrier means anything that is said is completely lost on me, and I haven’t read Don Quixote. I will read it, as it is cited as one of the greatest works of fiction ever written. But the movie itself didn’t move me particularly. It was very pretty, though. There was a nice shot of a Tower of Babel, but all in all, I found it difficult to be particularly moved by or interested in an array of unrelated scenes of references to horses and artwork. That said, I would watch it again. This brings me nicely onto the next movie…</p>
<h2 id="ลงบญมระลกชาต-uncle-boonmee-who-can-recall-his-past-lives">ลุงบุญมีระลึกชาติ (Uncle Boonmee Who Can Recall His Past Lives)</h2>
<p>I didn’t watch this at Let’s Movie, but anyway, it’s related. A Thai art movie about a man who is ill, soon to die, who then contemplates his past lives. I wasn’t impressed or moved by the movie, but I enjoyed watching it. Again, like Quijote, it’s nice to see artistic references and watch an array of random scenes, but little more than that. Particularly nice was a reference to the Zen story of the bull that escapes its master, runs away, and then comes back to its master, realizing it does not know what to do or have anywhere to go. This reminds me of Zhuangzi’s treatment of uselessness. The bull’s life is being used, put it back in the forest and it does not know how to be useless. In summary, I’m glad I watched it, I might even watch it again.</p>
<h2 id="bed-time">Bed Time</h2>
<p>This movie was pretty good. Better than expected. It’s about a guy, César, who is so miserable that his mission in life is to wipe the smile off the face of a pretty, happy woman who lives in the apartment block that he manages (and has the keys for). What’s great about this movie is that César is both an antagonist and a protagonist, in the sense that we feel sorry for him, and don’t want him to get caught doing the terrible acts that he does, and yet we know he is a bad person and should not be excused for the sick things he does. Also, in the end, he wins. The bad guy comes out on top. A realistic ending. Just like 1984. I loved it.</p>
<h2 id="i-giorni-della-vendemmia">I giorni della vendemmia</h2>
<p>An all-Italian movie, this movie was very slow and deliberate, with very little content, but intentionally simple, and pleasant. It was a typical hormonal-boy-meets-girl story, with patient, relaxed camera shots of dull farm work and sweltering fields and sweaty bodies. Boy does meet girl, infatuation ensues. In particular, the surrounding culture is an isolated catholic village—well, not even a village; set of streets. The boy’s older brother returns and there is a very well done treatment of the subject of the alpha-beta male relationship. His older brother is an alpha male, attractive, confident, funny, and immediately the boy and the girl know that such tension has started. It is natural for the girl to be smitten by such a guy, and forget about the boy. The inevitable scene occurs, but it later turns out that the older brother is gay, and in love with a friend who comes to pick him up. I felt that this cheapened the alpha-beta-male tension story, which had a refreshingly realistic approach: the beta male lost out. However, and I suppose this topic is worth giving some coverage too, if only a little, the point was that the older brother was gay in a catholic family and that this is still a big deal. Gay isolation is a well-trodden topic, but okay, feel free. All in all, it was good. A little depressing, but good.</p>
<h2 id="bella-addormentata">Bella Addormentata</h2>
<p>Another Italian movie by Marco Bellocchio. Upfront I will say I understood very little of this movie, as the best parts of this movie were subtle pieces of comedy that I could not understand. It’s not very enjoyable to be in a room full of laughing people and not know the joke. One story, at the end, of a woman who wanted to die, against a doctor who would not let her, was rather touching and hopeful. In the end, with him at her bedside, sleeping, she got up, walked towards the window, opened it, and stopped. She turned back, and did a cute gesture, removed his shoes, and got back into bed. I thought the whole scene was perfect. I wish I had seen the movie in English because I think I would’ve enjoyed it a lot more, but alas, such is the isolation of living here. One day my Italian will be up to scratch.</p>]]></description>
<pubDate>Sat, 15 Sep 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/movies</guid>
</item>
<item>
<title>Fay, JavaScript, etc.</title>
<link>http://chrisdone.com/posts/fay</link>
<description><![CDATA[<p>A couple months back I released Fay in a preliminary stage, with a <a href="http://fay-lang.org/">little web site of its own</a>. I haven’t blogged about it yet, so I thought I’d do that.</p>
<h2 id="setting-the-scene">Setting the scene</h2>
<p>And lo, when God created the world, he looked at it, and saw that it was good.</p>
<p>When Brendan Eich created JavaScript, he looked at it, and saw that it was good enough given the questionable requirements and strict time constraints.</p>
<p>When I look at JavaScript, I see that it is bad. And not good enough given the various other superior languages out there.</p>
<p>But I repeat myself, see <a href="http://www.haskell.org/haskellwiki/The_JavaScript_Problem">The JavaScript Problem</a> for more details.</p>
<h2 id="recognizing-it-as-a-real-problem">Recognizing it as a real problem</h2>
<p>I think any developer with their head screwed on knows about the above problems and that JavaScript needs to be replaced as soon as possible. But the problem is immediate.</p>
<p>My approach to the problem, as with everyone else, has long been: well, we can’t do anything about it, let’s just wait for Google to complete their native client project and hope that it breaks the market. Or, let’s wait until the existing compiling-to-JavaScript solutions become usable.</p>
<p>Any way you look at it, as you sit down to write a new project, and every time you get a stupid error due to JavaScript’s wackiness, you say to yourself “just one more project in JavaScript… just this quick script…”</p>
<p>After seeing Inventing on Principle<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup>, I was profoundly influenced by Bret Victor’s message. His talk was impressive, but his message was moreso. The idea that I took away from watching it was:</p>
<p>“If you recognise something as a problem, and you have the capability to fix it, you have a moral duty to fix that problem.”</p>
<p>I’m not sure I have such strong convictions as Bret to apply that generally, but his principled approach influenced me. One day I wanted to write a web app, and got that sinking feeling of wasting it on JavaScript, and decided never to write any JavaScript again for a new project.</p>
<h2 id="fixing-the-problem">Fixing the problem</h2>
<p>I decided that to make such a claim, I should have to back it up with a solution, and do it fast. So I spent that weekend hacking on a Haskell compiler for JavaScript. I spent another weekend polishing it, and on the third week I was using it at work in production. Back then the project was called “hj.” And for months it sat hidden, private to me. A mini-success and a solution to the problem I saw.</p>
<p>I’ll note that Elm and Roy also inspired me to give it a go.</p>
<h2 id="reaction">Reaction</h2>
<p>Fast-forward a couple months, I decide it’s time to re-brand it to something friendly and put it online. I called it “Fay.”</p>
<p>Someone posted it to Reddit’s programming forum and Hacker News, and the site got about ten thousand hits in two days. Lots of interest generated, and people emailed me asking what the implications of such a project are. That’s really encouraging!</p>
<p>I got invited to talk at <a href="http://2012.lxjs.org/">LXJS</a>, a JavaScript conference. I will be going in two weeks. Ironically, I will go to basically say how much I dislike JavaScript to a crowd of people who mostly like JavaScript, but that’s how I roll.</p>
<p>After putting it on Github I had quite <a href="https://github.com/faylang/fay/network">a few contributions</a>, too!</p>
<p>Today and tomorrow I’ll be producing a bunch of demo examples of Fay code, and finalizing my short 20-minute talk.</p>
<h2 id="future-work">Future work</h2>
<p>Fay is missing some things that would be nice to have:</p>
<ul>
<li>Type-classes</li>
<li>Tail-call optimization</li>
<li>Strictness analysis</li>
<li>Source mappings</li>
<li>Cabal support</li>
<li>Lots more other stuff</li>
</ul>
<p>But these can wait a bit of time. I could/would write more, in more detail, but I have a lot of stuff to do at the moment. So, apologies for the brief post, but I thought it was worth having this post in the blog for the sake of chronology, and to get this series of events out of my system. That’s the point of a blog, right?</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Watch it on <a href="http://vimeo.com/36579366">Vimeo</a>, or on <a href="http://www.youtube.com/watch?v=PUv66718DII">YouTube</a>.<a href="#fnref1">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Sat, 15 Sep 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/fay</guid>
</item>
<item>
<title>Rock 'n' Roll outing</title>
<link>http://chrisdone.com/posts/rock</link>
<description><![CDATA[<p>Last night I just walked into a sea of students, got a beer and started chatting to random people. It’s useful that people into rock music tend to be easy to spot: long hair, wearing black, etc. we ended up going to a show of a cover band of The Doors.</p>
<p>But in fact that was on another night, this night it was a cover band of rock ‘n’ roll music. My dad would’ve loved it. At first there were like three people in the crowd, later on there was a full crowd and people dancing 50s style. It was great!</p>
<p>At the end a few of the band members asked how I knew all the songs, I was like… my dad… they played all the classics. Even “don’t roll those bloodshot eyes at me.” I requested next time they play that they play Runaway by Del Shannon.</p>
<p>All in Italian. One thing I’ve learned is to avoid Italians who can speak English, because they will use it every chance they get, and anything they try to teach you about Italian in English just doesn’t sink in. So, all the Italians at work fall into that category.</p>
<p>But talking to someone who can only speak Italian, at a bar or the cinema or w/e, they say one word and you remember it forever. It just gets absorbed. Learn loads just by talking. So I tend to avoid people who can speak English. Like “sorry my English is not good”, I’m like ‘PERFETTO!’ I expect (or hope) my Italian fluency will explode once I’ve moved downtown. As will the number of social events I visit!</p>]]></description>
<pubDate>Fri, 14 Sep 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/rock</guid>
</item>
<item>
<title>Making HaskellDB slightly more type-safe</title>
<link>http://chrisdone.com/posts/haskelldb-more-type-safe</link>
<description><![CDATA[<p>I was just discussing HaskellDB’s major flaws with Oliver Charles and I noted that one <em>huge</em> problem is that the type of <code>update</code> does not restrict the record given to make the update. Its type is</p>
<pre><code>update :: (ShowLabels s, ToPrimExprs s)
=&gt; Database -- ^ Database.
-&gt; Table r -- ^ Entity.
-&gt; (Rel r -&gt; Expr Bool) -- ^ Predicate.
-&gt; (Rel r -&gt; Record s) -- ^ Updates.
-&gt; IO ()</code></pre>
<p>which is straight-forward enough. The problem is the “updates” argument, which will allow me to write a bogus field that does not belong to <code>r</code>, like</p>
<pre><code>update mytable
(\row -&gt; row!field .==. whatever)
(\row -&gt; badfield &lt;&lt;- whatever)</code></pre>
<p>This problem actually bit me in the ass in production once before. That is not an exciting bug to have.</p>
<p>So I thought, we need to prove that for the type above, <code>s &lt;: r</code> (read as “s is a <a href="http://en.wikipedia.org/wiki/Subtype_polymorphism">subtype</a> of r”). How do we express that? How about a type class.</p>
<p>The type-class can be</p>
<pre><code>class Subset sub super</code></pre>
<p>But how to implement it? Well, we need to say that for every <code>field</code> of sub, that <code>field</code> is also a field of <code>super</code>. That’s made easy for us, because HaskellDB already has a <code>HasField field record</code> class for exactly that!</p>
<pre><code>instance (HasField field super,Subset sub super) =&gt;
Subset (RecCons field typ sub) super</code></pre>
<p>This is similar to traversing a list at the value level, with <code>RecCons field type sub</code> like a pattern-match on the current element. You can read it as:</p>
<blockquote>
<p><code>sub</code> is a subset of <code>super</code>, if <code>super</code> has the <code>field</code> of the head of the list, and the tail is a subset of super</p>
</blockquote>
<p>So far so good. Now we need a base case, to cover the last element of the list:</p>
<pre><code>instance Subset RecNil super</code></pre>
<p>And we’re done. Update now becomes</p>
<pre><code>update :: (Subset s r,ShowLabels s, ToPrimExprs s)
=&gt; Database -- ^ Database.
-&gt; Table r -- ^ Entity.
-&gt; (Rel r -&gt; Expr Bool) -- ^ Predicate.
-&gt; (Rel r -&gt; Record s) -- ^ Updates.
-&gt; IO ()</code></pre>
<p>Testing this on my codebase actually found a bug in which I was using the wrong field!</p>
<p>I will send this to the maintainer of HaskellDB as it’s a glaring bug waiting to happen to someone.</p>]]></description>
<pubDate>Sat, 25 Aug 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/haskelldb-more-type-safe</guid>
</item>
<item>
<title>Last.fm / scrobbling</title>
<link>http://chrisdone.com/posts/lastfm</link>
<description><![CDATA[<p>Last.fm has served me well over the years. I don’t remember it ever being down. They went from free to paying for listening, but at a couple euros per month, I didn’t mind, at all. I’m a subscriber now. I didn’t mind paying for Spotify either.</p>
<p>But what bugs me about the services; Last.fm, Spotify, and Grooveshark, etc. is that the information is not mine to control. I can’t fix it, there’s no crowd-sourcing. Whether the data is about me, or about an artist, I can’t change it. If I’m offline, I can’t get at it.</p>
<p>In Spotify I asked them to correct the track titling of an album I liked to listen to as half of the track titles were in the wrong order, a year later it remains the same. Fine. BE LIKE THAT!</p>
<p>Since for as long as I can remember, Last.fm has confused various artists together, but notably Prodigy and The Prodigy. The Prodigy are an electronic/dance/techno outfit that I love, and Prodigy is a rapper I’ve never heard of. They haven’t solved this despite the five year old complaints about it. Fine. I ain’t even mad.</p>
<p>Grooveshark’s meta data is a joke, not worth criticizing.</p>
<p>Such discrepancies aren’t a huge deal, but they are a problem. And they make me realize more and more how much I value having control of my data. As a normal everyday user, I can only be satisfied with what I’m given, maybe I can complain, but it’s likely to be ignored.</p>
<p>But as a programmer, someone who has the know-how to scrape the data and import it into a database and create an alternative infrastructure, I almost have a moral duty to myself to fix it! It’s a principle!</p>
<p>So the first thing I did was use <a href="http://encukou.github.com/lastscrape-gui/">a program</a> which scrapes from the public-access API about 50 tracks per second. I had 70k tracks to download, so this took some time, and it failed the first time, I had to patch the source to resume and then merge the output later.</p>
<p>Then I wrote a little Haskell script to rewrite that 8MB file into an SQL script, and imported into PostgreSQL. Lovely. I can make all sorts of charts and graphs and I can mash-up data from MusicBrainz, buuuut, wait…</p>
<p>Now, it’s all well and good with kendle mint cake having the past data, but what about new tracks? New scrobbles? Now I need some way to record new scrobbles into my personal database. I googled around looking for some simple scrobbling services but didn’t turn anything up. I had a look at the scrobble protocol, and it’s actually really simple. So I made <a href="https://github.com/chrisdone/scrobble">this.</a> A library to purely handle taking “currently listening” notifications, and scrobbles.</p>
<p>Now all that remains is a few lines to insert into the database on scrobble. Another thing that would be nice is to also push the same data to Last.fm and Libre.fm, just to retain that social aspect (user compatibility) that those web sites provide.</p>
<p>But I am enticed at the prospect of extending the notion of an “open standard” — if scrobbling is an open standard, why not music profiles? Why tie ourselves down to one implementation?</p>]]></description>
<pubDate>Mon, 11 Jun 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/lastfm</guid>
</item>
<item>
<title>Some poems</title>
<link>http://chrisdone.com/posts/poems</link>
<description><![CDATA[<p>Here are some little poems I’ve written. All of my poems are uninteresting, cliché, rhyming and bad puns. But I have fun making them and that’s what poetry is about, to me.</p>
<h2 id="one-liner">One-liner</h2>
<p><em>Long have the wronged longed to wrong the wrong.</em></p>
<p>Poor attempt to sum up the cycle of hate.</p>
<h2 id="going-to-bed-getting-up">Going to bed / getting up</h2>
<p><em>The world and more with sleepy head,</em> <em>stop will I not till I’m dead,</em> <em>creaky feet touch cold floor,</em> <em>it doesn’t matter anymore.</em></p>
<p>Sums up the way I imagine all sorts of projects and activities for the future when I’m sleepy, when I get up in the morning none of it seems to matter much.</p>
<h2 id="wind">Wind</h2>
<p><em>Feel that wind? Consider</em> <em>The rushing spirits</em> <em>Of leaves and hill-sides,</em> <em>Crashing under trees, over turrets,</em> <em>Bouncing across rivers, their eyes</em> <em>Searching in nooks and crannies,</em> <em>Giving shivers, turning pages of books,</em> <em>It sucks, and whistles,</em> <em>To and from, here and gone.</em></p>
<p>Don’t know.</p>
<h2 id="writing">Writing</h2>
<p><em>I want to write</em> <em>to gorge on the fruits</em> <em>of the dead tree.</em></p>
<p>I liked the pun of dead tree/book.</p>
<h2 id="little-concept">Little concept</h2>
<p><em>She approaches the river alone</em> <em>She has never waded fresh water</em> <em>She cannot swim</em> <em>She does not perceive the tide</em> <em>She does not see the other side</em> <em>She steps in</em></p>
<p>I knew what this was about at the time I wrote it, now I have no idea.</p>
<h2 id="nerves-and-crap">Nerves and crap</h2>
<p><em>Are not these excited nerves of we</em> <em>That feed on cream and root of glee</em> <em>Sated not by silk and sound</em> <em>Nor coloured leaves and earthy ground</em> <em>No huff or sniff of fresh cut grass</em> <em>Our kettles hiss, a brew at last</em> <em>And what to speak of but our love</em> <em>Of crooked visions; perverse, a frenzy</em> <em>That which we deem to be scary</em> <em>Of disgust depart our thoughts</em> <em>The dark unknown that is sought</em> <em>For truth and knowing of ourselves</em> <em>Or entertainment—hey, it sells!</em> <em>Either way, the sword is split</em> <em>To wit, it sits, on two blades, fit.</em></p>
<p>Just fun with rhyming, doesn’t mean anything.</p>
<h2 id="gaze">Gaze</h2>
<p><em>Wait a moment, clocking visions,</em> <em>past or side-ways; peripheral divisions,</em> <em>catch a handful, pull it direct,</em> <em>facing, zooming, leaving the rest,</em> <em>what’s this? I look upon a</em> <em>nothing, an absense of,</em> <em>a sweet without, a lack of anything,</em> <em>transparent, circular inside the lens,</em> <em>discard the rest, focus up to see</em> <em>my mind’s eye,</em> <em>they’re darting, stabbing at never-there,</em> <em>all comprising the wonderful,</em> <em>senseful,</em> <em>vacant stare.</em></p>
<p>Little ditty about that vacant stare you have sometimes.</p>
<h2 id="the-house-spider">The House Spider</h2>
<p><em>I wait—sit, sleep, watch, feel, sense,</em> <em>what have you, another month I’ll wait here hence,</em> <em>scuttling? maybe, or weaving in the dark,</em> <em>I scoot across, or up and down,</em> <em>gravity has no meaning here,</em> <em>surface is not the only tension, and my</em> <em>hunger for a taste of flesh, to wrap it up,</em> <em>and suck it fresh,</em> <em>all sense and order, they flee</em> <em>for what instinct brings for me, but She</em> <em>the one I seek,</em> <em>in autumn cool I approach, meek,</em> <em>my desire, ancient species dance,</em> <em>entering, feeling, I take my chance,</em> <em>my life, its purpose, these textures, gone</em> <em>the embrace with She,</em> <em>bound, connected, we fill with lust,</em> <em>I thrust, we must,</em> <em>within the dust,</em> <em>her fleshy torso turns to me,</em> <em>eyes staring, post-ecstasy,</em> <em>my loving warmth, this tender moment,</em> <em>without a thought, sets upon</em> <em>my smaller frame,</em> <em>advances, then</em> <em>takes me for game,</em> <em>mouths and hands and legs and feet,</em> <em>my crippled carcass, she starts to eat.</em></p>
<p>Pretty self-explanatory. The breeding ritual of spiders is interesting.</p>
<h2 id="others">Others</h2>
<p>A poem that isn’t mine but that I love:</p>
<p><em>Yesterday upon the stair</em> <em>I met a man who wasn’t there</em> <em>He wasn’t there again today</em> <em>Oh, how I wish he’d go away</em></p>
<p>I can’t top that.</p>]]></description>
<pubDate>Sun, 10 Jun 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/poems</guid>
</item>
<item>
<title>Deoderant</title>
<link>http://chrisdone.com/posts/deoderant</link>
<description><![CDATA[<img src="/images/deoderant.png"/>
<style>.page-wrap{width:640px;background:#fff;color:#333}a,a:visited{color:#555}
</style>
]]></description>
<pubDate>Sat, 09 Jun 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/deoderant</guid>
</item>
<item>
<title>The Hunger Games (and Battle Royale)</title>
<link>http://chrisdone.com/posts/the-hunger-games</link>
<description><![CDATA[<p>The Hunger Games left a lasting impression on me. Spoiler alert for both The Hunger Games and Battle Royale.</p>
<p>The violence was as expected, and not particularly shocking, quite tame in fact, especially when compared with its Japanese counterpart, Battle Royale. Actually, after watching it, I found that they were in fact, not the same, at least in execution, though the premise was basically same.</p>
<p>What actually I found impressive was the “different worlds” setup of both the highly isolated oppressed proletariat and the extremely decadent aristocracy. It has elements of 1984 (in outside society), The Truman Show (in the actual games part), and actually helped me identify what I found so strange in Brazil but couldn’t identify in the past, it was the trivial lives and concerns of the pseudo-Georgian/Roman privileged citizens living in the kind of inner-city. Actually the talk with the great bearded leader reminded me of a cross between Big Brother and the director from Brave New World.</p>
<p>It’s been said that all great civilizations collapse, and one sign of that collapse is decadence, and creation of a Colosseum or something like it; with entertainment of the upper classes climaxing at being audience to battles to the death. When life, especially of others, has become so meaningless, only this kind of entertainment will satisfy.</p>
<p>What was great about the upper class in Hunger Games was their fictionalization of the suffering of others. That’s the only word I can think of to describe it. They aren’t incapable of empathy, it’s that they don’t feel sympathy, i.e. they’re too far away, from another world, to consider the “tributes” even human, at least their kind of human. The television show with the interviewer who feigned compassion for the tributes, and yet relished in it, only shows that their way of looking at the drama of the children was as a fiction; entertainment and entertainment alone. Katniss (and Peeta) recognized this. As does their adviser who drinks. That’s why he drinks.</p>
<p>That said, another ironic aspect that couldn’t go unnoticed was the irony of watching this drama unfold as a viewer of the film, feeling and fictionalizing in my own way. In a way, we’re guilty of doing what the spectators in the film are doing. It’s an interesting cognitive dissonance. As Maximus broke the fourth wall in Gladiator, “Are you not entertained?” The only difference is that we know it’s not real, in both cases it’s vicarious, and if it were real, we’d (hopefully) be outraged and stand up against it. I hope.</p>
<p>So that was the lasting impression of this movie for me. For me, this movie is about class difference, and the long battles and violence just an incidental plot point, and Katniss witnesses this.</p>
<p>This is in contrast with Battle Royale, which really is, for me, a movie about teenagers and teenager relationships, what brings people to be violent, and paranoia. Consider the lighthouse sequence. The girls are trying to work together, they’re trying to be grown-ups and see it through. The relationships of the characters are stretched throughout, but the paranoia and distrust heavily gets the better of them in the lighthouse. The girl with the long hair who takes pleasure in hurting people, the participants who merely chose to be in the battle for the fun of it. Even the orchestrator of the Royale is merely a lonely man feeling despair about life.</p>
<p>That’s the real distinction between these two movies, for me. One is about class/politics in which there happens to be children and violence, and the other is about children, relationships, violence and paranoia, in which there happens to be a political angle. And they’re both great movies.</p>]]></description>
<pubDate>Sun, 06 May 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/the-hunger-games</guid>
</item>
<item>
<title>How I spent Easter weekend</title>
<link>http://chrisdone.com/posts/spent-easter-programming</link>
<description><![CDATA[<p>I have recently bought a bike, so I would’ve gone out for another trip around the local mountains, but it’s been pretty iffy weather, I don’t feel like going out riding in the rain.</p>
<p>So instead I spent time at home hacking. In fact the whole three days (friday evening to monday evening) I’ve spent programming and pretty much zero relaxation. Usually I have some down-time to my workflow but this weekend I’ve been hacking non-stop. My fingers are about ready to give out on me as I write this blog.</p>
<p>The first thing I wrote was <a href="https://github.com/chrisdone/bdo">bdo</a>, an Emacs mode, and some JavaScript, to allow me to update the CSS file of my web site on the fly from Emacs in the browser. This gives it a Firebug-like feel, except that the changes to the CSS is saved. This is very nice. I started writing that because I wanted to overhaul the theme of a web site at work. That took the better part of Saturday to whip up.</p>
<p>Then, armed with this new tool, I set my sights on overhauling the design of said web site. The problem is that a new design was created for it, which is used for the entry page, but once logged in the old design remains. My job was to bring the new design into the logged in area. Fortunately my UI library and general way of working has been strict enough that modifying the theme quite a bit was a piece of cake. With bdo it was 10 times faster and a more pleasant experience.</p>
<p>In between that I took a brief break to chat a bit on IRC, and watch the first episode of an anime that was recommended to me called Code Geass - Lelouch of the Rebellion. I’ve yet to decide whether I like the show based on the pilot. I also watched some more Twin Peaks. And listened to some Ethics of Liberty on audiobook.</p>
<p>After that I decided with the new theme rolled out I would work on the UX part, which involved creating about five new pages for different users and different tasks. This, I think, simplified and made the overall process more robust. So I spent most of the weekend, my vacation, hacking on a work project. I’m not sure exactly why I spent all my weekend working on something for free, but I think it has something to do with pride, and wanting to make the software slicker and more awesome.</p>
<p>After that I eventually got round to what I’ve wanted to do for a while, which is to setup a wiki for myself, to jot ideas down that I have. Seeing as gitit fails to understand its own config file, I am left with a subdomain instead of a sub path, so the address is <a href="http://wiki.chrisdone.com/">http://wiki.chrisdone.com/</a>. All the pages are <a href="http://wiki.chrisdone.com/_index">here.</a> Pretty much ideas and observations I’ve made in the past or thought about, that I’d like to jot down for future reference to people in conversation, and just for the mental health aspect of writing things down in a coherent, linked manner.</p>
<p>After that I took a pic of myself with my iPod, touched it up with GIMP, and stuck it on <a href="http://chrisdone.com/">my homepage</a>. So I’m there, upside down, looking down at my content. Fun.</p>
<p>So that’s what I got up to this weekend. Now I’m going to kick back with a bowl of cereal and watch <a href="http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2012/A-Means-to-Many-Ends-10-Years-of-Haskell-at-Galois">this talk about Haskell by Galois</a>.</p>]]></description>
<pubDate>Mon, 09 Apr 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/spent-easter-programming</guid>
</item>
<item>
<title>Thoughts on an interview with RMS</title>
<link>http://chrisdone.com/posts/fsf-stallman-interview-jupiter</link>
<description><![CDATA[<p>I just watched a live interview with Richard Stallman <a href="http://www.jupiterbroadcasting.com/">by Bryan Lunduke and Chris Fisher</a>. It was reprehensible. The format was as follows: there is live video footage of the two interviewers, Stallman’s voice can be heard from the other side of the world, and below was the chat room dedicated to this interview filled with just over a hundred people.</p>
<p>Throughout the show both interviewers failed to demonstrate a solid understanding of the subject matter they were discussing. Stallman repeatedly corrected them on factual matters. While disappointing, this is okay as their ignorance makes them a good representation of the audience, and it’s those people who should be listening to a Stallman interview.</p>
<p>At many points it was clear that both interviewers were unfamiliar with the basic principles of the FSF, such as that it is unethical to restrict people’s freedom to use software. Further, Bryan Lunduke noticeably strongly disagreed with, and failed to understand, this basic principle.</p>
<p>He asked questions such as, how do game developers, like himself, make a living without making proprietary software? Stallman replied with a stock statement that such a job is unethical and that he should do something else, and further elaborated that there are lots of jobs writing custom software for clients, and that those clients, if they’re not stupid, will demand the source code.</p>
<p>Lunduke further pursued this line of argument, observing that in this generation, everybody is working in such a model. Stallman rightly addressed this by saying that because it’s what everybody’s doing right now it doesn’t mean it’s right or that you should follow it.</p>
<p>As this discussion became more heated, at least on Lunduke’s side, who seemed unable to comprehend the idea that writing restricted software can be unethical, Lunduke pulled an appeal to emotion and said that his job puts food on the table for his children. Stallman repeated that there are lots of other jobs to take, and wished him well, “I hope you find a job writing custom software”. He put things in perspective by saying that half of America are jobless or working jobs they don’t want to.</p>
<p>Lunduke pressed on and stooped lower, asking whether Stallman would prefer that his daughter starve than for him to write unethical software. Stallman replied that yes, personal plights don’t excuse unethical behaviour. Stressing again that “you don’t have to be a programmer to make money”. Lunduke, visibly offended on camera, continued and asked Stallman whether he has any children of his own.</p>
<p>This set Stallman off in a tangent about overpopulation problems, but essentially the interview had ended here after Lunduke’s misconduct. The heated line of discussion should have ended a lot earlier, as Stallman himself had suggested, that they were “retreading the same ground.” However, it continued, as above and Lunduke has embarrassed himself.</p>
<p>After the interview, after Stallman had hung up, while Fisher appeared to understatedly and inarticulately agree with Stallman, Lunduke continued his unprofessionalism, calling Stallman a “crackpot”, “crazy” and that “Stallman wants my daughter to starve,” confirming that he completely missed the point of the whole discussion and of the FSF. Fisher was the one who finally stopped the interview too late.</p>
<p>Stallman was rigorous and consistent throughout, even leading the interview in many places. His approach could be more elaborate and flexible, but such is the difficulty of maintaining correctness in what you say. I was impressed that he didn’t become riled up.</p>
<p>Of course, great minds discuss ideas, average minds discuss events, and small minds discuss people. So, after, doing the latter two, I’ll finish on the ideas. I’ve finished calling out Fisher and Lunduke on their misconduct, everyone makes mistakes and I hope next time they’ll do better.</p>
<p>This interview, and the reactions in the chat below it, demonstrates that a great many people, developers in particular, even those in the public eye who are supposed to be well versed in such matters, really don’t have a clue about the FSF and what it stands for. I will do my best to educate people who ask me about it.</p>]]></description>
<pubDate>Sun, 11 Mar 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/fsf-stallman-interview-jupiter</guid>
</item>
<item>
<title>If expressions in Haskell-Emacs</title>
<link>http://chrisdone.com/posts/haskell-emacs-ifs</link>
<description><![CDATA[<p>A little treat for myself an users of Haskell-Emacs, <code>if</code> expression completion. It’s just a small addition, but can be nice. There is way more to come regarding structural editing which will make all this textual editing business obsolete, but that’s for later.</p>
<p>Suppose you’re at the start of a statement and you want to write an if-expression:</p>
<p>
<img src="/images/if1.png"/>
</p>
<p>Now you can type “if” and it’ll fill one in and put you at the condition point. If there’s nothing before the current expression, it assumes it’s okay to use layout and not include parentheses.</p>
<p>
<img src="/images/if2.png"/>
</p>
<p>But what if you’re in between some expressions, what gets inserted then? Surely I don’t want it using layout between two expressions, that’d be odd.</p>
<p>
<img src="/images/if3.png"/>
</p>
<p>I decided if there’s something after the current point, it just writes the if on the same line.</p>
<p>
<img src="/images/if4.png"/>
</p>
<p>If you want, you can make sure it uses one line by hitting `(’ to insert two parens, and then type “if” inside.</p>
<p>
<img src="/images/if6.png"/>
</p>
<p>And then it puts it on one line:</p>
<p>
<img src="/images/if7.png"/>
</p>
<p>If in doubt about how to trigger layout rather than parens, make sure the if is the first thing on the line. So you’ll not get this:</p>
<p>
<img src="/images/if8.png"/>
</p>
<p>But instead get what you want, which is this:</p>
<p>
<img src="/images/if9.png"/>
</p>
<p>And if all that isn’t your cup of tea, you can disable it in <code>hs-config.el</code></p>
<pre><code>(defvar hs-config-clever-ifs nil)</code></pre>]]></description>
<pubDate>Thu, 16 Feb 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/haskell-emacs-ifs</guid>
</item>
<item>
<title>Towards a nicer shell?</title>
<link>http://chrisdone.com/posts/nice-shell</link>
<description><![CDATA[<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>]]></description>
<pubDate>Tue, 07 Feb 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/nice-shell</guid>
</item>
<item>
<title>Currying vs partial application</title>
<link>http://chrisdone.com/posts/currying-vs-partial-application</link>
<description><![CDATA[<p>If you’re looking for an explanation of currying and partial application in JavaScript, I wrote one here.</p>
<p>In lambda calculus (bear with me) all functions take one argument, but you can invent some syntactic sugar to express a conceptual multi-argument function,</p>
<pre><code>foo = λx y z. x * y * z</code></pre>
<p>which can be transformed (curried) to</p>
<pre><code>bar = λx. λy. λz. x * y * z</code></pre>
<p>therefore it can be trivially partially applied (where “→” reads “evaluates to”)</p>
<pre><code>bar 1 2 → λz. 1 * 2 * z</code></pre>
<p>and finally</p>
<pre><code>bar 1 2 3 → 6</code></pre>
<p>the same is true for Haskell and ML. In JavaScript, however, all functions take any number of arguments, so you have syntax to express that already,</p>
<pre><code>var foo = function(x,y,z){ return x * y * z; };</code></pre>
<p>which can be curried (implementing the <code>curry</code> function can be a fun exercise for the reader) like this,</p>
<pre><code>var bar = function(x){ return function(y){ return function(z){ return x * y * z; }; }; };</code></pre>
<p>and therefore can be trivially partially applied</p>
<pre><code>bar(1)(2) → function(z){ return 1 * 2 * z; };</code></pre>
<p>and finally</p>
<pre><code>bar(1)(2)(3) → 6</code></pre>
<p>However, JavaScript functions can be partially applied without currying, too, with a simple implementation like</p>
<pre><code>var partially_apply = function(){
var self = this;
var func = arguments[0];
var original_args = Array.prototype.slice.call(arguments,1);
return function(){
return func.apply(self,original_args.concat(Array.prototype.slice.call(arguments)));
}
}</code></pre>
<p>in other words, take a function and some args to apply partially, and return a function that takes the rest of the arguments, so you can partially apply like,</p>
<pre><code>partially_apply(foo,1,2) → function(){
return func.apply(self,[1,2].concat(Array.prototype.slice.call(arguments)));
}</code></pre>
<p>or semantically</p>
<pre><code>partially_apply(foo,1,2) → function(z){ return 1 * 2 * z; };</code></pre>
<p>and finally</p>
<pre><code>partially_apply(foo,1,2)(3); → 6</code></pre>
<p>or if <code>partially_apply</code> is renamed to something more pretty, like <code>$</code>,</p>
<pre><code>$(foo,1,2)(3); → 6</code></pre>
<p>This can be very convenient for avoiding explicit anonymous functions, e.g.</p>
<pre><code>var add = function(x,y){ return x + y; }
[1,2,3,4].map($(add,5)); → [6,7,8,9]</code></pre>
<p>Thus we have shown currying is not necessary for partial application with sufficient reflection.</p>]]></description>
<pubDate>Tue, 31 Jan 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/currying-vs-partial-application</guid>
</item>
<item>
<title>Upgrading GHC</title>
<link>http://chrisdone.com/posts/ghc-upgrade</link>
<description><![CDATA[<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>]]></description>
<pubDate>Sun, 22 Jan 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/ghc-upgrade</guid>
</item>
<item>
<title>Comments on my blog</title>
<link>http://chrisdone.com/posts/blog-comments</link>
<description><![CDATA[<p>Comments are unsupported on my blog for the same reason as <a href="http://www.scripting.com/2007/01/01.html#theUneditedVoiceOfAPerson">Dave Winer</a> gives:</p>
<blockquote>
<p>“…to the extent that comments interfere with the natural expression of the unedited voice of an individual, comments may act to make something not a blog…. The cool thing about blogs is that while they may be quiet, and it may be hard to find what you’re looking for, at least you can say what you think without being shouted down. This makes it possible for unpopular ideas to be expressed. And if you know history, the most important ideas often are the unpopular ones…. That’s what’s important about blogs, not that people can comment on your ideas. As long as they can start their own blog, there will be no shortage of places to comment.”</p>
</blockquote>
<p>Joel Spolsky first exposed me to the above. He elaborates <a href="http://www.joelonsoftware.com/items/2007/07/20.html">in his blog</a>:</p>
<blockquote>
<p>The important thing to notice here is that Dave does not see blog comments as productive to the free exchange of ideas. They are a part of the problem, not the solution. You don’t have a right to post your thoughts at the bottom of someone else’s thoughts. That’s not freedom of expression, that’s an infringement on their freedom of expression. Get your own space, write compelling things, and if your ideas are smart, they’ll be linked to, and Google will notice, and you’ll move up in PageRank, and you’ll have influence and your ideas will have power.</p>
</blockquote>
<p>If I wanted to have my expression shared and democratised I’d comment on a forum.</p>
<p>People email me regarding my blog with ideas and errata/amendments all the time, I’m glad for them, and I reply.</p>]]></description>
<pubDate>Thu, 19 Jan 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/blog-comments</guid>
</item>
<item>
<title>Using GMail for bookmarking</title>
<link>http://chrisdone.com/posts/using-gmail-for-bookmarking</link>
<description><![CDATA[<p>I have <a href="http://hpaste.org/raw/56662">this link</a> in my Bookmarks toolbar in Chrome. It pops up GMail composer in another window and pre-fills the recipient, subject and body with me, the page title, and the link.</p>
<p>When it hits my inbox, it’s tagged as Bookmark. The fact that it hits my inbox is sure that I will actually see it and look at the link at some point.</p>
<p>Later I can tag the email with (various) categories for easier browsing later. I have about a hundred bookmarks so far, 19 are marked unread, as I’ve chosen that I don’t intend on reading them soon, but marked that I haven’t read them. <a href="http://img546.imageshack.us/img546/2435/gmailbookmarks.png">A screenshot of the first page of my bookmarks.</a></p>
<p>If someone has given me a link to see, I’ll bookmark it in this way and then keep it in my inbox until I’ve looked at it. This system seems to work well for me.</p>]]></description>
<pubDate>Wed, 18 Jan 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/using-gmail-for-bookmarking</guid>
</item>
<item>
<title>The Others, scary movie</title>
<link>http://chrisdone.com/posts/the-others</link>
<description><![CDATA[<p><a href="http://www.bbc.co.uk/blogs/markkermode/2011/11/creature_feature_1.html">Referring to Mark Kermode’s Creature Feature blog post</a></p>
<p>The first physical manifestation that springs to mind for me is in The Others; the scene when Grace’s daughter is playing on the floor, turned away from her, and she notices that the hand of her daughter is an old woman’s hand, but her child’s (humming) voice remains normal. Grace approaches slowly to face her and sees an old woman’s face who says in her child’s voice, ‘I Am your daughter, are you mad?’ Grace then goes a bit mental and shakes the torso and stops when the now-returned daughter cries.</p>
<p>This short scene seriously freaked me out when I first saw it, shivers went down my spine, and still gives me the creeps to this day. And I find it very difficult to explain. It’s not that old people are so frightening, they’re just old.</p>
<p>At a guess, it may be that the juxtaposition of children, who are supposed to be reliably innocent with the strange and unsettling. (The Exorcist, Omen, anyone?) At a deeper level, you could even consider the whole scene as a metaphor for the struggle between a parent and their child, as the child becomes more mature, independent, behaves unpredictably and strangely, this frightens and alienates the parent.</p>
<p>A more recent disturbing monster was from the TV show The Walking Dead, the pilot episode (imho the only episode worth watching), in which the protagonist and two survivors (father and son) of The Zombie Apocalypse are camping in the dark in the house of father and son. Turns out that the mother was zombified and, at night, the zombies start strolling around in their slow, confused state, and the mother zombie, who isn’t so disfigured, but has VERY good make-up to just appear more gaunt and animalistic, with empty, dead eyes, still dressed in her night gown approaches the front door of the house, and rattles the door handle, evidently recalling some distant memory of this house, and then peers into the peep hole which the protagonist is peering through on the other side. Very, very, eerie and disturbing.</p>]]></description>
<pubDate>Sun, 08 Jan 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/the-others</guid>
</item>
<item>
<title>Moogle (movie reviews) and web frameworks</title>
<link>http://chrisdone.com/posts/moogle</link>
<description><![CDATA[<p>My latest harebrained scheme, a movie/TV review web site that only shows reviews by your friends and people you’ve chosen to see.</p>
<h2 id="links-of-trust">Links of Trust</h2>
<p>The problem with finding movies that you’ll like is that critics and mainstream reviewers are rarely aligned with your personal tastes.</p>
<p>But you can trust people you know to have similar tastes and to be a good source of new movies.</p>
<p>So you add people who you trust to give good reviews and subscribe to notifications from them. You can also just browse their reviews to find new movies.</p>
<h2 id="review-everything">Review Everything</h2>
<p>By giving a short review and some tags of every movie you watch, you really help out your friends deciding what to watch.</p>
<ul>
<li>Step 1: Watch movie.</li>
<li>Step 2: Jump onto moogle, save a little write-up.</li>
<li>Step 3: Your friends get an email and check out the review, decide to grab the movie or decide they wouldn’t like it.</li>
<li>Step 4: You can come back later and see what your favourite movies are, or invite your friends.</li>
</ul>
<h2 id="design-mockup">Design Mockup</h2>
<p>I’ve done a design mockup pitching it as <a href="http://moogle.tv/">moogle for reviewing movies and TV</a>. I want this site to look professional and be simple and clean. I’ve produced the best I can do with Inkscape, the rest CSS3 can take care of.</p>
<p>The idea of the site is quite trivial and implementation will be easy. However, see the next section.</p>
<h2 id="the-framework">The Framework</h2>
<p>The next problem is choosing the web framework. The Big Three<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup> are:</p>
<ul>
<li><a href="http://happstack.com/">Happstack.</a></li>
<li><a href="http://snapframework.com/">Snap.</a></li>
<li><a href="http://www.yesodweb.com/">Yesod.</a><sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup></li>
</ul>
<p>Choosing between them is a very slow and boring task. They all appear to be production-ready. I could just use FastCGI as I do at work with my pre-existing web utilities that I wrote before these frameworks existed, where I’d have everything I need to get going,<sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup> but I feel it’s time to consolidate efforts.<sup><a href="#fn4" class="footnoteRef" id="fnref4">4</a></sup></p>
<p>Surprisingly I am unable to find a straight blog that compares all the technical features and philosphies of Happstack, Snap and Yesod.<sup><a href="#fn5" class="footnoteRef" id="fnref5">5</a></sup> I’m not sure whether I have the time and motivation to make such a long and detailed post, but I will try if so.<sup><a href="#fn6" class="footnoteRef" id="fnref6">6</a></sup></p>
<p>I might even use <a href="http://chrisdone.com/posts/2011-12-26-ji-haskell-web.html">Ji</a> or <a href="http://chrisdone.com/posts/2012-01-06-uhc-javascript.html">UHC JavaScript</a> and abstract over it, we’ll see.</p>
<p>More to come.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>There’s also Salvia which is also interesting and fairly complete, though I don’t know if actively maintained or used (pretty sure the author uses Happstack).<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>Not sure why they choose to stop using <a href="http://chrisdone.com/posts/2011-04-10-yesod-design.html">my design</a>, couldn’t reworked the concept rather than scrapping it, but go figure.<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>Haskell is a powerful enough language that it’s easy to work from the ground up.<a href="#fnref3">↩</a></p></li>
<li id="fn4"><p>For example, I’d like to provide OpenID. This is implemented already in both Snap and Yesod (and probably Happstack). I don’t feel like implementing and testing this myself. There is also the problem of contribution. Choosing a popular framework will aid contribution. It’s just a shame I have to pick one.<a href="#fnref4">↩</a></p></li>
<li id="fn5"><p>On the other hand one can find plenty of contention between the Yesod and Snap lead developers.<a href="#fnref5">↩</a></p></li>
<li id="fn6"><p>It would seem that (few non-author) people have tried all three of these frameworks, otherwise there would be more comparative literature out there (suppose), this would imply that people pick the frameworks fairly arbitrarily, or based on the community.<a href="#fnref6">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Sun, 08 Jan 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/moogle</guid>
</item>
<item>
<title>Compiling to JavaScript with UHC</title>
<link>http://chrisdone.com/posts/uhc-javascript</link>
<description><![CDATA[<p>Last week I took a crack at testing the JavaScript compilation backend supported by UHC. There don’t seem to be any instructions<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup>, that I have been able to find, on working with the JS backend. But it’s more or less straight-forward to figure out.</p>
<p>As far as I understand quite a lot of what’s working now is thanks to Atze Dijkstra and Jurriën Stutterheim,<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup> so cheers to those!</p>
<h1 id="build-and-install-uhc">Build and Install UHC</h1>
<p><strong>UPDATE 2012-04-23</strong>: The Git repo has moved to: git://github.com/UU-ComputerScience/uhc.git</p>
<p>I used the UHC repository from Github:</p>
<pre><code>$ mkdir uhcjs
$ cd uhcjs
$ git clone git@github.com:uhc/uhc.git
$ cd uhc/EHC</code></pre>
<p>GHC 7+ should work okay, I imagine.<sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup></p>
<p>There is no INSTALL file and the README doesn’t mention installation, but the configure script is helpful.</p>
<pre><code>$ ./configure</code></pre>
<p>Have a look, see if it mentions that you need something installed.<sup><a href="#fn4" class="footnoteRef" id="fnref4">4</a></sup> Personally, I had to install a few:</p>
<pre><code>$ cabal install uuagc fgl EH-Util syb</code></pre>
<p>Then I just ran make (<code>-j</code> runs n jobs and I have four cores):</p>
<pre><code>$ make uhc -j 4
real 4m40.388s
user 6m19.628s
sys 0m12.053s</code></pre>
<p>Takes about 5 minutes on a modern machine,<sup><a href="#fn5" class="footnoteRef" id="fnref5">5</a></sup> so you probably want to run both make and make install (sans <code>-j</code>), which takes about 4 minutes:</p>
<pre><code>$ make uhc -j 4 &amp;&amp; sudo make install</code></pre>
<p>And go get a cup of tea.</p>
<pre><code>$ uhc --version
ehc-1.1.2, Revision exported</code></pre>
<p>Now UHC is installed.</p>
<h1 id="get-the-javascript-library">Get the JavaScript library</h1>
<p><strong>UPDATE 2012-02-16</strong>: Git repo below is currently not working due to rename from jscript → js, use git://github.com/spockz/uhc-jscript.git instead.</p>
<pre><code>$ cd ../..
$ git clone git://github.com/norm2782/uhc-jscript.git</code></pre>
<p>There is a Cabal file which does configure and build, but I couldn’t figure out how it was supposed to link up the JavaScript dependencies and generate a HTML file (that worked), but a direct call to uhc works.</p>
<h1 id="first-program">First program</h1>
<p>Go to the src directory:</p>
<pre><code>$ cd uhc-jscript/uhc-jscript/src</code></pre>
<p>Open up <code>Main.hs</code> and replace everything with something nice like:</p>
<pre><code>import Language.UHC.JScript.Assorted
main = alert &quot;Hello, Haskell!&quot;</code></pre>
<p>Then run:</p>
<pre><code>$ uhc -tjs Main.hs</code></pre>
<p>And open <code>Main.html</code> in your browser.</p>
<p>That’s about as far as I got. There’s a fairly substantial API already defined by Jurriën Stutterheim in src/, e.g. a <a href="https://github.com/norm2782/uhc-jscript/blob/master/uhc-jscript/src/Language/UHC/JScript/W3C/HTML5.hs">HTML5 API</a> and <a href="https://github.com/norm2782/uhc-jscript/blob/master/uhc-jscript/src/Language/UHC/JScript/JQuery/JQuery.hs">jQuery</a> and <a href="https://github.com/norm2782/uhc-jscript/blob/master/uhc-jscript/src/Language/UHC/JScript/JQuery/Ajax.hs">AJAX</a>. Enjoy hacking! It’s more complete than GHCJS, so it may be an interesting route to take for the Ludum Dare for making a browser-based game.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Bar a <a href="http://www.cs.uu.nl/wiki/bin/view/Ehc/UhcUserDocumentation#5_7_3_jscript_Core_based_JavaScr">short mention</a> in the user manual.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>Check <a href="http://www.norm2782.com/improving-uhc-js.pdf">the paper on improving the UHC backend</a>.<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>I had to use GHC 7.0.4 as GHC 6.12.3 failed with a rather unsightly plethora of linker errors. So I enabled GHC 7.0.4:</p>
<pre><code>$ export PATH=/opt/ghc/7.0.4/bin/:$PATH</code></pre>
<a href="#fnref3">↩</a></li>
<li id="fn4"><p>For example:</p>
<pre><code>Required:
uuagc is available? : yes
version : Attribute Grammar compil…
command for uuagc : /home/chris/.cabal/bin/uuagc
ghc is available? : yes
version : 6.12.3
command for ghc : /home/chris/Programs/bin/ghc
command for ghc raw : /home/chris/Programs/bin/ghc
libraries:
uulib is available? : yes
version : uulib-0.9.14</code></pre>
<a href="#fnref4">↩</a></li>
<li id="fn5"><p>Intel(R) Core(TM) i7 CPU M 620 (2.67GHz and 4096 KB cache size) x× 4.<a href="#fnref5">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Fri, 06 Jan 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/uhc-javascript</guid>
</item>
<item>
<title>Posting on Reddit</title>
<link>http://chrisdone.com/posts/posting-on-reddit</link>
<description><![CDATA[<img src="/images/comics/reddit_posting.png" style="margin:2em"/>
<style>.page-wrap{text-align:center}</style>
<p><small>No one’ll see it. -_-</small></p>]]></description>
<pubDate>Fri, 06 Jan 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/posting-on-reddit</guid>
</item>
<item>
<title>Monads are burritos?</title>
<link>http://chrisdone.com/posts/monads-are-burritos</link>
<description><![CDATA[<p><a href="http://blog.plover.com/prog/burritos.html">Apparently.</a></p>
<img src="/images/comics/monads_are_burritos.png" style="margin:2em"/>
<style>.page-wrap{text-align:center}</style>
<p>Just felt like doodling.</p>]]></description>
<pubDate>Fri, 06 Jan 2012 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/monads-are-burritos</guid>
</item>
<item>
<title>darcs get</title>
<link>http://chrisdone.com/posts/darcs</link>
<description><![CDATA[<img src="/images/comics/darcs.png" style="border:3px solid #aaa;margin:2em"/>
<style>.page-wrap{text-align:center}</style>
]]></description>
<pubDate>Thu, 29 Dec 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/darcs</guid>
</item>
<item>
<title>Ji, a little library for controlling a web browser from Haskell</title>
<link>http://chrisdone.com/posts/ji-haskell-web</link>
<description><![CDATA[<p>As of recent I have only been creating a lot of new projects, not working one existing ones or finishing half done ones off.<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup></p>
<p>So here’s yet another little project that is to test the concept of controlling the web browser’s DOM from Haskell as a means to write user applications.</p>
<p>It doesn’t use websockets as websockets aren’t well supported<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup>, so I just used a simple poll/push protocol.</p>
<p>The code is on Github:</p>
<ul>
<li><a href="https://github.com/chrisdone/ji">https://github.com/chrisdone/ji</a></li>
</ul>
<p>Haddock docs <a href="http://chrisdone.com/ji/doc/html/ji/Graphics-UI-Ji.html">here</a>.</p>
<p>Here are two examples I made so far:</p>
<ul>
<li><a href="http://chrisdone.com/ji/buttons/">Some simple buttons</a></li>
<li><a href="http://chrisdone.com/ji/missing-dollars/">Missing dollars question</a></li>
</ul>
<p>It seems fairly viable so far. I would have liked to produce many more examples, but I couldn’t really think of any. I stole the idea for the dollars from Albert Lai. There is more room for optimizations, but until I do a more large scale test, hard to say exactly where needs it.</p>
<p>It might be a good test to rewrite TryHaskell with it. Probably still too easy. I’ll give it a while to think about it.</p>
<p>It could be a base on which to build a more high-level library or framework.</p>
<p>I could also write a back-end for digestive-formlets.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Partly this is a way to feel like I’ve spent my time well as it’s easier to complete something small, and partly that ideas I get which sound feasible typically linger in my head asking to be prototyped, so this is a way of flushing them out.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>I wanted to use socket.io but there is no Haskell socket.Io back-end, and I didn’t feel like writing Node. There are several websockets Haskell libraries, but as mentioned websockets itself isn’t well supported, I’d have to upgrade to try it (and so would everyone else). Websockets would be the eventual protocol, though.<a href="#fnref2">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Mon, 26 Dec 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/ji-haskell-web</guid>
</item>
<item>
<title>Online “piracy”, downloading and Louis CK</title>
<link>http://chrisdone.com/posts/online-piracy</link>
<description><![CDATA[<p>I just bought Louis CK’s latest standup for $5 from <a href="http://www.louisck.net">his web site</a>.</p>
<h2 id="the-business-model">The business model</h2>
<p>He was very transparent about his business model, production (he produced it by himself) and how much money he made.</p>
<ul>
<li>He produced everything himself.<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup></li>
<li>He got the web site made to be very easy to buy his material with no annoying sign-up process<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup>.</li>
<li>The money goes straight to him<sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup>.</li>
<li>He earned &gt;$1,000,000.</li>
<li>He donated $280,000~ to charity.</li>
<li>Put $250,000~ back into his business.</li>
<li>$250,000~ for bonuses for the people who work for him.</li>
<li>Pocketed $220,000~.</li>
</ul>
<p>So:</p>
<ul>
<li>Good for Louis CK.</li>
<li>Good for Louis CK’s employees.</li>
<li>Good for the charities: <a href="www.fistulafoundation.org/">Fistula Foundation</a>, <a href="http://www.greenchimneys.org/">Green Chimneys</a>, <a href="http://www.charitywater.org/">CharityWater</a>, <a href="http://pablove.org/">Pablove Foundation</a> and <a href="http://www.kiva.org/">Kiva</a>.</li>
</ul>
<h2 id="the-price">The price</h2>
<p>$5 is nothing. That’s the price of a pizza and a drink. I actually wanted to pay more, I would’ve if the interface allowed me to.</p>
<h2 id="the-distribution">The distribution</h2>
<p>The download was perfectly done.</p>
<ul>
<li>It’s available world-wide. No locality nonsense.</li>
<li>After paying, access to the download was immediate.</li>
<li>There were options for medium or high definition quality.</li>
<li>There were no restrictions on using the video afterwards; feel free to watch it on your computer, burn it to DVD, whatever.</li>
<li>A maximum of three downloads, which is reasonable; bandwidth costs money.</li>
</ul>
<h2 id="the-content">The content</h2>
<p>Well, it’s Louis CK. He’s a quality comedian and his material is fresh every year. I cried a bit with laughter watching it. I won’t spoil anything from it. You can go download it for 5 bucks.</p>
<h2 id="lesson-learned">Lesson learned</h2>
<p>For a least a famous comedian,</p>
<ul>
<li>putting out material to be freely downloaded,</li>
<li>for a reasonable price,</li>
<li>with transparency of business model, and with</li>
<li>clear indication that the money will go straight to the artist</li>
</ul>
<p>it works. As Louis said on his blog:</p>
<blockquote>
<p>I really hope people keep buying it a lot, so I can have shitloads of money, but at this point I think we can safely say that the experiment really worked. If anybody stole it, it wasn’t many of you. Pretty much everybody bought it.</p>
</blockquote>
<p>It ends up convenient, fast, legal <em>and</em> there is the warm feeling that I am supporting the artist, and encouraging them to produce more material.</p>
<p>With the traditional means of production and distribution, Louis would’ve made more money merely to perform it, but the content would have been restricted and the price would’ve been jacked up.<sup><a href="#fn4" class="footnoteRef" id="fnref4">4</a></sup></p>
<h2 id="applying-it-to-movies-and-television-generally">Applying it to movies and television generally</h2>
<p>The same could be done for movies (and television, but after this I will say ‘movies’ as a generic term). It could, but I doubt it will. For the following reasons:</p>
<ul>
<li>Most movies are low quality. They’re not worth watching.</li>
<li>They’re not worth the money paid for them or the time wasted watching.</li>
<li>Movies are produced by large faceless production companies that nobody gives a shit about.</li>
<li>Their business model is based on targetting the most people with the most generically pleasing content, not high quality content. They’re making millions this way and have no incentive to do it differently. Therefore their movies are shit.</li>
<li>The writer, director and actors get a cut of this huge pot, and therefore are also happy with writing, directing and appearing in shit movies.</li>
<li>People don’t really care about whether they’re hurting the movie industry by downloading them for free, because of the above. It’s not a loss.</li>
</ul>
<p>Contrast this to Louis CK; his audience knows what he puts out will be quality. And they know that paying for his material will help him to produce more. They care about his work.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>From his blog, “I directed this video myself and the production of the video cost around $170,000. (This was largely paid for by the tickets bought by the audiences at both shows).”<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>The website cost him $32,000.<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>From his blog, “keeping as few people between you and me as possible in the transaction.”<a href="#fnref3">↩</a></p></li>
<li id="fn4"><p>From his blog “As of Today, we’ve sold over 110,000 copies for a total of over $500,000. Minus some money for PayPal charges etc, I have a profit around $200,000 (after taxes $75.58). This is less than I would have been paid by a large company to simply perform the show and let them sell it to you, but they would have charged you about $20 for the video. They would have given you an encrypted and regionally restricted video of limited value, and they would have owned your private information for their own use. They would have withheld international availability indefinitely.”<a href="#fnref4">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Fri, 23 Dec 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/online-piracy</guid>
</item>
<item>
<title>A concept for editing code as an AST rather than text</title>
<link>http://chrisdone.com/posts/concept-for-editing-asts-rather-than-text</link>
<description><![CDATA[<p><a href="http://www.youtube.com/watch?v=v2ypDcUM06U">Here is a demo video</a>.</p>
<p>It’s not my intention for this to be all point and click, at all, but coming up with keybindings and a means to navigate the AST via keyboard is an interesting problem somewhat separate to the problem of creating/displaying/editing as-is. As you can see I’m even confused myself when using it, and it’s a lot slower with the mouse. With keyboard control it could be blindingly faster than any text editing-based language editors available now. Think paredit-mode, but for non-Lisp languages.</p>
<p>I’ve had this idea in the back of my mind for years and today thought that I might do a concept implementation to solidify the idea somewhat.</p>
<p>The idea is that you can’t create a syntactically invalid tree, and at each point it can offer you a choice between the valid choices. That’s one part, the correctness. But that’s merely a nice side-effect to the idea of purely syntactical editing, rather than textual editing, so that jumping around, transposing, moving, deleting expressions will be a lot easier. Even so that there is no need to care about indentation, but rather moving things about the AST. Still merely a concept at this point. It’s really hard to think about what you might like from an editing mode like this without going ahead and implementing something.</p>
<p>It can technically be generalized to any programming language, but Haskell is my main working language so I am targeting it specifically.</p>
<p>It could also be helpful for newbies, being guided on the syntax. Purists will argue people should be able to write syntax. I suppose they’d be right.</p>
<p>In summary I made a little DSL for describing an AST for manipulating like this. There is a “list of things” combinator, an “optional” combinator (e.g. the “module” decl is optional), there is a “choice” combinator, e.g. when adding a new top-level decl it prompts for a choice between the different types of decls, validating text inputs (e.g. module name, constructor, variable, etc.), and that is more or less enough, as far as I can tell, so far. Hopefully it won’t get much more complicated than that.</p>
<p>For a real implementation I would probably do it in Emacs, if overlays would permit me enough power to do it (I think so). But it could also be implemented in Yi, or Leksah, or Vim, or whatever, were those users so inclined.</p>
<p>If you’re implementing something like this already, I’d be interested to see it. If you have some interesting ideas, feel free to comment.</p>]]></description>
<pubDate>Sat, 17 Dec 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/concept-for-editing-asts-rather-than-text</guid>
</item>
<item>
<title>A map generic upon the value thanks to typeable</title>
<link>http://chrisdone.com/posts/generic-map</link>
<description><![CDATA[<p>Not sure why I never tried this before.</p>
<pre><code>{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE DeriveDataTypeable #-}
import Data.Typeable
import qualified Data.Map as M
import Data.Map (Map)
data Person = Person Integer String
deriving (Typeable,Show)
data Value = forall v. Typeable v =&gt; Value v
demo = do
print (glookup &quot;foo&quot; map :: Maybe ())
print (glookup &quot;bar&quot; map :: Maybe Char)
print (glookup &quot;chris&quot; map :: Maybe Person)
where map = M.insert &quot;bar&quot; (Value &#39;a&#39;) $
M.insert &quot;foo&quot; (Value ()) $
M.insert &quot;chris&quot; (Value (Person 123 &quot;Chris Done&quot;)) $
M.empty
glookup :: (Typeable a,Ord key) =&gt; key -&gt; Map key Value -&gt; Maybe a
glookup key map =
case M.lookup key map of
Nothing -&gt; Nothing
Just (Value x) -&gt; (cast x)
-- λ&gt; demo
-- Just ()
-- Just &#39;a&#39;
-- Just (Person 123 &quot;Chris Done&quot;)</code></pre>]]></description>
<pubDate>Mon, 05 Dec 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/generic-map</guid>
</item>
<item>
<title>Programmer at work: statistics from a two year project (gitstats)</title>
<link>http://chrisdone.com/posts/programmer-at-work-statistics</link>
<description><![CDATA[<p>Recently I discovered a tool called <a href="http://gitstats.sourceforge.net/">gitstats</a>, which generates some interesting statistics from commits made to a Git project. I thought it would be fun to reflect on a particular project I have been working on.<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup></p>
<h2 id="the-project">The project</h2>
<p>For roughly the past two years I have been working on a web application.<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup> Actually, gitstats tells me that it has been exactly 456 days.<sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup> I am the only developer on this project. I thought I’d write up on some simple statistics from this project.</p>
<p>The application is a research paper submission and publication system, among other things.</p>
<h2 id="scope">Scope</h2>
<p>The project program code spans several languages, including:</p>
<ul>
<li>Haskell: 125 modules, 17,837+ lines of code</li>
<li>JavaScript: 92~ modules, 21,854+ lines of code</li>
<li>CSS: 4,385 lines of code</li>
<li>Java: 734 lines of code</li>
<li>HTML, SQL: negligable raw code, most generated by JS or Haskell</li>
</ul>
<p>For features and bugs, there have been 68+ pushes to production, resulting in an internal tag version of 2.6.5, with an average of 37 commits per tag (release).</p>
<p>I tried out <a href="http://grosser.it/2009/11/14/what-are-your-git-stats/">this Ruby script</a> that generates stats of inserts/deletions, and the output is:</p>
<pre><code>Git scores (in LOC):
unknown : +3469917 -3150559</code></pre>
<p>I don’t know if any of these details help to paint a picture of the scope of the project, but that’s it.</p>
<h2 id="commits-over-the-year">Commits over the year</h2>
<h3 id="by-year">By year</h3>
<p>I have produced substantially more code in 2011 than in 2010, which feels somewhat accurate. I started in august of 2010, so this seems to add-up.</p>
<img src="/images/commits_by_year.png"/>
<h3 id="by-month">By month</h3>
<p>The pattern you might expect happens across the months year; the most work occurs in Autumn where tensions and expectations are high for things to be completed before the end of the year. Winter is expectedly very quiet due to the holidays and effective low demand. Summer, equally, is a very lazy and unproductive time<sup><a href="#fn4" class="footnoteRef" id="fnref4">4</a></sup>, partly due to the heat and partly due to holidays.</p>
<img src="/images/month_of_year.png"/>
<h2 id="commits-during-the-day">Commits during the day</h2>
<p>This result confirmed my suspicions, that I’m most productive in the morning before lunch, and then a little around 5ish. The table below confirms it; I make most commits just before lunch or just after lunch, because I did all the work in the morning. After lunch I’m always very sluggish and lethargic. Somehow it appears I still manage to finish commits I started in the morning. I very rarely work in the evening, though it does happen.</p>
<img src="/images/by_hour.png"/>
<h2 id="commits-during-the-week">Commits during the week</h2>
<p>In this case I was surprised. I’d always thought that my productivity was high on average, but very sporadic. I’m aware that some days once in a while I just don’t feel like doing anything/can’t get in the groove.</p>
<p>However, from the chart below it seems that, on average, there is a distinct, and perfectly reasonable pattern.</p>
<ul>
<li>I start mondays with a surprising amount of energy; I hit the ground running, clocking 491 commits in total for monday, or 7.5 commits per monday on average.</li>
<li>I go through tuesdays and wednesdays churning out code with presumably very good flow, clocking 561 and 563 commits respectively, or 8.6 commits each day.</li>
<li>But then on thursday I drop down to less than monday’s great start, to a mere decently good<sup><a href="#fn5" class="footnoteRef" id="fnref5">5</a></sup> 422 (or 6.4 for the day), implying that, somehow, for me thursdays are either less tense and urgent; I feel more relaxed, or it could be that I burn out by thursday after the bursts on monday, tuesday and wednesday and start pacing myself.</li>
<li>Finally on fridays, I drop down to 329. Clearly by friday I am ready for the weekend, and so is everyone else. Nothing gets pushed to production on a friday. There is little urgency about it, more time for discussion and reflection for next week. Only 5 commits on average for this day.</li>
<li>Sometimes I do some work on weekends. I thought I never did anything on weekends but there is some activity.</li>
</ul>
<img src="/images/day_of_week.png"/>
<h2 id="are-commits-a-good-indication-of-work-done">Are commits a good indication of work done?</h2>
<p>I think so. It’s true for sure that I can work all day and not commit anything, but on average I break my tasks into smaller tasks that can fit into a few hour’s worth of work and one or two commits.</p>
<p>A commit is a complete piece of work. This is a much better indicator of productivity than merely being at the office, sat at the computer.</p>
<p>I will also say that my stats are <em>very similar</em> to a colleague of mine, on a project of about the same size, who exhibits similar patterns of days of the week, but different hours of the day (he’s more active in the afternoon).</p>
<h2 id="what-did-i-learn-from-this-information">What did I learn from this information?</h2>
<p>One thing I’ve learned is that my performance is fairly consistently spread in an uneven way. It would be interesting to pace myself better over the week so that I maintain a pace like monday across the board. I’m not sure if this would increase my morale or weaken it.</p>
<p>It might be wise for me to eat smaller meals throughout the day, rather than a big lunch. This seems to really slow me down; I’m not sure whether it’s the full stomach or just a necessary recharge. Also, if I can’t change this pattern, it might be good for me to start scheduling non-coding/hard stuff to that period of the day, such as cleaning up tickets and organizing/planning.</p>
<h2 id="mildly-curious-how-everyone-else-works">Mildly curious how everyone else works</h2>
<p>I would be interested to see people’s work patterns based on this gitstats tool for their activity over the year, over the week, and during the day. Especially if you have a year or more worth of data.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>As this project has been my main activity and I have two year’s worth of data, there is enough data to generalise my general work.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>There have been other projects on the side, but mainly it has been this one.<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>2010-07-25 14:36:51 to 2011-10-24 16:45:13 (456 days)<a href="#fnref3">↩</a></p></li>
<li id="fn4"><p>Comparatively. In absolute terms that’s still 100+ commits per month.<a href="#fnref4">↩</a></p></li>
<li id="fn5"><p>For some value of “good.” Bear in mind that when I talk about “speed” or “good”, I’m talking relatively to the other days, not in absolute terms, your mileage may vary substantially.<a href="#fnref5">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Fri, 02 Dec 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/programmer-at-work-statistics</guid>
</item>
<item>
<title>/r/haskell</title>
<link>http://chrisdone.com/posts/rhaskell</link>
<description><![CDATA[<p>Slowly I am learning that, <a href="/images/rhaskell.png">sometimes</a>, you just have to call it a day and move on.</p>
<p>Post here as a reminder to myself.</p>]]></description>
<pubDate>Mon, 28 Nov 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/rhaskell</guid>
</item>
<item>
<title>Days of the Week</title>
<link>http://chrisdone.com/posts/days-of-the-week</link>
<description><![CDATA[<img src="/images/daysoftheweek.png"/>
<style>body{background:#11100e}.page-wrap{width:640px;background:#11100e;color:#333}a,a:visited{color:#555}
</style>
]]></description>
<pubDate>Tue, 08 Nov 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/days-of-the-week</guid>
</item>
<item>
<title>HaskellDB: A long tutorial</title>
<link>http://chrisdone.com/posts/haskelldb-tutorial</link>
<description><![CDATA[<p>I’ve been using HaskellDB in production for about two years. I decided that I’d write a proper, up-to-date description, or tutorial, about what it is, how it works, what it can do, and my experience using it in projects.<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup></p>
<h2 id="what-is-haskelldb">What is HaskellDB?</h2>
<p><a href="http://hackage.haskell.org/package/haskelldb">HaskellDB</a> is a database interface library for Haskell which features</p>
<ul>
<li>explicit declaration of schema of entities and fields,</li>
<li>an EDSL<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup>—a <code>Query</code> monad—for making queries and statements based on using operations based on the relational algebra<sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup>,</li>
<li>a simple record system for dealing with entities and fields.</li>
</ul>
<p>It was originally developed for Hugs making use of the TRex, but was later made portable and is now happy in both Hugs and GHC<sup><a href="#fn4" class="footnoteRef" id="fnref4">4</a></sup>.</p>
<p>The <a href="http://rubyonrails.org/">Ruby on Rails project</a> recently adopted <a href="http://github.com/rails/arel">ARel, a library based on the same idea</a>.</p>
<h2 id="connecting">Connecting</h2>
<p>So to connect to a database with HaskellDB, you can use different backends. In this case, I’ll assume you’re using HDBC as a backend.</p>
<p>Pop them in a separate module:</p>
<pre><code>module Caturday.Model.Connect where
import Database.HaskellDB.HDBC
import Database.HaskellDB.Sql.PostgreSQL
import Database.HDBC.PostgreSQL (connectPostgreSQL)
withDB :: [(String,String)] -&gt; (Database -&gt; IO a) -&gt; IO a
withDB opts = hdbcConnect generator (connectPostgreSQL conninfo)
where conninfo = unwords [ k ++ &quot;=&quot; ++ v | (k,v) &lt;- opts ]
opts = [(&quot;host&quot;,&quot;localhost&quot;)
,(&quot;user&quot;,&quot;your_username&quot;)
,(&quot;password&quot;,&quot;your_password&quot;)
,(&quot;dbname&quot;,&quot;your_db_name&quot;)]</code></pre>
<p>Usually you ought to combine this with configuration options.</p>
<h2 id="orm-approach">ORM approach</h2>
<h3 id="fields">Fields</h3>
<p>The approach for the object relational mapping is that one defines the column types and entity schemas up front. So, supposing our project is named Caturday, in a module named <code>Caturday.Model.Fields</code>,<sup><a href="#fn5" class="footnoteRef" id="fnref5">5</a></sup> using the <code>field</code> macro,<sup><a href="#fn6" class="footnoteRef" id="fnref6">6</a></sup> one declares fields. For example:</p>
<pre><code>{-# LANGUAGE TemplateHaskell #-}
-- | All database fields.
module Caturday.Model.Fields where
import Database.HaskellDB.TH
-- Keys.
field &quot;Id&quot; &quot;id&quot; &quot;id&quot; [t|Int|]
-- Data fields.
field &quot;Title&quot; &quot;title&quot; &quot;title&quot; [t|String|]</code></pre>
<p>This produces three things:</p>
<ul>
<li>A type called <code>Title</code>.</li>
<li>A field variable called <code>title</code>.</li>
<li>An instance of the field class which can be used to reference <code>title</code> in the database.</li>
</ul>
<p>In other words, a Haskell-level representation of the database field “title”.</p>
<h3 id="tables">Tables</h3>
<p>Then one defines the entities that use those fields in a module such as <code>Caturday.Model.Tables</code>, using the <code>table</code> macro<sup><a href="#fn7" class="footnoteRef" id="fnref7">7</a></sup>. For example:</p>
<pre><code>{-# LANGUAGE TemplateHaskell #-}
-- | Database tables and entities.
module Caturday.Model.Tables where
import Caturday.Model.Fields as Fields
import Database.HaskellDB.TH
import Prelude ()
-- | Content table.
table &quot;content&quot; &quot;content&quot;
[&#39;id
,&#39;title
]</code></pre>
<p>The first argument is the Haskell-level value name for the table, and the second is the SQL-level name of the entity. To import <code>Fields as Fields</code> is a good idea.<sup><a href="#fn8" class="footnoteRef" id="fnref8">8</a></sup></p>
<h3 id="importing">Importing</h3>
<p>Once the model schema has been defined in these two modules, one ought to import them like so:</p>
<pre><code>import qualified Caturday.Model.Fields as F
import qualified Caturday.Model.Tables as T
import Database.HaskellDB
import Database.HaskellDB.HDBRec</code></pre>
<p>So that later we will refer to fields as <code>F.foo</code> and tables as <code>T.bar</code>.</p>
<h2 id="querying">Querying</h2>
<h3 id="selection">Selection</h3>
<p>Queries and statements in HaskellDB are composed with the <code>Query</code> monad. For example, simple selection works like this:</p>
<pre><code>simpleSelection = do
table T.content</code></pre>
<p>We use the <code>table</code> function to select tables from our predefined set of tables. It returns a relation of some kind; i.e. tables or result of a sub-select or projection, etc.</p>
<p>To select more tables (i.e., <em>joining</em>) we just list more tables:</p>
<pre><code>simpleDoubleSelection = do
table T.content
table T.content</code></pre>
<p>We execute this query with <code>withDB</code>, for example:</p>
<pre><code>λ&gt; fmap (take 1) $ withDB opts $ \db -&gt; query db simpleSelection
[[(&quot;id&quot;,&quot;34750&quot;),(&quot;title&quot;,&quot;\&quot;Spanner Based Distributed Channel Assignment in Wireless Mesh Networks\&quot;&quot;)]]</code></pre>
<h3 id="projection">Projection</h3>
<p>For projection we use the <code>project</code> function defined in <code>Database.HaskellDB.Query</code>:</p>
<pre><code>simpleProjection = do
content &lt;- table T.content
project $ F.id &lt;&lt; content!F.id</code></pre>
<p>For each field we want to project, we specify a value for it using the <code>(&lt;&lt;)</code> function, defined in <code>Database.HaskellDB.Query</code>. To project more fields, we use the record constructing operator, <code>(#)</code>:</p>
<pre><code>simpleProjection2 = do
content &lt;- table T.content
project $ F.id &lt;&lt; content!F.id
# F.title &lt;&lt; content!F.title</code></pre>
<p>One can see this operator as akin to the tuple constructor <code>(,)</code> as in <code>(1,2)</code>.</p>
<p>We can also project our own Haskell-level values as SQL constants:</p>
<pre><code>simpleStringProjection = do
content &lt;- table T.content
project $ F.id &lt;&lt; constant 123
# F.title &lt;&lt; constant &quot;Hello, World!&quot;</code></pre>
<p>Personally in my use, I have renamed <code>constant</code> to <code>val</code>.<sup><a href="#fn9" class="footnoteRef" id="fnref9">9</a></sup> I just find this more convenient. I will use this henceforth.</p>
<pre><code>import Database.HaskellDB.Extra</code></pre>
<h3 id="restriction">Restriction</h3>
<p>We restrict results using the <code>restrict</code> function:</p>
<pre><code>simpleRestriction = do
content &lt;- table T.content
restrict $ content!F.title .==. val &quot;Coco Jambo&quot;
return content</code></pre>
<p>The restrict function takes an SQL boolean expression:</p>
<pre><code>λ&gt; :i restrict
restrict :: Expr Bool -&gt; Query ()
-- Defined in Database.HaskellDB.Query</code></pre>
<p>For boolean expressions there are a bunch of logical operators that commonly appear in SQL:</p>
<pre><code>-- | Equality comparison on Exprs, = in SQL.
(.==.) :: Eq a =&gt; Expr a -&gt; Expr a -&gt; Expr Bool
-- | Inequality on Exprs, &lt;&gt; in SQL.
(.&lt;&gt;.) :: Eq a =&gt; Expr a -&gt; Expr a -&gt; Expr Bool
(.&lt;.) :: Ord a =&gt; Expr a -&gt; Expr a -&gt; Expr Bool
(.&gt;=.) :: Ord a =&gt; Expr a -&gt; Expr a -&gt; Expr Bool
-- | \&quot;Logical and\&quot; on &#39;Expr&#39;, AND in SQL.
(.&amp;&amp;.):: Expr Bool -&gt; Expr Bool -&gt; Expr Bool
-- | \&quot;Logical or\&quot; on &#39;Expr&#39;. OR in SQL.
(.||.) :: Expr Bool -&gt; Expr Bool -&gt; Expr Bool</code></pre>
<p>Note that the convention is for operators in HaskellDB to be surrounded by periods. For more see the Operators section of Database.HaskellDB.Query.</p>
<h3 id="raw-sql-output">Raw SQL Output</h3>
<p>To get a concrete feeling of what SQL this code will produce, let’s observe the output. To do that, we can use <code>ppSqlUnOpt</code>:</p>
<pre><code>λ&gt; :i ppSqlUnOpt
ppSqlUnOpt :: Query (Rel r) -&gt; Text.PrettyPrint.HughesPJ.Doc
-- Defined in Database.HaskellDB.PrintQuery</code></pre>
<p>The simple selection:</p>
<pre><code>λ&gt; ppSqlUnOpt simpleSelection
SELECT id,
title
FROM content as T1</code></pre>
<p>The projection example:</p>
<pre><code>λ&gt; ppSqlUnOpt simpleProjection
SELECT id as id1,
title as title1
FROM content as T1</code></pre>
<p>The constant value example:</p>
<pre><code>λ&gt; ppSqlUnOpt simpleStringProjection
SELECT 123 as id,
&#39;Hello, World!&#39; as title,
id1,
title1
FROM (SELECT id as id1,
title as title1
FROM content as T1) as T1</code></pre>
<p>The code is clear to read and not that surprising.</p>
<h3 id="insertion-delete-update">Insertion, delete, update</h3>
<p>Insertion uses the <code>insert</code> function. Similar to the <code>query</code> function, it takes a connection value. Pretty self-explanatory:</p>
<pre><code>simpleInsert conn = do
insert conn
T.content
( F.id &lt;&lt; val 123
# F.title &lt;&lt; val &quot;What is Love?&quot;)</code></pre>
<p>The delete function takes a restriction clause for the row to delete, with the ability to inspect the row for the condition.</p>
<pre><code>simpleDelete conn = do
delete conn
T.content
(\content -&gt; content!F.title .==. val &quot;Coco Jambo&quot;)</code></pre>
<p>Updating is the same as insert, but we provide a function for the update:</p>
<pre><code>simpleUpdate conn = do
update conn
T.content
(\content -&gt; content!F.title .==. val &quot;Coco Jambo&quot;)
(\content -&gt; F.title &lt;&lt; val &quot;What is Love?&quot;)</code></pre>
<h2 id="speed-and-optimisation">Speed and optimisation</h2>
<p>But the subquery is useless in this example, so clearly the optimizer isn’t magic.</p>
<pre><code>λ&gt; ppSqlUnOpt simpleDoubleSelection
SELECT id2 as id,
title2 as title
FROM (SELECT id as id2,
title as title2
FROM content as T1) as T1,
(SELECT id as id1,
title as title1
FROM content as T1) as T2</code></pre>
<p>In fact, subqueries are created in all cases.</p>
<p>For normal query optimizers, e.g. PostgreSQL, the subquery is lifted as to be equivalent to there being one query. I am not sure about MySQL; it may have trouble when joins are involved. Don’t expect good performance from HaskellDB if you’re using MySQL.<sup><a href="#fn10" class="footnoteRef" id="fnref10">10</a></sup></p>
<p>For example, PostgreSQL sees such use of sub-query as equivalent to direct join:</p>
<pre><code>=&gt; explain SELECT id2 as id,
title2 as title
FROM (SELECT id as id2,
title as title2
FROM content as T1) as T1,
(SELECT id as id1,
title as title1
FROM content as T1) as T2;
QUERY PLAN
------------------------------------------------------------------
Nested Loop (cost=1578.48..330231.64 rows=16353936 width=77)
-&gt;Seq Scan on content t1 (cost=0.00..1574.44 rows=4044 width=77)
-&gt;Materialize (cost=1578.48..1618.92 rows=4044 width=0)
-&gt;Seq Scan on content t1 (cost=0.00..1574.44 rows=4044 width=0)
(4 rows)
=&gt; explain SELECT T1.id as id,
T1.title as title
FROM content as T1,
content as T2;
QUERY PLAN
-------------------------------------------------------------------
Nested Loop (cost=1578.48..330231.64 rows=16353936 width=77)
-&gt;Seq Scan on content t1 (cost=0.00..1574.44 rows=4044 width=77)
-&gt;Materialize (cost=1578.48..1618.92 rows=4044 width=0)
-&gt;Seq Scan on content t1 (cost=0.00..1574.44 rows=4044 width=0)
(4 rows)
=&gt;</code></pre>
<p>I’m not joining on any indexes so it’s a sequence scan. For people not used to PostgreSQL output, this basically means it will do a cartesian product in both versions.</p>
<h2 id="maintenance">Maintenance</h2>
<p>The great part about HaskellDB is that it is in first-class Haskell land. Fields and tables have a statically enforced membership and field-type schema.</p>
<p>The obvious use case is that it avoids making mistakes in naming and ending up with the wrong field type, or using a field that doesn’t exist in a given table.</p>
<p>The fact that all fields are defined up front with the right type means that one really has to think about how meaningful a type is and how one will use it. For example:</p>
<pre><code>field &quot;Abstract&quot; &quot;abstract&quot; &quot;abstract&quot; [t|Maybe String|]</code></pre>
<p>This is how to encode a database text field that is nullable. When one is encoding their database schema into the Haskell type system, one finds that it really needs to be thought of properly of what types are there in the database, particularly nullability.</p>
<p>In my day to day work, I have to work with database schemas that aren’t mine, I have to interface with them. Due to my use of HaskellDB, I have a lot of correctness questions about these schemas I’m working with to the authors, if they are available for consultation.</p>
<p>Often it comes up, that I ask “why is this field nullable?” and the question often comes back, “I don’t know.” As the PostgreSQL documentation says, in most database designs the majority of columns should be marked not null.<sup><a href="#fn11" class="footnoteRef" id="fnref11">11</a></sup></p>
<p>Note that in Haskell nullability is not implicit. No values can be null. But you can have choice between a value or not a value, as in <code>Maybe</code>:</p>
<pre><code>data Maybe a = Just a | Nothing</code></pre>
<p>And so if we use the abstract field, as mentioned, and use it as a string, it’s not a string, it’s a <code>Maybe String</code>, so we get a compile error such as:</p>
<pre><code>Mismatch: Demo.hs:23:32: “Maybe String” ≠ “String”</code></pre>
<p>Another nice property is that fields named in your codebase, and their names in the database, are entirely separate and configurable. Just because Joe Master Designer chose certain names in his schema, that doesn’t mean that you have to conform to those names. Maybe they call it <code>thetitle</code>, and you just want <code>title</code>:</p>
<pre><code>field &quot;Title&quot; &quot;title&quot; &quot;thetitle&quot; [t|String|]</code></pre>
<p>Another fact is changes to the schema underneath: if someone (you or someone else) changes the type or availability of a field or table in the schema, all you need do is make the necessary change in the field module or table module, and the compiler will tell you immediately which modules need updating with the new invariants.</p>
<p>Suppose we change the type of the field title to <code>Int</code> (for example), when we recompile our examples above, we get:</p>
<pre><code>Mismatch: Demo.hs:23:32: “Int” ≠ “String”
Mismatch: Demo.hs:25:0: “String” ≠ “Int”</code></pre>
<p>So the following two functions are now inconsistent:</p>
<pre><code>simpleStringProjection = do
content &lt;- table T.content
project $ F.id &lt;&lt; constant 123
# F.title &lt;&lt; constant &quot;Hello, World!&quot;
simpleRestriction = do
content &lt;- table T.content
restrict $ content!F.title .==. val &quot;Coco Jambo&quot;
return content</code></pre>
<p>In a codebase of 10K+ lines, this starts to become very compelling.</p>
<p>I believe LINQ in C# et al provide similar static assurances.</p>
<h2 id="extension">Extension</h2>
<h3 id="pagination-and-composing-queries">Pagination and composing queries</h3>
<p>Because the query DSL is a monad (as plenty of Haskell DSLs are), it is really nicely composable. This means it’s trivial to split up queries into discrete parts that have meaningful and generic purposes.</p>
<p>For example, to implement pagination, which is essentially the simple problem of an offset and a count. I implemented this in <code>HaskellDB.Database.Pagination</code>.<sup><a href="#fn12" class="footnoteRef" id="fnref12">12</a></sup></p>
<p>Thus the following implementation is possible. Suppose we write some functions to search the articles by title in the database, but paginated. Two things we need for this are:</p>
<ul>
<li>The count of total articles filtered by the search query, <code>q</code>.</li>
<li>The paginated articles filtered by the search query.</li>
</ul>
<p>First we define a query that does the search and restriction:</p>
<pre><code>getContent q = do
article &lt;- table T.content
restrict $ article!F.title .==. val q
return article</code></pre>
<p>In the fields module we need another field:</p>
<pre><code>field &quot;Count&quot; &quot;count&quot; &quot;count&quot; [t|Int|]</code></pre>
<p>Then we write the function that uses this query, and projects the count:</p>
<pre><code>getArticlesCount conn q = fmap (sum . map (!F.count)) $ query conn $ do
article &lt;- getContent q
project $ F.count &lt;&lt; count (article!F.id)</code></pre>
<p>Then we can write a function to get the articles and then paginate.</p>
<pre><code>getArticles conn pn q = fmap (map (!F.title)) $ query conn $ do
article &lt;- getContent q
paginate pn
return article</code></pre>
<p>Very, very easy to compose.</p>
<h3 id="functions-and-operators">Functions and operators</h3>
<p>Sometimes you want to define more SQL functions and operators, which is <a href="http://hpaste.org/53608">a use case I had for PostgreSQL</a> as <code>Database.HaskellDB.PostgreSQL</code>.</p>
<p>The function to use for extending with new functions is <code>func</code>.</p>
<pre><code>λ&gt; :i func
func :: (Args a) =&gt; String -&gt; a
-- Defined in Database.HaskellDB.Query</code></pre>
<p><code>Args</code> is implemented as a way to have arbitrary number of serializable parameters, in the same way <code>Text.Printf.printf</code> works.</p>
<p>For example, <a href="http://www.postgresql.org/docs/8.1/static/functions-datetime.html">date_part</a> in PostgreSQL:</p>
<pre><code>-- | Get part of a date.
date_part :: Expr String -&gt; Expr CalendarTime -&gt; Expr Integer
date_part = func &quot;date_part&quot;</code></pre>
<p>Or maybe we want to use full text search support from PostgreSQL. Let’s add a field to represent the <code>ts_vector</code>, and define a table with the searchable stuff:</p>
<pre><code>-- | Search fields.
field &quot;Textsearchable&quot; &quot;textsearchable&quot; &quot;textsearchable_index_col&quot;
[t|TSVector|]
-- | Content table with searchable full text field.
table &quot;contentSearchable&quot; &quot;content&quot;
[&#39;id
,&#39;title
,&#39;textsearchable
]</code></pre>
<p>Now we can redefine <code>getContent</code> which matches on the <code>ts_vector</code>:</p>
<pre><code>getContentFullText q = do
article &lt;- table T.contentSearchable
restrict $ article!F.textsearchable .@@. (to_tsquery (val q))
order [descExpr $ ts_rank_cd (article!F.textsearchable)
(to_tsquery (val q))]
return article</code></pre>
<p>This can be achieved by a phantom type (i.e. an uninhabitable type at the value-level):</p>
<pre><code>-- | A text-search vector.
data TSVector
-- | Convert a string to a textsearch vector.
to_tsvector :: Expr String -&gt; Expr TSVector
to_tsvector = func &quot;to_tsvector&quot;</code></pre>
<p>And the function can be used, at the SQL-level, because the vector is constructed at the SQL-level, not the Haskell level. That’s quite nice.</p>
<p>Likewise, <code>descExpr</code> was written by me from the Database.HaskellDB.Extra module:</p>
<pre><code>-- | Order the query by an arbitrary expression.
descExpr :: Expr a -&gt; OrderExpr
descExpr e = OrderExpr OpDesc expr where
Expr expr = e</code></pre>
<p>One just needs access to the internal tree and a new combinator can be constructed.</p>
<h2 id="enums">Enums</h2>
<p>It’s also possible to use enum types with HaskellDB that map from DB-level enums and Haskell enums.</p>
<p>Suppose we define an Enums module, with an enum type <code>ArticleType</code>:</p>
<pre><code>module Caturday.Types.Enums where
import Data.Enum.Print
import Database.HaskellDB.Get
import Database.HaskellDB.PrimQuery
import Database.HaskellDB.Query
data ArticleType
= ResearchArticle
| Editorial
deriving (Show,Enum,Read,Eq)</code></pre>
<p>In order to get values of this type from the database with HaskellDB, we need to implement the <code>GetValue</code> and the <code>ShowConstant</code> classes:</p>
<pre><code>instance GetValue ArticleType where
getValue = getValueWith readEnum &quot;ArticleType&quot;
instance ShowConstant ArticleType where
showConstant = StringLit . showEnum</code></pre>
<p>This uses two <em>other</em> modules (I know, I’m referencing a lot of modules I’ve written, sorry), <a href="http://hpaste.org/53612">Data.Enum.Print</a>, a simple enum serialization module, and <a href="http://hpaste.org/53614">Database.HaskellDB.Get</a>, which provides the <code>getValueWith</code> function.</p>
<p>Now we can define the fields that use this type in our Fields module:</p>
<pre><code>import qualified Caturday.Types.Enums as Types (ArticleType)
-- | Enum types.
field &quot;ArticleType&quot; &quot;articleType&quot; &quot;type&quot; [t|Types.ArticleType|]</code></pre>
<p>and redefine the content table’s schema:</p>
<pre><code>-- | Content table.
table &quot;content&quot; content&quot;
[&#39;id
,&#39;title
,&#39;articleType
]</code></pre>
<p>So now, our Demo module doesn’t compile, so we update:</p>
<pre><code>import Caturday.Types.Enums
simpleInsert conn = do
insert conn
T.content
( F.id &lt;&lt; val 123
# F.title &lt;&lt; val &quot;What is Love?&quot;
# F.articleType &lt;&lt; val Editorial)</code></pre>
<p>And we can also use the enum for restriction as well as retrieval:</p>
<pre><code>restrictOnArticleType conn = query conn $ do
content &lt;- table T.content
restrict $ content!F.articleType .==. val Editorial
return content
λ&gt; fmap (take 1) $ withDB opts $ \db -&gt; restrictOnArticleType db
[[(&quot;id&quot;,&quot;82&quot;)
,(&quot;title&quot;,&quot;\&quot;Welcome message from the Editor-in-Chief\&quot;&quot;)
,(&quot;type&quot;,&quot;Editorial&quot;)]]</code></pre>
<h2 id="stability">Stability</h2>
<p>The problem with HaskellDB is that the implementation can be unstable. I found that I had to patch the PostgreSQL library to handle simple stupid things like fields named “user” or “order”, by making sure to quote all fields.</p>
<p>I also had to open up some of the internal parts of the API so that I could extend it further, such as for the operator <code>(.@@.)</code> defined above. I’ll push these fixes and extensions to fork repos at some point.</p>
<h2 id="reading-error-messages">Reading error messages</h2>
<p>HaskellDB gets a lot of stick for hard to read error messages. This is true when you get things badly wrong.</p>
<p>In the general case the errors are quite straight forward.</p>
<p>For example, if I try to use a field which doesn’t exist in the table, like this:</p>
<pre><code>simpleRestriction = do
content &lt;- table T.content
restrict $ content!F.count .==. val 1
return content</code></pre>
<p>Then the compile error looks like this:</p>
<pre><code>Error: Demo.hs:39:13: No instance for (HasField F.Count RecNil)
arising from a use of `!&#39; at Demo.hs:39:13-27
Possible fix:
add an instance declaration for (HasField F.Count RecNil)
In the first argument of `(.==.)&#39;, namely `content ! F.count&#39;
In the second argument of `($)&#39;, namely
`content ! F.count .==. val 1&#39;
In a stmt of a &#39;do&#39; expression:
restrict $ content ! F.count .==. val 1</code></pre>
<p>Which is a very useful error message. <code>content</code> does not has field <code>count</code>.</p>
<p>For getting the wrong type, it merely shows “couldn’t match type A against type B,” straight-forward.</p>
<p>The cases where compile errors blow up are, for example, if I wrote this:</p>
<pre><code>simpleRestriction = do
content &lt;- table T.content
restrict $ content!content .==. val &quot;Coco Jambo&quot;
return content
then the error is:
Error: Demo.hs:39:13:
No instance for
(Select
(Rel
(RecCons F.Id (Expr Int)
(RecCons F.Title (Expr String) RecNil)))
(Rel
(RecCons F.Id (Expr Int)
(RecCons F.Title (Expr String) RecNil)))
(Expr [Char]))
arising from a use of `!&#39;
at Demo.hs:39:13-27
Possible fix:
add an instance declaration for […]
In the first argument of `(.==.)&#39;, namely `content ! content&#39;
In the second argument of `($)&#39;, namely
`content ! content .==. val &quot;Coco Jambo&quot;&#39;
In a stmt of a &#39;do&#39; expression:
restrict $ content ! content .==. val &quot;Coco Jambo&quot;</code></pre>
<p>The error actually makes sense if you understand the API well enough, but otherwise it can be very confusing and worrying. Don’t worry about it, you didn’t break something complicated, you just made a typo somewhere. It shows the offending expression; you realised you tried to use a table as a field, and you correct.</p>
<h2 id="files">Files</h2>
<p>The complete files for this demo including patched libraries are <a href="https://github.com/chrisdone/haskelldb-demo">here in Github flavour.</a></p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Afterwards it would seem like a good idea to get a proper comprehensive tutorial on the HaskellWiki, or much better yet, embed a tutorial in the Haddock documentation for HaskellDB. At the moment the haddock docs are literally just an API listing, with no elaborative explanation or examples. Writing in Haddock mark-up is quite a painful, boring experience. Regardless, I believe the haddock docs of a project should (most of the time) be sufficient to explain its use, linking to external papers and blog posts and whatnot is annoyingly terse and quickly becomes out of date.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>Embedded domain-specific language. A common notion in Haskell and Lisp languages, though implemented differently in each.<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>See <a href="http://hackage.haskell.org/package/haskelldb">package description for HaskellDB</a>.<a href="#fnref3">↩</a></p></li>
<li id="fn4"><p>See the <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.136.3828&amp;rep=rep1&amp;type=pdf">“HaskellDB Improved” paper.</a><a href="#fnref4">↩</a></p></li>
<li id="fn5"><p>This is the convention I have chosen to use. It makes good sense and can be very helpful for all fields used in the project to be defined on a per-project basis, rather than per-entity, and of the same type.<a href="#fnref5">↩</a></p></li>
<li id="fn6"><p>A macro that you can get from <a href="http://hpaste.org/53595">Database.HaskellDB.TH</a>, which I have yet to put into a library or get added to HaskellDB mainline. I don’t care to debate API decisions with the HaskellDB maintainers right now.<a href="#fnref6">↩</a></p></li>
<li id="fn7"><p>A macro that you can get from <a href="http://hpaste.org/53595">Database.HaskellDB.TH</a>, which I have yet to put into a library or get added to HaskellDB mainline. I don’t care to debate API decisions with the HaskellDB maintainers right now.<a href="#fnref7">↩</a></p></li>
<li id="fn8"><p>When table names conflict with field names—and eventually it happens—this is useful to have. Alternatively <code>as F</code> also makes sense, to be consistent.<a href="#fnref8">↩</a></p></li>
<li id="fn9"><p>I have defined a few extra functions for HaskellDB in <a href="http://hpaste.org/53599">Database.HaskellDB.Extra</a>.<a href="#fnref9">↩</a></p></li>
<li id="fn10"><p><a href="http://pseudofish.com/blog/2008/05/18/haskelldb-performance/">Geoff Wilson on HaskellDB performance.</a><a href="#fnref10">↩</a></p></li>
<li id="fn11"><p><a href="http://www.postgresql.org/docs/8.3/static/ddl-constraints.html">PostgreSQL manual on constraints.</a><a href="#fnref11">↩</a></p></li>
<li id="fn12"><p><a href="http://hpaste.org/53619">Another simple module</a> and <a href="http://hpaste.org/53607">another</a> that would be cool to put in a package, but for now remains in my utility box.<a href="#fnref12">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Sun, 06 Nov 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/haskelldb-tutorial</guid>
</item>
<item>
<title>Common Lisp/Haskell syntactic comparison</title>
<link>http://chrisdone.com/posts/common-lisp-haskell</link>
<description><![CDATA[<p>This is a little reminder/documentation for myself to explain that, despite having nice regular s-expression syntax, Common Lisp actually has a lot of syntactic concepts. I add comparison to Haskell because Haskell is known (perhaps superfically) for having a lot of syntax compared to other languages.</p>
<pre><code>CL: ; comment here
HS: -- comment here
CL: (defun x () …)
HS: x = …
CL: (COND (((= x 1) r1) ((= x 2) r2)) (t r3))
HS: case x of 1 -&gt; r1; 2 -&gt; r2; _ -&gt; r3
CL: &#39;quotation
HS: &#39;value
&#39;&#39;type
CL: &#39;(quotation)
`(quasiquotation)
HS: [|quotation|]
CL: `(quasiquotation with ,splice)
HS: [| quotation with $(splice) |]
CL: `(list splice with ,@splice)
HS: [| list splice with $(splice) |]
CL: #(reader macros)
#(… …) ; vector
#p&quot; … &quot; ; path
HS: [| reader macros |]
[v| … … |]
[p| … |]
CL: :keyword arguments
CL: #: no idea what this is called
CL: (multiple-value-bind (x y) some-values (print x))
HS: (let (x,y) = someValues in print x)
CL: (list 1 2 3)
&#39;(1 2 3)
HS: [1,2,3]
CL: (cons 1 (cons 2 (cons 3 nil)))
(cons 1 (cons 2 (cons 3 &#39;())))
HS: 1 : 2 : 3 : []
CL: (funcall foo &#39;(arg1 arg2))
HS: foo arg1 arg2
CL: #&#39;function
HS: function
CL: (let ((f 1)) …)
(let*((g 0) (f g)) …)
(flet((g (n) (cons n …)) (f () (g 1))) …)
HS: let f = g 1; g n = n : g (n+1) in f
CL: *global*
CL: (lambda (a b) …)
HS: \a b -&gt; …
CL: (tagbody (go …))
CL: (defun x (f &amp;optional args) &quot;Docs here.&quot; …)
CL: (declare (single-float x) (optimize (safety 3)))
HS: x :: Float
CL: (do () (…) (…))
CL: (values a b c)
HS: (a,b,c)
CL: (loop … ? ¿ ‽)
CL: #\space
#\
HS: &#39; &#39;
CL: (+) =&gt; 0
HS: (+) =&gt; (+)
CL: (+ 1) =&gt; 1
HS: (+ 1) =&gt; (+ 1)
CL: (+ 1 2) =&gt; 3
HS: (1 + 2) =&gt; 3
CL: (sort (list &#39;(9 A) &#39;(3 B) &#39;(4 C)) #&#39;&lt; :key #&#39;first)
HS: sortBy (comparing fst) [(9,&#39;A&#39;),(3,&#39;B&#39;),(4,&#39;C&#39;)]
CL: #1=(programmable . #1#) programming language
HS: fix (\x -&gt; &quot;programmable &quot; ++ x) ++ &quot; programming language&quot;
CL: (defclass x (a b) ())
HS: class X a b
CL: (if foo-bar then-x else-y)
HS: if fooBar then x else y
HS: False, Nothing, []
CL: nil</code></pre>]]></description>
<pubDate>Mon, 31 Oct 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/common-lisp-haskell</guid>
</item>
<item>
<title>Deprecate Prelude.head and partial functions</title>
<link>http://chrisdone.com/posts/boycott-head</link>
<description><![CDATA[<p>Please boycott <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:head">Prelude.head</a> and all its partial friends.</p>
<p>I’m sick of seeing <a href="http://www.google.com/search?sourceid=chrome&amp;ie=UTF-8&amp;q=%22Prelude.head%3A+empty+list%22">this exception</a>:</p>
<pre><code>Prelude.head: empty list</code></pre>
<p>That’s 6,610 results for this ridiculous exception. Alternatives are:</p>
<pre><code>listToMaybe :: [a] -&gt; Maybe a
take :: Int -&gt; [a] -&gt; [a]
foldr :: (a -&gt; b -&gt; b) -&gt; b -&gt; [a] -&gt; b
data List a = Single a | Cons a (List a)
data NonEmpty a = NonEmpty a [a]
list :: (a -&gt; [a] -&gt; b) -&gt; b -&gt; [a] -&gt; b
Plain old pattern matching.</code></pre>
<p>And if your code really does not make sense to have an empty list (then why are you using a list data type?) and you cannot be swayed against using a list type, please at least do this:</p>
<pre><code>throw MeaningfulException
`fromMaybe` (listToMaybe xs)</code></pre>
<p>Please stop using partial functions. Seriously. Remove them from your codebase.</p>
<h2 id="expanding-with-examples">Expanding with examples</h2>
<p>Someone commented:</p>
<blockquote>
<p>What if my data type is a list and I know that head will not throw an exception?</p>
<pre><code>foo [] = 0
foo xs = bar $ head xs</code></pre>
</blockquote>
<p>The problem is that this is an invariant that only exists in the programmer’s head (sorry) and is not encoded in the type system (such is the problem with all partial functions), when it so easily can be. Some examples:</p>
<p>Sometime last year I found a Haddock bug:</p>
<pre><code>haddock: internal Haddock or GHC error: Prelude.head: empty list</code></pre>
<p>The cause is line 191:</p>
<pre><code>packageMod = ifaceMod (head ifaces)</code></pre>
<p>in the <code>render</code> function, because the author assumed that the “not-null” invariant would never be broken. But then he used the renderStep function again, and line 158, in the <code>main</code> function:</p>
<pre><code>renderStep flags packages []</code></pre>
<p>Breaking this invariant.</p>
<p>Around this time I also found a bug in Hakyll due to use of tail:</p>
<pre><code>./src/Text/Hakyll/Internal/CompressCss.hs:
| otherwise = head str : stripComments (tail str)</code></pre>
<p>which triggered <a href="http://hpaste.org/40264/hakyll_error">this exception</a>.</p>
<p>So, despite the invariant being satisfied at the time of writing, later that tacit invariant was broken and the developer didn’t realise it. This is more or less the most common case of partial function exceptions. You <em>just know</em> X will never happen, and then it does.</p>
<p>It’s trivial to abstract away partiality. In some cases handling cases might be a speed concern, but that should be a case-by-case localized optimization based on profiling.</p>]]></description>
<pubDate>Mon, 17 Oct 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/boycott-head</guid>
</item>
<item>
<title>“Value polymorphism”, simple explanation with examples</title>
<link>http://chrisdone.com/posts/value-polymorphism</link>
<description><![CDATA[<p>A concept in Haskell which is particularly novel is that polymorphism works at the value level rather than function-parameter or object-dereference level.</p>
<p>Function-parameter polymorphism comes in some different forms, for example, C++:</p>
<pre><code>void draw(Circle c){ … }
void draw(Triangle t){ … }
draw(circle); // draws a circle</code></pre>
<p>Function overloading is a type of function-parameter polymorphism. Generic functions in Common Lisp are another way to have function-parameter polymorphism:</p>
<pre><code>(defgeneric draw (shape))
(defmethod draw ((shape circle)) …)
(defmethod draw ((shape triangle)) …)
(draw circle) ;; draws a circle</code></pre>
<p>Object-dereference (or message passing) polymorphism is common to most object oriented languages. Depending on the object, the function/message will do something different:</p>
<pre><code>class Circle { void draw(){ … } }
class Triangle { void draw(){ … } }
circle.draw(); // draws a circle</code></pre>
<p>To avoid confusion, Haskell also has function parameter polymorphism:</p>
<pre><code>class Drawable a where draw :: a -&gt; Bitmap
instance Drawable Circle where draw = …
instance Drawable Triangle where draw = …
draw circle -- draws a circle</code></pre>
<p>Haskell has value polymorphism, which is that any value can be polymorphic and will be instantiated to a class instance depending on type signature or annotation:</p>
<pre><code>class Default a where def :: a
instance Default Int where def = 0
instance Default Char where def = &#39;a&#39;</code></pre>
<p>The type of an expression <code>def</code> therefore is <code>Default a =&gt; a</code>, or, “any instance of <code>Default</code>”. I can instantiate an instance myself by specifying a type signature:</p>
<pre><code>λ&gt; def :: Int
→ 0
λ&gt; def :: Char
→ &#39;a&#39;</code></pre>
<p>Or by type inference, meaning that the combination of this expression with other expressions allows the compiler to infer the single correct type instance:</p>
<pre><code>λ&gt; def : &quot;bc&quot;
→ &quot;abc&quot;
λ&gt; def - 2
→ -2
λ&gt; def == 0
→ True</code></pre>
<p>But with no information it will be a static compile error:</p>
<pre><code>λ&gt; def
Ambiguous type variable `a&#39; in the constraint:
`Default a&#39; arising from a use of `def&#39; at
&lt;interactive&gt;:1:0-2
Probable fix: add a type signature that fixes these type
variable(s)</code></pre>
<p>Why is value polymorphism beneficial? Some examples follow.</p>
<p>The <code>Read</code> class contains a method <code>read</code> which is polymorphic on the return value:</p>
<pre><code>class Read a where
read :: String -&gt; a</code></pre>
<p>It parses a data type from a string. Combined with the <code>Show</code> class, together <code>Read</code> and <code>Show</code> make a naive serialization library. In the same way, it would be ambiguous to read without specifying the instance:</p>
<pre><code>λ&gt; read &quot;2&quot;
Ambiguous type variable `a&#39; in the constraint:
`Read a&#39; arising from a use of `read&#39; at
&lt;interactive&gt;:1:0-7
Probable fix: add a type signature that fixes these type
variable(s)</code></pre>
<p>But specifying with a type signature or using type inference are fine:</p>
<pre><code>λ&gt; read &quot;2&quot; :: Int
→ 2
λ&gt; read &quot;2&quot; * 3
→ 6</code></pre>
<p>Another example is JSON parsing (the real class is different to this, but introduces questions that are irrelevant to the point of this post).</p>
<pre><code>class JSON a where
decode :: String -&gt; Result a</code></pre>
<p>The <code>decode</code> function is return-value polymorphic, it can be read like this:</p>
<pre><code>decode :: (JSON a) =&gt; String -&gt; Result a</code></pre>
<p>That is, it returns a result (success or fail) with a value which is an instance of the JSON class.</p>
<p>So both specifying an instance or using inference works:</p>
<pre><code>λ&gt; decode &quot;1&quot; :: Result Int
→ Ok 1
λ&gt; do x &lt;- decode &quot;1&quot;; return (x*3)
→ Ok 3</code></pre>
<p>And it works however complex you want to go with your types:</p>
<pre><code>λ&gt; decode &quot;[[1,\&quot;a\&quot;,{\&quot;x\&quot;:3}],[1,\&quot;a\&quot;,{\&quot;x\&quot;:2}]]&quot;
:: Result [(Int,String,JSObject Int)]
→ Ok [(1,&quot;a&quot;,JSONObject {fromJSObject = [(&quot;x&quot;,3)]})
,(1,&quot;a&quot;,JSONObject {fromJSObject = [(&quot;x&quot;,2)]})]</code></pre>
<p>Thus by merely specifying the return type we have effectively generated a parser. An invalid string will produce an error:</p>
<pre><code>λ&gt; decode &quot;[[1,\&quot;a\&quot;,{\&quot;x\&quot;:3}],[1,\&quot;a\&quot;]]&quot;
:: Result [(Int,String,JSObject Int)]
→ Error &quot;Unable to read Triple&quot;</code></pre>
<p>Similarly I made a URL handling library which can produce a result of a regex match on that URL:</p>
<pre><code>class RegexMatch a where
match :: [String] -&gt; Maybe a
-- | Match a URL into a value.
urlMatch :: RegexMatch match =&gt; String -&gt; Controller match
urlMatch regex = do
uri &lt;- gets controllerURI
case matchRegex (mkRegex regex) pathPart of
Just xs -&gt; case match xs of
Nothing -&gt; throw $ InvalidRegexFormat regex uri
Just x -&gt; return x
Nothing -&gt; throw $ InvalidURLFormat regex uri
where pathPart = dropWhile (==&#39;/&#39;) $ uriPath uri</code></pre>
<p>For any instances of <code>RegexMatch</code> I can say, e.g., for a tuple of <code>Int</code> and <code>Date</code>:</p>
<pre><code>do (user,date) &lt;- urlMatch &quot;([0-9]+)/(.+)$&quot;
printUserAndDate user date
…</code></pre>
<p>If the URL is <code>100/2011/08/12</code>, <code>urlMatch</code> (based on <code>match</code>) will parse, otherwise it will result in <code>InvalidURLFormat</code> — it’s the user’s fault. If the URL <em>does</em> parse, but the regex result does not match the values we expect (e.g. <code>(Int,Date)</code>) then it results in <code>InvalidRegexFormat</code> — it’s the programmer’s fault.</p>
<p>Such static value polymorphism is difficult to do in popular languages such as C#, Java, C++, without some kind of proxy objects to explicitly instantiate an object to dereference using generics or templates, and hard to do in Python, Ruby and JavaScript without static type systems.</p>
<p>The list goes on, more examples include database query results, monads, …</p>
<p>Lastly, the <code>Default</code> class is a real class and in common use today.</p>]]></description>
<pubDate>Sun, 16 Oct 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/value-polymorphism</guid>
</item>
<item>
<title>Rank-N types, a simple DB example</title>
<link>http://chrisdone.com/posts/rankntypes</link>
<description><![CDATA[<p>This is a very simple example of rank-N types to demonstrate to non-Haskellers/newbies.</p>
<p>Following the resources theme, rank-N types as seen in <a href="http://www.haskell.org/haskellwiki/Monad/ST">the ST monad</a> are also a gem:</p>
<pre><code>{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes #-}</code></pre>
<p>Define a monad for interacting with the DB parametrized on a connection type variable, <code>c</code>, as well as the return type:</p>
<pre><code>newtype DB c a = DB (IO a) deriving (Monad)</code></pre>
<p>And a connection data type parametrized on the connection type variable:</p>
<pre><code>newtype Connection c = Connection ()</code></pre>
<p>Define the connection opening function such that the quantified type variable <code>c</code> cannot escape from the DB monad:</p>
<pre><code>withConnection :: (forall c. DB c a) -&gt; IO a
withConnection m = case m of DB io -&gt; io</code></pre>
<p>Let’s say in a real implementation <code>withConnection</code> opens a database connection in a transaction and commits and closes when done, among other exception catching things.</p>
<p>Define some functions for the DB monad (note they all reference the <code>c</code> type variable):</p>
<pre><code>getConn :: DB s (Connection c)
getConn = return (Connection ())
query :: Connection c -&gt; String -&gt; DB c [String]
query _ _ = return [&quot;Hello!&quot;]</code></pre>
<p>Now we can use it like this:</p>
<pre><code>demo1 = withConnection $ do
conn &lt;- getConn
rows &lt;- query conn &quot;SELECT …&quot;
return rows
λ&gt; demo1
[&quot;Hello!&quot;]</code></pre>
<p>But if you try to return the connection…</p>
<pre><code> demo2 = withConnection $ do
conn &lt;- getConn
rows &lt;- query conn &quot;SELECT …&quot;
return conn</code></pre>
<p>You get a compile error:</p>
<pre><code>Error: Inferred type is less polymorphic than expected
Quantified type variable `c&#39; escapes</code></pre>
<p>This is pretty nice if your DB library implementation, e.g., is supposed to ensure operations on a connection run inside a transaction, or if your operations assume a connection exists. Otherwise you’re liable to having DB code run outside of a transaction, or code throwing exceptions because the connection was closed but we tried to use it anyway, or in severe cases, some C DB libraries will just segfault.</p>
<p>We didn’t have to do anything complex or write any boilerplate or macros or whatnot, just use the type system. That’s what it’s for.</p>]]></description>
<pubDate>Sun, 16 Oct 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/rankntypes</guid>
</item>
<item>
<title>Names in software systems</title>
<link>http://chrisdone.com/posts/names</link>
<description><![CDATA[<p>Another idea for another time.</p>
<p>It’s <a href="http://www.w3.org/International/questions/qa-personal-names">hard to get right internationally</a>. I would perhaps try a form like this:</p>
<pre><code>Full name: [ ]
Examples:
毛泽东
Björk Guðmundsdóttir
Christopher Smith
Isa bin Osman
María-Jose Carreño Quiñones
For correctly sorting your name amongst others, it helps us if you
can enter the parts of your name significant for searching. For
example, how would your name be sorted on a list?
Parts: [ ] [ ] [ ] [+] (in order of importance in your culture)
Examples:
[毛] [泽] [东]
[Björk] [Guðmundsdóttir]
[Smith] [Christopher]
[Isa] [Osman]
[Carreño Quiñones] [María-Jose]
How do we refer to you in correspondence?
Correspondance name: [ ]
Examples:
毛先生
Björk
Mr Smith or Christopher
Encik Isa
Señorita Carreño</code></pre>
<p>And then make this a standard (jQuery or w/e) library so I don’t have to write it ever again. You could do some limited detection and autofill with suggestions, e.g. if you detect Chinese then you can assume the order is the same, for an Englishy sounding name, you could venture reversing it. If you find [bin], [van], etc. you might consider dropping those. The more people contribute to the library, the better it can be at guessing name structure and the less work users have to do, but it still lets users tweak it to be correct.</p>]]></description>
<pubDate>Mon, 10 Oct 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/names</guid>
</item>
<item>
<title>Policy classes in Haskell</title>
<link>http://chrisdone.com/posts/policy-classes-haskell</link>
<description><![CDATA[<p>Policy classes parametrize a data type or class over polymorphic types (“policies”), allowing behaviour of the resulting composed class or function to be chosen entirely by the type.</p>
<p><a href="/code/cpp/policy-classes-languages.cpp">Here is a canonical example</a> of policy classes in C++.</p>
<p><a href="/code/hs/policy-classes-languages.hs">Here it is in Haskell</a> and <a href="/code/hs/policy-classes-languages2.hs">here is another way.</a> But these are more direct translations. A <a href="/code/hs/policy-classes-languages-idiomatic.hs">more idiomatic approach, similar to the first is here.</a></p>]]></description>
<pubDate>Mon, 05 Sep 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/policy-classes-haskell</guid>
</item>
<item>
<title>Simple JavaScript unifier</title>
<link>http://chrisdone.com/posts/js-unifier</link>
<description><![CDATA[<p>Wrote a <a href="/code/js/js-node-unifier-2011-09-05.js">simple JS unifier here</a>. Not verified correct. See test cases in <code>unify_test</code>. Also, for a laugh, <a href="/code/js/js-node-logic-2011-09-05.js">a unification-based searcher</a> a la logic languages.</p>
<p>JS is a bad language to implement such a thing, lacking algebraic types and pattern matching, among other faults.</p>]]></description>
<pubDate>Mon, 05 Sep 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/js-unifier</guid>
</item>
<item>
<title>Haskell-emacs</title>
<link>http://chrisdone.com/posts/haskell-emacs</link>
<description><![CDATA[<!-- Part 1: Introduce the topic -->
<h2 id="introduction">Introduction</h2>
<p>I am currently working on, and using, an Emacs package called <a href="https://github.com/chrisdone/haskell-emacs">haskell-emacs</a>. It is intended as an eventual general replacement for <a href="http://www.haskell.org/haskellwiki/Haskell_mode_for_Emacs">haskell-mode</a><sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup>. It won’t be released officially for a while.</p>
<!-- Part 2: Overview of the post -->
<p>I will describe my motivations and development process, the current features (with screenshots!) of this package, and the features intended for the future.</p>
<!-- Part 3: Motivations and development process -->
<h2 id="development-process">Development Process</h2>
<p>The reason for creating a new project and not patching the existing haskell-mode is that I find its codebase too disjointed and fairly messy to work with, and that it has different motivations and concerns than mine.<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup></p>
<p>My development process is threefold:</p>
<ul>
<li>Hack, hack, hack on Haskell.<sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup></li>
<li>Notice that some operation is inconvenient for my workflow.</li>
<li>Hack, hack, hack on Emacs.<sup><a href="#fn4" class="footnoteRef" id="fnref4">4</a></sup></li>
<li>Start using the new Emacs feature.</li>
</ul>
<p>It is for this reason that a lot of the features seem pointless or not so useful to other people<sup><a href="#fn5" class="footnoteRef" id="fnref5">5</a></sup>, and the project is clearly focused on my personal needs rather than general Haskellers but that doesn’t concern me too much. I’d expect there to be a substantial overlap, anyway.</p>
<!-- Part 4: Overview of feature set -->
<h2 id="overview-of-feature-set">Overview of Feature Set</h2>
<p>As a general description of the package, the main features are:</p>
<ul>
<li>A Haskell editing mode.</li>
<li>A Haskell interactive mode.</li>
<li>Support for associating open Haskell buffers<sup><a href="#fn6" class="footnoteRef" id="fnref6">6</a></sup> and interactive buffers with a common name, which are called “projects”.</li>
<li>Some awareness of Cabal files and support for cabal-dev.</li>
</ul>
<p>I will outline each of these features with example screenshots, by going from start to finish of starting a project and doing some hacking.</p>
<!-- Part 5: Starting a project -->
<h2 id="starting-a-project">Starting a project</h2>
<p>When you open a Haskell buffer or perform an action that needs a project to continue, based on the current directory and whether there’s a .cabal file in it<sup><a href="#fn7" class="footnoteRef" id="fnref7">7</a></sup>, you will be prompted to start a new project. In this case I’ve opened a file <code>~/Projects/me/amelie/src/Main.hs</code> and there is a .cabal file in <code>~/Projects/me/amelie</code>, so it infers the name of the project.</p>
<img src="/images/hs-start-project.png"/>
<p>Then it’ll prompt for the Cabal file/dir to use. It defaults to something sensible and displays why it’s sensible (i.e. it has a .cabal file).</p>
<img src="/images/hs-cabal-dir.png"/>
<p>Finally it prompts for what “load” directory to use for the interactive mode (GHCi), with some sensible default<sup><a href="#fn8" class="footnoteRef" id="fnref8">8</a></sup>.</p>
<img src="/images/hs-load-dir.png"/>
<p>Once this is set, a GHCi REPL<sup><a href="#fn9" class="footnoteRef" id="fnref9">9</a></sup> is opened. My project is now “started”, the file I originally opened is open and I have an interactive REPL buffer. Additionally, a TAGS<sup><a href="#fn10" class="footnoteRef" id="fnref10">10</a></sup> file is created based on the contents of the project.</p>
<img src="/images/hs-project-started.png"/>
<p>(Ignore the double welcome message, that’s a trivial bug I haven’t cared to fix.)</p>
<!-- Part 6: Explain the REPL -->
<h2 id="the-repl">The REPL</h2>
<p>A first test of the REPL shows a few things immediately:</p>
<ul>
<li>The prompt is merely a lambda.<sup><a href="#fn11" class="footnoteRef" id="fnref11">11</a></sup></li>
<li>Warnings are collapsed into basically nothing.<sup><a href="#fn12" class="footnoteRef" id="fnref12">12</a></sup></li>
<li>Warnings are displayed <em>before</em> the output of the expression.<sup><a href="#fn13" class="footnoteRef" id="fnref13">13</a></sup></li>
</ul>
<img src="/images/hs-repl-first-test.png"/>
<p>As mentioned previously, a TAGS file was generated when the project was started, so completion is available. The following name came from the Main.hs file.</p>
<img src="/images/hs-repl-completion.png"/>
<p>When in the REPL, if a badly typed expression is evaluated, an error buffer is raised containing the complete error message, and, if location information is available, that part of your REPL prompt is highlighted as an error.</p>
<img src="/images/hs-repl-error-demo.png"/>
<p>Hitting the <code>q</code> key closes this buffer and returns you to the REPL, with no errors listed in your REPL. You can correct your expression, and then everything is OK<sup><a href="#fn14" class="footnoteRef" id="fnref14">14</a></sup>.</p>
<img src="/images/hs-repl-error-ok.png"/>
<p>Hit <code>C-c C-k</code> to clear the REPL.</p>
<p>Regular GHCi commands can be used here:</p>
<img src="/images/hs-repl-regular-ghci-stuff.png"/>
<p>Compile errors are shrunk significantly in the REPL<sup><a href="#fn15" class="footnoteRef" id="fnref15">15</a></sup>. For example, to load a file into the REPL, hit <code>F5</code><sup><a href="#fn16" class="footnoteRef" id="fnref16">16</a></sup>. With a type error, this will be displayed in the REPL and the minibuffer<sup><a href="#fn17" class="footnoteRef" id="fnref17">17</a></sup><sup><a href="#fn18" class="footnoteRef" id="fnref18">18</a></sup>, note that the error is substantially smaller than usual GHC output:</p>
<img src="/images/hs-repl-load-error.png"/>
<p>Putting the cursor on that error line and hitting return will take you to the line and column in that file.</p>
<p>When you load a file successfully, there is no output in the REPL, merely an “OK” message in the minibuffer.</p>
<p>When you try to do something that requires an extension, GHC usually suggests which extension you need. Thanks to that, the loading feature can also prompt for you to add that extension to your file. So if I load a file that’s trying to use Typeable deriving, I get this:</p>
<img src="/images/hs-lang.png"/>
<!-- Part 7: Explain editing -->
<h2 id="editing">Editing</h2>
<h3 id="indentation">Indentation</h3>
<p>I haven’t yet added support for the various indentation modes from haskell-mode, because I don’t understand them and I don’t think they’re so great. I made a start a while ago on a set of test cases for an indentor<sup><a href="#fn19" class="footnoteRef" id="fnref19">19</a></sup>, but for now I put up with basic Emacs editing facilities. There is more work to do on this part of the project.</p>
<p><code>C-&lt;left/right&gt;</code> re-indents the whole block below the current line’s starting column. For example:</p>
<img src="/images/hs-edit-reindent-block.png"/>
<p>Now consider I rename <code>fooBar</code> to <code>foo</code>. I end up with this:</p>
<img src="/images/hs-edit-reindent-block-change-foo.png"/>
<p>In my mode, I can go to the top line and hit <code>C-&lt;left&gt;</code> thrice and it moves everything to:</p>
<img src="/images/hs-edit-reindent-block-change-foo-reindent.png"/>
<p>Without having to move the cursor at all. I’ve found this kind of feature indispensable once I have it.</p>
<h3 id="imports">Imports</h3>
<p>For an import list, e.g.</p>
<img src="/images/hs-edit-imports.png"/>
<p>it is possible to hit <code>C-c C-.</code> which alphabetically sorts those imports and spaces them out to be readable<sup><a href="#fn20" class="footnoteRef" id="fnref20">20</a></sup>:</p>
<img src="/images/hs-edit-imports-formatted.png"/>
<!-- Part 8: Explain completion -->
<h2 id="completion-and-jumping">Completion and Jumping</h2>
<p>I use <a href="http://www.emacswiki.org/emacs/AutoComplete">Auto Complete</a> for emacs for completion, and an etags module so that I can provide it with completions from a TAGS file. The TAGS file is updated when you load the project for the first time and every time you save a file<sup><a href="#fn21" class="footnoteRef" id="fnref21">21</a></sup>.</p>
<p>The sources for the completion are:</p>
<ul>
<li>Standard Haskell keywords</li>
<li>LANGUAGE modes</li>
<li>Standard functions</li>
<li>Anything from the TAGS file</li>
<li>Text from the current buffer(s)</li>
</ul>
<p>Thanks to the TAGS file, we get jumping to definition for free. Hit <code>M-.</code> to jump to the definition of the current symbol.</p>
<img src="/images/hs-edit-jump-to-def.png"/>
<p>And you will be taken to the definition of that function:</p>
<img src="/images/hs-edit-jump-to-def-jumped.png"/>
<p>Another form of completion is GHCi-based which completes when you press space after any symbol.</p>
<img src="/images/hs-edit-ghci-complete.png"/>
<p>The type appears at the bottom. This is avoids mental context switching when trying to remember the type of a function.</p>
<!-- Part 8: Cabal utilities -->
<h2 id="cabal">Cabal</h2>
<p>There is support for .cabal files (taken from the haskell-mode distribution), there is nothing interesting in this mode; it just does highlighting.</p>
<p>In any buffer, including the interactive mode or cabal file, <code>C-c C-c</code> will build the current project’s Cabal package.</p>
<img src="/images/hs-cabal-build.png"/>
<p>Notice also that the build output is substantially reduced<sup><a href="#fn22" class="footnoteRef" id="fnref22">22</a></sup>.</p>
<p><code>C-c c</code> similarly will prompt interactively for a Cabal command to run, which uses ido-mode to complete-as-you-type. These cabal commands will use <code>cabal-dev</code> if that is specified in the config previously mentioned.</p>
<img src="/images/hs-cabal-interactively.png"/>
<p>So if you choose <code>configure</code>, it will run <code>cabal configure</code>:</p>
<img src="/images/hs-cabal-configure.png"/>
<p>There is really very little that you need to outside of Emacs. I have even added a command for running non-Cabal commands, called “scripts”, which I have bound to <code>C-c t</code>:</p>
<img src="/images/hs-cabal-script.png"/>
<p>Which runs any commands, in your <code>hs-config-scripts</code> list<sup><a href="#fn23" class="footnoteRef" id="fnref23">23</a></sup>, from the project’s Cabal directory. This is useful for, e.g. restarting/refreshing services, running misc build scripts that you want to run for this particular project.</p>
<p>Further to that, it’s possible to define arbitrary commands to run in the background, for which you don’t care about the output, you just want to know when it completes, e.g., rebuilding your JavaScript or whatever. Here I am binding F5 to rebuild my JavaScript files in espresso-mode, which is Emacs’s JavaScript mode.</p>
<pre><code>(define-key espresso-mode-map (kbd &quot;&lt;f5&gt;&quot;)
&#39;(lambda ()
(interactive)
(when (buffer-modified-p)
(save-buffer))
(hs-process-background-arbitrary-command
(hs-project)
&quot;:!cd ../ &amp;&amp; scripts/client-dev-build&quot;)))</code></pre>
<!-- Part 8: Elaborate on TODO list and future work -->
<h2 id="future-work">Future Work</h2>
<p>There are many things to do in the future that are feasible for me to implement but just need doing. Some of these are:</p>
<ul>
<li>Debugger stepping support<sup><a href="#fn24" class="footnoteRef" id="fnref24">24</a></sup></li>
<li>Indentation that doesn’t suck<sup><a href="#fn25" class="footnoteRef" id="fnref25">25</a></sup></li>
<li>Syntax-highlighted REPL prompt<sup><a href="#fn26" class="footnoteRef" id="fnref26">26</a></sup></li>
<li>Show-based value inspection<sup><a href="#fn27" class="footnoteRef" id="fnref27">27</a></sup></li>
<li>Interactive creation/management of Cabal file</li>
<li>Automatic insertion of modules and Cabal dependency based on function/type use</li>
<li>Haskell-aware code-folding</li>
<li>Documentation of symbol at point</li>
<li>Hoogle search support (I want to use something like <a href="http://www.emacswiki.org/emacs/Anything">anything.el</a> for this)</li>
<li>Hayoo search support (and this)</li>
<li>Compilation on an interval</li>
<li>Put hint suggestions in build/load output after warnings</li>
<li>Ability to browse Haddock documentation inside Emacs (possibility for texinfo here)</li>
<li>Support imenu so that we can use quickbar as a browser</li>
</ul>
<p>Integration with Scion is an important aim, too. It would mean depending on GHC7+, but we all have to make that transition at some point.</p>
<p>At the top of my list right now is to use the index all of the currently installed packages and hoogle/hayoo to be able to support the automatic import and dependency insertion.</p>
<!-- Footnotes -->
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Although for me it has replaced it already and I am using it at work and home.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>The editing mode puts a lot of effort into supporting both normal Haskell and literate Haskell which makes the code a confusing mess. I don’t care about editing literate Haskell, and if I did I wouldn’t create a mode like for normal Haskell files.<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>I use Haskell at work from around 8:00-18:00 every day, so any small annoyance becomes a big annoyance and a development problem that I need to address quite quickly.<a href="#fnref3">↩</a></p></li>
<li id="fn4"><p>Depending on what I want, this can take any time between 5 minutes and a day.<a href="#fnref4">↩</a></p></li>
<li id="fn5"><p>For example, in asking Haskellers who use Emacs at <a href="http://www.haskell.org/haskellwiki/CamHac">CamHac</a>, I found that people tended not to care too much about having multiple projects, and therefore REPLs, open simultaneously, because you can just “switch projects” by loading a different file into GHCi. I don’t find this sufficient because I like my REPL history and output to be separate, and with <a href="http://hackage.haskell.org/package/cabal-dev">cabal-dev</a> it’s very important to have separate instances of GHCi.<a href="#fnref5">↩</a></p></li>
<li id="fn6"><p>For non-Emacs users, a buffer is something that a “window” can display. A “window” in Emacs is some rectangle on the screen that you can resize or remove, like windows (or “tabs”) inside Eclipse or Visual Studio or whatnot. Common buffers are files, compilation output, etc. and you display them in various windows arranged on the screen. There is no conceptual difference to popular IDEs, but the naming convention can be confusingly different.<a href="#fnref6">↩</a></p></li>
<li id="fn7"><p>I’m making an assumption here that all Haskell projects have a .cabal file. I think it’s a safe assumption to make. All useful Haskell projects eventually have a .cabal file.<a href="#fnref7">↩</a></p></li>
<li id="fn8"><p>I don’t remember at the time of writing whether this uses the src described in the .cabal file; I don’t think so, as there could be many of these entries.<a href="#fnref8">↩</a></p></li>
<li id="fn9"><p>Depending on whether you have set <code>hs-config-use-cabal-dev</code> to <code>t</code> or <code>nil</code>, it will start a cabal-dev-based GHCi process.<a href="#fnref9">↩</a></p></li>
<li id="fn10"><p>A TAGS file is an file for Emacs based on ctags for Vim, which is a list of symbols and meta data about them that your editor can use for semantic searching, jumping and completing.<a href="#fnref10">↩</a></p></li>
<li id="fn11"><p>This choice is because I want more space in my prompt, because I rarely care to see which module I’m in as it’s obvious, and because lambda is pretty.<a href="#fnref11">↩</a></p></li>
<li id="fn12"><p>This particular warning is an extreme example. I’ve come to a point personally where I just need to see the type and I know it’s a defaulting problem. I will in the future add some description to this warning message. It was intended to have, but I think at some point I forgot to do it and it didn’t bother me.<a href="#fnref12">↩</a></p></li>
<li id="fn13"><p>This is an incidental side effect, which I’ve taken to. I explain later why this happens.<a href="#fnref13">↩</a></p></li>
<li id="fn14"><p>And all your buddies viewing your REPL history will think you never make any mistakes!<a href="#fnref14">↩</a></p></li>
<li id="fn15"><p>To put things into perspective, the normal GHCi output for this action is:</p>
<pre><code>/home/chris/Projects/me/amelie/src/Main.hs:74:36:
Couldn&#39;t match expected type `Chan Text&#39;
against inferred type `Controller ()&#39;
In the first argument of `run&#39;, namely `Style.handle&#39;
In the expression: run Style.handle
In the expression: (&quot;/css/amelie.css&quot;
,run Style.handle)</code></pre>
<a href="#fnref15">↩</a></li>
<li id="fn16"><p>This is the default binding, you can set this to whatever you like.<a href="#fnref16">↩</a></p></li>
<li id="fn17"><p>The minibuffer in Emacs is just the little bit at the bottom which displays messages.<a href="#fnref17">↩</a></p></li>
<li id="fn18"><p>The reason for its display in the minibuffer is that the REPL doesn’t raise itself automatically when loading files. Maybe you don’t want it to do that. I rarely do. Often the type error in the minibuffer is sufficient for me to fix the error without having to switch buffers.<a href="#fnref18">↩</a></p></li>
<li id="fn19"><p>The current indentors, both very large and complicated modules, try to be very general, which shows, because it’s trivial to produce cases where they completely do the wrong thing with your code or go to the wrong place that you want. Half of the time it does what you want, i.e., the trivial case of stepping in or out, and the other half you’re hitting tab and going through the tab cycle. This really distracts you when trying to think.<a href="#fnref19">↩</a></p></li>
<li id="fn20"><p>I currently don’t support multi-line imports (nor will?). This encourages me not to have multi-line imports in my projects. None of them do as a result. I either import qualified, or just a few symbols. Or if <em>really</em> necessary, make another import line, one for types, one for functions. But I try to keep imports qualified if non-trivial. Nobody wants to read big import lines.<a href="#fnref20">↩</a></p></li>
<li id="fn21"><p>This is quite fast, I use this on a 15K~ line project and it’s no problem (and it is asynchronous).<a href="#fnref21">↩</a></p></li>
<li id="fn22"><p>The normal output would be:</p>
<pre><code>Preprocessing executables for amelie-0.1...
Building amelie-0.1...
[48 of 62] Compiling Amelie.Controller.Activity ( src/Amelie/Controller/Activity.hs, dist/build/amelie/amelie-tmp/Amelie/Controller/Activity.o )
[62 of 62] Compiling Main ( src/Main.hs, dist/build/amelie/amelie-tmp/Main.o )
Linking: dist/build/amelie/amelie</code></pre>
<a href="#fnref22">↩</a></li>
<li id="fn23"><p>For example, mine is:</p>
<pre><code> (setq hs-config-scripts &#39;(&quot;scripts/server-restart&quot;
&quot;../scripts/remote-refresh&quot;
&quot;../scripts/remote-update&quot;
&quot;../scripts/remote-prod&quot;
&quot;../scripts/remote-push&quot;))</code></pre>
<a href="#fnref23">↩</a></li>
<li id="fn24"><p>Alejandro Serrano demonstrated Eclipse’s support for debugger with GHCi and it looked very impressive and simple to implement. I would like to add this to Emacs because it sounds nice, I don’t think I would have much use for it as I rarely need a debugger in Haskell, but others will.<a href="#fnref24">↩</a></p></li>
<li id="fn25"><p>The current indentors, both very large and complicated modules, try to be very general, which shows, because it’s trivial to produce cases where they completely do the wrong thing with your code or go to the wrong place that you want. Half of the time it does what you want, i.e., the trivial case of stepping in or out, and the other half you’re hitting tab and going through the tab cycle. This really distracts you when trying to think.<a href="#fnref25">↩</a></p></li>
<li id="fn26"><p>I had a go at this but it font lock can be finicky when trying to have two modes in one buffer. More research is needed. Would appreciate help on this. I do have one idea for how to do it but it’s not pretty (make font lock regex aware of the prompt string).<a href="#fnref26">↩</a></p></li>
<li id="fn27"><p>I already made <a href="http://hpaste.org/raw/50518">a start on this</a> and have a parser working for Show output. Now all that’s left is to write the Elisp for inspecting these Show values.<a href="#fnref27">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Sun, 21 Aug 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/haskell-emacs</guid>
</item>
<item>
<title>Experimenting with GHCJS, the Haskell→JavaScript compiler</title>
<link>http://chrisdone.com/posts/ghcjs</link>
<description><![CDATA[<!-- Part 1: Explain what's wrong with JavaScript -->
<p>JavaScript <em>per se</em> is insufficient. The depths to which JavaScript fails is well-documented and well-understood. Its main faults are its verbose function syntax<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup>, late binding<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup>, which has led to the creation of various static analysis tools to alleviate this language flaw<sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup>, but with limited success<sup><a href="#fn4" class="footnoteRef" id="fnref4">4</a></sup> (there is even a static type checker<sup><a href="#fn5" class="footnoteRef" id="fnref5">5</a></sup>), <a href="http://stackoverflow.com/questions/5447153/javascript-equality-transitivity-is-weird/5447170#5447170">finicky equality</a>, <code>this</code> behaviour, and lack of static types and modules<sup><a href="#fn6" class="footnoteRef" id="fnref6">6</a></sup>.</p>
<!-- Part 2: Explain the ways in which we fix JavaScript -->
<p>Using JavaScript for what it is good for<sup><a href="#fn7" class="footnoteRef" id="fnref7">7</a></sup>, but not using the language <em>per se</em>, is therefore desirable, and many are working to achieve this<sup><a href="#fn8" class="footnoteRef" id="fnref8">8</a></sup>, in some form or another. There various ways to do it<sup><a href="#fn9" class="footnoteRef" id="fnref9">9</a></sup>, but I will opt for compiling an existing language, Haskell, to JavaScript, because I do not have time to learn or teach other people a new language, garner a new library set and a new type checker and all that Haskell implementations provide.</p>
<!-- Part 3: Explain compiler choice -->
<p>Given the option, I’d choose <a href="http://www.haskell.org/ghc/">GHC</a> because it is the flagship Haskell compiler, with <a href="http://www.haskell.org/ghc/docs/latest/html/users_guide/ghc-language-features.html">the most features</a>, which most Haskellers write all their projects with. Haskell has a standard, <a href="http://www.haskell.org/pipermail/haskell/2009-November/021750.html">presently Haskell 2010</a>, but I think that most projects out there use quite a few language extensions<sup><a href="#fn10" class="footnoteRef" id="fnref10">10</a></sup> outside of the standard; Haskellers target GHC. This is not to say that for compiling to JS, Haskell 98 wouldn’t be a vast improvement.</p>
<!-- Part 4: Introduce GHCJS -->
<p>Fortunately there is a project maintained by <a href="http://asviraspossible.livejournal.com/">Victor Nazarov</a> called <a href="https://github.com/sviperll/ghcjs">GHCJS</a>. You can use GHC 6.12.3 or GHC 7+. For my experimentation I am using 6.12.3. I followed <a href="https://github.com/sviperll/ghcjs/blob/master/README.markdown">the instructions given</a>, with a fix for the build process<sup><a href="#fn11" class="footnoteRef" id="fnref11">11</a></sup>, and some tweaks to the libraries<sup><a href="#fn12" class="footnoteRef" id="fnref12">12</a></sup>. In order to build the libraries and copy them to the <code>examples/</code> directory, I wrote a little script<sup><a href="#fn13" class="footnoteRef" id="fnref13">13</a></sup>, which helps automate this. There is also <code>BuildTest.hs</code> in the <code>examples/</code> dir which gentle reader should try first.</p>
<!-- Part 5: First GHCJS example -->
<p>After much twiddling and fudging with the example file and the provided FFI, some help from Victor Nazarov, with some trial and error, I managed to get some fundamental things working that are necessary to be able to write effectively in the JavaScript environment<sup><a href="#fn14" class="footnoteRef" id="fnref14">14</a></sup>. Timers work (and AJAX requests will), but <a href="http://hpaste.org/50477#line128">this example</a> is merely a clickable blank page which alerts “‘Ello, World!”. Uninteresting functionally, but a good test of the fundamentals (see the pasted Haskell source).</p>
<!-- Part 6: Where next -->
<p>Next up, I will write a simple pong game<sup><a href="#fn15" class="footnoteRef" id="fnref15">15</a></sup> to test integration with the canvas element and speed of the runtime and establish some sort of base library and project template from which other Haskellers can more easily experiment. Perhaps we could even have in the future a browser-based IDE and compiler which can of course run the compiled code in the user’s browser. That would be nice.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Its support for closures is commonly noted as being one of JavaScript’s redeeming features.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>Early binding allows for static verification of the existence of method-signature pairs (e.g. v-tables). Late binding does not give the compiler (or an IDE) enough information for existence verification, it has to be looked up at run-time.<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>There are several hinting libraries, which developers insist are indispensable tools when developing JavaScript seriously, such as <a href="http://www.javascriptlint.com/">JavaScript lint</a>, <a href="http://www.jslint.com/">JSLint</a>, and <a href="http://aurochs.fr/jsure.html">JSure</a>.<a href="#fnref3">↩</a></p></li>
<li id="fn4"><p>“Any non-trivial analysis is very difficult due to Javascript’s dynamic nature.” — Berke Durak, Ph.D., author of jsure.<a href="#fnref4">↩</a></p></li>
<li id="fn5"><p>Google Inc. thought it necessary to develop <a href="http://code.google.com/closure/compiler/">a compiler which does type-checking and limited inference</a>, e.g.</p>
<pre><code>/**
* Queries a Baz for items.
* @param {number} groupNum Subgroup id to query.
* @param {string|number|null} term An itemName,
* or itemId, or null to search everything.
*/
goog.Baz.prototype.query = function(groupNum, term) {
...
};</code></pre>
<p>This will ensure that invocations to <code>Bad.query()</code> will be well-typed. See the <a href="http://code.google.com/closure/compiler/docs/js-for-compiler.html">Google closure docs</a> for more examples. Developers I’ve spoken to at Google say this makes JS bearable with sufficient self-discipline, but without it, maintaining a large codebase in JS is unrealistic.<a href="#fnref5">↩</a></p></li>
<li id="fn6"><p>A <a href="http://www.google.com/search?aq=f&amp;sourceid=chrome&amp;ie=UTF-8&amp;q=javascript+module+system">quick Google search</a> demonstrates easily enough that there is a need for a module system.<a href="#fnref6">↩</a></p></li>
<li id="fn7"><p>It is established that JavaScript is now a target platform due to its browser ubiquity. If we want to write tools, applications, games, etc. that will reach a wide audience with little effort on the user’s part, targetting the browser and therefore JavaScript is an excellent option.<a href="#fnref7">↩</a></p></li>
<li id="fn8"><p>There are already many projects underway for doing this, such as <a href="http://pyjs.org/">Pyjamas</a>, <a href="http://hotruby.yukoba.jp/">HotRuby</a>, <a href="http://ejohn.org/blog/running-java-in-javascript/">Orto</a>, <a href="http://www.zkoss.org/">ZK</a>, and <a href="https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS">many which merely provide a layer ontop of JavaScript</a> to make using it marginally less painful. Some Haskell ones include <a href="http://utrechthaskellcompiler.wordpress.com/2010/10/18/haskell-to-javascript-backend/">UHC</a>, <a href="http://www.haskell.org/haskellwiki/Yhc/Javascript">YHC</a>, <a href="http://code.google.com/p/jshaskell/">jshaskell</a> and <a href="https://github.com/valderman/lambdascript">lambdascript</a>.<a href="#fnref8">↩</a></p></li>
<li id="fn9"><p>Some ways that I see are:</p>
<ul>
<li>Write JavaScript with a functional/OO/“better” standard library, a la <a href="https://github.com/runarorama/LambdaScript">LambdaScript</a> or <a href="http://www.commonjs.org/">CommonJS</a>.</li>
<li>Write JavaScript with additional tools to provide static semantics (a la Google Closure).</li>
<li>Write JavaScript in an EDSL in another more powerful language, e.g. <a href="http://common-lisp.net/project/parenscript/">ParenScript</a> and <a href="http://hackage.haskell.org/package/HJScript">HJScript</a>.</li>
<li>Create a new language that mostly preserves JavaScript semantics but adds some additional layer, e.g. <a href="http://jashkenas.github.com/coffee-script/">CoffeeScript</a>.</li>
<li>Interpret an existing language in JavaScript.</li>
<li>Compile an existing language to JavaScript.</li>
</ul>
<p>I prefer the last option.<a href="#fnref9">↩</a></p></li>
<li id="fn10"><p>To put it in perspective, here are the extensions available in GHC as of 6.12.3: OverlappingInstances NoOverlappingInstances, IncoherentInstances, NoIncoherentInstances UndecidableInstances, NoUndecidableInstances, Arrows, NoArrows DisambiguateRecordFields, NoDisambiguateRecordFields ForeignFunctionInterface, NoForeignFunctionInterface, Generics NoGenerics, ImplicitParams, NoImplicitParams, NoImplicitPrelude ImplicitPrelude, NoMonomorphismRestriction, MonomorphismRrestriction NoNPlusKPatterns, NPlusKPatterns, NoMonoPatBinds, MonoPatBinds RelaxedPolyRec, NoRelaxedPolyRec, ExtendedDefaultRules NoExtendedDefaultRules, OverloadedStrings, NoOverloadedStrings, GADTs NoGADTs, TypeFamilies, NoTypeFamilies, ScopedTypeVariables NoScopedTypeVariables, MonoLocalBinds, NoMonoLocalBinds, TemplateHaskell NoTemplateHaskell, QuasiQuotes, NoQuasiQuotes, BangPatterns NoBangPatterns, CPP, NoCPP, PatternGuards, NoPatternGuards, ViewPatterns NoViewPatterns, UnicodeSyntax, NoUnicodeSyntax, MagicHash, NoMagicHash NewQualifiedOperators, NoNewQualifiedOperators, ExplicitForALl NoExplicitForAll, PolymorphicComponents, NoPolymorphicComponents Rank2Types, NoRank2Types, RankNTypes, NoRankNTypes, ImpredicativeTypes NoImpredicativeTypes, ExistentialQuantification NoExistentialQuantification, KindSignatures, NoKindSignatures EmptyDataDecls, NoEmptyDataDecls, ParallelListComp, NoParallelListComp TransformListComp, NoTransformListComp, UnliftedFFITypes NoUnliftedFFITypes, LiberalTypeSynonyms, NoLiberalTypeSynonyms TypeOperators, NoTypeOperators, DoRec, NoDoRec, RecursiveDo, NoRecursiveDo PArr, NoPArr, RecordWildCards, NoRecordWildCards, NamedFieldPuns NoNamedFieldPuns, DisambiguateRecordFields, NoDisambiguateRecordFields UnboxedTuples, NoUnboxedTuples, StandaloneDeriving, NoStandaloneDeriving DeriveDataTypeable, NoDeriveDataTypeable, GeneralizedNewtypeDeriving NoGeneralizedNewtypeDeriving, TypeSynonymInstances NoTypeSynonymInstances, FlexibleContexts, NoFlexibleContexts FlexibleInstances, NoFlexibleInstances, ConstrainedClassMethods NoConstrainedClassMethods, MultiParamTypeClasses NoMultiParamTypeClasses, FunctionalDependencies NoFunctionalDependencies, PackageImports, and NoPackageImports.<a href="#fnref10">↩</a></p></li>
<li id="fn11"><p>On Ubuntu, I had to explicitly add -pthread to the build configuration of libraries/unix, otherwise it didn’t figure it out automatically.<a href="#fnref11">↩</a></p></li>
<li id="fn12"><p>There were maybe 5 <code>foo#</code> shaped functions that were out of scope throughout the base libraries, particularly in GHC. I simply replaced these with <code>undefined</code>, or because that’s not available, <code>let a = a in a</code>, or whatever bottom value to stop it complaining. I don’t know whether GHC will detect <code>let a = a in a</code>, I think it does. So the runtime will just throw an exception on these values.</p>
<pre><code> chris@cn-done:~$ cat &gt; loop.hs
main = putStrLn $ let r = r in r
chris@cn-done:~$ ghc --make loop.hs -O2
[1 of 1] Compiling Main ( loop.hs, loop.o )
Linking loop ...
chris@cn-done:~$ ./loop
loop: &lt;&lt;loop&gt;&gt;</code></pre>
<p>Looks OK.<a href="#fnref12">↩</a></p></li>
<li id="fn13"><p>I called it <code>ghcjs_buildlibs</code>, and run it from the <code>ghc-6.12.3</code> directory. I think it should work fine for GHC 7, too.</p>
<pre><code> JSDIR=$1
cd libraries/ghc-prim &amp;&amp;
echo cding to libraries/ghc-prim &amp;&amp;
ghcjs -odir $JSDIR/ghc-prim \
-hidir $JSDIR/ghc-prim \
-cpp -fglasgow-exts \
-package-name ghc-prim \
GHC/Types.hs &amp;&amp;
ghcjs -odir $JSDIR/ghc-prim \
-hidir $JSDIR/ghc-prim \
-cpp -fglasgow-exts \
-package-name ghc-prim \
GHC/* &amp;&amp;
cd ../.. &amp;&amp;
echo cding to ../.. &amp;&amp;
cd libraries/integer-simple &amp;&amp;
echo cding to libraries/integer-simple &amp;&amp;
ghcjs -odir $JSDIR/integer-simple \
-hidir $JSDIR/integer-simple \
-cpp -fglasgow-exts \
-package-name integer-simple \
GHC/Integer.hs &amp;&amp;
cd ../.. &amp;&amp;
echo cding to ../.. &amp;&amp;
cd libraries/base &amp;&amp;
echo cding to libraries/base &amp;&amp;
ghcjs -odir $JSDIR/base -hidir $JSDIR/base \
-hide-package base \
-package-name base \
-I./include \
-i./dist-install/build -XMagicHash \
-XExistentialQuantification \
-XRank2Types -XScopedTypeVariables \
-XUnboxedTuples -XForeignFunctionInterface \
-XUnliftedFFITypes -XDeriveDataTypeable \
-XGeneralizedNewtypeDeriving -XFlexibleInstances \
-XStandaloneDeriving -XPatternGuards \
-XEmptyDataDecls -XNoImplicitPrelude -XCPP \
Prelude.hs &amp;&amp;
echo &quot;Copying lib to main ...&quot; &amp;&amp;
cp $1/ghc-prim/GHC \
$1/../main/ -R &amp;&amp;
cp $1/integer-simple/GHC/ \
$1/../main/ -R &amp;&amp;
cp $1/base/* \
$1/../main/ -R</code></pre>
<a href="#fnref13">↩</a></li>
<li id="fn14"><p>I.e. a way to use closure callbacks for e.g. setInterval/setTimeout and AJAX, a way to serialize data structures like strings and arrays from/to Haskell and JavaScript, and a way to access the DOM and bind events to it.<a href="#fnref14">↩</a></p></li>
<li id="fn15"><p>Pong is a good demo. I’ve already started work on this, but hit some walls when trying to separate the build into a more generic and less example-y structure. It’s quite easy to break this system at present.<a href="#fnref15">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Sat, 20 Aug 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/ghcjs</guid>
</item>
<item>
<title>Flo: Generate flow diagrams from your codebase using annotations</title>
<link>http://chrisdone.com/posts/flo-flow-diagrams-from-your-codebase</link>
<description><![CDATA[<p>After discussing the idea with my colleague I thought it would be a nice idea if you could annotate your source code in comments and from that produce a flow diagram. I whipped up a proof of concept in Haskell.</p>
<p>For an example <a href="https://github.com/chrisdone/amelie/commit/d80da7c59514c5cbb279ea99c7c5921d9a2f3ec3">I’ve annotated the hpaste.org codebase.</a></p>
<p><a href="http://i.imgur.com/Va8Xo.png">The output</a> is quite nice. I produced it with this command line:</p>
<pre><code>$ cd src
$ find -name &#39;*.hs&#39; | xargs flo &#39;-hs=-- @ &#39; | dot -Tpng &gt; amelie.png</code></pre>
<p>I uploaded it <a href="http://hackage.haskell.org/package/flo">to hackage</a> and I have <a href="http://github.com/chrisdone/flo">a Github project here</a>.</p>
<p>Give it a try.</p>]]></description>
<pubDate>Sun, 07 Aug 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/flo-flow-diagrams-from-your-codebase</guid>
</item>
<item>
<title>Step-wise evaluation of simple Haskell code to hpaste (via Stepeval)</title>
<link>http://chrisdone.com/posts/stepeval-hpaste</link>
<description><![CDATA[<p>I recently discovered <a href="https://github.com/benmachine/stepeval">stepeval</a>, a program (and now library since I patched it) written by <a href="https://github.com/benmachine">Ben Millwood</a> for evaluating simple Haskell expressions step-wise, from a simple Prelude<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup>. <a href="https://github.com/chrisdone/stepeval">In my fork</a>, I merely <a href="https://github.com/chrisdone/stepeval/commit/efe3f7de2664f080d7c8e7edced32d25a09cebe8">add a Library interface and rename the hierarchy</a> to <code>Language.Haskell.Stepeval</code>. See <a href="http://www.srcf.ucam.org/~bm380/cgi-bin/stepeval.cgi">the example web service of stepeval here</a>. For example, try <code>tail (map (const 'z') &quot;ab&quot;)</code>.</p>
<p>I thought this library was a really neat idea. Especially given that I’d recently read in <a href="http://www.cse.unsw.edu.au/~chak/papers/CK02a.html">The Risks and Benefits of Teaching Purely Functional Programming in First Year</a>, the claim that being able to evaluate Haskell code stepwise is a useful teaching tool following nicely into equational reasoning, correctness proof and derivation.<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup></p>
<p>I added it to <a href="http://hpaste.org/">hpaste</a>, <a href="http://hpaste.org/steps/48627?expr=droprev+%22ab%22&amp;submit=Submit">here is an example.</a> I added <a href="http://hpaste.org/stepeval">an “about” page</a> to explain what library I’m using and display the current Prelude. Any Haskell paste will display a “Steps” link at the top right, which allows one to run an expression given the source paste. Another nice example a la <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_thm_1.10">SICP</a> order of growth demonstration is <a href="http://hpaste.org/steps/48629?expr=a+1+2&amp;submit=Submit">ackermann</a>.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p><a href="https://github.com/benmachine/stepeval">The README of the stepeval Github project explains</a>: “stepeval is a tool that can operate as a command-line utility or CGI script. In either case, it is given a Haskell expression in string form, applies a single evaluation operation (e.g. pattern matching, lambda application), and prints the result, while also feeding it back into its evaluation mechanism until the expression cannot be evaluated any further, or in the case of the CGI script a time limit has expired.”<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>Manuel M. T. Chakravarty and Gabriele Keller write, p4: “As already mentioned, the clean semantics of functional languages leads to a good integration of the teaching of programming techniques with computing concepts and theory. For example, we encourage students from the start to get a feeling for what a program does by way of stepwise evaluation of expressions on a piece of paper. This neatly provides a starting point for the introduction of equational reasoning by performing stepwise evaluation on expressions that are not closed, which brings us to correctness proofs and program derivation. In our opinion, this is signicantly [sic] easier to motivate and implement than the calculus of weakest preconditions or the Hoare calculus that would be the corresponding theory for imperative languages.”<a href="#fnref2">↩</a></p></li>
</ol>
</div>]]></description>
<pubDate>Sat, 02 Jul 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/stepeval-hpaste</guid>
</item>
<item>
<title>Some insights from The Mythical Man Month starting from Chapter 11</title>
<link>http://chrisdone.com/posts/the-mythical-man-month-insights</link>
<description><![CDATA[<p>I recently read <a href="http://en.wikipedia.org/wiki/The_Mythical_Man-Month">The Mythical Man Month</a>, a classic book about software development.</p>
<p>I thought this quote was tres amusant:</p>
<blockquote>
<p>“The Bible of Software Engineering”, because, “everybody quotes it, some people read it, and a few people go by it.”</p>
</blockquote>
<p>In my reading of the book, around chapter 11, “Plan to Throw One Away”, I got the idea to annotate and underline sentences and paragraphs that ringed true with my experience or that I thought were insights that I and everyone should take into account.</p>
<p>Now that I’ve finished it, I thought I’d jot those points, that I felt the need to underscore, here. Flicking back through the earlier chapters there are lots of other points I ought to underscore, but that’s for another time.</p>
<p>I often see or participate in debates about software development that are better summed up by many clear insights from <em>MMM</em>, so it’s good for me to jot them down; having a common vocabulary and literature avoids a bunch of redundant discussion. For example, I saw some rather odd posts to Reddit’s programming section with laboured gardening and writing analogies.</p>
<p>I’m not sure what the legality of typing up so much of a book is. There is a lot more context to each of the points below, so you really need <a href="http://www.amazon.com/gp/reader/0201835959">the book</a> anyway to fully grok everything covered. Many points in the book may or may not have been underscored depending on the availability of a pen at the time, and I miss out the first ten chapters. Others downright do not make sense without the context which I don’t feel comfortable in further quoting verbatim.</p>
<p>At any rate, most of the quotes below have been quoted verbatim elsewhere.</p>
<h2 id="plan-to-throw-one-away">Plan to Throw One Away</h2>
<h3 id="pilot-plants-and-scaling-up">Pilot Plants and Scaling Up</h3>
<ul>
<li>“Programming system builders have also been exposed to this lesson, but it seems to have not yet been learned. Project after project designs a set of algorithms and then plunges into construction of customer-deliverable software on a schedule that demands delivery of the first thing built.”</li>
<li>“In most projects, the first system built is barely usable. It may be too slow, too big, awkward to use, or all three.”</li>
<li>“The discard and redesign may be done in one lump, or it may be done piece-by-piece. But all large-system experience shows that it will be done.”</li>
<li>“The management question, therefore, is not <em>whether</em> to build a pilot system and throw it away. You <em>will</em> do that. The only question is whether to plan in advance to build a throwaway, or to promise to deliver the throwaway to customers.”</li>
<li>“Hence <em>plan to throw one away; you will, anyhow.</em>”</li>
</ul>
<h3 id="the-only-constancy-is-change-itself">The Only Constancy is Change Itself</h3>
<ul>
<li>“But the very existence of a tangible object serves to contain and quantize user demand for changes.”</li>
<li>“Clearly a threshold has to be established, and it must get higher and higher as development proceeds, or no product ever appears.”</li>
<li>“The throw-one-away concept is itself just an acceptance of the fact that as one learns, he changes the design.”</li>
</ul>
<h3 id="plan-the-system-for-change">Plan the System for Change</h3>
<ul>
<li>“Most important is the use of a high-level language and self-documenting techniques so as to reduce errors induced by changes. Using compile-time operations to incorporate standard declarations helps powerfully in making changes.”</li>
<li>“Every product should have numbered versions, and each version must have its own schedule and a freeze date, after which changes go into the next version.”</li>
</ul>
<h3 id="plan-the-organization-for-change">Plan the Organization for Change</h3>
<ul>
<li>“[…] the reluctance to document designs is not due merely to laziness or time pressure. Instead it comes from the designer’s reluctance to commit himself to the defense of decisions which he knows to be tentative.”</li>
<li>“[M]anagers themselves often think of senior people as ‘too valuable’ to use for actual programming.”</li>
</ul>
<h3 id="two-steps-forward-and-one-step-back">Two Steps Forward and One Step Back</h3>
<ul>
<li>“The fundamental problem with program maintenance is that fixing a defect has a substantial (20-50 percent) chance of introducing another. So the whole process is two steps forward and one step back.”</li>
<li>“If fact it often has system-wide ramifications, usually nonobvious. […] the far-reaching effects of the repair will be overlooked.”</li>
<li>“Clearly, methods of designing programs so as to eliminate or at least illuminate side effects can have an immense payoff in maintenance costs. So can methods of implementing designs with fewer people, fewer interfaces, and hence fewer bugs.”</li>
</ul>
<h3 id="one-step-forward-and-one-step-back">One Step Forward and One Step Back</h3>
<ul>
<li>“Soon or later the fixing ceases to gain any ground. Each forward step is matched by a backward one. Although in principle usable forever, the system has worn out as a base for progress.”</li>
<li>“A brand-new, from-the-ground-up redesign is necessary.”</li>
<li>“Systems program building is an entropy-decreasing process, hence inherently metastable. Program maintenance is an entropy-increasing process, and even its most skillful execution only delays the subsidence of the system into unfixable obsolescence.”</li>
</ul>
<h2 id="sharp-tools">Sharp Tools</h2>
<ul>
<li>“A good workman is known by his tools.” (proverb)</li>
</ul>
<h3 id="high-level-language-and-interactive-programming">High-level Language and Interactive Programming</h3>
<ul>
<li>“I cannot easily conceive of a programming system I would build in assembly language.”</li>
</ul>
<h2 id="the-other-face">The other face</h2>
<h3 id="self-documenting-programs">Self-Documenting Programs</h3>
<ul>
<li>(An almost meta-quote here considering the context of this post) “Refer to standard literature to document basic algorithms wherever possible. This saves space, usually points to a much fuller treatment than one would provide, and allows the knowledgeable reader to skip it with confidence that he understands you.”</li>
</ul>
<h2 id="no-silver-bullet">No Silver Bullet</h2>
<h3 id="does-it-have-to-be-hardessential-difficulties">Does It Have to Be Hard?—Essential difficulties</h3>
<ul>
<li>“First, we must observe that the anomaly is not that software progress is so slow, but that computer hardware progress is so fast.”</li>
<li>“No other technology since civilization began has seen six orders of magnitude price-performance gain in 30 years.”</li>
<li>“Second, to see what rate of progress we can expect in software technology, let us examine its difficulties. Following Aristotle, I divide them into <em>essense</em>—the difficulties inherent in the nature of the software—and <em>accidents</em>—those difficulties that today attend its production but that are not inherent.”</li>
<li>“I believe the hard part of building software to be the specification, design and testing of this conceptual construct, not the labour of representing it and testing the fidelity of the representation. […] If this is true, building software will always be hard. There is inherently no silver bullet.”</li>
</ul>
<h3 id="complexity">Complexity</h3>
<ul>
<li>“Software entities are more complex for their size than perhaps any other human construct, because no two parts are alike (at least above the statement level). If they are, we make the two similar parts into one, a subroutine, open or closed. In this respect software systems differ profoundly from computers, buildings, automobiles, where repeated elements abound.”</li>
<li>“Digital computers are themselves more complex than most things people build; they have very large numbers of states. This makes conceiving, describing, and testing them hard. Software systems have orders of magnitude more states than computers do.”</li>
</ul>
<p>Below; functional programming springs to mind:</p>
<ul>
<li>“From the complexity comes the difficulty of enumerating, much less understanding, all the possible states of the program, and from that comes the unreliability.”</li>
<li><p>“From complexity of structure comes the difficulty of extending programs to new functions without creating side effects. From complexity of structure comes the unvisualized states that constitute security trapdoors.”</p></li>
<li>“The physicist labors on, however, in a firm faith that there are unifying principles to be found […] because God is not capricious or arbitrary. No such faith comforts the software engineer.”</li>
<li>“[…] not because of necessity but only because they were designed by different people, rather than God.”</li>
<li>“Partly this is because the software in a system embodies its function, and the function is the part that most feels the pressures of change. Partly it is because software can be changed more easily—it is pure thought-stuff, infinitely malleable.”</li>
<li>“All successful software gets changed. Two processes are at work. As a software product is found to be useful, people try it in new cases at the edge of, or beyond, the original domain. The pressures for extended function come chiefly from users who like the basic function and invent new uses for it.”</li>
<li><p>“As soon as we attempt to diagram software, we find it to constitute not one, but several, general directed graphs, superimposed on one another.”</p></li>
</ul>
<p>I think the below is a very interesting point; having a visual mind does not seem to help you in programming.</p>
<ul>
<li>“In spite of progress in restricting and simplifying the structures of software, they remain inherently unvisualizable, thus depriving the mind of some of its most powerful conceptual tools.”</li>
</ul>
<p>Which follows nicely into the next point I underscored a page later:</p>
<h3 id="graphical-programming">Graphical programming</h3>
<ul>
<li>“Nothing even convincing, much less exciting, has yet emerged from such efforts. I am persuaded that nothing will.”</li>
</ul>
<h3 id="program-verification">Program verification</h3>
<ul>
<li>“Program verification does not mean error-proof programs. There is no magic here, either. Mathematical proofs also can be faulty. So whereas verification might reduce the program-testing load, it cannot eliminate it.”</li>
<li>“More seriously, even perfect program verification can only establish that a program meets its specification. The hardest part of the software task is arriving at a complete and consistent specification, and much of the essence of building a program is in fact the debugging of the specification.”</li>
</ul>
<h3 id="environments-and-tools">Environments and tools</h3>
<p>One point that reminded me of <a href="http://erlang.org/pipermail/erlang-questions/2011-May/058769.html">a recent post by Joe Armstrong to the Erlang mailing list</a>:</p>
<ul>
<li>“Perhaps the biggest gain yet to be realized in the programming environment is the use of integrated database systems to keep track of the myriads of details that must be recalled accurately by the individual programmer and kept current in a group of collaborators on a single system.”</li>
</ul>
<p>(And I don’t think ‘intellisense’ really covers it.)</p>
<h3 id="promising-attacks-on-the-conceptual-essense">Promising Attacks on the Conceptual Essense</h3>
<p>I found this to be a very interesting perspective considering the era in which it was written:</p>
<ul>
<li>“There are dramatic exceptions to my argument that the generalization of the software packages has changed little over the years: electronic spreadsheets and simple database systems. These powerful tools, <strong>so obvious in retrospect and yet so late appearing</strong> [bold added for emphasis], lend themselves to myriad uses, some quite unorthodox.”</li>
</ul>
<h3 id="incremental-development-grow-not-build-software">Incremental development — grow, not build, software</h3>
<ul>
<li>“Some years ago, Harlan Mills proposed that any software system should be grown by incremental development. That is, the system should first be made to run, even though it does nothing useful except call the proper set of dummy subprograms. Then, bit by bit it is fleshed out, with the subprograms in turn being developed into actions or calls to empty stubs in the level below.”</li>
<li>“The morale effects are startling. Enthusiasm jumps when there is a running system, even a simple one.”</li>
<li>“I find that teams can <em>grow</em> much more complex entities in four months than they can <em>build</em>.” (Yes, I see the gardener analogy here, but <em>please</em>.)</li>
</ul>
<h3 id="great-designers">Great designers</h3>
<ul>
<li>“I think the most important single effort we can mount is to develop ways to grow great designers.”</li>
</ul>
<p>There is a lot more crammed in this book, some several more chapters. But I’ll stop here.</p>]]></description>
<pubDate>Sun, 26 Jun 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/the-mythical-man-month-insights</guid>
</item>
<item>
<title>Haskell site design</title>
<link>http://chrisdone.com/posts/haskell-design</link>
<description><![CDATA[<p>Just messing about, here’s <a href="http://chrisdone.com/designs/haskell/">a Haskell.org design I whipped up</a>.</p>
<p>I always thought Haskell deserved a simple, elegant home page. Unfortunately I can’t do either of those things very well, but that’s the idea.</p>
<p>I was thinking what the target market for Haskell.org is, and I think it’s people who have never heard of Haskell. Haskell programmers, as far as I’m aware, don’t go on Haskell.org directly. They go on the Wiki, or Hackage, and get updates via the mailing list.</p>
<p>But most programmers in the whole world have probably never heard of Haskell, or don’t know what it is. Most programmers I meet and talk to ask me what it is. So, Haskellers don’t actually visit the home page, or, at least, it doesn’t matter much what they see; Haskell.org is purely for newbies, fresh faces who have never seen Haskell, ever.</p>
<p>So I wondered about what I as a newbie like to see on a programming language home page, and what I came up with was:</p>
<ul>
<li>Examples and a way to try it; see it in action. I don’t care about buzzwords and claims (fast? scalable? robust? meaningless to me at this point).</li>
<li>I want to see what kind of language it is (imperative? strict? object oriented?) in a list of points.</li>
<li>Where I can get it and</li>
<li>how I can learn it, and</li>
<li>who to talk to while I’m learning it.</li>
<li>I also want to know it’s not dead. So I put the events there.</li>
</ul>
<p>Also good would be to put a list of sponsors and businesses using or backing that language (e.g. Galois, Well-Typed, Microsoft).</p>
<p>A list of projects using it would also be something I’d be interested in.</p>
<p>I also figured, if it’s basically an advertisement of the language, <em>why not</em> have it all spaced out and self-indulgent? It sort of says, we care about you using our language and we put effort into doing things right and being professional.</p>
<p>Anyway, the current home page does the job fine so it will probably stay like that forever until we switch technologies or something. I just like to experiment with designs. Back to programming in it!</p>]]></description>
<pubDate>Sat, 25 Jun 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/haskell-design</guid>
</item>
<item>
<title>PostgreSQL, hpaste, and EDSLs</title>
<link>http://chrisdone.com/posts/postgres-hpaste-edsls</link>
<description><![CDATA[<p>I’m nearing the end of a four day hacking weekend, starting at the 2nd of June, thanks to the Festa della Repubblica in Italy.</p>
<p>Since then I’ve hacked on some things.</p>
<h1 id="pgsql-simple">pgsql-simple</h1>
<p>I started dabbling with writing pure Haskell bindings to PostgreSQL a few weeks ago and this weekend I decided I’ve give it a real API. While thinking of how I wanted the API to be, I saw that Bryan O’Sullivan announced <a href="http://www.haskell.org/pipermail/haskell-cafe/2011-May/091538.html">mysql-simple</a>, a fast and easy to use library for working with MySQL. I liked the API as it resembled my prototype, and so he proposed we use a consistent API.</p>
<p>So I gutted mysql-simple and replaced the MySQL bits with my PostgreSQL library. <a href="https://github.com/chrisdone/pgsql-simple">The result of that is here.</a></p>
<p>And by Jove, it works!</p>
<p>What I particularly like about Bryan’s API is that serialization to and from the database is not bidirectional; there are two classes, <code>Param</code> and <code>Result</code>, because sometimes you have data that should be written to the database, but never read, or vise-versa. I have this same problem with Text.JSON, but that’s a different bucket of squid.</p>
<h1 id="hpaste">hpaste</h1>
<p>I thought I’d test out my new library with a simple web application, hpaste.org. My existing codebase for it needing rewriting anyway <a href="http://en.wikipedia.org/wiki/The_Mythical_Man-Month#The_pilot_system">“Plan to throw one away.”</a></p>
<p>The new one in development is <a href="https://github.com/chrisdone/amelie">here</a>.</p>
<p>I also figured I’d try out Snap and move away from FastCGI because it’s a bit clunky.</p>
<p>I also thought I’d try out using <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">the Model-View-Controller pattern</a> properly from the start.</p>
<p>The main entry point to the web site is the Snap router, then I pass everything onto the appropriate controller with a database connection pool. The pool just maintains a list of open DB connections to avoid the overhead of reconnecting.</p>
<pre><code>import Database.PostgreSQL.Simple (Pool,newPool)
-- | Main entry point.
main :: IO ()
main = do
p &lt;- newPool auth
setUnicodeLocale &quot;en_US&quot;
httpServe config (serve p)
where config = addListen (ListenHttp &quot;0.0.0.0&quot; 10000) defaultConfig
-- | Serve the controllers.
serve :: Pool -&gt; Snap ()
serve p = route routes where
routes = [(&quot;/css/amelie.css&quot;, run Style.handle)
,(&quot;/js/amelie.js&quot;, run Script.handle)
,(&quot;/css/&quot;,serveDirectory &quot;wwwroot/css&quot;)
,(&quot;/js/&quot;,serveDirectory &quot;wwwroot/js&quot;)
,(&quot;&quot;,run Home.handle)
,(&quot;/:id&quot;,run Paste.handle)
]
run = runHandler p</code></pre>
<h2 id="mvc">MVC</h2>
<p>First I came up with some <a href="https://github.com/chrisdone/amelie/blob/master/src/Amelie/Types/MVC.hs">types for the controller and model</a>. I wanted the following properties:</p>
<ul>
<li>The controller can request things of the model, do IO, and do web request stuff.</li>
<li>The model can talk to the database, and do arbitrary IO, but cannot call the controller or do web request stuff (no redirecting, no header passing, etc.)</li>
<li>The view can only take data provided to it by the controller and output text.</li>
</ul>
<p>Thus spake the Haskell source:</p>
<pre><code>-- | The state accessible to the controller (DB/session stuff).
data ControllerState = ControllerState {
controllerStateConn :: Connection
}
-- | The controller monad.
newtype Controller a = Controller {
runController :: ReaderT ControllerState Snap a
} deriving (Monad
,Functor
,Applicative
,Alternative
,MonadReader ControllerState
,MonadSnap
,MonadIO
,MonadPlus
,MonadCatchIO)</code></pre>
<p>There’s my controller. And my model:</p>
<pre><code>-- | The state accessible to the model (just DB connection).
data ModelState = ModelState {
modelStateConn :: Connection
}
-- | The model monad (limited access to IO, only DB access).
newtype Model a = Model {
runModel :: ReaderT ModelState IO a
} deriving (Monad,Functor,Applicative,MonadReader ModelState)</code></pre>
<p>The controller has the connection in its environment, but it cannot use it directly. The model does that.</p>
<h3 id="the-controller">The Controller</h3>
<p>So, for example, I have <a href="https://github.com/chrisdone/amelie/blob/master/src/Amelie/Controller/Home.hs">the home page Controller module</a> defined like so:</p>
<pre><code>import Amelie.Controller (output)
import Amelie.Controller.Paste (pasteForm)
import Amelie.Model
import Amelie.Model.Home (getPastes)
import Amelie.View.Home (page)
handle :: Controller ()
handle = do
pastes &lt;- model $ getPastes
form &lt;- pasteForm
output $ page pastes form</code></pre>
<p>The <code>model</code> function lets us talk to the model from the controller. The import structure is quite revealing here of what’s going on. So here the MVC parts are:</p>
<ul>
<li>Model: <code>getPastes</code></li>
<li>View: <code>page</code></li>
<li>Controller: <code>handle</code>, <code>pasteForm</code></li>
</ul>
<h3 id="the-view">The View</h3>
<p>The <a href="https://github.com/chrisdone/amelie/blob/master/src/Amelie/View/Home.hs">view for the page</a> is a pure function, taking in data and outputting some <code>Html</code>:</p>
<pre><code>-- | Render the home page.
page :: [Paste] -&gt; Html -&gt; Html
page ps form =
layoutPage $ Page {
pageTitle = &quot;λ Knights!&quot;
, pageBody = content ps form
, pageName = &quot;home&quot;
}</code></pre>
<p>And layoutPage is another view function that just takes a Page spec and renders a basic HTML page:</p>
<pre><code>-- | Render the page in a layout.
layoutPage :: Page -&gt; Html
layoutPage Page{..} = do
docTypeHtml $ do
html $ do
head $ do
title $ toHtml $ pageTitle
…</code></pre>
<p>I thought this would be a nice way to do a simple template.</p>
<h3 id="the-model">The Model</h3>
<p>In <a href="https://github.com/chrisdone/amelie/blob/master/src/Amelie/Model/Paste.hs"><code>Amelie.Model.Paste</code></a> I have a set of functions that only talk to the database.</p>
<pre><code>-- | Get the latest pastes.
getLatestPastes :: Model [Paste]
getLatestPastes =
queryNoParams [&quot;SELECT *&quot;
,&quot;FROM public_toplevel_paste&quot;
,&quot;ORDER BY id DESC&quot;
,&quot;LIMIT 20&quot;]
-- | Get a paste by its id.
getPasteById :: PasteId -&gt; Model (Maybe Paste)
getPasteById pid =
listToMaybe &lt;$&gt; query [&quot;SELECT *&quot;
,&quot;FROM public_paste&quot;
,&quot;WHERE id = ?&quot;]
(Only pid)</code></pre>
<h1 id="css-edsl">CSS EDSL</h1>
<p>I also decided that I didn’t want to write in normal CSS anymore, and that I didn’t really need <a href="http://sass-lang.com/">Sass</a> and those like it when I could just embed a trivial DSL in Haskell.</p>
<p>I just <a href="https://github.com/chrisdone/amelie/blob/master/src/Text/CSS/Properties.hs">encoded all CSS properties as functions</a>, and then <a href="https://github.com/chrisdone/amelie/blob/master/src/Text/CSS/Types.hs">made a writer</a>, and then a <a href="https://github.com/chrisdone/amelie/blob/master/src/Text/CSS.hs">printer and pretty printer</a>.</p>
<p>Long story short I can now write <a href="https://github.com/chrisdone/amelie/blob/master/src/Amelie/View/Style.hs">some nice source for my stylesheets.</a>. Example:</p>
<pre><code>-- | Side-wide style sheet.
style :: Text
style = renderCSS $ runCSS $ do
layout
sections
paste
utils
highlighter
form
home
-- | Paste view styles.
paste :: CSS Rule
paste = do
classRule &quot;paste-specs&quot; $ do
margin &quot;0&quot;
padding &quot;0&quot;
listStyle &quot;none&quot;
lineHeight &quot;1.5em&quot;
subRule &quot;strong&quot; $ do
fontWeight &quot;normal&quot;
width &quot;8em&quot;
display &quot;block&quot;
float &quot;left&quot;</code></pre>
<p>And so on. I defined this as a Style view.</p>
<h1 id="javascript-edsl">JavaScript EDSL</h1>
<p>I also decided based on this trend I would go with a JavaScript DSL, too, namely, <a href="http://hackage.haskell.org/package/HJScript-0.5.0">HJScript</a></p>
<p>On the hpaste paste page, the layout of the page resizes according to the visual width of the code, so <a href="https://github.com/chrisdone/amelie/blob/master/src/Amelie/View/Script.hs">I use a little jQuery to look-up the size of it and adjust the wrapper accordingly</a>. Here’s the code:</p>
<pre><code>-- | All scripts on the site. Not much to do.
script :: Text
script = pack $ show $ snd $ evalHJScript $ do
ready $ do
each (setWidth (j &quot;.amelie-wrap&quot;)
(mathMax (getWidth this&#39; + 50) 500))
(j &quot;.highlighttable&quot;)</code></pre>
<p>I defined this as a Script view.</p>
<h1 id="summary">Summary</h1>
<p>Overall I’m very happy with how pgsql-simple has worked out so far. I haven’t benchmarked it yet, but it’s quite instantaneous in my preliminary tests. It’s really nice to have a pure Haskell database library.</p>
<p>I’m also very happy with the decision to use an MVC architecture so far, it has kept my code very tidy and clear. It seems like overkill for small projects but in actuality it’s great preparation for a larger codebase.</p>
<p>And Haskell seems to be terribly well-suited to forcing such separation of concerns, as in the MVC, at the type-level.</p>
<p>I will probably produce a simple DSL for querying and insert into the database, similar to the CSS and JS ones. Nothing particularly advanced at this stage, just something to avoid string manipulation.</p>
<p>P.S.</p>
<p>I also kinda implemented <a href="https://github.com/chrisdone/amelie/blob/master/src/Text/Formlet.hs">a small Formlets-ish library</a> because I wanted to give names to my inputs, but shh, don’t tell anyone.</p>
<p>I also switched to using the <a href="http://hackage.haskell.org/package/highlighter">highlighter</a> package because that’s BSD3 and therefore I can make the whole Amelie project BSD3.</p>]]></description>
<pubDate>Sun, 05 Jun 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/postgres-hpaste-edsls</guid>
</item>
<item>
<title>Yesod design</title>
<link>http://chrisdone.com/posts/yesod-design</link>
<description><![CDATA[<p>Was messing about in Inkscape and thought I’d come up with a design for <a href="http://www.yesodweb.com/">Yesod’s home page.</a> The <a href="http://chrisdone.com/designs/yesod-homepage/">HTML build is here.</a> Took a couple hours to whip up a logo and the design. <a href="http://chrisdone.com/designs/yesod-homepage/yesod.png">Original mock-up here.</a> Build to HTML seems to be a success. Took an hour or so to whip up the HTML &amp; CSS.</p>
<p><a href="http://chrisdone.com/designs/yesod-homepage/yesod-wide.png">Possible wide version here for reading docs.</a></p>
<p>I quite like the Droid font family.</p>
<a href="http://chrisdone.com/designs/yesod-homepage/yesod.png"> <img
src="http://chrisdone.com/designs/yesod-homepage/yesod-preview.png"> </a>]]></description>
<pubDate>Sun, 10 Apr 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/yesod-design</guid>
</item>
<item>
<title>‘amb’ operator and the list monad</title>
<link>http://chrisdone.com/posts/amb-list-monad</link>
<description><![CDATA[<p>A friend was <a href="http://mihai.bazon.net/blog/amb-in-javascript/take-two">messing about with the <code>amb</code> operator</a> in JavaScript after seeing it in Common Lisp. The <code>amb</code> (or <em>ambiguous</em>) operator, first described by our pal John McCarthy (1967), and something I first <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-28.html#%_sec_4.3">encountered in SICP.</a></p>
<p>These kind of constraint/logic puzzles seem naturally solved by the list monad, <a href="http://hpaste.org/45504/who_owns_the_fish">here’s an example of solving ‘Who owns the fish?’</a> Similar to <a href="http://en.wikipedia.org/wiki/Zebra_Puzzle">the Zebra puzzle.</a></p>
<pre><code>-- Translation of
-- http://mihai.bazon.net/blog/amb-in-javascript/take-two#wotf
import Control.Monad
import Data.Maybe
import Data.List
whoOwnsTheFish = addHouse []
addHouse houses = do
nat &lt;- other &quot;nat&quot; [&quot;British&quot;,&quot;Swedish&quot;,&quot;Danish&quot;,&quot;Norwegian&quot;
,&quot;German&quot;]
col &lt;- other &quot;col&quot; [&quot;red&quot;,&quot;green&quot;,&quot;white&quot;,&quot;yellow&quot;,&quot;blue&quot;]
pet &lt;- other &quot;pet&quot; [&quot;dogs&quot;,&quot;cats&quot;,&quot;horses&quot;,&quot;birds&quot;,&quot;fish&quot;]
bev &lt;- other &quot;bev&quot; [&quot;tea&quot;,&quot;milk&quot;,&quot;coffee&quot;,&quot;beer&quot;,&quot;water&quot;]
tob &lt;- other &quot;tob&quot; [&quot;pallmall&quot;,&quot;dunhill&quot;,&quot;marlboro&quot;
,&quot;winfield&quot;,&quot;rothmans&quot;]
(nat == &quot;British&quot;) `iff` (col == &quot;red&quot;)
(nat == &quot;Swedish&quot;) `iff` (pet == &quot;dogs&quot;)
(nat == &quot;Danish&quot;) `iff` (bev == &quot;tea&quot;)
(col == &quot;white&quot;) `iff`
(thisHouse &gt; 0 &amp;&amp; &quot;col&quot; `lookup` (houses!!(thisHouse - 1))
== Just &quot;green&quot;)
(col == &quot;green&quot;) `iff` (bev == &quot;coffee&quot;)
(tob == &quot;pallmall&quot;) `iff` (pet == &quot;birds&quot;)
(col == &quot;yellow&quot;) `iff` (tob == &quot;dunhill&quot;)
(thisHouse == 2) `iff` (bev == &quot;milk&quot;)
(thisHouse == 0) `iff` (nat == &quot;Norwegian&quot;)
(tob == &quot;winfield&quot;) `iff` (bev == &quot;beer&quot;)
(nat == &quot;German&quot;) `iff` (tob == &quot;rothmans&quot;)
let h = [(&quot;nat&quot;,nat),(&quot;bev&quot;,bev),(&quot;tob&quot;,tob),(&quot;pet&quot;,pet)
,(&quot;col&quot;,col)]
a = houses ++ [h]
if length a == 5
then do neighbors a &quot;tob&quot; &quot;marlboro&quot; &quot;pet&quot; &quot;cats&quot;
neighbors a &quot;pet&quot; &quot;horses&quot; &quot;tob&quot; &quot;dunhill&quot;
neighbors a &quot;nat&quot; &quot;Norwegian&quot; &quot;col&quot; &quot;blue&quot;
neighbors a &quot;tob&quot; &quot;marlboro&quot; &quot;bev&quot; &quot;water&quot;
return a
else addHouse a
where other typ = filter (isNothing . findHouse houses typ)
thisHouse = length houses
findHouse houses typ val =
fmap fst . find ((==Just val) . lookup typ . snd) . zip [0..]
$ houses
neighbors houses typ1 val1 typ2 val2 = guard $ diff == Just 1
where diff = do h1 &lt;- findHouse houses typ1 val1
h2 &lt;- findHouse houses typ2 val2
return $ abs $ h1 - h2
iff x y = guard $ x == y</code></pre>]]></description>
<pubDate>Sun, 10 Apr 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/amb-list-monad</guid>
</item>
<item>
<title>Numbergeddon game</title>
<link>http://chrisdone.com/posts/numbergeddon-game</link>
<description><![CDATA[<p><a href="http://chrisdone.com/numbergeddon/">Here’s a little game that I whipped</a> up on my day off. A flying game in which you destroy your enemies by typing in the answers to trivial arithmetic above their heads. It’s aimed at kids.</p>
<p>Controls: Use <code>wsad</code> or the arrow keys, and the numpad to type in answers/hit return to submit.</p>
<p>Screenshot:</p>
<img src="/images/ng.png" title="Numbergeddon screenshot">
<p>Tested on: Chrome/Chromium 10 and Firefox 4. It’s not the fastest code so it varies between being totally smooth and not really playable on Firefox. On Chrome it’s always smooth.</p>]]></description>
<pubDate>Sun, 20 Mar 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/numbergeddon-game</guid>
</item>
<item>
<title>Hulk: A Haskell IRC server</title>
<link>http://chrisdone.com/posts/hulk-haskell-irc-server</link>
<description><![CDATA[<p>Hulk is an working-and-work-in-progress IRC server. <a href="https://github.com/chrisdone/hulk/">Github repo.</a></p>
<h2 id="motivation">Motivation</h2>
<p>Last Wednesday night I whipped up <a href="https://github.com/chrisdone/hulk/tree/f1f8c662acfecbe7bb325ea1c1cda8f4284f0524">a simple IRC server in Haskell in about four hours</a>. We have been long time sick of the poor quality of the Skype Linux implementation, which was, on the dev team, our main point of communication. We agreed something like IRC would be good, so I thought it would be easy in Haskell to make such a thing, and it was; the next day we were chatting on it!</p>
<h2 id="good-timing">Good Timing</h2>
<p>I noticed that <a href="http://catonmat.net/">Peteris Krumins</a> made a blog on Thursday about <a href="http://catonmat.net/blog/simple-haskell-tcp-server">how to write a TCP server in Haskell.</a> I thought, “That’s good timing!” I also use the <a href="hhttp://hackage.haskell.org/packages/archive/network/latest/doc/html/Network.html">Network</a> module and <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Concurrent.html">Control.Concurrent</a>, and do pretty much everything he is demonstrating in the blog. So it seems like Hulk is a nice “real-world” demonstration of a non-simple TCP server in Haskell.</p>
<h2 id="requirements">Requirements</h2>
<p>Our requirements for a server are quite narrow:</p>
<ul>
<li>It needs to be internal, so it has a mandatory login system (using the Crypto package for salted SHA1 passwords). This not optional right now.</li>
<li>We don’t care about flooding, IRC standards for nicknames, message length of 512 bytes, lack of a specific encoding support, etc. The server supports UTF8 everything.</li>
<li>I will be adding history, a la Skype and MSN Messenger, which stores a log of all IRC activity and sends the ones of concern to you when you re-connect.</li>
<li>I will also add OpenSSL support using <a href="http://hackage.haskell.org/packages/archive/HsOpenSSL/0.9/doc/html/OpenSSL-Session.html#g:2">the HsOpenSSL package which seemingly makes the whole process trivial.</a></li>
</ul>
<p>We also pipe some feeds to it like tickets, Git commits, site issues, etc.</p>
<h2 id="a-brief-overview">A Brief Overview</h2>
<h3 id="general-haskell-projects">General Haskell Projects</h3>
<p>In the spirit with which Peteris writes I thought that I might describe the design of the project a little bit.</p>
<pre><code>$ ls
auth history hulk.conf README src
dist hulk.cabal LICENSE Setup.hs txt</code></pre>
<p>It’s good Haskell practice to start any project with <code>cabal init</code> which asks you a series of questions and generates a <code>.cabal</code> file for you. Common practice is to put source in the <code>src</code> dir, and have your Project in a sub-directory matching the project name:</p>
<pre><code>$ ls src
Control Data GeneratePass.hs Hulk Main.hs</code></pre>
<p>Code that isn’t specific to the particular project but could be used anywhere should go in appropriate modules such as <code>Control.*</code>, <code>Data.*</code>, etc. It occurs commonly that you will need this code in other projects and because the dependency between these modules and your main project’s modules is only in one direction you can simply copy the files over to your new project.</p>
<h3 id="hulks-module-hierarchy">Hulk’s module hierarchy</h3>
<pre><code>Control.Monad.IO
Data.String
Hulk
Hulk.Auth
Hulk.Client
Hulk.Config
Hulk.Event
Hulk.Options
Hulk.Providers
Hulk.Server
Hulk.Types
Main</code></pre>
<p>The first two just contain utilities that I tend to use often. The <code>Main</code> module is the main entry point, then control goes to <code>Hulk.Server</code> which starts listening on the right port, accepting connections and handling/sending messages to/from clients.</p>
<h3 id="purity-vs-impurity">Purity vs Impurity</h3>
<p>In order to handle messages and reply to them from clients, the <code>Hulk.Client</code> module is used. The code in Hulk.Client is entirely pure, and it is the bulk of the project. This is an intentional effort. The original program I whipped up used a bunch of MVars and was basically an imperative program, and about as confusing.</p>
<center>
<img
src="http://img684.imageshack.us/img684/4484/spiderskullisland480x27.jpg"
title="Spider Skull Island from Venture Bros">
</center>
<p>Another “good practice” is for Haskell programs to be like a well-oiled super villain base. On the edge is where all the explosions happen, and inside is where the bad guys sit and drink Orzo and control everything.</p>
<blockquote>
<p><img style="float:right;margin-left:10px;margin-bottom:5px;"
src="http://img593.imageshack.us/img593/1179/3202x.jpg"
title="Henchmen"> Impure code is like the wreckless henchmen who always wreck everything, and double-cross you at every opportunity. Pure code is the evil genius who devises the master plan, tells the henchmen what to do, and keeps them in separate living quarters.</p>
</blockquote>
<p>It’s also common to put all your types into one module named <code>Types</code>, as you tend to use types from every module and this avoids circular dependency problems in the long run.</p>
<h3 id="flow-of-the-program">Flow of the program</h3>
<p>The main entry point to the project is in <code>Main</code>, as it should be:</p>
<pre><code>{-# OPTIONS -Wall #-}
module Main where
import Network
import System.Console.CmdArgs
import System.Posix
import Hulk.Config (getConfig)
import Hulk.Options (options,optionsConf)
import Hulk.Server (start)
import Hulk.Types ()
main :: IO ()
main = withSocketsDo $ do
_ &lt;- installHandler sigPIPE Ignore Nothing
cmdArgs options &gt;&gt;= getConfig . optionsConf &gt;&gt;= start</code></pre>
<p>I initialise the sockets subsystem for Windows and then install a handler for <code>SIGPIPE</code>, because that signal is sent in Unix when a program attempts to write to a socket that has been closed. Both Windows and Unix have their novel design choices. Go figure.</p>
<p>I’m using the <a href="http://hackage.haskell.org/package/cmdargs">CmdArgs library</a>, <a href="http://neilmitchell.blogspot.com/2010/08/cmdargs-example.html">tutorial here by the author, Neil Mitchell</a>, which I am pleased is becoming part of my standard project repertoire.</p>
<p>I define my options merely as a way to specify the configuration file, for now.</p>
<pre><code>{-# LANGUAGE DeriveDataTypeable, RecordWildCards, ScopedTypeVariables #-}
{-# OPTIONS -Wall -fno-warn-missing-signatures #-}
module Hulk.Options (Options
,options
,optionsConf) where
import System.Console.CmdArgs
data Options = Options
{ conf :: FilePath
} deriving (Show,Data,Typeable)
options = Options
{ conf = def &amp;= opt &quot;hulk.conf&quot; &amp;= help &quot;The config file.&quot;
}
&amp;= summary &quot;Hulk IRC Daemon (C) Chris Done 2011&quot;
&amp;= help &quot;Runs an IRC server based on the provided configuration file.&quot;</code></pre>
<p>And I read the config file with <a href="http://hackage.haskell.org/package/ConfigFile">the great ConfigFile library</a>:</p>
<pre><code>{-# OPTIONS -Wall -fno-warn-missing-signatures -fno-warn-name-shadowing #-}
module Hulk.Config
(Config(..)
,getConfig)
where
import Data.Word
import Data.ConfigFile
import Hulk.Types
getConfig :: FilePath -&gt; IO Config
getConfig conf = do
contents &lt;- readFile conf
let config = do
c &lt;- readstring emptyCP contents
hostname &lt;- get c &quot;LISTEN&quot; &quot;hostname&quot;
listen &lt;- get c &quot;LISTEN&quot; &quot;port&quot;
motd &lt;- get c &quot;STRINGS&quot; &quot;motd_file&quot;
preface &lt;- get c &quot;STRINGS&quot; &quot;preface_file&quot;
passwd &lt;- get c &quot;AUTH&quot; &quot;passwd_file&quot;
key &lt;- get c &quot;AUTH&quot; &quot;passwd_key&quot;
return Config { configListen = fromIntegral (listen::Word16)
, configMotd = Just motd
, configHostname = hostname
, configPasswd = passwd
, configPasswdKey = key
, configPreface = Just preface
}
case config of
Left cperr -&gt; error $ show cperr
Right config -&gt; return config</code></pre>
<p>The reading process is merely a simple monad that either returns the <code>Config</code> object or an error. I choose to just throw an error when there’s an issue. I use this library for pretty much every project I use, it really is an essential library.</p>
<p>An alternative way to express the code above is to <code>runReaderT</code>, define a function like <code>get' = ask &gt;&gt;= flip get</code> and then you can express the above with Applicative operators <code>(&lt;$&gt;)</code> and <code>(&lt;*&gt;)</code>.</p>
<p>This module will read a file like this:</p>
<pre><code>[LISTEN]
port = 6667
hostname = cn-done
[STRINGS]
motd_file = txt/MOTD
preface_file = txt/PREFACE
[AUTH]
passwd_file = auth/passwd</code></pre>
<h3 id="server-starter">Server starter</h3>
<p>I start the server by using the <code>listenOn</code> function, covered in Peteris’s post, and accept connections, setting the buffering to <code>NoBuffering</code>. This turns out to be rather important; as Peteris mentions, this avoids surprises with buffering, which is something I experienced when testing out <code>LineBuffering</code> in this project. In certain situations unknown to me, access to handles locks up.</p>
<pre><code>-- | Start an IRC server with the given configuration.
start :: Config -&gt; IO ()
start config = withSocketsDo $ do
hSetBuffering stdout LineBuffering
listenSock &lt;- listenOn $ PortNumber (configListen config)
envar &lt;- newMVar Env { envClients = M.empty
, envNicks = M.empty
, envChannels = M.empty }
forever $ do
(handle,host,_port) &lt;- accept listenSock
hSetBuffering handle NoBuffering
let conn = Conn { connRef = newRef handle
, connHostname = host
, connServerName = configHostname config
}
_ &lt;- forkIO $ handleClient config handle envar conn
return ()</code></pre>
<h3 id="connection-handling">Connection handling</h3>
<p>I fork a new thread per handle. No big deal. I have one value, <code>envar</code>, of type <code>MVar Env</code>, which stores the state of the whole server. It can only be accessed by one thread at a time, that’s why I put it on an <code>MVar</code>. The definition of <code>Env</code> is:</p>
<pre><code>data Env = Env {
envClients :: Map Ref Client
,envNicks :: Map Nick Ref
,envChannels :: Map ChannelName Channel
}</code></pre>
<p>where</p>
<pre><code>newtype Ref = Ref { unRef :: Handle }
deriving (Show,Eq)</code></pre>
<p><code>Ref</code> is merely a wrapper for Handles, to avoid me accidentally using a handle. It is only used as a unique reference to a client.</p>
<p>In the new thread I have a handler which receives newlines from the client:</p>
<pre><code>-- | Handle a client connection.
handleClient :: Config -&gt; Handle -&gt; MVar Env -&gt; Conn -&gt; IO ()
handleClient config handle env conn = do
let runHandle = runClientHandler config env handle conn
runHandle $ makeLine CONNECT []
fix $ \loop -&gt; do
line &lt;- catch (Right &lt;$&gt; UTF8.hGetLine handle) (return . Left)
case filter (not.newline) &lt;$&gt; line of
Right [] -&gt; loop
Right line -&gt; do runHandle (line++&quot;\r&quot;); loop
Left _err -&gt; runHandle $ makeLine DISCONNECT [&quot;Connection lost.&quot;]
where newline c = c==&#39;\n&#39; || c==&#39;\r&#39;</code></pre>
<p>I get a line which is Right, or fail and return what’s Left. The case of getLine failing is when the socket is closed. I ignore messages only containing newline characters, and the middle case is actually getting a valid line which I pass to <code>runHandle</code> that runs the pure client handler, then <code>loop</code>s again.</p>
<h3 id="client-handler">Client handler</h3>
<p>To run the client handler, I have the following function:</p>
<pre><code>-- | Handle a received line from the client.
runClientHandler :: Config -&gt; MVar Env -&gt; Handle -&gt; Conn -&gt; String -&gt; IO ()
runClientHandler config env handle conn line = do
modifyMVar_ env $ \env -&gt; do
(replies,env) &lt;- runReaderT (runHulkIO $ handleLine env conn line) config
mapM_ (handleReplies handle) replies
return env</code></pre>
<p>It passes the program state (<code>env</code>) and the current connection info (<code>conn</code>) to the function <code>handleLine</code>, which is the single export from <code>Hulk.Client</code>, which is a transformer over an arbitrary monad. Technically, in this case I’m running it inside a <code>readerT</code> on <code>IO</code>, so it’s not actually pure. The <code>handleLine</code> action returns a bunch of replies/instructions for the <code>Server</code> module to perform and a new state (<code>env</code>).</p>
<p>When I said that the <code>Hulk.Client</code> module was pure, I meant that it is abstracted over whether it is pure or impure, and therefore can be treated as pure for testing and developing, and when running the server, runs in IO, but only 0.1% of the code uses IO. Also, when I said “arbitrary monad”, I meant any monad implementing the <code>MonadProvider</code> class.</p>
<pre><code>class Monad m =&gt; MonadProvider m where
providePreface :: m (Maybe String)
provideMotd :: m (Maybe String)
provideKey :: m String
providePasswords :: m String</code></pre>
<p>Meaning that these are the only “impure” things I need when running the program. I need to read the preface, motd, key, and password files on demand. In the <code>IO</code> case, I simply read the file. In the pure case, I can stick it in a <code>Reader</code> or <code>Identity</code> monad and the whole computation is thus pure.</p>
<p>What’s the benefit? This means I can run arbitrary parts of the computation trivially, and make pure test suites out of it. QuickCheck my IRCd, anyone? The main benefits are not to have to worry about conflicting simultaneous threads, and being able to run any function from the module with whatever state one desires.</p>
<h3 id="client-replies">Client replies</h3>
<p>The <code>Client</code> module replies with one of the following:</p>
<pre><code>data Reply = MessageReply Ref Message | LogReply String | Close</code></pre>
<ul>
<li><code>MessageReply</code>: Send this <code>Message</code> to the given handle (<code>Ref</code>).</li>
<li><code>LogReply</code>: Log this <code>String</code>.</li>
<li><code>Close</code>: Close the current connection.</li>
</ul>
<p>I find this separation of IO and logic to be useful.</p>
<h3 id="the-irc-monad-stack">The IRC monad stack</h3>
<p>The rest of the project lies in <code>Hulk.Client</code> and is academic/straight-forward. I will explain the <code>IRC</code> monad, though:</p>
<pre><code>newtype IRC m a = IRC {
runIRC :: ReaderT Conn (WriterT [Reply] (StateT Env m)) a
}
deriving (Monad
,Functor
,MonadWriter [Reply]
,MonadState Env
,MonadReader Conn)</code></pre>
<ul>
<li>I output replies, hence the <code>MonadWriter [Reply]</code>.</li>
<li>I read the connection info (<code>Conn</code>), but I <em>don’t/shouldn’t</em> modify it or write to it.</li>
<li>I <em>do</em> read/modify the <code>Env</code>, which is the whole server state.</li>
<li>Finally, it is parametrized over an arbitrary monad, but the functions in <code>Client</code> constrain to <code>MonadProvider</code>.</li>
</ul>
<p>This is called <a href="http://book.realworldhaskell.org/read/monad-transformers.html">a monad transformer stack</a>. <a href="http://en.wikibooks.org/wiki/Haskell/Monad_transformers">Haskell Wikibook on transformers</a></p>
<h3 id="examples">Examples</h3>
<p>Example of a <code>MessageReply</code>:</p>
<pre><code>-- | Send a message reply.
reply :: Monad m =&gt; Ref -&gt; Message -&gt; IRC m ()
reply ref msg = do
outgoing $ encode msg
tell . return $ MessageReply ref msg</code></pre>
<p>Examples of <code>LogReply</code>:</p>
<pre><code>-- | Log an outgoing line.
outgoing :: Monad m =&gt; String -&gt; IRC m ()
outgoing = log . (&quot;-&gt; &quot; ++)
-- | Log a line.
log :: Monad m =&gt; String -&gt; IRC m ()
log = tell . return . LogReply</code></pre>
<p>Example of the <code>StateT</code>:</p>
<pre><code>-- | Modify the nicks mapping.
modifyNicks :: Monad m =&gt; (Map Nick Ref -&gt; Map Nick Ref) -&gt; IRC m ()
modifyNicks f = modify $ \env -&gt; env { envNicks = f (envNicks env) }</code></pre>
<p>Example of using the <code>Conn</code> object from the <code>ReaderT</code>:</p>
<pre><code>-- | Make a new IRC message from the server.
newServerMsg :: Monad m =&gt; String -&gt; [String] -&gt; IRC m Message
newServerMsg cmd ps = do
hostname &lt;- asks connServerName
return $ Message {
msg_prefix = Just $ Server hostname
,msg_command = cmd
,msg_params = ps
}</code></pre>
<h2 id="summary">Summary</h2>
<p>That’s all, folks! I hope this is useful to some people thinking of writing their first Haskell daemon project.</p>
<p>Haskell is the only language I know in which I can write 400~ lines of code without running it and then run it and have it work as expected.</p>]]></description>
<pubDate>Sun, 30 Jan 2011 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/hulk-haskell-irc-server</guid>
</item>
<item>
<title>Shime progress and multiple sessions</title>
<link>http://chrisdone.com/posts/shime-progress</link>
<description><![CDATA[<p>Recently I mentioned I started work on <a href="http://chrisdone.com/posts/2010-10-14-shime-haskell-interaction-mode-for-emacs.html">a Haskell interaction mode for Emacs called Shime.</a> Since mentioning it I have basically achieved what I use from inf-haskell, but with the addition of multiple sessions which turns out to be very very cool.</p>
<p>I uploaded <a href="http://www.youtube.com/watch?v=Ly_T1hFGoXg">a video on YouTube a while ago demonstrating multiple sessions.</a> I use this constantly. Right now I have two work project sessions open, and one of my own personal projects, each with their own load paths, Cabal configuation/build paths, and of course GHCi sessions. I can kill/relaunch/compile them all in a natural way.</p>
<p>When I first open a Haskell file and hit <code>F5</code> (my binding for “load the file in GHCi”), it asks me which session I want, I pick, e.g. “amelie” and then it loads the file and remembers for the remainder of the Emacs session. Actually, it only prompts if there is more than one session open, otherwise it <em>Does What You Mean</em>.</p>
<p>Likewise when I hit <code>C-c C-c</code> it asks me which session I want to build it with, using Cabal. I can use all the Cabal commands <code>configure</code>, <code>build</code>, <code>install</code>, <code>upload</code>, etc. all from Emacs without thinking about it. Pretty nice.</p>
<p>Sometimes you need to patch a library package that you’re using. You want to be able to load the files in GHCi to test your changes, and then to build and install it, then rebuild your actual project and test that. Shime makes that really easy.</p>
<p>Regarding the other features, they will be implemented when I really want them. I did at least implement collapsed error messages (not fully collapsed, just removing newlines – turns out I rarely read anything other than the type error or line number in error messages). My REPL is now significantly more space efficient than it was.</p>]]></description>
<pubDate>Thu, 25 Nov 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/shime-progress</guid>
</item>
<item>
<title>Lisk - Lisp and Haskell</title>
<link>http://chrisdone.com/posts/lisk-lisp-haskell</link>
<description><![CDATA[<p>In my spare time I’m working on a project called Lisk. Using the <code>-pgmF</code> option for GHC, you can provide GHC a program name that is called to preprocess the file before GHC compiles it. It also works in GHCi and imports. You use it like this:</p>
<pre><code>{-# OPTIONS -F -pgmF lisk #-}
(module fibs
(import system.environment)
(:: main (io ()))
(= main (&gt;&gt;= get-args (. print fib read head)))
(:: test (-&gt; :string (, :int :string)))
(= test (, 1))
(:: fib (-&gt; :int :int))
(= fib 0 0)
(= fib 1 1)
(= fib n (+ (fib (- n 1))
(fib (- n 2)))))</code></pre>
<p>The git repo is here:</p>
<pre><code>git://github.com/chrisdone/lisk.git</code></pre>
<p>And the <a href="https://github.com/chrisdone/lisk">github page is here.</a></p>
<p>I literally only support what is exhibited in the example above, and it is not ready for use at all. But I am using <a href="http://hackage.haskell.org/package/haskell-src-exts">haskell-src-exts’s</a> AST and pretty printer in order to convert from Lisk to Haskell, so I’m in good hands regarding completeness of the syntax. I don’t have a lot of time to work on it right now, but I will be doing.</p>]]></description>
<pubDate>Thu, 25 Nov 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/lisk-lisp-haskell</guid>
</item>
<item>
<title>Duck typing in Haskell</title>
<link>http://chrisdone.com/posts/duck-typing-in-haskell</link>
<description><![CDATA[<p>This is a simple Literate Haskell file demonstrating <a href="http://en.wikipedia.org/wiki/Duck_typing">duck typing</a> in Haskell. You copy the whole web page and paste it into a .hs file and compile/load it. Grab the normal Haskell version <a href="http://hpaste.org/41710/duck_typing">here.</a></p>
<p>I’m using <a href="http://hackage.haskell.org/package/has">a library called Has which you can grab from Hackage</a> (or just <code>cabal install has</code>). It’s pretty neat, it allows you to define field names and their types, that you are going to use at some point, and then lets you construct/access/update arbitrary records based on those fields.</p>
<p>We need to enable type families and flexible class contexts to work with this library. And also it’s nice if we disable the monomorphism restriction. I don’t want mono, I want manymorphism! As many as you can fit in your pocket.</p>
<pre><code>&gt; {-# LANGUAGE TypeFamilies, FlexibleContexts, NoMonomorphismRestriction #-}</code></pre>
<p>In this library you define fields like this:</p>
<pre><code>data Flap = Flap; type instance TypeOf Flap = IO ()</code></pre>
<p>Here I’m defining a “flap” method. Ducks flap! The <code>Flap</code> part is the accessor. But it sucks to have to write that, so we define a synonym. So the whole field definition ends up being:</p>
<pre><code>data Flap = Flap; type instance TypeOf Flap = IO (); flap = Flap</code></pre>
<p>Which is getting a little tedius, so I whipped up a little template haskell to make this easier. You can install that <a href="http://hackage.haskell.org/package/has-th">from Hackage too</a> (or just <code>cabal install has-th</code>). So let’s enable template haskell:</p>
<pre><code>&gt; {-# LANGUAGE TemplateHaskell #-}</code></pre>
<p>Now I just import the Has library and my template haskell module.</p>
<pre><code>&gt; import Data.Has hiding (field)
&gt; import Data.Has.TH</code></pre>
<p>And defining accessors is really easy:</p>
<pre><code>&gt; field &quot;flap&quot; [t|IO ()|]
&gt; field &quot;quack&quot; [t|String|]
&gt; field &quot;swim&quot; [t|IO ()|]
&gt; data Food = Bread | Pasta | Duck deriving Show
&gt; field &quot;eat&quot; [t|Food -&gt; Either String String|]
&gt; field &quot;name&quot; [t|String|]
&gt; field &quot;age&quot; [t|Integer|]</code></pre>
<p>The <code>[t|Foo|]</code> is just a reader macro for reading types that exist.</p>
<p>So I’ve defined a bunch of things that a duck generally <em>does</em> and <em>has</em>. Referring to James Whitcomb Riley:</p>
<blockquote>
<p>“When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.”</p>
</blockquote>
<p>Now let’s make some ducks! The obvious being Donald Duck:</p>
<pre><code>&gt; donald = flap ^- putStrLn &quot;*Flap flap flap*&quot;
&gt; &amp; quack ^- &quot;QUACK!&quot;
&gt; &amp; swim ^- putStrLn &quot;*Ducky paddle*&quot;
&gt; &amp; eat ^- nom
&gt; &amp; name ^- &quot;Donald Duck&quot;
&gt; where nom Bread = Right &quot;Nom nom nom!&quot;
&gt; nom Pasta = Right &quot;Ew, give me something bweady.&quot;
&gt; nom Duck = Left &quot;Are you cwazy!?&quot;</code></pre>
<p>He flaps, quacks, swims, eats and has a name. Also, I’ll pretend to be a duck, too:</p>
<pre><code>&gt; chris = flap ^- putStrLn &quot;I&#39;m flapping my arms!&quot;
&gt; &amp; quack ^- &quot;Erm, quack?&quot;
&gt; &amp; swim ^- putStrLn &quot;I&#39;m doing the butterfly because it&#39;s efficient ...&quot;
&gt; &amp; age ^- 67
&gt; &amp; eat ^- nom
&gt; &amp; name ^- &quot;Chris Done&quot;
&gt; where nom Bread = Left &quot;Bread is alright, but no thanks.&quot;
&gt; nom Pasta = Right &quot;Pasta is okay. Got anything to go with it?&quot;
&gt; nom Duck = Right &quot;Om nom nom.&quot;</code></pre>
<p>Notice that I’ve got one more field than <code>donald</code>, I’ve got an <code>age</code>. This means we are two distinct record types. We’ve got different stuff! But we’re both ducks! See:</p>
<pre><code>λ&gt; flap ^. donald
*Flap flap flap*
λ&gt; flap ^. chris
I&#39;m flapping my arms!
λ&gt; quack ^. donald
&quot;QUACK!&quot;
λ&gt; quack ^. chris
&quot;Erm, quack?&quot;</code></pre>
<p>Here is a nice thing that we get, we can define any function as taking anything that <strong>has</strong> certain fields, and we know that those fields have the right type because we defined them above:</p>
<pre><code>&gt; fly :: (Has Flap duck) =&gt; duck -&gt; IO ()
&gt; fly duck = do go; go; go where go = flap ^. duck
λ&gt; fly donald
*Flap flap flap*
*Flap flap flap*
*Flap flap flap*</code></pre>
<p>We do this multiple times, too:</p>
<pre><code>&gt; playInPond :: (Has Swim duck, Has Flap duck, Has Eat duck, Has Name duck)
&gt; =&gt; duck -&gt; Food -&gt; IO ()
&gt; playInPond duck food = do
&gt; putStrLn $ (name ^. duck) ++ &quot; is swimming happily.&quot;
&gt; swim ^. duck
&gt; putStrLn $ &quot;You give them some &quot; ++ show food ++ &quot; to eat.&quot;
&gt; case (eat ^. duck) food of
&gt; Left dnw -&gt; do putStrLn dnw; fly duck
&gt; Right nom -&gt; putStrLn nom
&gt; swim ^. duck</code></pre>
<p>And let’s see the ducks play in the pond when someone’s throwing some food:</p>
<pre><code>λ&gt; playInPond donald Bread
Donald Duck is swimming happily.
*Ducky paddle*
You give them some Bread to eat.
Nom nom nom!
*Ducky paddle*
λ&gt; playInPond chris Bread
Chris Done is swimming happily.
I&#39;m doing the butterfly because it&#39;s efficient ...
You give them some Bread to eat.
Bread is alright, but no thanks.
I&#39;m flapping my arms!
I&#39;m flapping my arms!
I&#39;m flapping my arms!
I&#39;m doing the butterfly because it&#39;s efficient ...
λ&gt; playInPond donald Duck
Donald Duck is swimming happily.
*Ducky paddle*
You give them some Duck to eat.
Are you cwazy!?
*Flap flap flap*
*Flap flap flap*
*Flap flap flap*
*Ducky paddle*</code></pre>
<p>They both have the same things. However, they <em>are</em> different:</p>
<pre><code>λ&gt; age ^. chris
67
λ&gt; age ^. donald
&lt;interactive&gt;:1:0: No instance for (Contains (Labelled Age Integer)
TyNil) arising from a use of `^.&#39; at &lt;interactive&gt;:1:0-12</code></pre>
<p>So there you have it, duck typing in a statically typed way. We get to have our cake and eat it too.</p>
<hr />
<p>By the way, and this isn’t particularly important, I used a function to make creating record fields a little nicer, because I don’t like the namelessness of writing <code>fieldOf 23</code>:</p>
<pre><code>&gt; -- | Creation: I like to be able to name the fields that I&#39;m assigning.
&gt; (^-) :: a -&gt; TypeOf a -&gt; FieldOf a
&gt; (^-) = const $ fieldOf
&gt; infixr 6 ^-</code></pre>]]></description>
<pubDate>Mon, 22 Nov 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/duck-typing-in-haskell</guid>
</item>
<item>
<title>Shime - Superior Haskell Interaction Mode for Emacs</title>
<link>http://chrisdone.com/posts/shime-haskell-interaction-mode-for-emacs</link>
<description><![CDATA[<h1 id="shimem-nom-nom-nom">Shimem nom nom nom</h1>
<p>I have bare-faced stolen that name from <a href="http://common-lisp.net/project/slime/">SLIME</a>, one of the best programming environments available for any language. I originally thought “inf-haskell” → “superior-haskell”, but <code>M-x shime</code> is nicer to type than <code>M-x superior-haskell</code>. The superiority of Haskell is well-established, at any rate.</p>
<p>I decided I wasn’t into <a href="http://code.haskell.org/haskellmode-emacs/inf-haskell.el">inf-haskell</a> anymore. I like it but I want more features and a more content-aware display (e.g. inf-haskell works on matching upon the buffer, which works in most cases but often misses error messages when scanning). I had a read through the <a href="http://www.gnu.org/s/emacs/manual/html_node/elisp/Major-Modes.html#Major-Modes">Major Modes section of the Emacs manuals</a> and it was far easier than I thought to create a mode. There’s a lot of hullabaloo about the manual being spare, but go figure.</p>
<p>I made a start and have very basic REPL interaction working. I made a Github repo:</p>
<ul>
<li><a href="http://github.com/chrisdone/shime">Shime Github repo</a></li>
</ul>
<p>It’s BSD licensed.</p>
<p>It talks to GHCi via a pipe. Observe:</p>
<pre><code>GHCi, version 6.12.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package ffi-1.0 ... linking ... done.
λ&gt; 5 * 7
35
λ&gt; :t 5 * 7
5 * 7 :: (Num t) =&gt; t
λ&gt; &quot;λx.x&quot;
&quot;\955x.x&quot;
λ&gt; putStrLn &quot;λx.x&quot;
λx.x
λ&gt; :q
Leaving GHCi.</code></pre>
<p><em>The Shime process died. Restart it? (y or n)</em> <strong>y</strong></p>
<pre><code>GHCi, version 6.12.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package ffi-1.0 ... linking ... done.
λ&gt;</code></pre>
<p><strong><em>IT’S ALIVE!</em></strong></p>
<h2 id="future-plans">Future plans</h2>
<p>I intend on the following things (some of which I kind of implemented in inf-haskell, but weren’t very reliable):</p>
<ul>
<li>“Physical” error/warning messages – ones that are collapsed and navigable with <code>TAB</code> and <code>Space</code> (or some combination that makes sense).</li>
<li>Clickable types and variables; either displays definition or goes to definition, not sure yet.</li>
<li>Some hardcore integration with Scion. Mostly for inspection.</li>
<li>Support to keep certain modules loaded. Ever load some module, but get some simple type error, and you go to inspect a type from that module, but you can’t because GHCi unloaded it? Me too<em>!</em></li>
<li>Defining of types inside GHCi: with interactive questioning this becomes less difficult, e.g. “Type A has dependencies, re-define it and re-evaluate its depending types? (y or n)”, etc.</li>
<li>Syntax highlighting.</li>
<li>Multi-line expressions (by parsing and inserting semi colons).</li>
</ul>
<p>Most probably I’ll do about three of these and be satisfied, but the intention is there.</p>]]></description>
<pubDate>Thu, 14 Oct 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/shime-haskell-interaction-mode-for-emacs</guid>
</item>
<item>
<title>HaskellDB and TypeOperators madness</title>
<link>http://chrisdone.com/posts/haskelldb-and-typeoperator-madness</link>
<description><![CDATA[<h2 id="haskelldb">HaskellDB</h2>
<p>So in HaskellDB, there is a nice, clever record system which is used to express tables, queries, projections, etc. – anything that has fields and types related to them. It’s kind of similar to Hugs’s TRex record system, but invented to work with plain Haskell and, most importantly, in GHC.</p>
<p>The idea behind HaskellDB is that you generate these records for your tables from your database schema. But I’ve found that sometimes you don’t want all fields from the schema, or that you want to operate on a projection. All the examples of HaskellDB, and there aren’t many, don’t have explicit type signatures on the functions that operate on records, and that’s a good thing, because if they did, it would be a huge ugly verbose signature.</p>
<p>I wanted to:</p>
<ol style="list-style-type: decimal">
<li>Make defining entities trivial.</li>
<li>Make annotating my functions that work on them not verbose and ugly.</li>
</ol>
<h2 id="haskelldb-works-like-this">HaskellDB works like this</h2>
<p>Entities in HaskellDB are typed like this:</p>
<pre><code>type Person = RecCons Name (Expr String)
(RecCons Age (Expr Integer)
(RecCons Email (Expr String)
(RecCons Blurb (Expr (Maybe String))
RecNil)))</code></pre>
<p>It’s sort of like a heterogenous list type but restricted to instances of <code>FieldTag</code>. RecCons describes the field, e.g. <code>Name</code>, which is a data type implementing the <code>FieldTag</code> class, e.g.:</p>
<pre><code>data Name = Name
instance FieldTag Name where fieldName _ = &quot;name&quot;</code></pre>
<p>This allows HaskellDB to associate this field with an actual field in the database by its schema name <code>name</code>. And then for writing actual fields of a record, there’s usually a value that goes with it:</p>
<pre><code>name :: Attr Name String
name = mkAttr Name</code></pre>
<p>Which describes that its field is <code>Name</code> and the corresponding type is <code>String</code>. The type of <code>mkAttr</code> is:</p>
<pre><code>mkAttr :: (FieldTag f) =&gt; f -&gt; Attr f a</code></pre>
<p>Maybe I should write an up-to-date explanation of how HaskellDB works from the bottom up. It’s really simple but when I first approached it I thought it was a bit magic and over the top, and didn’t enjoy it. The documentation available isn’t great or is out of date, and the paper, although great, uses Hugs’s TRex and is kind of unfamiliar. But I’ll leave that for another time, I’ll probably do a write-up on the HaskellWiki.</p>
<h2 id="enter-type-operators">Enter type operators!</h2>
<p>Anyway, to make my life a bit easier, I defined the following type:</p>
<pre><code>type F a b c = RecCons a (Expr b) c</code></pre>
<p>Now, I could define entities in a way that wasn’t so ugly:</p>
<pre><code>type Person = (F Id Integer
(F Age Integer
(F Email String
(F Blurb (Maybe String)
RecNil))))</code></pre>
<p>And it feels a bit more efficient, but still kind of clunky and obvious that I’m manually constructing a list and balancing parentheses.</p>
<p>I found that if I define this helper type operator,</p>
<pre><code>type a :=&gt;: b = RecCons a b
infixr 2 :=&gt;:</code></pre>
<p>then I can make this nice type operator to define a type for a record:</p>
<pre><code>type a :&lt;: b = a :=&gt;: (Expr b)
infixr 2 :&lt;:</code></pre>
<p>And then combine records together with this operator,</p>
<pre><code>type a :+: b = a b
infixr 1 :+:</code></pre>
<p>and with an aesthetic type to complete the abstraction:</p>
<pre><code>type End = RecNil</code></pre>
<p>Now I’ve got a more natural, more familiar way of writing records:</p>
<pre><code>type Person = Id :&lt;: Integer
:+: Age :&lt;: Integer
:+: Email :&lt;: String
:+: Blurb :&lt;: Maybe String
:+: End</code></pre>
<p>Isn’t that nice!</p>
<h2 id="parametrizing-the-record">Parametrizing the record</h2>
<p>This is pretty good, but I have another problem. I want to be able to define an entity which is parametrized by a type function over the type of the field. E.g. the <code>person</code> entity’s fields are wrapped by the <code>Expr</code> type function. The above is really:</p>
<pre><code>type Person = RecCons Name (Expr String)
(RecCons Age (Expr Integer)
(RecCons Email (Expr String)
(RecCons Blurb (Expr (Maybe String))
RecNil)))</code></pre>
<p><code>Expr</code> is used when we’re constructing a query or restriction for an entity. But when we have the actual record, i.e. from a result, the type is:</p>
<pre><code>type Person = RecCons Name String
(RecCons Age Integer
(RecCons Email String
(RecCons Blurb (Maybe String)
RecNil)))</code></pre>
<p>If I want to annotate my top-level functions which work on these types, I’ve got to write it out every time … Or I can parametrize the type:</p>
<pre><code>type Person a = RecCons Name (a String)
(RecCons Age (a Integer)
(RecCons Email (a String)
(RecCons Blurb (a (Maybe String))
RecNil)))</code></pre>
<p>Now I can have:</p>
<pre><code>type PersonQuery = Person Expr</code></pre>
<p>And with a type-level id function,</p>
<pre><code>type TId a = a</code></pre>
<p>I can have:</p>
<pre><code>type PersonRow = Person TId</code></pre>
<p>So to deal with this extra notion in my little set of type operators, I defined another operator:</p>
<pre><code>type a :~&gt;: f = f a
infixr 3 :~&gt;:</code></pre>
<p>Now I can define <code>Person</code> like this:</p>
<pre><code>type Person a =
Id :=&gt;: Integer :~&gt;: a
:+: Age :=&gt;: Integer :~&gt;: a
:+: Email :=&gt;: String :~&gt;: a
:+: Blurb :=&gt;: Maybe String :~&gt;: a
:+: End</code></pre>
<p>This is okay! It’s still a bit verbose, though. I don’t like the fact I need to mention the <code>a</code> for every single field. It’s practically a type-level reader/environment monad.</p>
<h2 id="type-level-monad-kinda">Type-level monad, kinda …</h2>
<p>Here’s what I came up with:</p>
<pre><code>type (c :~~&gt;: b) a k = (RecCons c (a b)) k
infixr 2 :~~&gt;:</code></pre>
<p><code>(:~~&gt;:)</code> is kind of a binary <code>return</code> function, because it constructs a record from a field type <code>c</code> and value type <code>b</code>, and then takes an <code>a</code> which is the environment, and corresponds to the <code>a</code> that we duplicated n times above in <code>Person</code>. Finally it takes another field, <code>k</code>. GHCi tells us:</p>
<pre><code>λ&gt; :k (:~~&gt;:)
(:~~&gt;:) :: * -&gt; * -&gt; (* -&gt; *) -&gt; * -&gt; *</code></pre>
<p>Which makes it very clear.</p>
<p>Then I need a way to combine fields which doubles up as a <code>(&gt;&gt;)</code> function for the types, passing the <code>a</code> type to each field (“monadic type”):</p>
<pre><code>type (x :&gt;&gt;: y) (a :: * -&gt; *) = x a (y a)
infixr 1 :&gt;&gt;:</code></pre>
<p>A kind-of bind type function. GHCi again gives insight as to the meaning of this:</p>
<pre><code>λ&gt; :k (:&gt;&gt;:)
(:&gt;&gt;:) :: ((* -&gt; *) -&gt; * -&gt; *) -&gt; ((* -&gt; *) -&gt; *) -&gt; (* -&gt; *) -&gt; *</code></pre>
<p>Which can be read as taking a record constructor, that’s</p>
<pre><code>((* -&gt; *) -&gt; * -&gt; *)</code></pre>
<p>and a record to combine it with that doesn’t take a record constructor (this is analogous to x : y in combining lists):</p>
<pre><code>((* -&gt; *) -&gt; *)</code></pre>
<p>And then finally take the <code>a</code> type which is merely <code>(* -&gt; *)</code>.</p>
<p>To help create a <code>((* -&gt; *) -&gt; *)</code> type, which is basically the same as the first parameter to the type, but ignores the <code>a</code> environment variable, I define a type-level <code>const</code>:</p>
<pre><code>type Const c a = c</code></pre>
<p>I don’t really have to explain the use much, the kinds tell everything:</p>
<pre><code>λ&gt; :k Const End
Const End :: (* -&gt; *) -&gt; *</code></pre>
<p><strong>Note:</strong> Paul Graphov kindly pointed out to me that in my Person examples below I had put <code>End</code> instead of <code>Const End</code>, which was incorrect and confusing. Thank you, Paul.</p>
<p>Now I can combine the record with the final nil record, and I have a kind of monad-ish type that accepts an environment variable:</p>
<pre><code>λ&gt; :k (Id :~~&gt;: Integer) :&gt;&gt;: (Const End)
(Id :~~&gt;: Integer) :&gt;&gt;: (Const End) :: (* -&gt; *) -&gt; *</code></pre>
<p>I can provide it by merely applying it:</p>
<pre><code>λ&gt; :k ((Id :~~&gt;: Integer) :&gt;&gt;: (Const End)) TId
((Id :~~&gt;: Integer) :&gt;&gt;: (Const End)) TId :: *
λ&gt; :k ((Id :~~&gt;: Integer) :&gt;&gt;: (Const End)) Expr
((Id :~~&gt;: Integer) :&gt;&gt;: (Const End)) Expr :: *</code></pre>
<p>Done! The type is sound. I think that’s pretty nice!</p>
<p>I can now define my parametrized table:</p>
<pre><code>type Person a =
(Id :~~&gt;: Integer
:&gt;&gt;: Age :~~&gt;: Integer
:&gt;&gt;: Email :~~&gt;: String
:&gt;&gt;: Blurb :~~&gt;: Maybe String
:&gt;&gt;: Const End) a</code></pre>
<p>Sweet!</p>
<p>Then I went a bit type operator crazy and defined a type-level <code>flip ($)</code> and <code>($)</code>:</p>
<pre><code>type a :%: f = f a
infixr 0 :%:
type f :$: a = f a
infixr 0 :$:</code></pre>
<p>So that I could write:</p>
<pre><code>type PersonTable = Table :$: Expr
:%: Id :~~&gt;: Integer
:&gt;&gt;: Age :~~&gt;: Integer
:&gt;&gt;: Email :~~&gt;: String
:&gt;&gt;: Blurb :~~&gt;: Maybe String
:&gt;&gt;: Const End</code></pre>
<h2 id="the-end-result-lessons-learned">The end result, lessons learned</h2>
<p>Suddenly type-annotating my functions that work on HaskellDB’s records seems a lot more attractive! Shortly after, I redefined the operators to be more specific to the record idea, and changed them to:</p>
<pre><code>type PersonTable = Table :$: Expr
:%: Id ::: Integer
:+: Age ::: Integer
:+: Email ::: String
:+: Blurb ::: Maybe String
:+: Const End</code></pre>
<p>Which I think reads pretty nicely. Kind of like Haskell’s native records. Have I gone type operator mad? Maybe, but I love that I can define them. And I didn’t have to change the HaskellDB library one bit!</p>
<p>And kinds are surprisingly easy to grok with the GHCi <code>:k</code> command! I stepped through, checking my type-expressions on the way, just like I do with types and checking my value-expressions. I did try defining a <code>flip</code>, which works:</p>
<pre><code>type Flip (f :: (* -&gt; *) -&gt; * -&gt; *) a b = f b a</code></pre>
<p>But it’s not polymorphic on the parameters of <code>f</code>. Kind polymorphism would be neat, but I wonder how much use it would have. It we had it, though, this “reader monad” could be parameterized over an arbitrary kind.</p>]]></description>
<pubDate>Thu, 07 Oct 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/haskelldb-and-typeoperator-madness</guid>
</item>
<item>
<title>Little Codepad library</title>
<link>http://chrisdone.com/posts/codepad</link>
<description><![CDATA[<p><a href="http://codepad.org/">Codepad.org</a> is a nice paste site that runs your programs and displays the output. For <a href="http://hpaste.org/">hpaste.org</a> I used it to optionally run pastes. I made <a href="http://hackage.haskell.org/package/codepad">a little library and put it on Hackage</a>.</p>]]></description>
<pubDate>Fri, 01 Oct 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/codepad</guid>
</item>
<item>
<title>Crashing IE8 with two lines of code</title>
<link>http://chrisdone.com/posts/crash-ie8</link>
<description><![CDATA[<p>In my wonderful time developing for IE8, I discovered, after some swearing, this gem:</p>
<pre><code>&lt;script src=&quot;http://code.jquery.com/jquery-1.4.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;$(&#39;&lt;link rel=&quot;stylesheet&quot;/&gt;&#39;).attr(&#39;href&#39;,&#39;&#39;);&lt;/script&gt;</code></pre>
<p>Are you running IE8? <a href="http://chrisdone.com/code/ie8-crash.html">Crash my browser.</a></p>
<p>I can’t believe in 2010 I can write some JavaScript that can <strong>crash</strong> a web browser. But, then, taking <em>all</em> things into consideration, I can.</p>
<p>I downloaded the latest IE8 (8.0.6001.18702) and am running this in XP SP2 in VirtualBox. I hope, but doubt, this bug has been fixed, and that it does not crash your browser. Kind of.</p>]]></description>
<pubDate>Thu, 30 Sep 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/crash-ie8</guid>
</item>
<item>
<title>Juicy juicy web feeds!</title>
<link>http://chrisdone.com/posts/juicy-juicy-web-feeds</link>
<description><![CDATA[<p>A while ago I made a Haskell web app called Juicy which downloads feeds from community-voted aggregators and calculates how “juicy” they are, i.e., how much movement there is and how much new stuff comes in over time. It downloads the feeds once an hour.</p>
<p>I put it <a href="http://github.com/chrisdone/juicy">on Github</a> and then forgot about it. Today I found it again and fixed a bug that baffled me a while ago – an integer overflow on <a href="http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Control-Concurrent.html#v%3AthreadDelay">threadDelay</a> – and thought I’d put it online <a href="http://chrisdone.com/juicy/">here</a>. It should build a better picture over time. Originally I wrote it to prove that YCombinator is more fresh than Reddit. We’ll see, I guess. I don’t visit either anymore.</p>]]></description>
<pubDate>Sun, 26 Sep 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/juicy-juicy-web-feeds</guid>
</item>
<item>
<title>More hpaste goodies</title>
<link>http://chrisdone.com/posts/more-hpaste-goodies</link>
<description><![CDATA[<p>It’s been ten days since launching the new <a href="http://hpaste.org/">hpaste.org</a> and it seems to be successful. I completed the following:</p>
<ul>
<li>Import old pastes from old web site</li>
<li>Add a simple spam trap, which seems to be doing a good job</li>
<li>Add a <a href="http://community.haskell.org/~ndm/hlint/">HLint</a> hints feature</li>
<li>Added <a href="http://codepad.org/">Codepad.org</a> run output feature</li>
</ul>
<p><a href="http://hpaste.org/40093/xmonadhs">An example of both HLint and Codepad.org</a>. Remember: To run the code (in Haskell at least) it needs a main function. I will later add a bit of code to detect whether the code is parseable (valid syntax) and runnable (includes main function) automatically with <a href="http://hackage.haskell.org/package/haskell-src-exts">haskell-src-exts</a>.</p>
<p>As of this post, Codepad.org supports the following languages: C, C++, D, Haskell, Lua, OCaml, PHP, Perl, Plain Text, Python, Ruby, Scheme, and Tcl. I wrote the code as a separate library that you can use. It’s on <a href="http://github.com/chrisdone/amelie/blob/master/src/Web/Codepad.hs">the Amelie project on Github</a> for now, I also put it <a href="http://hpaste.org/40120/webcodepad">on hpaste as a more permanent place.</a> Not sure if it’s worth making as a Hackage package.</p>
<p>I still need to add the <a href="http://bc.tech.coop/blog/041020.html">Context in IRC</a> feature that paste.lisp.org used to support and an RSS feed, and a <a href="http://tryhaskell.org/">tryhaskell</a> prompt.</p>
<p>After making the title and author fields mandatory, there’s a big difference in naming: <a href="http://i.imgur.com/qmsKR.png">here’s the old hpaste.org pastes</a> and <a href="http://i.imgur.com/ftYWL.png">here’s the new ones since launching</a>.</p>
<p>The amelie gitcast is still in the pipeline.</p>
<p>Drop me an email if you have interesting, do-able ideas for hpaste.</p>
<p>For those interested, here’s <a href="http://chrisdone.com/docs/GA_20100826-20100925.pdf">a Google Analytics report for tryhaskell.org for the last month.</a> I am curious about how many of those goal conversions actually encourage anyone to look at a Haskell book or download the compiler.</p>]]></description>
<pubDate>Sat, 25 Sep 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/more-hpaste-goodies</guid>
</item>
<item>
<title>Amelie: hpaste.org gets an update</title>
<link>http://chrisdone.com/posts/hpaste-update</link>
<description><![CDATA[<p>The hpaste.org site had some database locking issues and the person hosting it has not been around to fix it for a long time. I thought the source code for the site was a bit big, so I thought it would be a neat project to write from scratch as <a href="http://github.com/chrisdone/amelie-emacs-cast">a long screencast about writing a Haskell project from scratch, using Hackage libraries, etc..</a> I will post more about the screencast later once I am done. The project is called <a href="http://github.com/chrisdone/amelie">amelie.</a></p>
<p><a href="http://www.serpentine.com/blog/">Bryan O’Sullivan</a> kindly pointed the <a href="http://hpaste.org/">hpaste.org</a> domain to my new server. The service is also available under the domain <a href="http://paste.tryhaskell.org/">paste.tryhaskell.org</a>.</p>
<p>I plan on adding some niceties like <a href="http://community.haskell.org/~ndm/hlint/">hlint</a> and the <a href="http://bc.tech.coop/blog/041020.html">Context in IRC</a> feature that paste.lisp.org used to support. I will add some trivial spam filters depending on the type and frequency of the spam recieved. I will also add an API pretty soon and an RSS feed. Once the spam’s sorted out we can properly bring back the hpaste bot into the IRC channel.</p>
<p>I also have an archive of all the old pastes from hpaste.org (there are 37,000 of them). I have already written an import script for this so I will get those imported sometime this week.</p>
<p>I recently had to switch my VPS host to a new one, it may be that tryhaskell will be a little twitchy. It seems okay though! Contact me at <script type="text/javascript">
<!--
h='&#x67;&#x6d;&#x61;&#x69;&#108;&#46;&#x63;&#x6f;&#x6d;';a='&#64;';n='&#x63;&#104;&#114;&#x69;&#x73;&#100;&#x6f;&#110;&#x65;';e=n+a+h;
document.write('<a h'+'ref'+'="ma'+'ilto'+':'+e+'">'+'<code>'+e+'</code>'+'<\/'+'a'+'>');
// -->
</script><noscript>&#x63;&#104;&#114;&#x69;&#x73;&#100;&#x6f;&#110;&#x65;&#32;&#x61;&#116;&#32;&#x67;&#x6d;&#x61;&#x69;&#108;&#32;&#100;&#x6f;&#116;&#32;&#x63;&#x6f;&#x6d;</noscript> if you experience problems.</p>
<p>(Yes, I did just re-use the design/colours from TryHaskell.)</p>]]></description>
<pubDate>Wed, 15 Sep 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/hpaste-update</guid>
</item>
<item>
<title>Haskell mode Emacs extensions</title>
<link>http://chrisdone.com/posts/haskell-mode-exts</link>
<description><![CDATA[<p>I have made <a href="http://github.com/chrisdone/haskell-mode-exts">a github project for a package of Emacs modules for extending Haskell mode.</a> Some initial modules so far:</p>
<ol style="list-style-type: decimal">
<li>haskell-align-imports.el</li>
<li>haskell-installed-packages.el</li>
<li>haskell-navigate-imports.el</li>
<li>haskell-sort-imports.el</li>
<li>inf-haskell-send-cmd.el</li>
</ol>
<p>I have more in progress and more planned.</p>
<p>One example is <a href="http://www.youtube.com/watch?v=UXHSiUPKLvg&amp;fmt=35">making editing imports automatically alphabetically ordered and indented.</a> This one is a little tricky to get right so I will get back to you on this one. Once I am happy with it, I will generalize it to a lot of Haskell statements, like <code>data</code> declarations:</p>
<pre><code>data Foo = X
| Y</code></pre>
<p>If I type <code>bar</code> after <code>Foo</code>, I should get,</p>
<pre><code>data Foobar = X
| Y</code></pre>
<p>automatically. I have seen this type of thing in <a href="http://haskell.org/haskellwiki/Yi">the Yi editor</a> and it is a really good idea. Equally for definitions:</p>
<pre><code>foo x = do x
y</code></pre>
<p>If I add another parameter, the rest of the function body should be indented accordingly,</p>
<pre><code>foo x y = do x
y</code></pre>
<p>and so on.</p>]]></description>
<pubDate>Wed, 11 Aug 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/haskell-mode-exts</guid>
</item>
<item>
<title>Getting all installed Haskell packages/modules from Emacs</title>
<link>http://chrisdone.com/posts/emacs-haskell-installed-packages</link>
<description><![CDATA[<p>I wrote a self-contained Emacs module for retrieving all the installed Haskell package descriptions (as an association list), and the exposed modules inside them.</p>
<ul>
<li><a href="http://gist.github.com/511670">Haskell installed packages</a></li>
</ul>
<p>This is intended for Elisp programmers to use to make import handling and package handling easier.</p>
<p>For example, if I run <code>(haskell-installed-packages)</code>, I get:</p>
<pre><code>(&quot;Cabal-1.8.0.2&quot; &quot;array-0.3.0.0&quot; &quot;base-3.0.3.2&quot; &quot;base-4.2.0.0&quot;
&quot;bin-package-db-0.0.0.0&quot; &quot;bytestring-0.9.1.5&quot;
&quot;containers-0.3.0.0&quot; &quot;directory-1.0.1.0&quot; &quot;extensi\
ble-exceptions-0.1.1.1&quot; &quot;ffi-1.0&quot; &quot;filepath-1.1.0.3&quot;
&quot;ghc-6.12.1&quot; ...)</code></pre>
<p>I can also run the following:</p>
<pre><code>(haskell-read-pkg-description
(haskell-ghc-pkg-command &quot;describe Cabal-1.8.0.2&quot;))</code></pre>
<p>And the following is returned:</p>
<pre><code>((&quot;name&quot; . &quot;Cabal&quot;) (&quot;version&quot; . &quot;1.8.0.2&quot;) (&quot;id&quot;
. &quot;Cabal-1.8.0.2-bc92fe595a99db06fca8c2eb712108b4&quot;)
(&quot;license&quot; . &quot;BSD3&quot;) (&quot;copyright&quot; . &quot;2003-2006, Isaac Jones
2005-2009, Duncan Coutts&quot;) (&quot;maintainer&quot;
. &quot;cabal-devel@haskell.org&quot;) (&quot;stability:&quot; . &quot;&quot;) (&quot;homepage&quot;
. &quot;http://www.haskell.org/cabal/&quot;) (&quot;package-url:&quot; . &quot;&quot;)
(&quot;description&quot; . &quot;The Haskell Common Architecture for
Building Applications and Libraries: a framework defining a
common interface for authors to more easily build their
Haskell applications in a portable way. . The Haskell Cabal
is part of a larger infrastructure for distributing,
organizing, and cataloging Haskell libraries and tools.&quot;)
(&quot;category&quot; . &quot;Distribution&quot;) (&quot;author&quot; . &quot;Isaac Jones
&lt;ijones@syntaxpolice.org&gt; Duncan Coutts
&lt;duncan@haskell.org&gt;&quot;) ...)</code></pre>
<p>Finally I acquire a complete list of all modules installed with <code>(haskell-installed-modules)</code>, which is defined in terms of the above two functions.</p>
<pre><code>(&quot;Distribution.Compiler&quot; &quot;Distribution.InstalledPackageInfo&quot;
&quot;Distribution.License&quot; &quot;Distribution.Make&quot;
&quot;Distribution.ModuleName&quot; &quot;Distribution.Package&quot;
&quot;Distribution.PackageDescription&quot;
&quot;Distribution.PackageDescription.Configuration&quot;
&quot;Distribution.PackageDescription.Parse&quot;
&quot;Distribution.PackageDescription.Check&quot; &quot;Distribution.ParseUtils&quot;
&quot;Distribution.ReadE&quot; ...)</code></pre>
<p>These functions cache automatically. You can force them to refresh the cache by passing <code>t</code> to them. Or run the following function.</p>
<p>In your .emacs start-up file, put:</p>
<pre><code>(haskell-installed-packages-refresh-all)</code></pre>
<p>Which will refresh all packages and modules. It takes about 3 seconds on my machine. But I am okay with that because I restart Emacs rarely. You do not have to put it here, but it saves waiting for it to update when you are mid-way through some action.</p>
<p>In the future it is completely possible to speed this up by checking the last modified date on the Haskell package databases, and to only update the changed packages.</p>
<p>For my use case, I am going to use it for smex or anything.el-like completion and write another module with clever import insertion so that one can navigate between import statement parts with arrow keys. What can I say?; I really do not like typing out import statements.</p>
<p>For Emacs newbies, if you are impatient and want to use this right away, pop this in your .emacs file:</p>
<pre><code>(require &#39;haskell-installed-packages)
(setq haskell-ghc-pkg-bin-path &quot;/home/chris/Programs/bin/ghc-pkg&quot;)
(haskell-installed-packages-refresh-all)</code></pre>
<p>You can omit the <code>setq</code> line if it works without it; otherwise change it to wherever your ghc-pkg binary lies. Now a very simple shortcut for completing Haskell modules:</p>
<pre><code>(defun haskell-complete-module ()
&quot;Insert a completed Haskell module.&quot;
(interactive)
(insert (ido-completing-read &quot;Module: &quot;
(haskell-installed-modules))))</code></pre>
<p>Then bind it to a key:</p>
<pre><code>(define-key haskell-mode-map (kbd &quot;C-c i&quot;) &#39;haskell-complete-module)</code></pre>
<p>Or whatever you prefer.</p>]]></description>
<pubDate>Sat, 07 Aug 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/emacs-haskell-installed-packages</guid>
</item>
<item>
<title>Navigating to/from Haskell import lists in Emacs</title>
<link>http://chrisdone.com/posts/haskell-navigate-modules</link>
<description><![CDATA[<p>I wrote a self-contained Emacs module for navigating to and from the import list in Haskell files.</p>
<ul>
<li><a href="http://gist.github.com/511240">Haskell modules navigator</a></li>
</ul>
<p>The use case is, for example, two sets of module lists:</p>
<pre><code>import Control.Applicative ((&lt;$&gt;))
import Data.Bool.Higher (bool)
import Data.List (sort,intercalate)
import Data.Maybe (catMaybes)
import System.Process (readProcess)
import System.Environment (getArgs)
import qualified Distribution.PackageDescription.Parse as P
import qualified Distribution.PackageDescription as PD
import qualified Distribution.ModuleName as PM
import Text.Regex.Posix ((=~))</code></pre>
<p>And I am half way down the file, and realise I need to import <code>Control.Concurrent</code>. So I hit <code>F8</code>, which takes the cursor to the <code>Control.Applicative</code> line. I enter my import statement, and then hit <code>C-u F8</code> to return back to the middle of the file to what I was doing.</p>]]></description>
<pubDate>Fri, 06 Aug 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/haskell-navigate-modules</guid>
</item>
<item>
<title>Haskell align imports</title>
<link>http://chrisdone.com/posts/haskell-align-imports</link>
<description><![CDATA[<p>I made a little Elisp script which aligns your import lists in your Haskell code. I pasted it to Gist:</p>
<ul>
<li><a href="http://gist.github.com/453933">Haskell align imports for Emacs</a></li>
<li><a href="http://gist.github.com/454255">Haskell align imports for Vim</a></li>
</ul>
<p>mauke from the Freenode IRC contributed an equivalent vim plugin.</p>]]></description>
<pubDate>Sat, 31 Jul 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/haskell-align-imports</guid>
</item>
<item>
<title>Uploading Hackage Packages</title>
<link>http://chrisdone.com/posts/uploading-hackage-packages</link>
<description><![CDATA[<p>I found two good Haskell libraries recently and realised they were not packaged up and put on Hackage! So I updated them to the latest base and GHC extensions, made a proper Cabal package out of them and uploaded them:</p>
<ul>
<li><a href="http://hackage.haskell.org/package/frisby">frisby: Linear time composable parser for PEG grammars.</a></li>
<li><a href="http://hackage.haskell.org/package/pappy">pappy: Packrat parsing; linear-time parsers for grammars in TDPL.</a></li>
</ul>
<p>If you have interest in being the maintainer of these packages, please let me know.</p>
<p>Lots of people had not even heard of these two packages above before I uploaded them to Hackage. So I am gonna go out on a limb and say packaging up substantial code bases and putting them on Hackage should be standard practice in the Haskell community.</p>]]></description>
<pubDate>Tue, 13 Jul 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/uploading-hackage-packages</guid>
</item>
<item>
<title>The Haskell module landscape</title>
<link>http://chrisdone.com/posts/haskell-module-landscape</link>
<description><![CDATA[<p>I was pondering how naming Haskell packages with a proper hierarchy is quite important, and wondered what the general hierarchy of the Hackage packages was like. So I grabbed the <a href="http://hackage.haskell.org/packages/archive/00-index.tar.gz">tarball of pakage descriptions</a> from <a href="http://hackage.haskell.org/packages/hackage.html">Hackage</a> and ran <a href="http://gist.github.com/463472">a little messy Haskell script</a> and got <a href="http://gist.github.com/raw/463423/f8458d83b1a7cc26cdbf812747188993e50cd8a2/The%20Haskell%20module%20landscape">this list.</a></p>
<p>Here is a snippet:</p>
<pre><code>hsdns: ADNS
hsdns: ADNS.Base
hsdns: ADNS.Endian
hsdns: ADNS.Resolver
cv-combinators: AI.CV.ImageProcessors
HOpenCV: AI.CV.OpenCV.CV
HOpenCV: AI.CV.OpenCV.CxCore
HOpenCV: AI.CV.OpenCV.HighGui</code></pre>
<p>It is interesting to see how there are quite a few packages that could be easily put into the proper namesace, e.g ADNS below should be in the Network hierarchy. It is also cool to see clusters of separate packages providing functionality for the same module, e.g check out Control.Applicative!</p>
<pre><code>special-functors: Control.Applicative
base: Control.Applicative
applicative-extras: Control.Applicative.Backwards
applicative-extras: Control.Applicative.Compose
applicative-extras: Control.Applicative.Error
InfixApplicative: Control.Applicative.Infix
category-extras: Control.Applicative.Parameterized
action-permutations: Control.Applicative.Permutation
applicative-extras: Control.Applicative.State
yjtools: Control.Applicative.Tools
unicode-symbols: Control.Applicative.Unicode
base-unicode-symbols: Control.Applicative.Unicode</code></pre>
<p>Control.Concurrent also has a lot going on inside it. There are quite a lot of packages under Network, too.</p>
<p>One idea: Hackage could have an additional page which displays this, fully linked up to the packages in question, with an MSDN-style complete collapsible/expandable module hierarchy menu on the left and documentation on the right. I am not saying that is the right way to do it, but it certainly makes for fun browsing for the Haskell entire open source codebase. (It would also encourage library writers to put their libraries in a useful namespace.)</p>]]></description>
<pubDate>Sun, 04 Jul 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/haskell-module-landscape</guid>
</item>
<item>
<title>Try Haskell Updates</title>
<link>http://chrisdone.com/posts/try-haskell-updates</link>
<description><![CDATA[<p>In the past month I moved to Italy for a new Haskell job. Hopefully, we will be releasing some open source contributions.</p>
<p>I added <a href="http://github.com/chrisdone/tryhaskell/commits/master/">about 25 more steps to Try Haskell and touched on types in Haskell, clickable code samples</a>, lessons selection, go-back support, stricter expression checking, from the help of feedback from <a href="http://news.ycombinator.com/item?id=1393593">YCombinator</a>, including <a href="http://simondavidpratt.com/">Simon Pratt</a>, who provided <a href="http://github.com/chrisdone/jquery-console/commits/master/">various patches to the jquery console</a> with refactoring, fixing the history and adding standard console shortcuts.</p>
<p>I <a href="http://github.com/chrisdone/haskell-json/commits/master/">tidied up the JSON service code</a>, removed redundant files, tided up module imports, made the mueval-core path not hard coded, etc. It is currently written with the FastCGI API. I have started a branch with the aim of switching it to <a href="http://snapframework.com/">Snap</a>.</p>
<p>I have also added top-level binding support, e.g.:</p>
<pre><code>&gt; x = 1
&gt; (y,z) = (5,6)
&gt; x * y * z
=&gt; 30
&gt;</code></pre>
<p>It <a href="http://github.com/chrisdone/haskell-json/commit/ee87544698759eadbb90a911b78343bbde8531a6">works mostly in the same way GHCi does, with nested LET expressions</a>. I think this way is sound. The bindings are per-session; they expire when you close your browser.</p>
<p>There is one change to the JSON service, when evaluating a top-level expression, the success return value is:</p>
<pre><code>{&quot;bind&quot;:&quot;OK.&quot;}</code></pre>
<p>Failure is returned as normal, e.g.</p>
<pre><code>{&quot;error&quot;:&quot;Not in scope: `y&quot;}</code></pre>
<p>Another neat thing I added as <a href="http://news.ycombinator.com/item?id=1393735">suggested by tumult on YCombinator</a> is support to link to a given expression, e.g.:</p>
<pre><code>&gt; map (*2) [1..1 0]
=&gt; [2,4,6,8,10,12,14,16,18,20]
&gt; link
link for map (*2) [1..10]
&gt;</code></pre>
<p>(The <a href="http://tryhaskell.org/?input=%6d%61%70%20%28%2a%32%29%20%5b%31%2e%2e%31%30%5d"><code>link for map (*2) [1..10]</code></a> text is a link.)</p>
<p>I also <a href="http://tryhaskell.org/?input=circle%2020%2020%2020">re-enabled Raphael support</a> for the hell of it.</p>
<p>I have more plans for it such as embedded code editor and smallcheck exercises, user-uploaded tutorials, and adding an embedded console to Hackage at some point would be nice, but that is all for now.</p>
<p>In other news, two other languages have started their own Try <em>Lang</em> sites! Check these out:</p>
<ul>
<li><a href="http://www.try-clojure.org/">Try Clojure</a></li>
<li><a href="http://www.tryerlang.org/">Try Erlang</a></li>
</ul>
<p>Raising awareness of all functional languages is a great thing!</p>]]></description>
<pubDate>Sun, 13 Jun 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/try-haskell-updates</guid>
</item>
<item>
<title>Yay! hpaste bot is back</title>
<link>http://chrisdone.com/posts/hpaste-bot</link>
<description><![CDATA[<p>The <a href="http://hpaste.org/">hpaste</a> site used to join the #haskell IRC channel and sit there waiting for pastes. When someone made a paste it would announce them in the channel with a link. Half a year ago (or longer, I guess) hpaste was rewritten and hpaste2 was born. Unfortunately, the IRC announcer failed to work on the server it runs on.</p>
<p>It’s a pretty convenient feature and it encourages people to paste and share the code they’re having problems with and the code they find interesting and want to share. If hpaste sends the link for you, it’s not an active thing on your part.</p>
<p>I figured it would be a good idea to use the <a href="http://hackage.haskell.org/package/rss2irc">rss2irc program on Hackage</a>, which, I believe, is what the Hackage IRC announcer uses. E.g.</p>
<pre><code>* hackagebot hashed-storage 0.4.11 - Hashed file storage support code.
http://hackage.haskell.org/package/hashed-storage-0.4.11 (EricKow)</code></pre>
<p>I read the hpaste source and it has some code for generating an RSS feed but it’s all commented out. So I wrote <a href="http://github.com/chrisdone/hpaste-feed">a little program to periodically fetch the main page of hpaste and generate an RSS feed from it</a> and write it to <a href="http://tryhaskell.org/hpaste.rss">a file in my web server directory.</a> I’ve been thinking of doing this for more than half a year, but thought “someone’ll sort it out”.. never did. So here we go.</p>
<p>I run it like this:</p>
<pre><code>hpaste-feed /var/www/tryhaskell.org/hpaste.rss 30</code></pre>
<p>And then just hook-up rss2irc with it:</p>
<pre><code>rss2irc http://tryhaskell.org/hpaste.rss \
&#39;hpaste@irc.freenode.net/#hpaste-test&#39; \
-i 1 -l --author &amp; disown</code></pre>
<p>I make a paste, and within a couple seconds, tada!</p>
<pre><code>&lt;hpaste&gt; a test paste (chrisdone) http://hpaste.org/fastcgi/hpaste.fcgi/view?id=24822</code></pre>
<p>I’m running it on the tryhaskell server so hopefully it should be stable 24/7. Only problem is hpaste.org going down, but can’t be avoided. I’ll need to see what errors are thrown with the <a href="http://hackage.haskell.org/package/HTTP">Network.HTTP</a> library when the request times out or fails.</p>]]></description>
<pubDate>Sun, 11 Apr 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/hpaste-bot</guid>
</item>
<item>
<title>A bit of cabal-install hacking</title>
<link>http://chrisdone.com/posts/cabal-install-hacking</link>
<description><![CDATA[<p><strong>EDIT:</strong> It appears cabal-install already supports bash completion for commands, provided by a script in the bash-completion directory of the cabal-install package. It also supports flag completion. Cool!</p>
<p>A couple other people at Zurihac agreed that it would be nice if Cabal (cabal-install) supported completion like <code>git</code>. You can write <code>git co</code> instead of <code>git commit</code>, etc. saving a bit of typing in the late hacking hours. I made <a href="http://github.com/chrisdone/cabal-install/commit/cf74c1e9136b53ac198bc6915abd57cb9972ec2c">a wee patch for Cabal 0.6.4 to do this.</a> Here’s me building cabal-install with cabal-install.</p>
<pre><code>chris@chrisamilo:~/Haskell/cabal-install-0.6.4$ cabal co;cabal b;cabal i
Resolving dependencies...
Configuring cabal-install-0.6.4...
Preprocessing executables for cabal-install-0.6.4...
Building cabal-install-0.6.4...
Resolving dependencies...
Configuring cabal-install-0.6.4...
Preprocessing executables for cabal-install-0.6.4...
Building cabal-install-0.6.4...
Installing executable(s) in /home/chris/.cabal/bin</code></pre>
<p>It’s pretty nice. I guess it’s probably preferable to write some personal scripts to run on top of cabal but it’d be nice if everyone had it.</p>
<p>As with most Haskell projects the source code is really easy to patch so I’ll probably do more cabal-install hacking.</p>]]></description>
<pubDate>Fri, 09 Apr 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/cabal-install-hacking</guid>
</item>
<item>
<title>A Haskell JSON service and updated Try Haskell!</title>
<link>http://chrisdone.com/posts/haskell-json-service-tryhaskell</link>
<description><![CDATA[<p><strong>UPDATE:</strong> The service went down 5 April at about 19:50 GMT+1 to about 20:21. I had to update the watchdog to be more aggressive for Linode (as opposed to my development machine). Just letting you guys know.</p>
<h2 id="make-your-own-try-haskell">Make your own Try Haskell!</h2>
<p>You can now run <a href="http://tryhaskell.org/">Try Haskell!</a> as a simple HTML file locally, or on your own domain, if you like! All you need is an internet connection.</p>
<p>Grab the source with git (or download a <a href="http://github.com/chrisdone/tryhaskell/zipball/master">.zip</a> or <a href="http://github.com/chrisdone/tryhaskell/tarball/master">.tar.gz</a> of the latest version):</p>
<pre><code>$ git clone git://github.com/chrisdone/tryhaskell.git</code></pre>
<p>Get writing interactive tutorials! Please let me know how you get on.</p>
<h2 id="evaluate-haskell-code-anywhere">Evaluate Haskell code anywhere</h2>
<p>You can now also use the JSONP service that Try Haskell uses from anywhere!</p>
<p>It is located at: <code>http://tryhaskell.org/haskell.json</code></p>
<p>And you can download <a href="http://github.com/chrisdone/haskell-json">the haskell-json source from Github</a>:</p>
<pre><code>$ git clone git://github.com/chrisdone/haskell-json.git</code></pre>
<p>Here is a simple Haskell evaluating text box. <a href="/code/haskell-json-example.zip">Download the source.</a></p>
<form action="" id="evaluator">
<fieldset>
<legend>Haskell evaluation</legend> <label>Expression:</label> <input type="text" id="expr"/> <input type="submit" value="Evaluate"/>
<p>
Result: <code id="eval-output">Output here.</code>
</p>
<p>
Type: <code id="eval-type">Type here.</code>
</p>
</fieldset>
</form>
<form action="" id="loader">
<fieldset>
<legend>Haskell loading</legend> <label>Code:</label> <textarea id="contents"></textarea> <input type="submit" value="Load code"/>
<p>
Result: <code id="load-output">Output here.</code>
</p>
</fieldset>
</form>
<script type="text/javascript" src="/code/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/code/haskell-json/encode-hex.js"></script>
<script type="text/javascript" src="/code/haskell-json/haskell-json.js"></script>
<p>Feel free to make this pretty and use it in your blog or books, Haskell courses, etc. Trying Haskell should be easy!</p>
<h2 id="methods-and-options">Methods and options</h2>
<h3 id="eval-method"><code>eval</code> method</h3>
<p>There is an <strong>eval</strong> method for evaluating expressions, used like this:</p>
<pre><code>http://tryhaskell.org/haskell.json?method=eval&amp;expr=23*52</code></pre>
<p>and you get back:</p>
<pre><code>{&quot;result&quot;:&quot;1196&quot;,&quot;type&quot;:&quot;(Num t) =&gt; t&quot;,&quot;expr&quot;:&quot;23*52&quot;}</code></pre>
<p>Note that computations are limited to 750ms. This limit may be softened if people have problems doing useful things.</p>
<h3 id="load-method"><code>load</code> method</h3>
<p>And there is a <strong>load</strong> method for loading your own file into the service for later evaluation, used like this:</p>
<pre><code>http://tryhaskell.org/haskell.json?method=load&amp;contents=x=1</code></pre>
<p>and you get back:</p>
<pre><code>{&quot;success&quot;:&quot;wrote file.&quot;}</code></pre>
<p>Then you can request</p>
<pre><code>http://tryhaskell.org/haskell.json?method=eval&amp;expr=x</code></pre>
<p>and get back:</p>
<pre><code>{&quot;result&quot;:&quot;5&quot;,&quot;type&quot;:&quot;Integer&quot;,&quot;expr&quot;:&quot;x&quot;}</code></pre>
<p>Hurrah!</p>
<h3 id="guid-for-unique-states"><code>guid</code> for unique states</h3>
<p>If you are writing a tutorial or a blog post, maybe you want your visitors to be able to maintain two different states depending on what post/chapter they have open in what tab. You can do this by adding a guid to your request:</p>
<pre><code>http://tryhaskell.org/haskell.json?method=load&amp;contents=x=1&amp;guid=ch2</code></pre>
<p>For “chapter2”, or maybe you could use the ID of your blog post, or whatever you want, with the condition that it is <strong>alphanumeric.</strong></p>
<h3 id="pad-or-jsonp"><code>pad</code> or “JSONP”</h3>
<p>If you are making your request from JavaScript, you will need to follow the JSON style of making requests. <code>haskell.json</code> supports this by adding a <code>pad</code> parameter:</p>
<pre><code>http://tryhaskell.org/haskell.json?method=eval&amp;expr=Just%201&amp;pad=doStuff</code></pre>
<p>and you get back:</p>
<pre><code>doStuff({&quot;result&quot;:&quot;Just 1&quot;,&quot;type&quot;:&quot;(Num t) =&gt; Maybe t&quot;,&quot;expr&quot;:&quot;Just 1&quot;})</code></pre>
<h2 id="implementing-simple-jsonp-in-javascript">Implementing simple JSONP in JavaScript</h2>
<p>I use jQuery in these examples, because it is really easy.</p>
<p>So for example I wrote a little function for tryhaskell for making JSONP requests:</p>
<pre><code>function jsonp(url,func) {
handleJSON = function(r){
script.remove();
func(r);
};
var script = $(&#39;&lt;script type=&quot;text/javascript&quot; src=&quot;&#39;+url+&#39;&quot;&gt;&lt;/script&gt;&#39;);
script.attr(&#39;src&#39;,url);
$(&#39;body&#39;).append(script);
}</code></pre>
<p>And it references a global <code>handleJSON</code> function that I define at the top level so that any script file could access it:</p>
<pre><code>var handleJSON = function(a){ alert(&#39;Unassigned JSONP: &#39; + a); }</code></pre>
<p>(Just have a little alert message in case we get something wrong.)</p>
<p>It adds a script tag to the body with the URL we want to query. This is how it gets around the domain restriction of normal AJAX. It is kind of an ugly solution if you ask me, but there you go!</p>
<p>Once the script has been loaded, the global function <code>handleJSON</code> is called. So before that happens, we need to overwrite it <code>handleJSON</code> with our closure to remove our <code>script</code> tag from the DOM and then call the function provided to <code>jsonp</code>.</p>
<p>Bringing it all together we can write something like this:</p>
<pre><code>jsonp(&quot;http://tryhaskell.org/haskell.json?method=eval&amp;pad=handleJSON&amp;expr=&quot;
+ encodeHex(&quot;34*23&quot;),
function(resp){
alert(&quot;Result: &quot; + resp.result);
});</code></pre>
<p>Encoding what you provide in the URL is important.</p>
<p>See the sample zip file above for an example of this.</p>]]></description>
<pubDate>Mon, 05 Apr 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/haskell-json-service-tryhaskell</guid>
</item>
<item>
<title>Tweet your Haskell type errors from Emacs</title>
<link>http://chrisdone.com/posts/tweet-your-haskell-errors</link>
<description><![CDATA[<h2 id="tweet-your-failures">Tweet your failures!</h2>
<p>I wrote <a href="/code/haskell-tweet-errors.el">an Elisp script to send your GHCi type errors to Twitter.</a></p>
<div class="figure">
<img src="/images/tweet-haskell-errors.png" alt="Twitter showing my type errors" /><p class="caption">Twitter showing my type errors</p>
</div>
<p>Add a little something like this to your .emacs:</p>
<pre><code>;; (add-hook &#39;haskell-mode-hook
;; &#39;(lambda ()
;; (load &quot;haskell-tweet-errors.el&quot;)
;; (define-key haskell-mode-map [f5]
;; (lambda ()
;; (interactive)
;; (inferior-haskell-load-file-tweet-errors
;; &quot;&lt;username&gt;&quot; &quot;&lt;password&gt;&quot;)))))</code></pre>
<p>Hit F5 to load your Haskell file with Emacs into GHCi. If there’s a type/kind/class error, it will twitter it and present you with a message:</p>
<blockquote>
<p>Tweeted. Now the world knows about your type error!</p>
</blockquote>
<h2 id="why">Why?</h2>
<p>It’s something called intellectual honesty! According to a talk I saw by Simon Peyton-Jones, the early Haskell compilers would delete your source code upon a type error.</p>
<p>I figure why not replace mild annoyance with public shame?</p>]]></description>
<pubDate>Sun, 04 Apr 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/tweet-your-haskell-errors</guid>
</item>
<item>
<title>Write your blog with Hakyll and Git</title>
<link>http://chrisdone.com/posts/hakyll-and-git-for-you-blog</link>
<description><![CDATA[<p>My home page and blog is written in <a href="http://daringfireball.net/projects/markdown/">Markdown</a> and built with <a href="http://jaspervdj.be/hakyll/">Hakyll</a>. It’s hosted on a Linode VPS account and I update it with <a href="http://git-scm.com/">Git</a>. Here’s how I do it.</p>
<h2 id="work-locally">Work locally</h2>
<p>I have my local web site directory:</p>
<pre><code>chris@chrisamilo:~/Projects/chrisdone-homepage$ ls
code css hakyll.hs images index.html posts posts.html README
templates</code></pre>
<p>Which is mostly stolen from <a href="http://jaspervdj.be/hakyll/tutorials/part06.html">Jasper Van der Jeugt’s Hakyll blog example</a></p>
<p>I work on it locally by building the Hakyll program:</p>
<pre><code>chris@chrisamilo:~/Projects/chrisdone-homepage$ ghc --make hakyll
[1 of 1] Compiling Main ( hakyll.hs, hakyll.o )
Linking hakyll ...</code></pre>
<p>And previewing it locally:</p>
<pre><code>chris@chrisamilo:~/Projects/chrisdone-homepage$ ./hakyll preview
Rendering _site/posts.html
Rendering _site/tags/blog.html
Rendering _site/tags/emacs.html
Rendering _site/tags/hakyll.html
Rendering _site/tags/haskell.html
Rendering _site/tags/twitter.html
Rendering _site/index.html
Rendering _site/posts/2010-04-04-tweet-your-haskell-errors.html
Rendering _site/posts/2010-04-04-hakyll-and-a-new-blog.html
Rendering _site/rss.xml
Starting hakyll server on port 8000...</code></pre>
<p><code>hakyll preview</code> watches your directories for changes and renders any updated files and saves them in the <code>_site</code> directory.</p>
<h2 id="push-to-remote">Push to remote</h2>
<p>Once I’m happy with all my site/blog changes, I commit them:</p>
<pre><code>chris@chrisamilo:~/Projects/chrisdone-homepage$ git commit -m &quot;added code directory, post about tweeting your haskell errors&quot;
[master 02bc308] added code directory, post about tweeting your haskell errors
4 files changed, 166 insertions(+), 0 deletions(-)
create mode 100644 code/haskell-tweet-errors.el
create mode 100644 images/tweet-haskell-errors.png
create mode 100644 posts/2010-04-04-tweet-your-haskell-errors.markdown
chris@chrisamilo:~/Projects/chrisdone-homepage$ git status
# On branch master
nothing to commit (working directory clean)</code></pre>
<p>Then I (personally) push to github, just because I like looking at projects on Github.</p>
<pre><code>chris@chrisamilo:~/Projects/chrisdone-homepage$ git push github
Counting objects: 18, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (13/13), done.
Writing objects: 100% (13/13), 34.59 KiB, done.
Total 13 (delta 3), reused 0 (delta 0)
To git@github.com:chrisdone/chrisdone-homepage.git
62836bf..02bc308 master -&gt; master</code></pre>
<p>Finally I push to my Linode server, which pushes the commit, then runs the post-receive hook which recompiles the <code>hakyll</code> program, and runs <code>./hakyll build</code>, which updates the changed files in the <code>_site</code> directory (which is really just a softlink to my <code>/var/www/chrisdone.com</code> directory.)</p>
<pre><code>chris@chrisamilo:~/Projects/chrisdone-homepage$ git push linode
Counting objects: 18, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (13/13), done.
Writing objects: 100% (13/13), 34.59 KiB, done.
Total 13 (delta 3), reused 0 (delta 0)
[1 of 1] Compiling Main ( hakyll.hs, hakyll.o )
Linking hakyll ...
Rendering _site/css/default.css
Rendering _site/images/tweet-haskell-errors.png
Rendering _site/code/haskell-tweet-errors.el
Rendering _site/posts.html
Rendering _site/tags/emacs.html
Rendering _site/tags/haskell.html
Rendering _site/tags/twitter.html
Rendering _site/index.html
Rendering _site/posts/2010-04-04-tweet-your-haskell-errors.html
Rendering _site/rss.xml
To chris@chrisdone.com:chrisdone-homepage.git
62836bf..02bc308 master -&gt; master
chris@chrisamilo:~/Projects/chrisdone-homepage$</code></pre>
<p>And that’s it!</p>
<h2 id="my-configuration">My configuration</h2>
<p><code>.gitignore</code>:</p>
<pre><code>_cache
_site
*~
*.hi
*.o
hakyll</code></pre>
<p><code>.git/config</code>:</p>
<pre><code>[remote &quot;github&quot;]
url = git@github.com:chrisdone/chrisdone-homepage.git
fetch = +refs/heads/*:refs/remotes/origin/*
push = +master:refs/heads/master
[remote &quot;linode&quot;]
url = chris@chrisdone.com:chrisdone-homepage.git
push = +master:refs/heads/master</code></pre>
<p>I never fetch from the Linode server, just push to it, so I don’t include a fetch configuration key.</p>
<p>The remote repository can just be empty:</p>
<pre><code>$ mkdir chrisdone-homepage.git
$ cd chrisdone-homepage.git
$ git init
Initialized empty Git repository in /home/chris/chrisdone-homepage.git</code></pre>
<p>And then in my <code>chrisdone-homepage.git/.git/hooks/post-receive</code> file:</p>
<pre><code>#!/bin/sh
if [ -n $GIT_DIR ]; then
unset GIT_DIR
cd ..
fi
git checkout -f
ghc --make hakyll
./hakyll build</code></pre>
<p>I had to look this one up. Git uses <code>GIT_DIR</code> to overwrite the current pwd, so you have to unset it, and the pwd starts as <code>$YOURPROJECT/.git</code>, so you have to <code>cd ..</code>. Once that’s done you just <code>git checkout -f</code>, which does the following:</p>
<pre><code>-f
Proceed even if the index or the working tree differs from HEAD.
This is used to throw away local changes.</code></pre>
<p>Then we build <code>hakyll</code> and update the <code>_site</code> directory!</p>]]></description>
<pubDate>Sun, 04 Apr 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/hakyll-and-git-for-you-blog</guid>
</item>
<item>
<title>A new blog and Hakyll</title>
<link>http://chrisdone.com/posts/hakyll-and-a-new-blog</link>
<description><![CDATA[<p>This is my first post on my new blog which is generated using <a href="http://jaspervdj.be/hakyll/">the fantastic Hakyll package.</a></p>
<p>I previously used my Blogination package which also statically generated blogs, but it wasn’t that flexible and you needed to hack on the actual source to change your blog. It was also quite slow. It was nice though (<a href="http://blog.nicolaspouillard.fr/tags/blogination.html">example blog</a>) and I got a taste for static generation and liked it.</p>
<p>I could possibly do with adding a feed.</p>
<p>Hopefully soon I will have more time for personal open source projects and blogging about them.</p>]]></description>
<pubDate>Sun, 04 Apr 2010 00:00:00 UT</pubDate>
<guid>http://chrisdone.com/posts/hakyll-and-a-new-blog</guid>
</item>
</channel>
</rss>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment