<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>BAM Weblog</title>
    <link href="https://brianmckenna.org/blog/feed.xml" rel="self" />
    <link href="https://brianmckenna.org/blog" />
    <id>https://brianmckenna.org/blog/feed.xml</id>
    <author>
        <name>Brian McKenna</name>
        
        <email>brian@brianmckenna.org</email>
        
    </author>
    <updated>2025-01-17T00:00:00Z</updated>
    <entry>
    <title>Overriding Flakes Inputs in Hydra</title>
    <link href="https://brianmckenna.org/blog/hydra_dynamic_flakes" />
    <id>https://brianmckenna.org/blog/hydra_dynamic_flakes</id>
    <published>2025-01-17T00:00:00Z</published>
    <updated>2025-01-17T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve been using NixOS for over 10 years now. I run NixOS on all of my servers, desktops and laptops - but also weird things like game consoles, e-book readers and mobile phones. Since I have a reasonable amount of personal Nix code, it’s important I have continuous integration configured for my various systems.</p>
<p>So I run a few Hydra servers with that goal. Hydra supports periodically fetching different inputs then building - but not for Nix Flakes! When using Flakes, the inputs can only come from the <code>flake.lock</code> file. This means that you can’t say “build this Flake every 24 hours with the latest nixpkgs” - i.e. if you give Hydra a Flake, it’s always going to build the same thing.</p>
<p><img src="https://brianmckenna.org/files/nix-legacy-flake-hydra.png" /></p>
<p>It would be ideal if Hydra fully understood Nix Flakes and was able to override inputs. Instead, I’ve hacked up a workaround which I’ve been using for a year now, so I should document it here.</p>
<p>The idea is:</p>
<ol type="1">
<li>Hydra supports supplying updated inputs to “legacy” (non-flake) Nix expressions</li>
<li>flake-compat implements Flakes using “legacy” Nix</li>
</ol>
<p>We should be able to just combine those two things and have a daily build of our Flake code. Sadly, flake-compat also doesn’t support overriding inputs. Luckily, after <a href="https://github.com/puffnfresh/flake-compat/commit/f87ebeacafa2f20cbd8e211dd11d0a4d7c49d749">deleting some legacy code which I personally didn’t need</a> in my fork, the change was super simple:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode diff"><code class="sourceCode diff"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="dt">@@ -5,7 +5,10 @@</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a> # containing &#39;defaultNix&#39; (to be used in &#39;default.nix&#39;), &#39;shellNix&#39;</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a> # (to be used in &#39;shell.nix&#39;).</span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a><span class="st">-{ src, system ? builtins.currentSystem or &quot;unknown-system&quot; }:</span></span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a><span class="va">+{ src</span></span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a><span class="va">+, system ? builtins.currentSystem or &quot;unknown-system&quot;</span></span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a><span class="va">+, nodeOverrides ? {}</span></span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a><span class="va">+}:</span></span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a> let</span>
<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a><span class="dt">@@ -199,7 +202,7 @@ let</span></span>
<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a>           else</span>
<span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a>             sourceInfo</span>
<span id="cb1-16"><a href="#cb1-16" aria-hidden="true" tabindex="-1"></a>       )</span>
<span id="cb1-17"><a href="#cb1-17" aria-hidden="true" tabindex="-1"></a><span class="st">-      lockFile.nodes;</span></span>
<span id="cb1-18"><a href="#cb1-18" aria-hidden="true" tabindex="-1"></a><span class="va">+      lockFile.nodes // nodeOverrides;</span></span>
<span id="cb1-19"><a href="#cb1-19" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-20"><a href="#cb1-20" aria-hidden="true" tabindex="-1"></a>   result =</span>
<span id="cb1-21"><a href="#cb1-21" aria-hidden="true" tabindex="-1"></a>     if !(builtins.pathExists lockFilePath)</span></code></pre></div>
<p>Which makes it possible to write a plain Nix expression which takes the inputs from Hydra and passes them into the existing Flake code.</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode nix"><code class="sourceCode nix"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="op">{</span> <span class="va">nixpkgs</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="op">,</span> <span class="va">jovian-nixos</span></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a><span class="op">,</span> <span class="va">flake-compat</span></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a><span class="op">}</span>:</span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span></span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a>  <span class="va">flake</span> <span class="op">=</span> <span class="va">src</span><span class="op">:</span></span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a>    <span class="op">(</span><span class="bu">import</span> flake<span class="op">-</span>compat <span class="op">{</span></span>
<span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a>      <span class="kw">inherit</span> src<span class="op">;</span></span>
<span id="cb2-10"><a href="#cb2-10" aria-hidden="true" tabindex="-1"></a>      <span class="va">nodeOverrides</span> <span class="op">=</span> <span class="op">{</span></span>
<span id="cb2-11"><a href="#cb2-11" aria-hidden="true" tabindex="-1"></a>        <span class="va">nixpkgs</span> <span class="op">=</span> flake nixpkgs<span class="op">;</span></span>
<span id="cb2-12"><a href="#cb2-12" aria-hidden="true" tabindex="-1"></a>        <span class="va">jovian-nixos</span> <span class="op">=</span> flake jovian<span class="op">-</span>nixos<span class="op">;</span></span>
<span id="cb2-13"><a href="#cb2-13" aria-hidden="true" tabindex="-1"></a>      <span class="op">};</span></span>
<span id="cb2-14"><a href="#cb2-14" aria-hidden="true" tabindex="-1"></a>    <span class="op">})</span>.result<span class="op">;</span></span>
<span id="cb2-15"><a href="#cb2-15" aria-hidden="true" tabindex="-1"></a><span class="kw">in</span></span>
<span id="cb2-16"><a href="#cb2-16" aria-hidden="true" tabindex="-1"></a><span class="op">(</span>flake <span class="ss">../.</span><span class="op">)</span>.outputs.hydraJobs;</span></code></pre></div>
<p>Which we can configure in Hydra:</p>
<p><img src="https://brianmckenna.org/files/nix-hydra-inputs.png" /></p>
<p>And there we go. I have daily builds for each of my NixOS systems. When something changes in nixpkgs and breaks a system, I am notified and can fix it.</p>]]></summary>
</entry>
<entry>
    <title>Off-Grid Men's Shed</title>
    <link href="https://brianmckenna.org/blog/off_grid_mens_shed" />
    <id>https://brianmckenna.org/blog/off_grid_mens_shed</id>
    <published>2024-06-14T00:00:00Z</published>
    <updated>2024-06-14T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I live near the <a href="https://lner.com.au/">Launceston &amp; North East Railway</a>. I’ve always wanted to see the railway used. I got involved with the group after reading an article that mentioned the idea of an <a href="https://www.abc.net.au/news/2023-08-13/northern-tasmania-railway-group-rail-bugs-attract-tourists/102677074">electric train</a>.</p>
<p>I’ve been interested in electric vehicles for many years now, and I even own the former <a href="https://ficr.com.au/clean-green-shuttle-flinders-island/">Flinders Island Clean Green Airport Shuttle</a>. This 2011 Mitsubishi i-MiEV is possibly the first modern mass-produced electric car in Tasmania. Here’s a photo of it with Tasmanian Greens MP Cassy O’Connor:</p>
<p><img src="https://brianmckenna.org/blog/static/imiev-cassy-oconnor.jpg" /></p>
<p>I’ve had to do electrical repairs on this vehicle because of its age and battery degredation, which has taught me more about electric vehicle components such as inverters and batteries.</p>
<p>When I got involved with the Launceston &amp; North East Railway group, they had just erected a shed using grant funding from Tasmanian Liberal MP Bridget Archer. They received another grant from the <a href="https://www.tasmanianmensshed.org.au/">Tasmanian Men’s Shed Association</a> to add off-grid power to the site. Knowing a bit about the topic, I designed a system for their requirements.</p>
<p><img src="https://brianmckenna.org/blog/static/lner-shed.jpg" /></p>
<p>The requirements were pretty simple. The ability to charge a roughly 20kWh electric train overnight and enough power to run the average 2.4kW power tool during the day. So we’re only looking for roughly a 5kW discharge capacity.</p>
<p>The group had already found some very cheap lithium nickel manganese cobalt oxide battery cells (LG E63B) at a local metal recycler. Most off-grid systems work with 12V, 24V or 48V batteries. It is possible to go higher but regulations in Australia make it easiest to stay below 60V, for safety reasons. Most lithium-ion batteries have an maximum voltage of 4.2V per cell, so 14 cells in series works really well, giving 58.8V at maximum charge. Having 14 cells in series also gives a voltage range which works with most hardware designed for 48V batteries.</p>
<p>Victron makes a few models of combined inverter/chargers. After comparing the range, I noticed the Multi RS Solar which had a power rating of 6kVA, with two independent solar MPPT inputs. I had prior experience with the JK brand of BMS and I knew it was possible to somehow integrate it into a Victron system.</p>
<p>I came up with the following diagram and sent it to the group:</p>
<p><img src="https://brianmckenna.org/blog/static/lner-off-grid-design.png" /></p>
<p>In the end, we ordered the following parts:</p>
<ul>
<li>Victron Multi RS Solar 48/6000/100-450/100 2 Tracker</li>
<li>Victron Ekrano GX</li>
<li>JK BMS 8S-20S 100A BD6A20S10P</li>
<li>12x Suntech 415W solar panels</li>
</ul>
<p>The cells are put together into 14S3P batteries. We had so many cells that we made 8 batteries - almost 80kWh of storage! But we decided to only wire in a single battery to start off with. The solar panels are split into two 6-panel strings. We have two electricians in the group who were able to handle the solar panels and 240V AC wiring. Random bits of wiring and breakers were donated by members.</p>
<p>The Ekrano GX runs <a href="https://github.com/victronenergy/venus">Venus OS</a> and controls the inverter and batteries. I installed <a href="https://github.com/Louisvdw/dbus-serialbattery">dbus-serialbattery</a> on the device and plugged in a USB to RS485 adapter. The RS485 is wired to a port on the JK BMS. This allows the controller to change discharging/charging speeds depending on BMS state. I decided to go for a conservative configuration at first and came up with:</p>
<pre><code>MIN_CELL_VOLTAGE = 3.200
MAX_CELL_VOLTAGE = 4.00
FLOAT_CELL_VOLTAGE = 3.975 

SOC_RESET_VOLTAGE = 4.200

CELL_VOLTAGES_WHILE_CHARGING      = 4.20, 4.10, 4.00, 3.90
CELL_VOLTAGES_WHILE_DISCHARGING   = 3.20, 3.30, 3.40, 3.50

BMS_TYPE = Jkbms

BATTERY_CAPACITY = 180</code></pre>
<p>There’s a flaky network connection, which allows us to remotely monitor the system using Victron’s VRM portal. For example, the shed is only running a fridge and security system most days, so it only discharges to 85% state of charge overnight and quickly gets back to full when the sun comes out:</p>
<p><img src="https://brianmckenna.org/blog/static/lner-vrm-soc.png" /></p>
<p>Here’s a photo of the functional but unfinished installation:</p>
<p><img src="https://brianmckenna.org/blog/static/lner-off-grid-installed.jpg" /></p>
<p>It has been running pretty much like this since the end of March. I’m amazed by how stable everything is. Obviously, it’s underutilised and overkill at the moment, so if you have an electric vehicle charger, hydrogen electrolyser, or NixOS build farm to donate, please do!</p>
<p>This should be the first off-grid men’s shed in Tasmania. The group has workdays most Saturdays, and you’d be welcome to take a look.</p>]]></summary>
</entry>
<entry>
    <title>Type system of Fortnite's Verse language</title>
    <link href="https://brianmckenna.org/blog/verse_types" />
    <id>https://brianmckenna.org/blog/verse_types</id>
    <published>2023-03-29T00:00:00Z</published>
    <updated>2023-03-29T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Epic Games released an initial public implementation of the Verse programming language. Verse has been <a href="https://simon.peytonjones.org/assets/pdfs/verse-March23.pdf" title="‌">designed by some people</a> who really know what they’re doing:</p>
<ul>
<li>Lennart Augustsson</li>
<li>Joachim Breitner</li>
<li>Koen Claessen</li>
<li>Ranjit Jhala</li>
<li>Simon Peyton Jones</li>
<li>Olin Shivers</li>
<li>Tim Sweeney</li>
</ul>
<p>It’s amazing to see a CEO help design a programming language but Tim Sweeney has been advocating for functional programming in games <a href="https://web.archive.org/web/20001202193200/http://www.gamespy.com/legacy/articles/devweek_d.shtm" title="‌">since at least 2000</a> and has previously <a href="http://www.leafpetersen.com/leaf/publications/dtp2013/lambda-aleph-overview.pdf" title="‌">worked on dependent typing</a>.</p>
<p>I’ve read comments that it’s funny for Fortnite to use such a unique and interesting functional programming language. First of all, <em>why not</em> implement Fortnite using functional programming? But it’s also missing the point.</p>
<p>The goal behind Verse is even more ambitious. When people think of Fortnite, they’re probably thinking about the battle royale game mode. A battle royale lobby has just 100 players, which fit within a single compute shard.</p>
<p>But Fortnite is much more than just battle royale. A huge number of Fortnite players are on custom game modes made by people outside of Epic Games. It’s easy to imagine game modes having a few thousand players which can’t fit within a single shard. How do you scale to handle all that game state, correctly?</p>
<p>Software transactional memory is at the core of Verse. Computation is categorised by transactions and ability to rollback. The goal is to make it easy to write working software across multiple servers. A big goal; we don’t often see programmers do that successfully!</p>
<p>As a functional programmer, here are my thoughts about the current implementation of the Verse type system.</p>
<h4 id="types-are-values">Types are values</h4>
<p>Type aliasing is giving names to types. In Verse, this works just like giving names to any other values.</p>
<pre><code>ExampleValue := &quot;Hello world&quot;

integer := int
optional(a : type)&lt;computes&gt; := ?a</code></pre>
<p>This might remind you of Agda or Idris, where type aliases are written in pretty much the same way.</p>
<p>Which might make you ask about full on dependent typing! Let’s try something simple:</p>
<pre><code>int_or_float(b : logic)&lt;computes&gt; : type :=
  if(b?):
    int
  else:
    float

X : int_or_float(true) := 10
Y : int_or_float(false) := 10.0</code></pre>
<p>The above compiles, which <em>seems</em> fantastic! We should have a type which depends on a boolean (called <code>logic</code> in Verse) - but wait!</p>
<pre><code>Z : int_or_float(false) := &quot;Hello&quot;</code></pre>
<p>The above <em>also</em> compiles. How does that make any sense?</p>
<p><code>int_or_float</code> doesn’t actually represent either an <code>int</code> or a <code>float</code>. It always represents the <code>any</code> type! I’m not sure why but it happens whenever you have an explicit return type of <code>type</code>. All of the following uselessly represent the <code>any</code> type:</p>
<pre><code>any1 : type := int
any2 : type := string
any3() : type := interface:
any4() : type := class:</code></pre>
<p>I thought that Verse should just make explicit returns of <code>type</code> into an error, but the issue is much deeper. You can write a function which allows explicit type ascription and things are still broken:</p>
<pre><code>The(x : type, X : x)&lt;computes&gt; : x := X
typeOfInt()&lt;computes&gt; := The(type, int)

# Broken()&lt;computes&gt; : int := The(typeOfInt(), 1)</code></pre>
<p>And I have no idea what the error means:</p>
<blockquote>
<p>This function parameter expects a value of type <code>tuple(type(false, int),int)</code>, but this argument is an incompatible value of type <code>tuple(supertype(int),type{1})</code></p>
</blockquote>
<p>So explicitly referencing <code>type</code> is only useful in type parameters and the only way to define an alias is to not say it returns a <code>type</code>. Maybe we can get dependent types without that! Let’s try something super simple:</p>
<pre><code>documentedInt(S : string)&lt;computes&gt; := int</code></pre>
<p>Nope, doesn’t compile. We hit an explicit Verse restriction and get an error message:</p>
<blockquote>
<p>Parameters of a function without a specified return type must be of type <code>type</code>.</p>
</blockquote>
<p>So actual dependent types are specifically prohibited right now, but I’m guessing that some form of dependent types are coming soon. The only paper available on Verse is on the untyped Verse Calculus, so it’s hard to say, but this really looks like it’s “just” an implementation restriction.</p>
<p>Simon Peyton Jones also gave an interesting type example at the <a href="https://simon.peytonjones.org/assets/pdfs/haskell-exchange-22.pdf" title="‌">Haskell Exchange</a>:</p>
<blockquote>
<p><code>isEven</code> (which succeeds on even numbers and fails otherwise) is a type</p>
</blockquote>
<p>But he must have been talking about this theoretically because I can not see a way of actually doing that today.</p>
<h4 id="higher-kinded-types">Higher-kinded types</h4>
<p>It’s almost possible to express the kind of type constructors:</p>
<pre><code>typeConstructor := type{_(:type)&lt;computes&gt; : type}</code></pre>
<p>This type checks but suffers from the same problem with <code>type</code> being used as a return type - it’s inferred to be <code>any</code>.</p>
<p>But we don’t have to use that broken alias, syntactically we can write down a <code>functor</code> interface like so:</p>
<pre><code>functor(F(: type)&lt;computes&gt; : type) : type := interface:
    Map(a : type, b : type, G(:a)&lt;computes&gt; : b, MA : F(a))&lt;computes&gt; : F(b)</code></pre>
<p>But this has an explicit return type of <code>type</code> which means it’s equivalent to <code>any</code>. If we remove that explicit return type we’ll again get the message about parameters only being able to be <code>type</code>:</p>
<blockquote>
<p>Parameters of a function without a specified return type must be of type <code>type</code>.</p>
</blockquote>
<p>So I think we’re blocked on being able to reduce code duplication. You’ll have to write functions for lists, maps, arrays, optionals, etc. separately. Code duplication! Gross!</p>
<h4 id="effects">Effects</h4>
<p>The effect system is different from most others, it’s all about transactions. The “<a href="https://dev.epicgames.com/documentation/en-us/uefn/specifiers-and-attributes-in-verse">exclusive effects</a>” are:</p>
<ul>
<li>Converges (terminates)</li>
<li>Computes (pure)</li>
<li>Varies (reads random or non-constant state)</li>
<li>Transacts (has mutation)</li>
<li>No rollback (side-effects)</li>
</ul>
<p>You can’t write your own effects and you can’t write effect handlers. It’s all built-in to Verse. You can’t even write a <code>converges</code> function today, that’s reserved for native code. I can imagine Verse gaining a totality checker to enable writing non-native <code>converges</code> functions.</p>
<p>The documentation says that the default effect is <code>no_rollback</code> but this isn’t true for at least one case. Above I wrote a type alias for optional types:</p>
<pre><code>optional(a : type)&lt;computes&gt; := ?a</code></pre>
<p>But it looks like when Verse infers a return of <code>type</code>, it implicitly adds the <code>computes</code> effect. So this is equivalent:</p>
<pre><code>optional(a : type) := ?a</code></pre>
<p>What about effect polymorphism? For example, these two functions are not the same:</p>
<pre><code>Twice(F() : void) : void :=
  F()
  F()

TwiceTransacts(F()&lt;transacts&gt; : void)&lt;transacts&gt; : void :=
  F()
  F()</code></pre>
<p>Sadly Verse doesn’t support writing it just once, but it’s easy to imagine:</p>
<pre><code>Twice(e : exclusive_effect, F()&lt;e&gt; : void)&lt;e&gt; : void :=
  F()
  F()</code></pre>
<p>Since effects are quite limited, I’m not sure how useful effect polymorphism would be in a production system. I can easily see it being possible but I’m not sure there would be a demand for it.</p>
<h4 id="documentation">Documentation</h4>
<p>From reading forum posts, it looks like Verse has been in alpha testing for at least 6 months. I’m guessing the documentation has been slowly written over this time because I can see things which are slightly off but which might have worked at some point in Verse’s development.</p>
<p>The page on <a href="https://dev.epicgames.com/documentation/en-us/uefn/type-aliasing-in-verse" title="‌">Type Aliasing</a> says parametric type aliases are not supported, but the example given actually seems to work totally fine:</p>
<pre><code>comparison := enum:
    LT
    EQ
    GT

predicate(t : type) := type{_(:t, :t)&lt;computes&gt; : comparison}
compareInts(a : int, b : int)&lt;computes&gt; : comparison :=
    if (a &gt; b):
        comparison.GT
    else if (a = b):
        comparison.EQ
    else:
        comparison.LT
intPredicate : predicate(int) := compareInts</code></pre>
<p>The last example from <a href="https://dev.epicgames.com/documentation/en-us/uefn/parametric-types-in-verse" title="‌">Parametric Types</a> has a shadowed name (i.e. <code>t</code>) - which Verse doesn’t allow:</p>
<pre><code>class4(t : type) := class:
    Property : ?t

    Flatten(X:?class4(t) where t:type):?t =
        if (Y := X):
            Y.Property
        else:
            false</code></pre>
<p>The first example for the <a href="https://dev.epicgames.com/documentation/en-us/uefn/type-macro-in-verse" title="‌">Type Macro</a> doesn’t work at all because <code>Foo</code> needs to have a <code>computes</code> effect to be used in a type context and the <code>type</code> macro just doesn’t <em>support arbitrary expressions at all</em> - it only supports function types!</p>
<pre><code>Foo() : int = 0
Bar(X : type{Foo()}) : type{Foo()} = X</code></pre>
<p>Finally, at the bottom of each of the documentation pages there’s a link to a “Learning Library” which is 404.</p>
<p>Since most of these documentation issues are about restrictions, I’m going to guess the restrictions were added/removed <em>after</em> the documentation was already written. I think Verse team just needs some help to keep the docs up to date!</p>
<h4 id="summary">Summary</h4>
<p>I remember getting into programming by modding games like Half-Life. I struggled with learning C++ to be able to build the experiences that I wanted to make. I’m really excited that there will be 12-year-olds being introduced to programming by making Fortnite islands, using Verse and functional programming. On the public release day of Verse and the Unreal Editor for Fortnite, over 1000 projects were created every minute. The number of people who will learn functional programming using this tool is extremely exciting!</p>
<p>Verse’s compiler and tooling are currently closed source but both Tim Sweeney and Simon Peyton Jones have said that Verse is going to be open at some point.</p>
<p>I can see a path to full dependent types and I believe some form of dependent typing must be coming in the near future. It looks like dependent types have just been explicitly been disallowed for reasons, I’m guessing mostly implementation.</p>
<p>The same restrictions make it impossible to abstract over type constructors and higher-kinded types. Code duplication will be here until this restriction is lifted and I hope it is long before full dependent types are sorted out.</p>
<p>The effect system is very limited and definitely not the algebraic form that functional programmers might be used to. Some categories will be familiar (e.g. <code>computes</code> means pure) but don’t be confused and expect Verse effects to have any extensible functionality in terms of IO, configuration, error handling, etc.</p>
<p>The Verse team needs to start automating their documentation pages, they’re slightly outdated and I’m sure the Verse team is making changes quickly given the massive influx of users.</p>
<p>Verse has some interesting features and is a key part of an enormous project. Very exciting, I’ll continue to follow closely!</p>]]></summary>
</entry>
<entry>
    <title>Architecture diagrams should be code</title>
    <link href="https://brianmckenna.org/blog/architecture_code" />
    <id>https://brianmckenna.org/blog/architecture_code</id>
    <published>2023-01-09T00:00:00Z</published>
    <updated>2023-01-09T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>For the past few years I’ve been the most senior developer on my teams in Atlassian, in both position (Principal Engineer) and time (almost 9 <em>years</em>) - this means I usually take on the responsibility of managing our software architecture.</p>
<p>Architecture is the relationships between systems, which can be fairly tricky to talk about. Probably the best form of communication is a diagram, with boxes representing systems (or components) and lines representing relationships between them. This can still have issues.</p>
<p>When my previous engineering manager joined the Atlassian Marketplace team, he asked everyone to draw an architecture diagram. Each came out extremely different. The people focused on frontend had things like Jira, Embedded Marketplace, Commerce, Provisioning, Atlassian Connect, then an arrow to a huge box - just labelled <em>Marketplace backend</em>.</p>
<p><img src="http://brianmckenna.org/blog/static/images/c4_code_frontend.png" /></p>
<p>The people focused on backend had the reverse - a huge box just labelled <em>frontend</em>!</p>
<p><img src="http://brianmckenna.org/blog/static/images/c4_code_backend.png" /></p>
<!--
@startuml
!include  [https://raw.githubusercontent.com/plantuml-stdlib/C4-PlantUML/master/C4_Container.puml](https://raw.githubusercontent.com/plantuml-stdlib/C4-PlantUML/master/C4_Container.puml "‌")

title Marketplace from frontend view

AddElementTag("highlight", $bgColor="orange")

System(emcee, "Embedded Marketplace")
System(jira, "Jira")
System(commerce, "Commerce")
System(provisioning, "Provisioning")
System(upm, "Universal Plugin Manager")
System(tcs, "Tenant Context Service")
System(marketplace, "Marketplace BACKEND", $tags="highlight")

Rel(jira, emcee, "Embeds")
Rel(emcee, marketplace, "Fetches app details")
Rel(emcee, commerce, "Fetches pricing")
Rel(emcee, upm, "Triggers install")
Rel(upm, provisioning, "Triggers license")
Rel(provisioning, tcs, "Creates license")
Rel(upm, tcs, "Polls license")

SHOW_LEGEND()
@enduml

@startuml
!include  [https://raw.githubusercontent.com/plantuml-stdlib/C4-PlantUML/master/C4_Container.puml](https://raw.githubusercontent.com/plantuml-stdlib/C4-PlantUML/master/C4_Container.puml "‌")

title Marketplace from frontend view

AddElementTag("highlight", $bgColor="orange")

System(marketplace, "Marketplace")
System(commerce, "Commerce")
System(hams, "HAMS")
System(identity, "Atlassian Identity")
System(pako, "People Atlassian Knows Of")
System(frontend, "Marketplace FRONTEND", $tags="highlight")
System(algolia, "Algolia")
System(upm, "Universal Plugin Manager")

Rel(marketplace, commerce, "Fetches pricing")
Rel(marketplace, hams, "Fetches legacy pricing")
Rel(marketplace, identity, "Fetches users")
Rel(marketplace, pako, "Queries reports")
Rel(marketplace, algolia, "Searches")
Rel(frontend, marketplace, "Queries")
Rel(upm, marketplace, "Queries")

SHOW_LEGEND()

@enduml
-->
<p>Actual relationships do exist between systems (e.g. network calls, shared storage) but an architecture diagram can’t give all details without becoming the code it’s meant to represent. That means all architecture diagrams are <em>views</em> into an abstraction. It’s not wrong to have a big box representing your backend; it’s just one way of viewing an abstraction.</p>
<p>Some teams and projects will have a diagram and point to it as “here is <em>the</em> architecture” - but it’s not <em>the</em> architecture, it’s just one particular view.</p>
<p>Ideally, we’d have dozens of architecture diagrams - from various views, from various proposals, from various teams. We don’t see this very much and I think part of the problem is that architecture diagrams can be costly.</p>
<p>Most diagramming tools require you to use the mouse, pointing and clicking and dragging and drawing. They can be very fiddly and even buggy; e.g. there’s one architecture diagram for Atlassian Marketplace with an old outdated box that can’t be deleted using the software it was diagrammed in, it just won’t allow that, for some reason.</p>
<p>If someone adds a relationship to a new system, will they even remember to visit the Confluence page to click and drag and draw over the architecture diagrams?</p>
<p>Maybe we should write architecture diagrams using code instead. With code, we can update architecture diagrams within a pull request, version them and quickly modify many of them at once.</p>
<p>We can also add some formality. Instead of modelling things with lines and boxes, we can directly model systems and relationships.</p>
<p>The <a href="https://c4model.com/" title="‌">C4 Model</a> formalises architecture into 4 abstractions: system context, containers, components and code. I only use system context and containers; components and code are too detailed. A container is something which runs, such as an application server, database, filesystem, etc. A system represents some group of software, and it can have containers which that software is deployed within.</p>
<p>There are a bunch of tools for using C4. There are two which you might have already used for other things, such as PlantUML and Mermaid. One of the above images was generated from this PlantUML code:</p>
<pre><code>@startuml
!include  https://raw.githubusercontent.com/plantuml-stdlib/C4-PlantUML/master/C4_Container.puml

title Marketplace from backend view

AddElementTag(&quot;highlight&quot;, $bgColor=&quot;orange&quot;)

System(marketplace, &quot;Marketplace&quot;)
System(commerce, &quot;Commerce&quot;)
System(hams, &quot;HAMS&quot;)
System(identity, &quot;Atlassian Identity&quot;)
System(pako, &quot;People Atlassian Knows Of&quot;)
System(frontend, &quot;Marketplace FRONTEND&quot;, $tags=&quot;highlight&quot;)
System(algolia, &quot;Algolia&quot;)
System(upm, &quot;Universal Plugin Manager&quot;)

Rel(marketplace, commerce, &quot;Fetches pricing&quot;)
Rel(marketplace, hams, &quot;Fetches legacy pricing&quot;)
Rel(marketplace, identity, &quot;Fetches users&quot;)
Rel(marketplace, pako, &quot;Queries reports&quot;)
Rel(marketplace, algolia, &quot;Searches&quot;)
Rel(frontend, marketplace, &quot;Queries&quot;)
Rel(upm, marketplace, &quot;Queries&quot;)

SHOW_LEGEND()

@enduml</code></pre>
<p>But instead of writing PlantUML, I use Haskell to model architecture. A simple example would look like:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">AtlassianSystem</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=</span> <span class="dt">Marketplace</span></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>  <span class="op">|</span> <span class="dt">Identity</span></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>  <span class="op">|</span> <span class="dt">Pako</span></span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> (<span class="dt">Eq</span>, <span class="dt">Ord</span>, <span class="dt">Show</span>)</span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">AtlassianTechnology</span></span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a>  <span class="ot">=</span> <span class="dt">REST</span></span>
<span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a>  <span class="op">|</span> <span class="dt">SQL</span></span>
<span id="cb2-10"><a href="#cb2-10" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> (<span class="dt">Eq</span>, <span class="dt">Ord</span>, <span class="dt">Show</span>)</span>
<span id="cb2-11"><a href="#cb2-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-12"><a href="#cb2-12" aria-hidden="true" tabindex="-1"></a><span class="ot">marketplaceSystem ::</span></span>
<span id="cb2-13"><a href="#cb2-13" aria-hidden="true" tabindex="-1"></a>  <span class="dt">SoftwareSystem</span></span>
<span id="cb2-14"><a href="#cb2-14" aria-hidden="true" tabindex="-1"></a>    <span class="dt">AtlassianSystem</span></span>
<span id="cb2-15"><a href="#cb2-15" aria-hidden="true" tabindex="-1"></a>    ()</span>
<span id="cb2-16"><a href="#cb2-16" aria-hidden="true" tabindex="-1"></a>    <span class="dt">AtlassianTechnology</span></span>
<span id="cb2-17"><a href="#cb2-17" aria-hidden="true" tabindex="-1"></a>    ()</span>
<span id="cb2-18"><a href="#cb2-18" aria-hidden="true" tabindex="-1"></a>marketplaceSystem <span class="ot">=</span></span>
<span id="cb2-19"><a href="#cb2-19" aria-hidden="true" tabindex="-1"></a>  softwareSystem</span>
<span id="cb2-20"><a href="#cb2-20" aria-hidden="true" tabindex="-1"></a>    <span class="op">&amp;</span> relationships <span class="op">.</span> at <span class="dt">Identity</span> <span class="op">?~</span> relationship <span class="dt">REST</span></span>
<span id="cb2-21"><a href="#cb2-21" aria-hidden="true" tabindex="-1"></a>    <span class="op">&amp;</span> relationships <span class="op">.</span> at <span class="dt">Pako</span> <span class="op">?~</span> relationship <span class="dt">SQL</span></span>
<span id="cb2-22"><a href="#cb2-22" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-23"><a href="#cb2-23" aria-hidden="true" tabindex="-1"></a><span class="ot">marketplace ::</span></span>
<span id="cb2-24"><a href="#cb2-24" aria-hidden="true" tabindex="-1"></a>  <span class="dt">Model</span></span>
<span id="cb2-25"><a href="#cb2-25" aria-hidden="true" tabindex="-1"></a>    ()</span>
<span id="cb2-26"><a href="#cb2-26" aria-hidden="true" tabindex="-1"></a>    ()</span>
<span id="cb2-27"><a href="#cb2-27" aria-hidden="true" tabindex="-1"></a>    <span class="dt">AtlassianSystem</span></span>
<span id="cb2-28"><a href="#cb2-28" aria-hidden="true" tabindex="-1"></a>    ()</span>
<span id="cb2-29"><a href="#cb2-29" aria-hidden="true" tabindex="-1"></a>    <span class="dt">AtlassianTechnology</span></span>
<span id="cb2-30"><a href="#cb2-30" aria-hidden="true" tabindex="-1"></a>    ()</span>
<span id="cb2-31"><a href="#cb2-31" aria-hidden="true" tabindex="-1"></a>marketplace <span class="ot">=</span></span>
<span id="cb2-32"><a href="#cb2-32" aria-hidden="true" tabindex="-1"></a>  model</span>
<span id="cb2-33"><a href="#cb2-33" aria-hidden="true" tabindex="-1"></a>    <span class="op">&amp;</span> softwareSystems <span class="op">.</span> at <span class="dt">Marketplace</span> <span class="op">?~</span> marketplaceSystem</span>
<span id="cb2-34"><a href="#cb2-34" aria-hidden="true" tabindex="-1"></a>    <span class="op">&amp;</span> softwareSystems <span class="op">.</span> at <span class="dt">Identity</span> <span class="op">?~</span> softwareSystem</span>
<span id="cb2-35"><a href="#cb2-35" aria-hidden="true" tabindex="-1"></a>    <span class="op">&amp;</span> softwareSystems <span class="op">.</span> at <span class="dt">Pako</span> <span class="op">?~</span> softwareSystem</span></code></pre></div>
<p>And the Haskell library can spit out PlantUML from this model. There’s a few checks which can be implemented on this model, e.g. do any components reference systems which their container doesn’t?</p>
<p>Going further into code, most systems have a consistent way of communicating with services. Atlassian has a Service Proxy to handle common service to service communication. When configuring Service Proxy, you give it a list of services that your service depends on. We can easily write some Haskell which takes that configuration and spits out a C4 Model, allowing us to create a bunch of diagrams.</p>
<p>We can also generate a model from running tests. Each test can generate a sequence diagram using something like <a href="https://github.com/sonyxperiadev/dataflow">DataFlow</a>. Collecting the systems used in all tests can generate a C4 system context and container diagram for our whole system. Here’s an example sequence diagram generated by running a single test:</p>
<p><img src="https://brianmckenna.org/blog/static/create-vendor-and-app.png" /></p>
<p>I’m pretty convinced that we should be using code to generate architecture diagrams. Code allows making quick changes. Architecture code can be versioned with the code which implements it. We can write algorithms to check our architecture. I’d like to see more tools available to describe architecture as part of code, allowing us to generate as many diagrams as we want, for accurate and easy communication.</p>
<p>Do you use code to diagram architecture? Do you do something other than just write PlantUML or Mermaid, by hand? I’d love to hear more!</p>]]></summary>
</entry>
<entry>
    <title>Higher Kinded Parametricity</title>
    <link href="https://brianmckenna.org/blog/higher_kinded_parametricity" />
    <id>https://brianmckenna.org/blog/higher_kinded_parametricity</id>
    <published>2018-12-24T00:00:00Z</published>
    <updated>2018-12-24T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I've moved to Bengaluru to teach functional programming (and other
things) to my team in Atlassian. Our project is a large Scala
application. Scala enables functional programming, but it is only made
possible, not easy.</p>
<p>Instead of using Scala to teach functional programming, we should use
something easier. For a few years I've been using Haskell to teach
functional programming. Sometimes I hear from people that Elm, Kotlin or
Java could be easier. I want to write about a big benefit I get out of
Haskell that I wouldn't be able to get from these tools.</p>
<p>The <a href="https://github.com/data61/fp-course">Data61 fp-course</a> contains a
lot of functional programming exercises. It starts with Optional and
List, then moves to Functor. One of the Functor exercises is the <code>void</code>
function:</p>
<pre><code>void ::
  Functor f =&gt;
  f a
  -&gt; f ()</code></pre>
<p>This takes a bit of explaining. I explain what <code>Functor</code> is, then I
explain what the parametric type constructor <code>f</code> means.</p>
<p>Elm, Kotlin and Java lack the type-system feature which makes the above
type possible to write. It's not an exercise that can be given.
Instead, we'd have code duplication:</p>
<pre><code>voidOptional ::
  Optional a
  -&gt; Optional ()

voidList ::
  List a
  -&gt; List ()</code></pre>
<p>Code duplication might seem preferable because these types don't
contain things we have to explain. The problem comes at implementation
time.</p>
<p>Our original <code>void</code> type had only one inhabitant:</p>
<pre><code>void fa = const () &lt;$&gt; fa</code></pre>
<p>But our <code>voidOptional</code> has four inhabitants:</p>
<pre><code>voidOptional = const Empty

voidOptional = const (Full ())

voidOptional Empty = Full ()
voidOptional (Full _) = Empty

voidOptional Empty = Empty
voidOptional (Full _) = Full ()</code></pre>
<p>And <code>voidList</code> has infinite inhabitants!</p>
<p>Making things specific instead of polymorphic makes things <em>more</em>
complicated. Someone trying to work on the <code>void</code> exercise will use
Haskell's tools to get directed toward <em>the</em> solution. If the exercise
got split into the specific versions, people no longer get directed;
implementors have to be careful.</p>
<p>This concept is <em>parametricity</em> on type constructors. When teaching, I
see people quickly gain an intution for parametricity and use it as a
reasoning tool, over and over.</p>
<p>The Functor exercises come after the Optional and List exercises. The
Functor exercises exist to teach about the operations that Functor
provides. They do not exist to teach about Optional and List, so should
not have to mention them.</p>
<p>During my experience with teaching Haskell, I have seen people learn
Functor, Applicative and Monad functions very quickly. I think a big
part comes from using parametricity during the exercises. I do not agree
that Elm, Kotlin nor Java could make learning these functions easier.</p>]]></summary>
</entry>
<entry>
    <title>Polymorphic Programming</title>
    <link href="https://brianmckenna.org/blog/polymorphic_programming" />
    <id>https://brianmckenna.org/blog/polymorphic_programming</id>
    <published>2018-01-07T00:00:00Z</published>
    <updated>2018-01-07T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I am convinced the way I program is broken. At work I write a lot of
Scala, Haskell and Nix. Almost all of the functions I write are
representing the problem I'm solving; not many functions have anything
to do with the language itself. Sometimes I have to consider or concede
to the language or runtime. I should be able to write programs by
abstracting over language, precisely up to the considerations I have to
make.</p>
<p>For example, I have written the identity function many times. I have
written it in Nix, JavaScript, Java and many more:</p>
<pre><code>a: a

function(a) { return a; }

A id(A a) { return a; }

\a -&gt; a</code></pre>
<p>That code increments my "implemented the identity function" counter by
four.</p>
<p>Each line represents the same function but with slightly different
runtime behaviour. When writing Nix or JavaScript, I have to remember
syntax. When writing Java I have to remember rules around methods vs
functions, where generics can be declared, etc. These don't really
matter to the problem I'm solving, but I have to think about them.</p>
<p>I would like to write the identity function just once:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="ot">makeIdentity ::</span> (<span class="dt">HasVariables</span> lang, <span class="dt">HasParametricTypes</span> lang) <span class="ot">=&gt;</span> lang</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>makeIdentity <span class="ot">=</span></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>  lam <span class="op">#</span> <span class="kw">do</span></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>    t <span class="ot">&lt;-</span> newTypeVar</span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a>    a <span class="ot">&lt;-</span> newVar t</span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a>    var <span class="op">#</span> a</span></code></pre></div>
<p>We can argue about the DSL that I've imagined but my point is the type
of the program. It is polymorphic - we can instantiate the program to
anything which has variables and parametric types. I should be able to
say:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="ot">makeIdentity ::</span> <span class="dt">Nix</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="ot">makeIdentity ::</span> <span class="dt">Scala</span></span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a><span class="ot">makeIdentity ::</span> <span class="dt">Haskell</span></span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a><span class="ot">makeIdentity ::</span> <span class="dt">JavaScript</span></span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a><span class="ot">makeIdentity ::</span> <span class="dt">Python</span></span></code></pre></div>
<p>But maybe there's more than one way to implement our functions. In
strict languages like Scala I have to sometimes trampoline my code to
stop it from hitting stack overflow errors (this has been especially
annoying since I've moved to Site Reliability Engineer) and this is a
mostly mechanical transformation. Could we represent trampolining as
just an instantiation of our program?</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ot">makeMyStackSafeProgram ::</span> <span class="dt">Trampolined</span> <span class="dt">Scala</span></span></code></pre></div>
<p>If I use a feature which isn't supported by the language, I should get
a compilation error:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="ot">makeTraverse ::</span> (<span class="dt">HasHigherKindedTypes</span> lang) <span class="ot">=&gt;</span> lang</span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a><span class="co">-- makeTraverse :: Java</span></span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a><span class="co">-- error: Could not deduce (HasHigherKindedTypes Java)</span></span></code></pre></div>
<p>If I get the above error telling me that Java has no higher kinded
types, I should then be able to work around Java by instantiating
specific code:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a>makeTraverseFor javaOptional javaList</span></code></pre></div>
<p>It might be useful to start more concretely; I have <a href="https://bitbucket.org/snippets/puffnfresh/n4k77/abstracting-over-java-and-python-classes">an example of
instantiating a class to both Java and
Python</a>
on Bitbucket.</p>
<p>There are some projects that I think are going in the right direction:</p>
<ul>
<li><a href="http://conal.net/papers/compiling-to-categories/">Compiling to
categories</a> by
Conal Elliott takes functions and instantiates them to any closed
cartesian category (his <a href="https://www.youtube.com/watch?v=vzLK_xE9Zy8">Lambda Jam
video</a> shows some
awesome examples)</li>
<li><a href="https://github.com/dhall-lang/dhall-lang">Dhall</a> is a common
language for configuration; compiles to JSON/YAML, Bash and text
templates</li>
<li><a href="https://isomorf.io/">Isomorf</a> abstracts away syntax, uses a core
language to give automatic refactoring and code reuse</li>
</ul>
<p>I've talked to people at <a href="http://qfpl.io/">Queensland Functional Programming
Lab</a> and they are working towards this idea. They are
starting with <a href="https://github.com/qfpl/hpython">a library for working with Python
code</a>. They will eventually make
another language library and then abstract the similarities. I think
this is a pretty good approach.</p>
<p>It might seem inconvenient to program one language to program another,
but I think enough optics and combinators, writing code using GHCi would
be more convenient than using Emacs.</p>
<p>This is a massive project but I'm fairly confident this is how I'd
like to program. I'm not confident on exactly what this would look
like, what abstractions would appear between languages or which
libraries would be necessary first. I'd love to hear what you think.</p>]]></summary>
</entry>
<entry>
    <title>Constraints are for methods, not data</title>
    <link href="https://brianmckenna.org/blog/constraints_are_for_methods" />
    <id>https://brianmckenna.org/blog/constraints_are_for_methods</id>
    <published>2017-11-22T00:00:00Z</published>
    <updated>2017-11-22T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I wrote this post a couple of years ago for a team at work. I just found
it again, so here it is:</p>
<p>We gain two things by making a type more polymorphic:</p>
<ol type="1">
<li>We can use it in more places</li>
<li>We can reason about what it can't do, often to the point that we
can count that there's only X possible implementations of a type
signature (a topic called parametricity, covered pretty well
elsewhere)</li>
</ol>
<p>We should strive to be as polymorphic as possible to get the maximum
advantages. I see a common mistake in Scala code where we put
constraints in the wrong places, artificially limiting our benefits.</p>
<p>We have a PrefixTree data type in our code. It used to be encoded as a
class like:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode scala"><code class="sourceCode scala"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">sealed</span> <span class="kw">abstract</span> <span class="kw">class</span> PrefixTree<span class="op">[</span>A<span class="op">:</span> Prefix<span class="op">]</span> <span class="op">{</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>  <span class="kw">def</span> <span class="fu">add</span><span class="op">(</span>a<span class="op">:</span> A<span class="op">):</span> PrefixTree<span class="op">[</span>A<span class="op">]</span></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a><span class="cf">case</span> <span class="kw">class</span> <span class="ex">Node</span><span class="op">[</span>A<span class="op">:</span> Prefix<span class="op">](</span>prefix<span class="op">:</span> A<span class="op">,</span> child<span class="op">:</span> PrefixTree<span class="op">[</span>A<span class="op">])</span> <span class="kw">extends</span> PrefixTree<span class="op">[</span>A<span class="op">]</span></span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a><span class="cf">case</span> <span class="kw">class</span> Children<span class="op">[</span>A<span class="op">:</span> Prefix<span class="op">](</span>suffixes<span class="op">:</span> <span class="ex">Vector</span><span class="op">[</span>PrefixTree<span class="op">[</span>A<span class="op">]])</span> <span class="kw">extends</span> PrefixTree<span class="op">[</span>A<span class="op">]</span></span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a><span class="cf">case</span> <span class="kw">class</span> End<span class="op">[</span>A<span class="op">:</span> Prefix<span class="op">]()</span> <span class="kw">extends</span> PrefixTree<span class="op">[</span>A<span class="op">]</span></span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a><span class="cf">case</span> <span class="kw">class</span> Empty<span class="op">[</span>A<span class="op">:</span> Prefix<span class="op">]()</span> <span class="kw">extends</span> PrefixTree<span class="op">[</span>A<span class="op">]</span></span></code></pre></div>
<p>Each of the constructors of a PrefixTree took evidence of being able to
calculate a prefix for a type. Adding an element would then look at the
evidence we got at construction time.</p>
<p>Now, what if we wanted to add an <code>isEmpty</code> method? Ideally the type
signature would not mention Prefix, since we don't need to talk about
any elements in the tree to check whether the tree is empty. Sadly the
type of PrefixTree already mentions Prefix, so we've failed - the
implementation could start using the methods on Prefix and return a
Boolean which depended upon the elements <em>within</em> the tree. We've not
obtained the 2nd goal I put above.</p>
<p>Instead, we should encode the data type slightly differently:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode scala"><code class="sourceCode scala"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">sealed</span> <span class="kw">trait</span> PrefixTree<span class="op">[</span>A<span class="op">]</span> <span class="op">{</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>  <span class="kw">def</span> <span class="fu">add</span><span class="op">(</span>a<span class="op">:</span> A<span class="op">)(</span><span class="kw">implicit</span> P<span class="op">:</span> Prefix<span class="op">[</span>A<span class="op">]):</span> PrefixTree<span class="op">[</span>A<span class="op">]</span></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a><span class="cf">case</span> <span class="kw">class</span> <span class="ex">Node</span><span class="op">[</span>A<span class="op">](</span>prefix<span class="op">:</span> A<span class="op">,</span> child<span class="op">:</span> PrefixTree<span class="op">[</span>A<span class="op">])</span> <span class="kw">extends</span> PrefixTree<span class="op">[</span>A<span class="op">]</span></span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a><span class="cf">case</span> <span class="kw">class</span> Children<span class="op">[</span>A<span class="op">](</span>suffixes<span class="op">:</span> <span class="ex">Vector</span><span class="op">[</span>PrefixTree<span class="op">[</span>A<span class="op">]])</span> <span class="kw">extends</span> PrefixTree<span class="op">[</span>A<span class="op">]</span></span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a><span class="cf">case</span> <span class="kw">class</span> End<span class="op">[</span>A<span class="op">]()</span> <span class="kw">extends</span> PrefixTree<span class="op">[</span>A<span class="op">]</span></span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a><span class="cf">case</span> <span class="kw">class</span> Empty<span class="op">[</span>A<span class="op">]()</span> <span class="kw">extends</span> PrefixTree<span class="op">[</span>A<span class="op">]</span></span></code></pre></div>
<p>The only change is taking the Prefix constraints away from the
constructors and moving it up to the method. Now if we wanted to add an
<code>isEmpty</code> method without talking about Prefix, we can!</p>
<p>I've done this for a things in our codebase and we're a lot better of
for it, both in benefits to reasoning but also reuse.</p>
<p>The method takes a bit of practice in Scala but please remember some
simple advice: <em>constraints belong on methods, not on data</em>.</p>]]></summary>
</entry>
<entry>
    <title>10x Engineers were the Silver Bullet</title>
    <link href="https://brianmckenna.org/blog/softwerewolves" />
    <id>https://brianmckenna.org/blog/softwerewolves</id>
    <published>2017-11-21T00:00:00Z</published>
    <updated>2017-11-21T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Fred Brooks published a paper titled "<a href="https://en.wikipedia.org/wiki/No_Silver_Bullet">No Silver Bullet – Essence and
Accident in Software
Engineering</a>" in 1986.
This paper is often cited for a few different reasons, one of the main
references goes something like:</p>
<blockquote>
<p>There's no such thing as a silver bullet...</p>
</blockquote>
<p>Which is a reference to the following paragraph:</p>
<blockquote>
<p>There is no single development, in either technology or in management
technique, that by itself promises even one order-of-magnitude
improvement in productivity, in reliability, in simplicity.</p>
</blockquote>
<p>Maybe there's no 10x tool which is going to solve all of our problems.</p>
<p>I think this is an enormous bar though. If I could only 5x your
productivity for 5 minutes of your day, you'd probably be willing to
spend some money on whatever I have to sell. If a tool made your
software 2x more reliable, you'd be jumping on board.</p>
<p>Ignoring the size of the bar, what evidence do we have for the claim?
Brooks notes that there's a difference between "essential" and
"accidental" complexity. Tools mostly take on accidental complexity
while most of our problems are essential. This seems like a very useful
separation.</p>
<p>By this definition, it probably means that trying to remove accidental
complexity won't make a 10x improvement <em>overall</em>. I don't know if we
can verify that or what practical thing would come out of it being true.
I may or may not get 10x advantages to my whole problem - but I should
still try to use best available tools.</p>
<p>A few paragraphs later in the paper:</p>
<blockquote>
<p>The differences are not minor--they are rather like the differences
between Salieri and Mozart. Study after study shows that the very best
designers produce structures that are faster, smaller, simpler,
cleaner, and produced with less effort. The differences between the
great and the average approach an order of magnitude.</p>
</blockquote>
<p>So the claims are:</p>
<ol type="1">
<li>There are no 10x tools</li>
<li>10x developers exist</li>
</ol>
<p>This second claim has become a bit of a meme. The cited source comes
from 1968 and many people have written about it. You can search for
"10x developer" to find some articles trying to figure out how true
this is. My personal experience on 10x developers definitely does not
reflect Brooks' experience.</p>
<p>The conclusion of No Silver Bullets is that we should stop looking for
10x tools because 10x developers will solve your problems. We should
hire these developers then treat them with the same compensation and
benefits that managers receive. I always wonder when a manager says
"there's no such thing as a silver bullet" if they also mean that
part!</p>
<p>So please remember that if you're referencing the paper by saying this
line:</p>
<blockquote>
<p>There's no such thing as a silver bullet...</p>
</blockquote>
<p>Then you're arguing:</p>
<ol type="1">
<li>Tools won't improve all the things by 10x (yawn)</li>
<li>That you believe 10x developers exist</li>
<li>Your team should be hiring these 10x developers and compensating
them like your managers</li>
</ol>
<p>If you're making these arguments, your experience must be very
different from mine. I'd love to talk to you.</p>]]></summary>
</entry>
<entry>
    <title>Tool Subsumption and Silver Bullets</title>
    <link href="https://brianmckenna.org/blog/tool_subsumption" />
    <id>https://brianmckenna.org/blog/tool_subsumption</id>
    <published>2017-10-09T00:00:00Z</published>
    <updated>2017-10-09T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I'm going to write some posts about the phrase "there's no such thing
as a silver bullet" and why I think it's not a very useful thing to
say. I'll write a post about the original paper but first I want to
write about an interpretation I've seen:</p>
<blockquote>
<p>Everything has trade-offs.</p>
</blockquote>
<p>I can go through things that I use and come up with trade-offs:</p>
<ul>
<li>Space vs time</li>
<li>Emacs vs Vim</li>
<li>Git vs Mercurial</li>
<li>JSON vs YAML</li>
</ul>
<p>Sometimes I need to carefully consider each option and choose. Sometimes
I can flip a coin because the differences are insignificant to what I'm
solving.</p>
<p>But I think some tools don't have trade-offs.</p>
<p>Functional programming is <em>programming with functions</em> and functions
have the property of <em>referential transparency</em>. When we see an
expression in a program, we can replace the expression with a binding or
vice versa.</p>
<p>An example is that:</p>
<pre><code>var x = 1;
x + x</code></pre>
<p>Has the same result as:</p>
<pre><code>1 + 1</code></pre>
<p>And vice versa.</p>
<p>A counter example is:</p>
<pre><code>var x = prompt(&quot;Name:&quot;);
x + x</code></pre>
<p>Does not have the same result as:</p>
<pre><code>prompt(&quot;Name:&quot;) + prompt(&quot;Name:&quot;)</code></pre>
<p>We gain some useful things when we have <em>referential transparency</em>. We
can thoughtlessly refactor, the best kind of refactoring. <a href="http://www.haskellforall.com/2013/12/equational-reasoning.html">Equational
reasoning</a>
with our programs is substitution. Code reuse, testing and optimised
compilation are easier.</p>
<p>And what do we lose? When I started doing functional programming, I
assumed there <em>must be</em> some trade-offs, because trade-offs in
programming are <em>so common</em>.</p>
<p>At first I rationalised this by saying "well sometimes it's awkward to
use immutable data" - that must be the problem! Much later I learned
<a href="https://hackage.haskell.org/package/lens">tools</a> which make it way less
awkward than the alternatives.</p>
<p>Then I thought "well we can't do fast mutation" - performance must be
bad if we restrict ourselves to referential transparency. Much later I
learned that there are referentially transparent
<a href="https://hackage.haskell.org/package/base/docs/Control-Monad-ST.html">tools</a>
<a href="https://hackage.haskell.org/package/array/docs/Data-Array-ST.html">for</a>
<a href="https://hackage.haskell.org/package/vector/docs/Data-Vector-Unboxed.html">fast</a>
<a href="https://hackage.haskell.org/package/repa">mutation</a>.</p>
<p>After iterating a few times I have arrived at: <em>referential transparency
is not a trade-off</em>. I'm fairly confident that the only reasons
referential transparency isn't used everywhere is:</p>
<ol type="1">
<li>A lack of awareness</li>
<li>Inaccessibility of resources for learning it</li>
</ol>
<p>I spend 2 hours a week teaching the Data61 <a href="https://github.com/data61/fp-course">Functional Programming
Course</a> at work in an effort to
teach referential transparency in my local environment. Please consider
helping the cause!</p>
<p>I've come to a similar conclusion on <em>dynamic typing</em>. It is exactly
<a href="https://existentialtype.wordpress.com/2011/03/19/dynamic-languages-are-static-languages/"><em>unityping</em></a>
and my experience is that allowing programs with more than one type has
no inherent disadvantage. Not a trade-off.</p>
<p>Some tools subsume others. Functional and typed programming subsume all
alternatives. When "there's no such thing as a silver bullet" is used
to mean something like "everything has trade-offs" then it might be
ignoring these cases. They're not a silver bullet to solving all of
your problems, but they are a silver bullet for the problems they solve.</p>]]></summary>
</entry>
<entry>
    <title>Haskell on Android using Eta</title>
    <link href="https://brianmckenna.org/blog/eta_android" />
    <id>https://brianmckenna.org/blog/eta_android</id>
    <published>2017-05-23T00:00:00Z</published>
    <updated>2017-05-23T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p><a href="http://eta-lang.org/">Eta</a> is a fork of GHC which provides Haskell with
a JVM backend. I've been working on it recently and did a <a href="http://brianmckenna.org/files/presentations/lambdajam-2017-eta.pdf">presentation
on
it</a>
at LambdaJam. One of the questions from my presentation was "since Eta
takes Haskell and produces JVM code, can I use it to write Android
apps?"</p>
<p>I had a feeling Eta was close to being able to. It turns out it's not
just close, it's pretty easy!</p>
<p>Let's write some code which uses the Android API:</p>
<pre><code>{-# LANGUAGE DataKinds #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module Xyz.Profunctor.Android where

import Java
import Java.StringUtils as S

data {-# CLASS &quot;android.content.Context&quot; #-}
  Context = Context (Object# Context)
  deriving Class

data {-# CLASS &quot;android.app.Activity&quot; #-}
  Activity = Activity (Object# Activity)
  deriving Class

type instance Inherits Activity = &#39;[Context]

data {-# CLASS &quot;android.view.View&quot; #-}
  View = View (Object# View)
  deriving Class

data {-# CLASS &quot;android.widget.TextView&quot; #-}
  TextView = TextView (Object# TextView)
  deriving Class

type instance Inherits TextView = &#39;[View]

foreign import java unsafe &quot;@new&quot;
  newTextView :: (c &lt;: Context) =&gt; c -&gt; Java a TextView

foreign import java unsafe &quot;setContentView&quot;
  setContentView :: (v &lt;: View) =&gt; v -&gt; Java Activity ()

foreign import java unsafe &quot;setText&quot;
  setText :: (c &lt;: CharSequence) =&gt; c -&gt; Java TextView ()

data {-# CLASS &quot;xyz.profunctor.android.ActivityImpl&quot; #-}
  ActivityImpl = ActivityImpl (Object# ActivityImpl)

foreign export java &quot;@static startActivity&quot;
  startActivity :: Activity -&gt; Java ActivityImpl ()

startActivity :: Activity -&gt; Java a ()
startActivity activity = do
  textView &lt;- newTextView activity
  textView &lt;.&gt; setText (foldr S.concat &quot;World!&quot; (replicate 10 &quot;Eta &quot;))
  activity &lt;.&gt; setContentView textView</code></pre>
<p>This shows some of the power of <a href="http://eta-lang.org/docs/html/eta-tutorials.html#java-foreign-import-declarations">Eta's foreign function
interface</a>.
We're able to describe the Android Java interface with some data types
representing classes, a type family for representing subtyping and
foreign imports representing methods.</p>
<p>The code uses some normal Prelude code (e.g. <code>foldr</code>, <code>replicate</code>) to
demonstrate that it's full Haskell.</p>
<p>The above file can be compiled:</p>
<pre><code>$ eta Android.hs</code></pre>
<p>And we get an <code>Android.jar</code> file!</p>
<p>Now using Android Studio we can create a new project and copy the above
JAR to the <code>app/libs</code> directory.</p>
<p>We also need the dependencies for this code. Ideally we'd be able to
use Eta's build tool, <code>etlas</code>, to bundle the dependencies in our JAR
(via <code>etlas configure --enable-uberjar-mode</code>) but sadly it <a href="https://github.com/typelead/eta/issues/396">doesn't yet
support the Uber JAR mode for code without a Main
module</a>.</p>
<p>So let's work around the problem for now. Some dodgy shell to copy the
dependency files:</p>
<pre><code>for library in ghc-prim base rts integer; do
  DIR=&quot;$(eta-pkg field $library library-dirs --simple-output)&quot;
  JAR=&quot;$(eta-pkg field $library hs-libraries --simple-output).jar&quot;
  cp &quot;$DIR/$JAR&quot; app/libs
done</code></pre>
<p>Now we can edit the project's Java code to use the exported Haskell
method:</p>
<pre><code>package xyz.profunctor.etaandroid;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import xyz.profunctor.android.ActivityImpl;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityImpl.startActivity(this);
    }
}</code></pre>
<p>Doing a debug build will try to create an APK but will fail because we
have an enormous number of methods. To work around this, we can enable
Multidex, which is supported since Android API level 21 (i.e. at least
Android Lollipop 5.0, <a href="https://developer.android.com/about/dashboards/index.html">around 70% of the devices hitting Google
Play</a>) -
getting Proguard to run during debug builds should work instead, but I
didn't bother because enabling Multidex was easy.</p>
<p>We need to merge the following settings with the generated
<code>app/build.gradle</code>:</p>
<pre><code>android {
    defaultConfig {
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled true
        }
    }
    lintOptions {
        disable &#39;InvalidPackage&#39;
    }
}</code></pre>
<p>And add these Proguard rules to <code>app/proguard-rules.pro</code>:</p>
<pre><code>-dontwarn base.**
-dontwarn eta.**
-dontwarn ghc_prim.**
-dontwarn integer.**
-dontwarn main.**</code></pre>
<p>Without Proguard we'll get a 5MB APK file. After Proguard it should be
only around 900KB.</p>
<p>Pressing the buttons in Android Studio will start the app up in the
emulator, or we can compile using <code>gradle</code>:</p>
<pre><code>$ gradle assembleDebug # for a debug build
$ gradle assembleRelease # for release build
$ gradle build # do all the things</code></pre>
<p>Here's what it looks like under Android Studio's emulator:</p>
<p><img src="https://brianmckenna.org/blog/static/eta-android-studio-emulator.png" /></p>
<p>And here's a screenshot from a physical Android device!</p>
<p><img src="https://brianmckenna.org/blog/static/eta-physical.png" /></p>
<p>I've chucked the code up for the <a href="https://github.com/puffnfresh/eta-android">Android Studio part of the
code</a> which just needs the
<code>app/libs</code> directory to be made.</p>]]></summary>
</entry>
<entry>
    <title>Running Unpatched Binaries on NixOS</title>
    <link href="https://brianmckenna.org/blog/running_binaries_on_nixos" />
    <id>https://brianmckenna.org/blog/running_binaries_on_nixos</id>
    <published>2017-03-22T00:00:00Z</published>
    <updated>2017-03-22T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I have been using <a href="https://nixos.org/">NixOS</a> since the end of 2014,
both at home and for work. One thing which has been a bit annoying over
these years is when I have to execute a downloaded binary. Atlassian has
some internal tools which are written in things like Go. I package these
binaries and install them into my user profile but sometimes it can be
annoying to spend the 5 minutes packaging something when you want to run
something <em>just once</em> or <em>right now</em>.</p>
<p>The first problem is the dynamic linker doesn't exist at the usual
place:</p>
<pre><code>/lib64/ld-linux.so.2</code></pre>
<p>Because there's not even a <code>/lib64</code> directory. When packaging, we use
<a href="https://nixos.org/patchelf.html">patchelf</a> to make the binary refer to
a dynamic linker in the Nix store.</p>
<p>The second problem is then getting the dynamic linker to find linked
libraries. When packaging we use patchelf to change the binary's
<a href="https://en.wikipedia.org/wiki/Rpath">rpath</a>.</p>
<p>I have come up with 2 ways to work around these problems. I'm not yet
sure which method is best, so I'll describe both.</p>
<p>The first method is a giant
<a href="https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard">FHS</a>
chroot environment. The chroot environment will put the linker and
libraries in the standard places. I have a command installed into my
user profile so that I can quickly enter the environment:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode nix"><code class="sourceCode nix"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">with</span> <span class="bu">import</span> &lt;nixpkgs&gt; <span class="op">{</span> <span class="op">};</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>buildFHSUserEnv <span class="op">{</span></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>  <span class="va">name</span> <span class="op">=</span> <span class="st">&quot;enter-fhs&quot;</span><span class="op">;</span></span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a>  <span class="va">targetPkgs</span> <span class="op">=</span> <span class="va">pkgs</span><span class="op">:</span> <span class="kw">with</span> pkgs<span class="op">;</span> <span class="op">[</span></span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a>    alsaLib atk cairo cups dbus expat file fontconfig freetype gdb git glib </span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a>    gnome.GConf gnome.gdk_pixbuf gnome.gtk gnome.pango libnotify libxml2 libxslt</span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a>    netcat nspr nss oraclejdk8 strace udev watch wget which xorg.libX11</span>
<span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a>    xorg.libXScrnSaver xorg.libXcomposite xorg.libXcursor xorg.libXdamage</span>
<span id="cb2-10"><a href="#cb2-10" aria-hidden="true" tabindex="-1"></a>    xorg.libXext xorg.libXfixes xorg.libXi xorg.libXrandr xorg.libXrender</span>
<span id="cb2-11"><a href="#cb2-11" aria-hidden="true" tabindex="-1"></a>    xorg.libXtst xorg.libxcb xorg.xcbutilkeysyms zlib zsh</span>
<span id="cb2-12"><a href="#cb2-12" aria-hidden="true" tabindex="-1"></a>  <span class="op">];</span></span>
<span id="cb2-13"><a href="#cb2-13" aria-hidden="true" tabindex="-1"></a>  <span class="va">runScript</span> <span class="op">=</span> <span class="st">&quot;$SHELL&quot;</span><span class="op">;</span></span>
<span id="cb2-14"><a href="#cb2-14" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<p>I can then run <code>enter-fhs</code> to get into a chrooted shell. Commands like
<code>enter-fhs -c ./my-binary</code> also work. If the binary needs an extra
library that's not listed, I just add it. Not ideal.</p>
<p>The second method is by putting a hook into <code>nix-shell</code> and calling the
dynamic linker on the binary. The hook allows specifying the libraries I
want via the <code>nix-shell</code> command:</p>
<pre class="shell"><code>$ nix-shell -p gcc.cc alsaLib dbus gtk &#39;callPackage &lt;nix-files/ld_library_path.nix&gt; { }&#39;

[nix-shell]$ runBinary ./my-binary my-arg-1 my-arg-2</code></pre>
<p>Where the <code>ld_library_path.nix</code> expression is:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode nix"><code class="sourceCode nix"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="op">{</span> <span class="va">makeSetupHook</span> <span class="op">}</span>:</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>makeSetupHook <span class="op">{</span> <span class="op">}</span> <span class="ss">./ld_library_path.sh</span></span></code></pre></div>
<p>And <code>ld_library_path.sh</code> is:</p>
<pre class="shell"><code>addLdLibraryPath () {
    if [ -d $1/lib ]; then
        export NIX_LD_LIBRARY_PATH=&quot;$1/lib${NIX_LD_LIBRARY_PATH:+:}$NIX_LD_LIBRARY_PATH&quot;
    fi
}
runBinary() {
    LD_LIBRARY_PATH=$NIX_LD_LIBRARY_PATH:$LD_LIBRARY_PATH $(&lt; $NIX_CC/nix-support/dynamic-linker) $@
}
envHooks+=(addLdLibraryPath)</code></pre>
<p>Docker is a third method which I used to use, but it can also be
annoying to configure a Docker container with persistence to run a
binary.</p>
<p>Hopefully the above tools can help you figure out how to quickly run
unpatched binaries on NixOS. If you don't need to do things quickly,
it's probably worth learning how to package existing binaries for real.</p>]]></summary>
</entry>
<entry>
    <title>How to stop functional programming</title>
    <link href="https://brianmckenna.org/blog/howtostopfp" />
    <id>https://brianmckenna.org/blog/howtostopfp</id>
    <published>2016-02-23T00:00:00Z</published>
    <updated>2016-02-23T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>The following has never happened to me but I often hear stories.</p>
<p>You go into work and discover that a coworker isn't happy with some
code you wrote because they don't understand it. They go to your
manager and tell them that you're being a problem by writing code they
don't understand. Your manager, being very skilled in conflict
resolution, makes a technical decision to avoid whatever tool you used
which caused the problem. In your case it was functional programming.</p>
<p>That's it. You've been told. No more functional programming.</p>
<p>The manager has figured out what's good for the business and you figure
that listening is what's good for your job.</p>
<p>You get back to your desk and take a ticket from JIRA. You've got to
add a page listing a person's coworkers to your internal employee
directory. First you write a function you need.</p>
<pre><code>def userCoworkers(u: User): List[Employee] =
  u.departments.flatMap(_.employees)</code></pre>
<p>But it's pure. You're doing functional programming! Stop</p>
<pre><code>def userCoworkers(u: User): List[Employee] = {
  val coworkers = ListBuffer[Employee]()
  for { d &lt;- departments }
    coworkers ++ d.employees
  coworkers.toList
}</code></pre>
<p>Well, there's a side-effect involved, but the whole method is pure.
You're still doing functional programming!</p>
<pre><code>def userCoworkers(u: User): List[Employee] = {
  logger.info(&quot;Collecting coworkers&quot;)
  val coworkers = ListBuffer[Employee]()
  for { d &lt;- departments }
    coworkers ++ d.employees
  coworkers.toList
}</code></pre>
<p>Now the method has 1 external side-effect. Is that enough? With "no
functional programming" you've been given a lower-bound of 1
side-effect per method but we don't really know what the ideal number
is. Hopefully you can slip it through code review.</p>
<p>After this exercise you've learned how easy it is to not do functional
programming.</p>
<p>You show it to your product manager. They didn't realise how many
coworkers the average person had. The page is huge. They ask you to just
change it to a number.</p>
<p>You're going to have to add numbers together. Without being pure.
You're going to have to think about this one.</p>
<p>Maybe you should ask your manager how to do it. Good luck.</p>]]></summary>
</entry>
<entry>
    <title>Don't write code on line #45</title>
    <link href="https://brianmckenna.org/blog/line45" />
    <id>https://brianmckenna.org/blog/line45</id>
    <published>2016-02-22T00:00:00Z</published>
    <updated>2016-02-22T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>There’s an argument going on in the DynamoDB community right now. Should you write code on line #45 or not. I strongly believe that line #45 should be left empty. Here’s why.</p>
<h2 id="line-45-is-below-the-fold">Line 45 is below the fold</h2>
<p>Terminals are 24 lines high by default. If you write any code on line #45 then programmers won’t immediately notice it. If you leave line #45 empty then the programmer won’t miss out on anything. We spend more time reading code than writing it, so make sure the code can be seen.</p>
<h2 id="line-45-is-unpractical">Line 45 is unpractical</h2>
<p>I’ve tried learning line #45 many times but I’ve never easily picked it up. If you look around the web you’ll find lots of different tutorials trying to teach you how to write code on line #45 and they’re full of abstract details. I just want to write some code. The current lines I use don’t make it this hard.</p>
<p>I got on IRC and someone told me that I was looking at the wrong tutorials and they had written some exercises instead. I’m sorry, but you can’t expect those lowly other industry programmers to spend time doing <em>exercises</em>. When you get a bug in production code, you can’t waste time working through exercises for line #45 and especially when you’re on call at 3 in the morning.</p>
<h2 id="line-45-is-unnecessary">Line 45 is unnecessary</h2>
<p>As far as I know there’s no programming language which really requires you to put any code on line #45. Since it’s not required, we should try and avoid it. I think everyone agrees that having no code on line #45 is more simple than having code on line #45.</p>
<blockquote>
<p>Everything should be made as simple as possible, but not simpler.</p>
</blockquote>
<p>You don’t have to delete the line, just leave it blank.</p>
<h2 id="lines-1-39-and-60-are-better">Lines 1, 39 and 60 are better</h2>
<p>I know it’s subjective but syntax really does matter. Anyone who has trained a junior developer knows that lines #39 and #60 are more intuitive. It does take a bit more time to write code which belongs on line #1 but everyone has become familiar with how it works by now. We shouldn’t go screwing with existing idioms by writing code on line #45 when schools are mostly teaching using line #1 instead.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Some of us have been writing code without line #45 for decades. We’ve shipped dozens of applications serving millions of users. It’s a solid and well understood method of programming. Trying to be clever by using line #45 is not serving your users and it’s just massaging your ego. Be kind to the poor ops people at midnight who have to keep your site live and have to step through line #45 in their debuggers.</p>
<p>Line #45 - we don’t need it.</p>]]></summary>
</entry>
<entry>
    <title>Optimising the PureScript Compiler</title>
    <link href="https://brianmckenna.org/blog/optimising_the_purescript_compiler" />
    <id>https://brianmckenna.org/blog/optimising_the_purescript_compiler</id>
    <published>2015-06-11T00:00:00Z</published>
    <updated>2015-06-11T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p><em><strong>2024-12-29:</strong> This post is from a former employer’s blog. I’m particularly proud of this contribution to PureScript, and the blog is no longer around, so here is the post.</em></p>
<p>I work on the SlamData front-end, which is completely written in <a href="https://www.purescript.org/">PureScript</a>. I work with 2 other PureScript engineers and we’ve noticed some slow compilation while working on the UI. If we have to modify one of the core modules, it could take up to 2.5 minutes to compile the application. Not a great situation when we want to iterate on our UI changes.</p>
<p>I have some experience with profiling Haskell applications and so had a look. I kept notes and wrote this blog post up to help people optimise Haskell code and the PureScript compiler in the future.</p>
<p>I use <a href="https://nixos.org/">NixOS</a> for pretty much everything. Here’s the Nix expression I wrote (with thanks to the <a href="https://github.com/NixOS/cabal2nix/blob/master/doc/user-guide.md#how-to-build-with-profiling-enabled">cabal2nix docs</a>) to make a PureScript installation which had profiling enabled:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode nix"><code class="sourceCode nix"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">with</span> <span class="bu">import</span> <span class="op">{</span> <span class="op">};</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a>  <span class="va">packages</span> <span class="op">=</span></span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a>    haskell.packages.ghc7101.override <span class="op">{</span></span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a>      <span class="va">overrides</span> <span class="op">=</span> <span class="va">self</span><span class="op">:</span> <span class="va">super</span><span class="op">:</span> <span class="op">{</span></span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a>        <span class="va">mkDerivation</span> <span class="op">=</span> <span class="va">args</span><span class="op">:</span> super.mkDerivation <span class="op">(</span>args <span class="op">//</span> <span class="op">{</span></span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a>          <span class="va">enableLibraryProfiling</span> <span class="op">=</span> <span class="cn">true</span><span class="op">;</span></span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a>        <span class="op">});</span></span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a>      <span class="op">};</span></span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a>    <span class="op">};</span></span>
<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a><span class="kw">in</span></span>
<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a>  haskell.lib.appendConfigureFlag packages.purescript <span class="op">[</span></span>
<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a>    <span class="st">&quot;–enable-executable-profiling&quot;</span></span>
<span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a>    <span class="st">&quot;–ghc-option=-fprof-auto&quot;</span></span>
<span id="cb1-16"><a href="#cb1-16" aria-hidden="true" tabindex="-1"></a>  <span class="op">]</span></span></code></pre></div>
<p>The <code>-fprof-auto</code> flag enables automatic <a href="https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/profiling.html#cost-centres">cost centre</a> creation. Alternatively I could have started with <code>-fprof-auto-top</code> and <code>-fprof-auto-exported</code> to get a general look first.</p>
<p>Haskell programs provide an <code>+RTS</code> option to tell the runtime what to do. The <code>-p</code> flag tells the runtime to profile and dump out a file:</p>
<pre><code>psc-make -o dist/node_modules \
  bower_components/purescript-*/src/**/*.purs \
  src/**/*.purs \
  +RTS -p</code></pre>
<p>Profiling of course slows things down a bit. Compilation of the UI went up to over 3.5 minutes when a core module was touched.</p>
<p>But it gave a nice <code>psc-make.prof</code> file. Here’s what the top cost centres were:</p>
<pre><code>COST CENTRE                   MODULE                                      %time   %alloc

typeCheckAll.go               Language.PureScript.TypeChecker             20.7    11.3
==                            Language.PureScript.Names                   17.9     0.0
fmap                          Language.PureScript.TypeChecker.Monad       10.0    26.4
entails.filterModule          Language.PureScript.TypeChecker.Entailment   8.0     0.0
compare                       Language.PureScript.Names                    5.5     0.0
typeCheckAll.go.instances.\\  Language.PureScript.TypeChecker              5.5     0.0
everywhereOnTypesTopDownM.go  Language.PureScript.Types                    4.4    17.4
fmap                          Control.Monad.Unify                          3.6    11.1</code></pre>
<p><a href="https://hackage.haskell.org/package/profiteur">profiteur</a> is a great tool which can load .prof files and visualise where time is spent. After clicking a few times I saw something like this:</p>
<p><img src="https://brianmckenna.org/blog/static/2015-06-11-profiteur-screenshot.png" /></p>
<p>Which helped confirm that we were spending a lot of time running the <code>typeCheckAll.go</code> clause. I went down to the “cost-centre stack” and looked for that identifier:</p>
<pre><code>                                                                                                individual   inherited
COST CENTRE                       MODULE                                     no.    entries    %time %alloc %time %alloc

typeCheckAll.go                   Language.PureScript.TypeChecker            32777          0   20.7   11.3  96.3   85.3
typeCheckAll.go.instances.\\      Language.PureScript.TypeChecker            36234  476948645    5.5    0.0  17.0    0.0
==                                Language.PureScript.Names                  36238  476948645   10.1    0.0  10.1    0.0
typeCheckAll.go.instances..mn     Language.PureScript.TypeChecker            36237  476948645    0.0    0.0   0.0    0.0
typeCheckAll.go.instances..(...)  Language.PureScript.TypeChecker            36235  476948645    1.5    0.0   1.5    0.0
tcdName                           Language.PureScript.TypeClassDictionaries  36236  476948645    0.0    0.0   0.0    0.0</code></pre>
<p>And saw that 96.3% of the total time was under that clause, not good. The <code>typeCheckAll.go.instances.\</code> entry referred to a lambda called 476,948,645 times! And names were checked for equality each time that lambda was called, adding to 10.1% of the total time running the program. Removing name equality tests seemed like something which could be fixed.</p>
<p>Here’s what the part of the <a href="https://github.com/purescript/purescript/blob/57f097662263f07c88faf9b7c8a36a8e7c34459f/src/Language/PureScript/TypeChecker.hs#L227">function</a> looked like:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a>go (d<span class="op">@</span>(<span class="dt">ImportDeclaration</span> importedModule _ _) <span class="op">:</span> rest) <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a>  tcds <span class="ot">&lt;-</span> getTypeClassDictionaries</span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a>  <span class="kw">let</span> instances <span class="ot">=</span> <span class="fu">filter</span> (\tcd <span class="ot">-&gt;</span> <span class="kw">let</span> <span class="dt">Qualified</span> (<span class="dt">Just</span> mn) _ <span class="ot">=</span> tcdName tcd <span class="kw">in</span> importedModule <span class="op">==</span> mn) tcds</span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a>  addTypeClassDictionaries [ tcd { tcdName <span class="ot">=</span> <span class="dt">Qualified</span> (<span class="dt">Just</span> moduleName) ident, tcdType <span class="ot">=</span> <span class="dt">TCDAlias</span> (canonicalizeDictionary tcd) }</span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a>                           <span class="op">|</span> tcd <span class="ot">&lt;-</span> instances</span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a>                           , tcdExported tcd</span>
<span id="cb5-7"><a href="#cb5-7" aria-hidden="true" tabindex="-1"></a>                           , <span class="kw">let</span> (<span class="dt">Qualified</span> _ ident) <span class="ot">=</span> tcdName tcd</span>
<span id="cb5-8"><a href="#cb5-8" aria-hidden="true" tabindex="-1"></a>                           ]</span>
<span id="cb5-9"><a href="#cb5-9" aria-hidden="true" tabindex="-1"></a>  ds <span class="ot">&lt;-</span> go rest</span>
<span id="cb5-10"><a href="#cb5-10" aria-hidden="true" tabindex="-1"></a>  <span class="fu">return</span> <span class="op">$</span> d <span class="op">:</span> ds</span></code></pre></div>
<p>Each time we imported a module, we found all type-class dictionaries and filtered down the ones which were in that module. We just needed a way to index to dictionaries by modules.</p>
<p>Turns out the dictionaries were already stored in a Map:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="ot">typeClassDictionaries ::</span></span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a>  <span class="dt">M.Map</span> (<span class="dt">Qualified</span> <span class="dt">Ident</span>, <span class="dt">Maybe</span> <span class="dt">ModuleName</span>) <span class="dt">TypeClassDictionaryInScope</span></span></code></pre></div>
<p>But indexed with the identifier. I took a while to see if the compiler actually did a lookup by the name, but I couldn’t easily see it. Instead of spending time looking for where, I decided to just delete the identifier part of the key and see what broke. Turns out that after preserving the “add this dictionary” and “return all dictionaries” functions, everything compiled. We never actually did a look up by the keys, we just used the Map for uniqueness.</p>
<p>We could make the lookup efficient and guarantee uniqueness by changing the type to:</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="ot">typeClassDictionaries ::</span></span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a>  <span class="dt">M.Map</span> (<span class="dt">Maybe</span> <span class="dt">ModuleName</span>) (<span class="dt">M.Map</span> (<span class="dt">Qualified</span> <span class="dt">Ident</span>) <span class="dt">TypeClassDictionaryInScope</span>)</span></code></pre></div>
<p>Easy.</p>
<p>Now I just needed to verify that I actually improved speed. Haskell has great tooling for this too, with the <a href="http://www.serpentine.com/criterion/">Criterion</a> library.</p>
<p>Here is a program which runs the previous compiler and the updated compiler, updating a file to trigger rebuilding of certain modules:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">Criterion.Main</span></span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">System.FilePath.Glob</span></span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">System.Posix.Files</span></span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a><span class="kw">import</span> <span class="dt">System.Process</span></span>
<span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-6"><a href="#cb8-6" aria-hidden="true" tabindex="-1"></a>unpatched <span class="ot">=</span> <span class="st">&quot;./psc-make-old&quot;</span></span>
<span id="cb8-7"><a href="#cb8-7" aria-hidden="true" tabindex="-1"></a>patched <span class="ot">=</span> <span class="st">&quot;./psc-make-new&quot;</span></span>
<span id="cb8-8"><a href="#cb8-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-9"><a href="#cb8-9" aria-hidden="true" tabindex="-1"></a><span class="ot">make ::</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> <span class="dt">String</span></span>
<span id="cb8-10"><a href="#cb8-10" aria-hidden="true" tabindex="-1"></a>make c <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb8-11"><a href="#cb8-11" aria-hidden="true" tabindex="-1"></a>  bowerFiles <span class="ot">&lt;-</span> glob <span class="st">&quot;bower\_components/purescript-_/src/**/\*.purs&quot;</span></span>
<span id="cb8-12"><a href="#cb8-12" aria-hidden="true" tabindex="-1"></a>  srcFiles <span class="ot">&lt;-</span> glob <span class="st">&quot;src/**/_.purs&quot;</span> touchFile <span class="st">&quot;src/EffectTypes.purs&quot;</span></span>
<span id="cb8-13"><a href="#cb8-13" aria-hidden="true" tabindex="-1"></a>  readProcess c ([<span class="st">&quot;-o&quot;</span>, <span class="st">&quot;dist/node\_modules&quot;</span>] <span class="op">++</span> bowerFiles <span class="op">++</span> srcFiles) <span class="st">&quot;&quot;</span></span>
<span id="cb8-14"><a href="#cb8-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-15"><a href="#cb8-15" aria-hidden="true" tabindex="-1"></a><span class="ot">main ::</span> <span class="dt">IO</span> ()</span>
<span id="cb8-16"><a href="#cb8-16" aria-hidden="true" tabindex="-1"></a>main <span class="ot">=</span></span>
<span id="cb8-17"><a href="#cb8-17" aria-hidden="true" tabindex="-1"></a>  defaultMain [</span>
<span id="cb8-18"><a href="#cb8-18" aria-hidden="true" tabindex="-1"></a>    bench <span class="st">&quot;unpatched&quot;</span> <span class="op">$</span> nfIO (make unpatched),</span>
<span id="cb8-19"><a href="#cb8-19" aria-hidden="true" tabindex="-1"></a>    bench <span class="st">&quot;patched&quot;</span> <span class="op">$</span> nfIO (make patched) </span>
<span id="cb8-20"><a href="#cb8-20" aria-hidden="true" tabindex="-1"></a>  ]</span></code></pre></div>
<p>This took a long time to run, since a single run of the original code took 2.5 minutes. An hour or so later, I got these results:</p>
<pre><code>benchmarking unpatched time 142.9 s (133.9 s .. 149.8 s) 1.000 R² (0.998 R² .. 1.000 R²) mean 145.8 s (144.0 s .. 146.9 s) std dev 1.699 s (0.0 s .. 1.938 s) variance introduced by outliers: 19% (moderately inflated)

benchmarking patched time 56.14 s (41.02 s .. 68.60 s) 0.992 R² (0.969 R² .. 1.000 R²) mean 58.99 s (56.64 s .. 60.73 s) std dev 2.642 s (0.0 s .. 3.008 s) variance introduced by outliers: 19% (moderately inflated)</code></pre>
<p>We got similar variance but ~86s taken off each run. Around a 2.5x speedup over the original.</p>
<p>I hope this shows how easy it can be to <a href="https://accidentallyquadratic.tumblr.com/">accidentally quadratic</a> but also how easy it can be to profile and optimise Haskell programs. There’s much more we can do to make the PureScript compiler even quicker and thankfully we have access to Haskell’s great tooling.</p>]]></summary>
</entry>
<entry>
    <title>QuickChecking non-Haskell Code</title>
    <link href="https://brianmckenna.org/blog/crosscheck" />
    <id>https://brianmckenna.org/blog/crosscheck</id>
    <published>2015-03-10T00:00:00Z</published>
    <updated>2015-03-10T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve been thinking a lot about minimal QuickCheck properties required
for asserting correctness of functions. I was inspired by <a href="https://gist.github.com/copumpkin/8758586">Daniel
Peeble’s proof of List reverse’s core
properties</a> and <a href="https://gist.github.com/mbrcknl/bfaa72c2ec6ff32a2826">Matthew
Brecknells’s
minimisation</a>.</p>
<p>I’ve been taking these ideas and playing around with them in Idris. I
have proofs that the following functions only need 2 properties to
checked:</p>
<ul>
<li><a href="https://gist.github.com/puffnfresh/99c139d4d0c4bdd155ac">List reverse</a></li>
<li><a href="https://gist.github.com/puffnfresh/67dee64b8a713ab4211a">Natural number addition</a></li>
</ul>
<p>Having the proof, we know that this is all we have to write to test that Haskell’s list reverse is correct:</p>
<pre><code>reverse1 a = reverse [a] == [a]
reverseFlip xs ys = reverse (xs ++ ys) == reverse ys ++ reverse xs

quickCheck $ reverse1 .&amp;&amp;. reverseFlip</code></pre>
<p>Haskell’s QuickCheck is a really great tool for property-based testing. But what if we’re not using Haskell? I’ve been thinking about this a lot, too.</p>
<p>There have been ports to other languages but most do not do a great
job. I’ve tried writing property-based tests using Python but the
closest I could get was
<a href="https://github.com/DRMacIver/hypothesis">Hypothesis</a>, which is a good
start but not near the quality of QuickCheck. JavaScript suffers from
the problem.</p>
<p>What if we could use QuickCheck but to execute Python code? Or node.js code? Or shell code?</p>
<p>I started work on <a href="https://github.com/puffnfresh/crosscheck">CrossCheck</a> to allow testing across these different environments. The library is a small wrapper for creating program strings and then forking them to an external process.</p>
<p>For example, here’s a custom reverse function written in JavaScript:</p>
<pre><code>module.exports = function(xs) {
  return xs.reduce(function(accum, x) {
      return [x].concat(accum);
  }, []);
};</code></pre>
<p>And here’s CrossCheck testing the list reverse properties for that function:</p>
<pre><code>reverse1 :: JsNumber -&gt; CrossProperty
reverse1 =
  comparePrograms &quot;console.log(require(&#39;./reverse&#39;)([ {0} ]));&quot;
                  &quot;console.log([ {0} ]);&quot;

reverseFlip :: JsList JsNumber -&gt; JsList JsNumber -&gt; CrossProperty
reverseFlip xs ys =
  comparePrograms &quot;console.log(require(&#39;./reverse&#39;)( {0}.concat( {1} ) ));&quot;
                  &quot;console.log(require(&#39;./reverse&#39;)( {1} ).concat(require(&#39;./reverse&#39;)( {0} )));&quot;
                  (Cross2 xs ys)

main :: IO ()
main = do
  crossCheck nodejsCheck reverse1
  crossCheck nodejsCheck reverseFlip</code></pre>
<p>We’ll get familiar output:</p>
<pre><code>+++ OK, passed 100 tests.
+++ OK, passed 100 tests.</code></pre>
<p>If we break one of the properties, we’ll get:</p>
<pre><code>*** Failed! Falsifiable (after 1 test):
JsInt (-6732904699341542)
&quot;[]\n&quot; /= &quot;[ -6732904699341542 ]\n&quot;</code></pre>
<p>You can see a <a href="https://github.com/puffnfresh/crosscheck/blob/master/Example.hs">full
example</a>
on the GitHub project. The main problem with this approach is that
forking twice for every iteration makes these tests fairly slow. Let
me know if you have an idea on how to improve the forking method.</p>]]></summary>
</entry>
<entry>
    <title>This Blog Uses Idris</title>
    <link href="https://brianmckenna.org/blog/idris_blog" />
    <id>https://brianmckenna.org/blog/idris_blog</id>
    <published>2015-02-12T00:00:00Z</published>
    <updated>2015-02-12T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I am not using node.js to generate this blog. I am now using
<a href="http://www.idris-lang.org/">Idris</a>! I’ve chucked the source up on
<a href="https://github.com/puffnfresh/bam-idris-blog">GitHub</a>.</p>
<p>I wanted to be the first to use a dependently typed compiler to
generate my blog. From what I can tell, I was beat
<a href="http://coq-blog.clarus.me/a-blog-engine-written-and-proven-in-coq.html">by just a couple of weeks</a>.</p>
<p>Sadly, there are no interesting uses of dependent types used yet but
one interesting thing I worked on was using
<a href="http://nixos.org/nix/">Nix</a> to build
<a href="https://github.com/idris-hackers/idrispkgs">Idris packages</a>. I worked
on and packaged:</p>
<ul>
<li><a href="https://github.com/idris-hackers/idris-lens">idris-lens</a></li>
<li><a href="https://github.com/soimort/idris-commonmark">idris-commonmark</a></li>
<li><a href="https://github.com/jfdm/idris-config">idris-config</a></li>
</ul>
<p>I also had to create a package to
<a href="https://github.com/idris-hackers/idris-posix">wrap some POSIX functions</a>,
such as listing the
<a href="https://github.com/idris-hackers/idris-posix/blob/master/src/System/Posix/Directory.idr#L18-L32">contents of a directory</a>
and
<a href="https://github.com/idris-hackers/idris-posix/blob/master/src/System/Posix/Directory.idr#L34-L35">checking if a file exists</a>.</p>
<p>To build my program I can just open up a
<a href="http://nixos.org/nix/manual/#sec-nix-shell">nix-shell</a> from a dummy
expression:</p>
<pre><code>with import &lt;nixpkgs&gt; { };
with import &lt;idrispkgs&gt; { };

runCommand &quot;dummy&quot; {
  buildInputs = [
    (idrisWithPackages [ idris-commonmark idris-config idris-lens idris-posix ])
  ];
} &quot;&quot;</code></pre>
<p>And compile it with a simple command:</p>
<pre><code>idris -p effects -p config -p commonmark -p lens -p posix -o bam-idris-blog Main.idr</code></pre>
<p>I plan on using Idris for what it’s good at (i.e. not as a poor
Haskell replacement) by introducing dependent types in some way but
I’m happy that I was able to improve some Idris libraries and tools.</p>]]></summary>
</entry>
<entry>
    <title>EvenOdd in Agda, Idris, Haskell, Scala</title>
    <link href="https://brianmckenna.org/blog/evenodd_agda_idris_haskell_scala" />
    <id>https://brianmckenna.org/blog/evenodd_agda_idris_haskell_scala</id>
    <published>2014-01-23T00:00:00Z</published>
    <updated>2014-01-23T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>A while ago I blogged about <a href="http://brianmckenna.org/blog/plus_equals_even_take_2">using Agda to prove the parity of added
numbers</a>. I’ve recently been <a href="https://github.com/idris-lang/Idris-dev/commits?author=puffnfresh">doing some work on Idris</a> and wondered how
easy it would be to translate my Agda proof to Idris.</p>
<p>The original Agda code looked something like this:</p>
<pre><code>module EvenOdd where

open import Data.Nat

data Even : ℕ → Set where
  evenZero : Even 0
  evenSuc : {n : ℕ} → Even n → Even (suc (suc n))

_e+e_ : {n m : ℕ} → Even n → Even m → Even (n + m)
evenZero e+e b = b
evenSuc a e+e b = evenSuc (a e+e b)</code></pre>
<p>The direct Idris translation looks like:</p>
<pre><code>module EvenOdd

data Even : Nat -&gt; Type where
  evenZ : Even Z
  evenS : Even n -&gt; Even (S (S n))

total
ee : Even n -&gt; Even m -&gt; Even (n + m)
ee evenZ m = m
ee (evenS n) m = evenS (ee n m)</code></pre>
<p>The few differences:</p>
<ul>
<li><p>We don’t have to import a Nat type</p></li>
<li><p>Totality is not the default (there is a flag to make it so, though)</p></li>
<li><p>We can’t define mixed letter and symbol operators</p></li>
</ul>
<p>Pretty easy! Time for something trickier. Now, I haven’t done very
much type level Haskell but I wanted to see how easy it would be to
translate to the recent GHC 7.8 release.</p>
<pre><code>{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}

module EvenOdd where

data Nat = Z | S Nat

data Even :: Nat -&gt; * where
  EvenZ :: Even Z
  EvenS :: Even n -&gt; Even (S (S n))

type family Plus (n :: Nat) (m :: Nat) :: Nat
type instance Plus Z m = m
type instance Plus (S n) m = S (Plus n m)

ee :: Even n -&gt; Even m -&gt; Even (Plus n m)
ee EvenZ m = m
ee (EvenS n) m = EvenS (ee n m)</code></pre>
<p>Getting a bit trickier. We’ve had to do the following:</p>
<ul>
<li><p>Enable data type promotion, so that data types can be kinds</p></li>
<li><p>Enable type families, so we can write a type level functions</p></li>
<li><p>Define our own Nat and use that as a kind</p></li>
<li><p>Define our own Plus type level function (the type family)</p></li>
<li><p>Get totality results as warnings (or errors via <code>-Wall</code>)</p></li>
</ul>
<p>The few problems are caused by Haskell’s distinction between values,
types and kinds. Everything else looks extremely similar - we’ve been
lucky to fall into an area where the GHC data kinds extension works
really well and we can promote our simple Nat type to a kind.</p>
<p>Let’s step it right up. Now let’s encode this in Scala. Are you ready?</p>
<pre><code>package org.brianmckenna.evenodd

sealed trait Nat
trait Z extends Nat
case object Z extends Z
case class S[N &lt;: Nat](n: N) extends Nat

sealed trait Even[N &lt;: Nat]
trait EvenZ extends Even[Z]
case object EvenZ extends EvenZ
case class EvenS[N &lt;: Nat](n: Even[N]) extends Even[S[S[N]]]

object Even {
  implicit val evenZ = EvenZ
  implicit def evenS[N &lt;: Nat](implicit even: Even[N]) = EvenS[N](even)
}

sealed trait Plus[N &lt;: Nat, M &lt;: Nat] {
  type Result &lt;: Nat
}

object Plus {
  type Aux[N &lt;: Nat, M &lt;: Nat, R &lt;: Nat] = Plus[N, M] {
    type Result = R
  }

  implicit def plusZ[M &lt;: Nat] = new Plus[Z, M] {
    type Result = M
  }

  implicit def plusS[N &lt;: Nat, M &lt;: Nat](implicit plus: Plus[N, S[M]]) = new Plus[S[N], M] {
    type Result = plus.Result
  }
}

object ee {
  def apply[N &lt;: Nat, M &lt;: Nat, R &lt;: Nat](n: Even[N], m: Even[M])(implicit sum: Plus.Aux[N, M, R], re: Even[R]) = re
}</code></pre>
<p>Now, this probably looks pretty verbose since we have to define our
own type level Nat and Plus function. The type level Plus uses Scala’s
<a href="http://danielwestheide.com/blog/2013/02/13/the-neophytes-guide-to-scala-part-13-path-dependent-types.html">path-dependent types</a>.</p>
<p>What’s interesting is that our theorem is expressed as a constraint
that given <code>Even[N]</code> and <code>Even[M]</code> then we can construct an <code>Even[N + M]</code> from an implicit. What we’ve given up is a constructive proof that
every combination of two even numbers always results in an even number
(but we know from our previous proofs that it’s true) - specifically,
we can’t tell if the the implicit <code>re</code> can be found for all values. We
could fix this by splitting the implicit up into each case but we
can’t get totality checking.</p>
<p>Hopefully this gives a very quick feel for programming at the type
level in Agda, Idris, Haskell and Scala. Type level programming in
Agda and Idris is just as easy as programming at the value level. Type
level programming in Haskell and Scala is a bit annoying, we have to
write functions very differently at the type level and value level,
but it’s impressive that we can achieve our goal in much more widely
used languages.</p>
<p>Thanks to <a href="https://twitter.com/milessabin">Miles Sabin</a> for help with simplifying the Scala version.</p>]]></summary>
</entry>
<entry>
    <title>Idris as a Library</title>
    <link href="https://brianmckenna.org/blog/idris_library" />
    <id>https://brianmckenna.org/blog/idris_library</id>
    <published>2013-12-22T00:00:00Z</published>
    <updated>2013-12-22T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve been playing around with making a dependently typed
language. It’s based upon Martin-Löf Type Theory (commonly just called
Type Theory, TT). Turns out that implementing a dependent type system
is a great way to learn how to use one!</p>
<p><img src="http://brianmckenna.org/blog/static/dependent-language.png" /></p>
<p><img src="http://brianmckenna.org/blog/static/language-tt.png" /></p>
<p>I had written code to translate from my toy languages’ terms into TT -
but I wanted a compiler, so that I could execute it somewhere outside
of the evaluator/normaliser. I started thinking about how I could
possibly compile TT to JavaScript but then I realised that <a href="http://www.idris-lang.org/">Idris</a>
already handles code generation from TT:</p>
<p><img src="http://brianmckenna.org/blog/static/language-tt-target.png" /></p>
<p>Well, I only wanted to compile to a single target, but wow, I’ll take
all four please! If only I could reuse the Idris backend…</p>
<p>So a few weeks ago I turned Idris into a Cabal library so I could just
depend on it in my project and use the code generators. I just had to
<a href="https://github.com/idris-lang/Idris-dev/commit/5000aeb2560393a1f3c5f16b0795d5b7dd14bb8d">move all of the files around and add a <code>Library</code> section to
<code>idris.cabal</code></a>. Easy!</p>
<p>The commit was only merged sometime today so there’s no Hackage
release yet. If you want to play with it, you should do something like
the following:</p>
<pre><code>git clone https://github.com/idris-lang/Idris-dev.git
mkdir my-language
cd my-language
cabal sandbox init
cabal sandbox add-source ../Idris-dev</code></pre>
<p>Which allows adding a dependency on the Idris library and have it
compile from master.</p>
<p>Here is a short and incomplete example of using the library:</p>
<pre><code>import IRTS.Compiler
import Idris.AbsSyntax
import Idris.Core.TT
import Idris.Delaborate
import Idris.ElabDecls
import Idris.ElabTerm
import Idris.Parser

run :: (PTerm -&gt; PDecl) -&gt; TT Name -&gt; TT Name -&gt; Idris ()
run makeDecl program runProgram = do
  ddir &lt;- runIO $ getIdrisLibDir
  addImportDir $ ddir &lt;/&gt; &quot;prelude&quot;
  addImportDir $ ddir &lt;/&gt; &quot;base&quot;
  elabPrims
  _ &lt;- loadModule stdout &quot;Builtins&quot;
  _ &lt;- loadModule stdout &quot;Prelude&quot;
  pterm &lt;- fmap (flip delab program) getIState
  elabDecls toplevel [makeDecl pterm]
  compile ViaNode &quot;wow.js&quot; runProgram</code></pre>
<p>The first 6 lines of <code>run</code> setup the Idris standard library, allowing
us to access primitive IO functions. The next line “delaborates” our
custom TT (defined in <code>program</code>) back to Idris terms. The next line
elaborates those Idris terms (yes, strange since we just delaborated;
but the compiler needs terms to be in scope, using the elaborator is
the easiest way to do it). The final line writes a <code>wow.js</code> node.js
program!</p>
<p>So, if you want to make a dependently typed language, Idris has a
great backend waiting for you to reuse (theoretically it doesn’t even
have to be dependently typed; it just has to compile to TT). The Idris
backend will handle compiling to JavaScript, Java, C, LLVM and any
other code generators which could be added later. You’ll be free to
focus on language features!</p>]]></summary>
</entry>
<entry>
    <title>Scala Code Linting via WartRemover 0.4</title>
    <link href="https://brianmckenna.org/blog/wartremover_point_four" />
    <id>https://brianmckenna.org/blog/wartremover_point_four</id>
    <published>2013-09-16T00:00:00Z</published>
    <updated>2013-09-16T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I was recently on a panel with some smart people discussing Rod
Johnsons’ infamous “Scala 2018” keynote. Most agreed that we should
start enforcing code standards. Sadly, the tools for doing that are a
bit lacking.</p>
<p>For a while I’ve had an idea on a flexible tool for writing lint rules
over Scala code. I already had WartRemover which was a linter for
things I considered bad. I decided to rewrite WartRemover into the
flexible tool I imagined.</p>
<p>The idea is to write lint rules using a
<a href="http://www.scala-lang.org/api/current/index.html#scala.reflect.api.Trees$Traverser">Traverser</a>
over the Scala AST. WartRemover then provides the wrappers to run
rules from:</p>
<ul>
<li>Macros</li>
<li>Command-line tool</li>
<li>Compiler plugin</li>
</ul>
<p>To run a rule as a macro:</p>
<pre><code>scala&gt; import language.experimental.macros
import language.experimental.macros
    
scala&gt; import org.brianmckenna.wartremover.warts.Unsafe
import org.brianmckenna.wartremover.warts.Unsafe
            
scala&gt; def safe(expr: Any) = macro Unsafe.asMacro
safe: (expr: Any)Any
                    
scala&gt; safe { null }
&lt;console&gt;:10: error: null is disabled
              safe { null }</code></pre>
<p>Using the command-line tool, which reports errors and gives an exit
code of 1 on failures:</p>
<pre><code>java -classpath target/classes:wartremover-assembly-0.4-SNAPSHOT.jar \
    org.brianmckenna.wartremover.Main \
    -traverser org.brianmckenna.wartremover.warts.Unsafe \
    src/main/scala/Main.scala</code></pre>
<p>Or, best for last, as a compiler plugin by adding the following to
<code>build.sbt</code>:</p>
<pre><code>resolvers += Resolver.sonatypeRepo(&quot;releases&quot;)

addCompilerPlugin(&quot;org.brianmckenna&quot; % &quot;wartremover&quot; % &quot;0.4&quot; cross CrossVersion.full)

scalacOptions += &quot;-P:wartremover:traverser:org.brianmckenna.wartremover.warts.Unsafe&quot;</code></pre>
<p>Which will check all code under the project for errors.</p>
<p>The provided rules are:</p>
<ul>
<li>No any2stringadd</li>
<li>No non-unit statements</li>
<li>No null</li>
<li>No var</li>
<li>No Nothing type</li>
<li>No unsafe (all of the above except Nothing is allowed)</li>
</ul>
<p>But WartRemover now allows you to write your own rules. Here is a
complete example:</p>
<pre><code>package unimplemented

import org.brianmckenna.wartremover.{WartTraverser, WartUniverse}

object Unimplemented extends WartTraverser {
  def apply(u: WartUniverse): u.Traverser = {
    import u.universe._

    val NotImplementedName: TermName = &quot;$qmark$qmark$qmark&quot; // ???
    new Traverser {
      override def traverse(tree: Tree) {
        tree match {
          case Select(_, NotImplementedName) =&gt;
            u.error(tree.pos, &quot;There was something left unimplemented&quot;)
          case _ =&gt;
        }
        super.traverse(tree)
      }
    }
  }
}</code></pre>
<p>The above disables usages of <code>???</code> - you could make that above rule
execute before committing, for example.</p>
<p>You can also combine rules like so:</p>
<pre><code>package org.brianmckenna.wartremover
package warts

object Unsafe extends WartTraverser {
  val safeTraversers = List(NonUnitStatements, Var, Null, Any2StringAdd)

  def apply(u: WartUniverse): u.Traverser =
    WartTraverser.sumList(u)(safeTraversers)
}</code></pre>
<p>If you’re interested in contributing rules (aka warts) or just want to
have a play, the
<a href="https://github.com/puffnfresh/wartremover">repository is on GitHub</a>.</p>]]></summary>
</entry>
<entry>
    <title>Odd Odd Even Agda Proof, Take (suc (suc zero))</title>
    <link href="https://brianmckenna.org/blog/plus_equals_even_take_2" />
    <id>https://brianmckenna.org/blog/plus_equals_even_take_2</id>
    <published>2013-08-03T00:00:00Z</published>
    <updated>2013-08-03T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Almost 2 years ago <a href="http://brianmckenna.org/blog/plus_equals_even">I attempted to write an Agda
proof</a> that two odd
numbers added together always result in an even number.</p>
<p>I picked Agda up again yesterday to have a little play. I quickly
wrote a HList, which used a list of types at the type level to
represent the heterogeneity:</p>
<pre><code>data HList : List Set → Set1 where
  HCons : forall {x xs} → x → HList xs → HList (x ∷ xs)
  HNil : HList []</code></pre>
<p>Really interesting. I definitely attribute some of my understanding to
working on <a href="https://github.com/milessabin/shapeless">shapeless</a>.</p>
<p>I felt comfortable enough to be able to go back to my original “odd +
odd = even” proof in Agda. I was so impressed by Agda that I’m writing
this.</p>
<p>Here we create types for even and odd, each taking a natural number
type:</p>
<pre><code>module EvenOdd where

open import Data.Nat

data Even : ℕ → Set where
  evenZero : Even 0
  evenSuc : {n : ℕ} → Even n → Even (suc (suc n))

data Odd : ℕ → Set where
  oddOne : Odd 1
  oddSuc : {n : ℕ} → Odd n → Odd (suc (suc n))</code></pre>
<p>Next, we just write a type signature like so:</p>
<pre><code>_o+o_ : {n m : ℕ} → Odd n → Odd m → Even (n + m)</code></pre>
<p>Agda has an interactive Emacs mode. We can write this:</p>
<pre><code>a o+o b = ?</code></pre>
<p>Then load it in Agda <code>C-c C-l</code> for it to find the <code>?</code> as a goal:</p>
<pre><code>a o+o b = {  }0</code></pre>
<p>We can get Agda to expand the patterns by typing <code>C-c C-c a RET</code>
(i.e. expand the <code>a</code> cases). It comes out like so:</p>
<pre><code>oddOne o+o b = {  }0
oddSuc a o+o b = {  }1</code></pre>
<p>We can expand the <code>b</code> side, similarly:</p>
<pre><code>oddOne o+o oddOne = {  }0
oddOne o+o oddSuc b = {  }1
oddSuc a o+o b = {  }2</code></pre>
<p>Looks like all the cases are covered. Now, here’s the coolest part. We
just hit <code>C-c C-a</code> over each of the goals and Agda figures out <em>the
only possible solution</em>:</p>
<pre><code>oddOne o+o oddOne = evenSuc evenZero
oddOne o+o oddSuc b = evenSuc (oddOne o+o b)
oddSuc a o+o b = evenSuc (a o+o b)</code></pre>
<p>Amazing.</p>
<p>With Agda’s huge help, we’ve proved that adding two odd numbers always
results in an even number.</p>
<p>Try it for yourself with the following type signature:</p>
<pre><code>_e+e_ : {n m : ℕ} → Even n → Even m → Even (n + m)</code></pre>
<p>I’ve posted <a href="https://gist.github.com/puffnfresh/6149037">the answer</a>
if you can’t properly setup Agda or Emacs.</p>]]></summary>
</entry>
<entry>
    <title>Bottom-up Type Annotation with the Cofree Comonad</title>
    <link href="https://brianmckenna.org/blog/type_annotation_cofree" />
    <id>https://brianmckenna.org/blog/type_annotation_cofree</id>
    <published>2013-07-06T00:00:00Z</published>
    <updated>2013-07-06T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p><em>This is <a href="https://gist.github.com/puffnfresh/5940556">also a Gist</a> for
you to clone and use <code>runhaskell</code> on</em></p>
<p>How do we add extra information to a tree? This has been called <a href="http://blog.ezyang.com/2013/05/the-ast-typing-problem/">The AST
Typing Problem</a>.</p>
<p>After being hit with this problem in Roy’s new type-inference engine, I
tried figuring out how to represent the algorithm. I eventually realised
that it looked like a comonadic operation. Turns out it’s been done
before but I couldn’t find any complete example.</p>
<p>Below is some literate Haskell to show how to use the Cofree Comonad to
perform <a href="http://igitur-archive.library.uu.nl/math/2007-1122-200535/heeren_02_generalizinghindleymilner.pdf">bottom-up, constraint-based
type-inference</a>.
It’s essentially a tiny version of how Roy’s new type-system works.</p>
<pre><code>{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE StandaloneDeriving #-}

module CofreeTree where

import Prelude hiding (sequence)

import Control.Comonad
import Control.Comonad.Cofree
import Control.Monad.State hiding (sequence)
import Data.Foldable (Foldable, fold)
import Data.Maybe (fromMaybe)
import Data.Monoid
import Data.Traversable (Traversable, sequence)
import qualified Data.Map as M</code></pre>
<p>Our little language is an extended lambda calculus with integer and
string literals. The interesting thing here is that the AST doesn’t
specify <code>(AST a)</code> for recursion, only <code>a</code> - this gives us more
flexibility; we can have a node that isn’t recursive or even a special
type of recursion (e.g. we’ll eventually get annotated recursion).</p>
<pre><code>data AST a = ALambda String a
           | AApply a a
           | ANumber Int
           | AString String
           | AIdent String</code></pre>
<p>But for now we want a normal recursive AST. If we use a fixed-point we
can get a normal one using <code>Mu AST</code>.</p>
<pre><code>newtype Mu f = Mu (f (Mu f))</code></pre>
<p>Now it’s surprisingly easy to create an unattributed AST. Our example
will use the following lambda expression: (λx.x)2</p>
<pre><code>example :: Mu AST
example = Mu $ AApply (Mu . ALambda &quot;x&quot; . Mu $ AIdent &quot;x&quot;) (Mu $ ANumber 2)</code></pre>
<p>Later on we’ll need to be able to traverse the AST and store it in a
map.</p>
<pre><code>deriving instance Show a =&gt; Show (AST a)
deriving instance Functor AST
deriving instance Foldable AST
deriving instance Traversable AST
deriving instance Eq a =&gt; Eq (AST a)
deriving instance Ord a =&gt; Ord (AST a)</code></pre>
<p>We’re going to add types to our AST. <code>TVar</code> is a parametric type. For
example, the type <code>α → α</code> is represented as <code>TLambda (TVar 0) (TVar 0)</code>.</p>
<pre><code>data Type = TLambda Type Type
          | TVar Int
          | TNumber
          | TString

deriving instance Show Type</code></pre>
<p>Bottom-up inference works by generating constraints required to
calculate the type of each node and propagating them up to the top
level, then solving them.</p>
<p>Our example will only use an equality constraint, asserting that two
types can unify. This should be easy to extend, allowing things like
let-polymorphism or type-classes.</p>
<pre><code>data Constraint = EqualityConstraint Type Type

deriving instance Show Constraint</code></pre>
<p>Each step of the inference algorithm will give us a set of constraints
and possibly a map of assumptions from identifier to type. For example
we could get a set of <code>{α ≡ TNumber, β ≡ TString}</code> with assumptions of
<code>{hello = {α}}</code>. We can combine the results of multiple steps using a
monoid instance.</p>
<pre><code>data TypeResult = TypeResult {
      constraints :: [Constraint],
      assumptions :: M.Map String [Type]
    }

deriving instance Show TypeResult

instance Monoid TypeResult where
    mempty = TypeResult {
               constraints = mempty,
               assumptions = mempty
             }
    mappend a b = TypeResult {
                             constraints = constraints a `mappend` constraints b,
                             assumptions = assumptions a `mappend` assumptions b
                           }</code></pre>
<p>We need to keep track of some state during the inference process. We
need the next fresh variable ID and a memoisation map for the result of
inference per AST node.</p>
<pre><code>data TypeState t m = TypeState {
      varId :: Int,
      memo :: M.Map t m
    }</code></pre>
<p>Each node will return a type along with its constraints and assumptions.
Since we’ll be using that a lot inside of the State Monad, we’ll define
an alias.</p>
<pre><code>type TypeCheck t = State (TypeState t (Type, TypeResult)) (Type, TypeResult)</code></pre>
<p>We have a function to retrieve the next fresh type variable and then
update the ID.</p>
<pre><code>freshVarId :: State (TypeState t m) Type
freshVarId = do
  v &lt;- gets varId
  modify $ \s -&gt; s { varId = succ v }
  return $ TVar v</code></pre>
<p>We’ll always want to memoise the result of each step so we define a
memoiser that takes the type-inferencing function and stores the results
in the memo map.</p>
<pre><code>memoizedTC :: Ord c =&gt; (c -&gt; TypeCheck c) -&gt; c -&gt; TypeCheck c
memoizedTC f c = gets memo &gt;&gt;= maybe memoize return . M.lookup c where
    memoize = do
      r &lt;- f c
      modify $ \s -&gt; s { memo = M.insert c r $ memo s }
      return r</code></pre>
<p>We need to convert our example AST from <code>Mu</code> into <code>Cofree</code>. Cofree takes
a parameterised type and makes it recursive with each step having an
attribute. Our initial attribution will be unit (i.e. we’ll initially
use Cofree just for the recursive comonadic structure).</p>
<pre><code>cofreeMu :: Functor f =&gt; Mu f -&gt; Cofree f ()
cofreeMu (Mu f) = () :&lt; fmap cofreeMu f</code></pre>
<p>The real annotation function will take a unit annotated Cofree AST then
do a comonadic extend so that each node is annotated with its type and
state. Fairly easy.</p>
<p>But we’ll get a Cofree where each attribute is a State operation. We can
sequence to get a combined State of a Cofree AST. Then we can run the
State to get just a Cofree AST with our attributes!</p>
<pre><code>attribute :: Cofree AST () -&gt; Cofree AST (Type, TypeResult)
attribute c =
    let initial = TypeState { memo = M.empty, varId = 0 }
    in evalState (sequence $ extend (memoizedTC generateConstraints) c) initial</code></pre>
<p>Let’s take a look at the comonadic operation which generates a type
along with its constraints and assumptions.</p>
<pre><code>generateConstraints :: Cofree AST () -&gt; TypeCheck (Cofree AST ())</code></pre>
<p>Literals are trivial. They don’t need any constraints or assumptions. We
immediately know their type.</p>
<pre><code>generateConstraints (() :&lt; ANumber _) = return (TNumber, mempty)
generateConstraints (() :&lt; AString _) = return (TString, mempty)</code></pre>
<p>Using an identifier just creates a fresh type variable and puts it in
the assumption map.</p>
<pre><code>generateConstraints (() :&lt; AIdent s) = do
  var &lt;- freshVarId
  return (var, TypeResult {
                   constraints = [],
                   assumptions = M.singleton s [var]
                 })</code></pre>
<p>A memoised recursive call to the lambda’s body is used for the lambda’s
return type and for propagating constraints. Lambdas take the name of
their bound variable out of the body’s assumption map and turn it into a
constraint for the input of the returned lambda type.</p>
<pre><code>generateConstraints (() :&lt; ALambda s b) = do
  var &lt;- freshVarId
  br &lt;- memoizedTC generateConstraints b
  let cs = maybe [] (map $ EqualityConstraint var) (M.lookup s . assumptions $ snd br)
      as = M.delete s . assumptions $ snd br
  return (TLambda var (fst br), TypeResult {
                        constraints = constraints (snd br) `mappend` cs,
                        assumptions = as
                      })</code></pre>
<p>Lambda application generates constraints for the lambda and the
argument. It then generates a fresh type variable to use as the return
type and; a constraint that the lambda can take the argument and returns
the type variable.</p>
<pre><code>generateConstraints (() :&lt; AApply a b) = do
  var &lt;- freshVarId
  ar &lt;- memoizedTC generateConstraints a
  br &lt;- memoizedTC generateConstraints b
  return (var, snd ar `mappend` snd br `mappend` TypeResult {
                   constraints = [EqualityConstraint (fst ar) $ TLambda (fst br) var],
                   assumptions = mempty
                 })</code></pre>
<p>To be able to get a type for the AST, we’ll need to solve all of the
constraints. Solving equality constraints is easy, we just try to unify
them which will give a substitution map of type variable ID to type. We
need to put a constraint through that substitution map before trying to
solve it, so that we know we have the latest information about its type
variables.</p>
<pre><code>solveConstraints :: [Constraint] -&gt; Maybe (M.Map Int Type)
solveConstraints =
    foldl (\b a -&gt; liftM2 mappend (solve b a) b) $ Just M.empty
          where solve maybeSubs (EqualityConstraint a b) = do
                  subs &lt;- maybeSubs
                  mostGeneralUnifier (substitute subs a) (substitute subs b)</code></pre>
<p>So given two types, we need to be able to get a map of substitutions if
the types unify.</p>
<pre><code>mostGeneralUnifier :: Type -&gt; Type -&gt; Maybe (M.Map Int Type)</code></pre>
<p>If one side is a type variable, then we map that type variable ID to the
type on the other side.</p>
<pre><code>mostGeneralUnifier (TVar i) b = Just $ M.singleton i b
mostGeneralUnifier a (TVar i) = Just $ M.singleton i a</code></pre>
<p>When both sides are obviously the same, they can unify with just an
empty substitution map.</p>
<pre><code>mostGeneralUnifier TNumber TNumber = Just M.empty
mostGeneralUnifier TString TString = Just M.empty</code></pre>
<p>Lambdas must unify their bound variables and then their bodies. They
must also substitute type variables as soon as they have information
about them.</p>
<pre><code>mostGeneralUnifier (TLambda a b) (TLambda c d) = do
    s1 &lt;- mostGeneralUnifier a c
    liftM2 mappend (mostGeneralUnifier (substitute s1 b) (substitute s1 d)) $ Just s1</code></pre>
<p>If none of the above cases apply then the types can’t be the same and
therefore don’t unify.</p>
<pre><code>mostGeneralUnifier _ _ = Nothing</code></pre>
<p>The type substitution using a substitution map is very simple. Type
variables don’t get substituted if they don’t exist in the substitution
map.</p>
<pre><code>substitute :: M.Map Int Type -&gt; Type -&gt; Type
substitute subs v@(TVar i) = maybe v (substitute subs) $ M.lookup i subs
substitute subs (TLambda a b) = TLambda (substitute subs a) (substitute subs b)
substitute _ t = t</code></pre>
<p>Now we can put it all together. We attribute the tree to get a type and
its constraints. We then solve those constraints to get a substitution
map. Finally, we can map over each AST node, discarding the constraints
and applying the substitution map to get a final type.</p>
<pre><code>typeTree :: Cofree AST () -&gt; Maybe (Cofree AST Type)
typeTree c =
    let result = attribute c
        (r :&lt; _) = result
        maybeSubs = solveConstraints . constraints $ snd r
    in fmap (\subs -&gt; fmap (substitute subs . fst) result) maybeSubs</code></pre>
<p>Now we can go back to the <code>cofreeMu</code> example we wrote above and print:</p>
<ol type="1">
<li>The AST</li>
<li>The AST attributed with constraints, assumptions and unsolved types</li>
<li>The AST with solved types</li>
</ol>
<p>From main:</p>
<pre><code>main :: IO ()
main = do
  print $ cofreeMu example
  print . attribute $ cofreeMu example
  print . typeTree $ cofreeMu example</code></pre>
<p>The last is the most interesting:</p>
<pre><code>Just
  (TNumber :&lt; AApply
    (TLambda TNumber TNumber :&lt; ALambda &quot;x&quot;
      (TNumber :&lt; AIdent &quot;x&quot;))
    (TNumber :&lt; ANumber 2))</code></pre>
<p>Awesome. Does exactly what we want. It seems like the type system allows
easy extension. We could even add extra comonadic operations for
different phases of the compiler, like annotating nodes with type-class
dictionaries.</p>
<p>But I can think of two problems with this comonadic approach:</p>
<ol type="1">
<li><p>We have to explicitly sequence comonadic phases. It’d be better if
we could annotate the AST with a semigroup and then append different
phases in parallel but then we’d probably lose type-safety when
trying to retrieve an attribute.</p></li>
<li><p>The memoisation is annoying and seems to reflect the way we’re
traversing using a comonad. But then, doing it without Cofree seems
even more annoying.</p></li>
</ol>
<p>Anyway, time to translate the
<a href="https://github.com/puffnfresh/fantasy-states">above</a>
<a href="https://github.com/puffnfresh/fantasy-cofrees">to</a>
<a href="https://github.com/puffnfresh/fantasy-land">JavaScript</a>…</p>]]></summary>
</entry>
<entry>
    <title>Row Polymorphism Isn't Subtyping</title>
    <link href="https://brianmckenna.org/blog/row_polymorphism_isnt_subtyping" />
    <id>https://brianmckenna.org/blog/row_polymorphism_isnt_subtyping</id>
    <published>2013-05-05T00:00:00Z</published>
    <updated>2013-05-05T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve been working on Roy’s new type system which uses a concept called
<em>row variables</em>. I’ve also been thinking about TypeScript’s
<a href="https://gist.github.com/toyvo/4449351">unsound variance issues</a> with
its implementation of structural subtyping. That lead to an
<a href="https://twitter.com/dyokomizo/status/330096592378003457">interesting discussion</a>
on Twitter about row polymorphism compared to structural subtyping.</p>
<p>Both are trying to type code like the following:</p>
<pre><code>let f x = x.a + x.b
f {a: 1, b: 2, c: 100}</code></pre>
<p>Also known as static duck typing.</p>
<p>Structural subtyping of course uses <em>subtyping</em> to achieve the
above. Subtyping involves the rule of subsumption:</p>
<p><img src="http://brianmckenna.org/blog/static/tsub.png" /></p>
<p>In English: if we have a term <code>t</code> in our environment of type <code>T1</code> and
<code>T1</code> is a subtype of <code>T2</code>, then that term also has type <code>T2</code>.</p>
<p>In structural subtyping, a wider record type is <em>subsumed</em> by a
narrower one. Due to contravariance of function inputs, we can supply
any subsumed record to <code>f</code>:</p>
<pre><code>f :: {a: Number, b: Number} -&gt; Number</code></pre>
<p>Row polymorphism instead achieves the original code is by allowing
records to have a special polymorphic variable:</p>
<p><img src="http://brianmckenna.org/blog/static/row.png" /></p>
<p>The rho (ρ) represents a variable which can be instantiated to extra
fields. That means the type of <code>f</code> is:</p>
<pre><code>f :: {a: Number, b: Number | ρ} -&gt; Number</code></pre>
<p>And when we apply <code>f</code>, <code>ρ</code> is <em>instantiated</em> to contain the extra
field, <code>c: Number</code>.</p>
<p>So now to answer the question, is row polymorphism a form of
subtyping? No, because of the <em>instantiation</em> of the row variable, we
can’t derive the rule of subsumption. It would need a separate
instantiation step defined and that means there is no subtyping
relationship.</p>
<p>Here’s a simple example of where the row instantiation can cause
differences:</p>
<pre><code>let f x = x with {sum: x.a + x.b}
let answer = f {a: 1, b: 2, c: 100}</code></pre>
<p>With structural subtyping, the type is upcast to what <code>f</code> needs and
we get back:</p>
<pre><code>answer :: {a: Number, b: Number, sum: Number}</code></pre>
<p>But with row polymorphism, the row variable <code>ρ</code> gets <em>instantiated</em> to
contain the <code>c</code> field:</p>
<pre><code>answer :: {a: Number, b: Number, c: Number, sum: Number}</code></pre>
<p>Great. Row polymorphism isn’t subtyping. Who cares? Well, subtyping
and type inference just don’t mix. Doing type inference with row
polymorphic records is much easier. There’s still undecidability
problems but if you’re writing a language with type inference and want
records, you should take a look at row variables.</p>]]></summary>
</entry>
<entry>
    <title>Read-only Guest tmux Sessions</title>
    <link href="https://brianmckenna.org/blog/guest_tmux" />
    <id>https://brianmckenna.org/blog/guest_tmux</id>
    <published>2013-04-29T00:00:00Z</published>
    <updated>2013-04-29T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>For a while now, I’ve wanted a way for people to watch how I work and
let me know how I could improve both my techniques and my code. I
mostly work in Emacs so being inside of a terminal works fine.</p>
<p>At <a href="http://precog.com/">Precog</a> we use tmux for pairing sessions. It
works really great but I wanted to make it read-only for guests.</p>
<p>I created a <code>guest</code> user on the VPS that brianmckenna.org is now
hosted on. The guest user is chrooted to <code>/srv/chroot/guest</code> via the
SSH config:</p>
<pre><code>Match User guest
    ForceCommand nologin
    ChrootDirectory /srv/chroot/guest
    X11Forwarding no
    AllowTcpForwarding no</code></pre>
<p>The chroot has hardlinks back to system binaries (symlinks can’t get
out of the jail). I had to hardlink <code>/bin/bash</code>, its libraries (found
via <code>ldd</code>) and my custom tmux (more on that below).</p>
<p>The guest user’s shell points to <code>/usr/bin/login</code>:</p>
<pre><code>guest:x:1001:1001::/home/guest:/usr/bin/login</code></pre>
<p>Which contains:</p>
<pre><code>#!/bin/bash
exec /usr/local/bin/tmux -S /var/lib/tmux-sessions/guest attach -r</code></pre>
<p>The <code>/var/lib/tmux-sessions</code> directory has group write/execute
permission for admin, so that my account can create the socket. I then
have to run a script to allow guest to have write permission:</p>
<pre><code>#!/bin/sh
exec chmod o+w /srv/chroot/guest/var/lib/tmux-sessions/guest</code></pre>
<p>Sadly, I have to run that script each time I recreate the session -
tmux loves to reset the permissions.</p>
<p>One thing about tmux is that read-only users can still resize the
window for everyone. I had to patch tmux to disable that:</p>
<pre><code>diff --git a/resize.c b/resize.c
index 5c365df..dab4508 100644
--- a/resize.c
+++ b/resize.c
@@ -58,7 +58,7 @@ recalculate_sizes(void)
        ssx = ssy = UINT_MAX;
        for (j = 0; j &lt; ARRAY_LENGTH(&amp;clients); j++) {
            c = ARRAY_ITEM(&amp;clients, j);
-			if (c == NULL || c-&gt;flags &amp; CLIENT_SUSPENDED)
+			if (c == NULL || c-&gt;flags &amp; (CLIENT_SUSPENDED | CLIENT_READONLY))
                continue;
            if (c-&gt;session == s) {
                if (c-&gt;tty.sx &lt; ssx)</code></pre>
<p>If a guest’s window is too small, the stdout stream will write over
itself when things change. Largely things looks fine but every now and
then things can look a bit strange.</p>
<p>I also had to change <code>/etc/ssh/sshd_config</code> to accept empty passwords:</p>
<pre><code>PermitEmptyPasswords yes</code></pre>
<p>And then PAM for SSH in <code>/etc/pam.d/sshd</code>:</p>
<pre><code>auth	[success=1 default=ignore]	pam_unix.so nullok</code></pre>
<p>So now users can run <code>ssh guest@brianmckenna.org</code> and have a read-only
view of my guest tmux session, if I have it running. I’m hoping to be
able to work on quite a few of my projects and let people spy on me.</p>
<p>If you have any security concerns, please send me an email at
<a href="mailto:brian@brianmckenna.org" class="email">brian@brianmckenna.org</a>.</p>]]></summary>
</entry>
<entry>
    <title>Category Theory for Promises/A+</title>
    <link href="https://brianmckenna.org/blog/category_theory_promisesaplus" />
    <id>https://brianmckenna.org/blog/category_theory_promisesaplus</id>
    <published>2013-04-09T00:00:00Z</published>
    <updated>2013-04-09T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Promises are
<a href="http://blog.jcoglan.com/2013/03/30/callbacks-are-imperative-promises-are-functional-nodes-biggest-missed-opportunity/">being debated</a>
in the JavaScript community. The most popular specification is
<a href="http://promises-aplus.github.io/promises-spec/">Promises/A+</a>. It’s a
fairly small specification, containing only a single function: <code>then</code>.</p>
<p>The function is heavily overloaded which makes it quite complicated -
way more than it has to be. I’ll try to show how category theory can
give us a much simpler, more generalised and lawful API!</p>
<p>A proper Promise/A+ implementation must provide a <code>then</code> method which
always returns a promise. The <code>then</code> method takes two arguments:</p>
<pre><code>Promise.prototype.then = function(onFulfilled, onRejected) {
    // ...
};</code></pre>
<p>The <code>onFulfilled</code> and <code>onRejected</code> callbacks can return a promise or
some other value. Both of the callbacks are optional - so let’s only
focus on the <code>onFulfilled</code> callback for now. If we tried to extract
some type signatures it would like something like so:</p>
<pre><code>// then :: Promise a -&gt; (a -&gt; Promise b) -&gt; Promise b
// then :: Promise a -&gt; (a -&gt; b) -&gt; Promise b</code></pre>
<p>Where the top signature is tested for and the bottom is a
fallback. Functional programmers might notice those two
type-signatures. They come up all the time in Scala and Haskell:</p>
<pre><code>// flatMap :: m a -&gt; (a -&gt; m b) -&gt; m b
// map :: m a -&gt; (a -&gt; b) -&gt; m b</code></pre>
<p>So <code>then</code> is an overloaded <code>flatMap</code>, which falls back to <code>map</code> if the
function passed in doesn’t return a promise. Now time for some
category theory.</p>
<h3 id="category-theory">Category Theory</h3>
<p>The <code>flatMap</code> function is part of being a Monad. The other part is a
function with multiple names:</p>
<ul>
<li>point</li>
<li>pure</li>
<li>return</li>
</ul>
<p>They all mean the same thing, taking a value and putting it into the
monadic context. Putting it together, here’s the monad class:</p>
<pre><code>class Monad m where
    flatMap :: m a -&gt; (a -&gt; m b) -&gt; m b
    point :: a -&gt; m a</code></pre>
<p>So does Promises/A+ define a monad? All we’d need is a way to take a
value and put it inside of a (fulfilled) promise. Sadly, the spec
states:</p>
<blockquote>
<p>As with Promises/A, this proposal does not deal with how to create,
fulfill, or reject promises.</p>
</blockquote>
<p>But what’s interesting is that the proposal defines what is a promise:</p>
<blockquote>
<p>“promise” is an object or function with a then method whose behavior
conforms to this specification.</p>
</blockquote>
<p>The specification doesn’t define a way of creating a promise - but it
<em>does</em> define what a promise looks like. That means we can define our
own <code>point</code> function which should hopefully work with other promise libraries:</p>
<pre><code>function point(a) {
    return {
        value: a,
        then: function(onFulfilled) {
            var promise = this;
            setTimeout(function() { promise.value = onFulfilled(promise.value).value; }, 0);
            return promise;
        }
    };
}</code></pre>
<p>(<strong>Update:</strong> original <code>point</code> implementation was completely wrong. I
<em>think</em> the above conforms to part of the spec. It’d need some more
details to work when passed to other libraries)</p>
<p>Let’s also make a function for treating <code>then</code> like <code>flatMap</code> (i.e. no
second argument):</p>
<pre><code>function flatMap(p, f) {
    return p.then(f);
}</code></pre>
<p>So, we’ve made a promise monad. What does that mean? Before I explain
why that’s useful, let me talk about the <code>map</code> function above.</p>
<p>If the function we give to <code>then</code> as <code>onFulfilled</code> <em>doesn’t</em> return a
promise, then it creates a new promise after applying the function. If
it didn’t have the special case for promises, then it’d be functor:</p>
<pre><code>class Functor f where
    map :: f a -&gt; (a -&gt; b) -&gt; f b</code></pre>
<p>What’s impressive is that we can <em>derive</em> a functor using just the
<code>point</code> and <code>flatMap</code> that we defined above!</p>
<pre><code>function map(p, f) {
    return flatMap(p, function(a) {
        return point(f(a));
    });
}</code></pre>
<p>The trick is that <code>point</code> will even make a promise out of a promise!</p>
<p>So monads are useful for defining functors, what else are they good
for? Let’s imagine a promise library gave us a nested promise (a
promise within a promise). We can write a function to flatten it:</p>
<pre><code>function identity(a) {
    return a;
}

function join(p) {
    return flatMap(p, identity);
}</code></pre>
<p>The above will work for <em>any monad</em>. List of lists? Optional optional
value? If the JavaScript community settled on using <code>flatMap</code> as a
method, we could write DRY, generalised code for monads.</p>
<p>Above I showed how we can get a functor from any monad. We can do one
better; all monads form <em>applicative</em> functors:</p>
<pre><code>class (Functor f) =&gt; Applicative f where
    point :: a -&gt; m a
    ap :: m a -&gt; m (a -&gt; b) -&gt; m b</code></pre>
<p>Here’s how to derive the <code>ap</code> function:</p>
<pre><code>function ap(p, pf) {
    return flatMap(pf, function(f) {
        return map(p, f);
    });
}</code></pre>
<p>Applicatives have some really useful functions:</p>
<pre><code>// liftA2 :: f a -&gt; f b -&gt; (a -&gt; b -&gt; c) -&gt; f c
function liftA2(pa, pb, f) {
    return ap(pb, map(pa, function(a) {
        return function(b) {
            return f(a, b);
        };
    }));
}</code></pre>
<p>This is very useful for promises. It allows use to run multiple
promises and run a function when they’re all finished:</p>
<pre><code>liftA2(readFile(&#39;hello.txt&#39;), readFile(&#39;world.txt&#39;), function(hello, world) {
    console.log(hello + &#39; &#39; + world);
});</code></pre>
<p>Lots of promises libraries write special functions to achieve the
above magic. But again, we can be more DRY because this stuff works
for all applicatives!</p>
<p>We could even combine the above with
<a href="http://brianmckenna.org/blog/applicative_validation_js">operator overloading</a>
for a nice DSL.</p>
<h3 id="recommendations">Recommendations</h3>
<p>We’ve only been focusing on the <code>onFulfilled</code> case - we left out the
<code>onRejected</code> case. What should we do with that?</p>
<p>I think that should just be an additional method on promises - not on
an overloaded <code>flatMap</code>:</p>
<pre><code>Promise.prototype.onRejected = function(callback) {
    // ...
};</code></pre>
<p>(<a href="http://www.scala-lang.org/api/current/index.html#scala.concurrent.Future">Scala provides an <code>onFailure</code> method</a>
to do the same thing)</p>
<p>It seems like the JavaScript community has settled on <code>then</code> as being
the name for <code>flatMap</code> (that’s fine, in Haskell it’s called <code>bind</code> or
<code>&gt;&gt;=</code>). I think <code>then</code> should only take the <code>onFulfilled</code> function and
it should have <em>unspecified</em> behaviour if the function doesn’t return a
promise (for simplicity; map can be derived).</p>
<p>I also think the specification should define a way of creating
promises. It’s only a few lines to create a compatible promise but I
don’t think that should be up to the library’s users.</p>
<p>And lastly, it would be nice to have a <code>done</code> method which forked the
promise. That would allow the API to be <em>purely</em> functional. No
effects would happen until <code>done</code> was called. Turning side-effects
into an effect. Sadly, I think the JavaScript community would not
appreciate this approach.</p>
<p>So we should have something which looks like this:</p>
<pre><code>Promise.point = function(a) {
    // ...
};
Promise.prototype.then = function(onFulfilled) {
    // ...
};
Promise.prototype.onRejected = function(callback) {
    // ...
};
// Possibly
Promise.prototype.done = function() {
    // ...
};</code></pre>
<p>Just having the two functions of the monad interface allows us to
<em>derive</em> functions to map over the promise, flatten a promise, run a
function when promises are finished and much more. These functions
will also work with other monads or applicative functors if we rely on
<code>point</code> and <code>then</code> as an API for different structures.</p>
<h3 id="summary">Summary</h3>
<p>Recognising that promises are monadic gives us an API which allows us
to derive lots of useful functions. These functions are based off of
category theory which also means that they work with not just promises
- allowing the API to be consistent and DRY for many structures.</p>
<p>I think we should apply that knowledge directly to a promises
specification. An implementation would only require three <em>very</em>
simple functions:</p>
<ul>
<li>point(a)</li>
<li>then(f)</li>
<li>onRejected(f)</li>
</ul>
<p>No surprising overloaded behaviour or optional arguments. It would be
compatible with some existing libraries.</p>
<p>I believe that the JavaScript community needs to act quickly to
achieve a more consistent and simple API before promises become
solidified. The time is now!</p>]]></summary>
</entry>
<entry>
    <title>Applicative Validation in JavaScript</title>
    <link href="https://brianmckenna.org/blog/applicative_validation_js" />
    <id>https://brianmckenna.org/blog/applicative_validation_js</id>
    <published>2013-03-27T00:00:00Z</published>
    <updated>2013-03-27T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Validation is known as scalaz’ gateway drug. Validation has the
following two states:</p>
<ul>
<li>Successful value</li>
<li>Failure with a Semigroup of errors</li>
</ul>
<p>Semigroup sounds scary but it’s something that can be appended
together. Think of a list, array or set. This allows multiple failures
to be combined, where the errors are appended together.</p>
<p>People love validation in scalaz because it allows nice, declarative
code like the following:</p>
<pre><code>case class Person(name: String, age: Int, postcode: String)

postcode &lt;*&gt; (age &lt;*&gt; (name map Person.curried))</code></pre>
<p>What if we could write JavaScript like the following?</p>
<pre><code>var Person = _.tagged(&#39;Person&#39;, [&#39;name&#39;, &#39;age&#39;, &#39;postcode&#39;]);

_.Do()(
    _.Do()(name &lt; _.curry(Person)) * age * postcode
);</code></pre>
<p>Now you can, with <a href="http://bilby.brianmckenna.org/">bilby.js</a>:</p>
<p><a href="http://bilby.brianmckenna.org/examples/validation.htm"><img src="http://brianmckenna.org/blog/static/applicative-validation-small.png" /></a></p>
<p>Here is
<a href="http://bilby.brianmckenna.org/examples/validation.htm">an online demo</a>. Continue
reading for details about the implementation.</p>
<h3 id="apply">Apply</h3>
<p>The <code>&lt;*&gt;</code> syntax in scalaz is adapted from Haskell’s Applicative
class. Haskell’s class is missing a little abstraction so scalaz
introduces a hierarchy like so:</p>
<ul>
<li>Functor (map)</li>
<li>Apply (ap)</li>
<li>Applicative (pure)</li>
</ul>
<p>bilby.js contains both Functor and Apply for Validation. Functor means
that Validations can be mapped over:</p>
<pre><code>_.map(
    _.success(1),
    function(x) {
        return x + 1;
    }
);
// Validation.success(2)</code></pre>
<p>A failure value won’t be mapped over - it will just be returned. Easy.</p>
<p>Apply means we can run functions from inside of the Validation:</p>
<pre><code>_.ap(
    _.success(
        function(x) {
            return x + 1;
        }
    ),
    _.success(1)
);
// Validation.success(2)</code></pre>
<p>The above use of <code>ap</code> might just look like a different way of writing
<code>map</code> but look at what happens when there are errors involved:</p>
<pre><code>_.ap(
    _.failure([&#39;Name must not be empty&#39;]),
    _.success(1)
);
// Validation.failure([&#39;Name must not be empty&#39;])

_.ap(
    _.failure([&#39;Name must not be empty&#39;]),
    _.failure([&#39;Age must be at least 1&#39;])
);
// Validation.failure([&#39;Name must not be empty&#39;, &#39;Age must be at least 1&#39;])</code></pre>
<p>So all involved errors are accumulated into a single failure.</p>
<h3 id="syntax">Syntax</h3>
<p>Sounds good but how do we overload the <code>&lt;</code> and <code>*</code> operators in
JavaScript!?</p>
<p>With a nice hack of a little known JavaScript feature, of course. What
happens when we write code like this?</p>
<pre><code>{} + {}</code></pre>
<p>JavaScript engines actually lookup a <code>valueOf</code> property on each of the
objects. It allows things like this:</p>
<pre><code>var ten = {valueOf: function() { return 10; }};
var two = {valueOf: function() { return 2; }};
ten + two == 12;</code></pre>
<p>Notice that the <code>valueOf</code> is just an arbitrary function that returns a
primitive value? We could also use it to perform a side-effect…</p>
<p>When <code>Do()</code> is called, a global stack is allocated:</p>
<pre><code>doQueue = [];</code></pre>
<p>Then an operator is used in the following expression. For example:</p>
<pre><code>_.Do()([1, 2, 3] + [4, 5, 6] + [7, 8, 9]);</code></pre>
<p>On each of the objects, <code>valueOf</code> is called and <code>this</code> is pushed onto the stack:</p>
<pre><code>doQueue.push(this);</code></pre>
<p>So we have a clean stack of all the operands. We can perform a
function on that stack and return a value! But how do we know what to
return from <code>valueOf</code> or which operator was used?</p>
<p>The value returned from <code>valueOf</code> can actually <em>tell us</em> which
operator was used. In bilby.js, 1 is always returned from the special
<code>valueOf</code>. We can then use the following logic to figure out the
operator:</p>
<pre><code>if(n === true) op = &#39;flatMap&#39;; // &gt;=
if(n === false) op = &#39;map&#39;; // &lt;
if(n === 0) op = &#39;kleisli&#39;; // &gt;&gt;
if(n === 1) op = &#39;ap&#39;; // *
if(n === doQueue.length) op = &#39;append&#39;; // +</code></pre>
<p>Stepping through the above example:</p>
<pre><code>Do() // doQueue = []

[1, 2, 3].valueOf() // doQueue.push([1, 2, 3]), 1
[4, 5, 6].valueOf() // doQueue.push([4, 5, 6]), 1
[7, 8, 9].valueOf() // doQueue.push([7, 8, 9]), 1
1 + 1 + 1 // 3

// 3 is doQueue.length; &#39;+&#39; must be the operator.

return [1, 2, 3].append([4, 5, 6]).append([7, 8, 9]);</code></pre>
<p>Almost magical…</p>
<p>Now put it all together and the following plain JavaScript:</p>
<pre><code>_.Do()(
    _.Do()(name &lt; _.curry(Person)) * age * postcode
);</code></pre>
<p>Desugars to this:</p>
<pre><code>_.ap(_.ap(_.map(name, f), age), postcode);</code></pre>
<h3 id="summary">Summary</h3>
<p>We can apply category theory to derive a readable, declarative
validation API in JavaScript. The theory is based around Functors,
Applicatives and Semigroups. A total of about 3 abstract functions.</p>
<p>We can (ab)use JavaScript’s magical <code>valueOf</code> property to achieve
operator overloading and provide an even more declarative syntax.</p>
<p>If you’d like to like to find out more about validation in bilby.js,
please
<a href="http://bilby.brianmckenna.org/#validation">read the documentation</a>. If
you want to find out more about the implementation, head to
<a href="https://github.com/pufuwozu/bilby.js">bilby.js’ GitHub repository</a>.</p>]]></summary>
</entry>
<entry>
    <title>Haskell Buildpack for Heroku</title>
    <link href="https://brianmckenna.org/blog/haskell_buildpack_heroku" />
    <id>https://brianmckenna.org/blog/haskell_buildpack_heroku</id>
    <published>2012-11-07T00:00:00Z</published>
    <updated>2012-11-07T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Last night I took <a href="https://twitter.com/luciferous">Neuman Vong’s</a> and
<a href="https://twitter.com/mwotton">Mark Wotton’s</a> Haskell Buildpack for
Heroku and got it working!</p>
<p><a href="http://haskell-buildpack-demo.herokuapp.com/"><img src="http://brianmckenna.org/blog/static/heroku-buildpack-2.png" /></a></p>
<p>I’ve been able to deploy a <a href="https://github.com/pufuwozu/haskell-buildpack-demo">simple Warp
example</a> and a
in-development Yesod application. The steps are quite easy:</p>
<pre><code>yesod init
cd yesod-buildpack-demo
mv deploy/Procfile .
git add -A
git commit -m &quot;Initial commit&quot;
heroku apps:create yesod-buildpack-demo --stack cedar --buildpack https://github.com/pufuwozu/heroku-buildpack-haskell.git
git push heroku master</code></pre>
<p>The push will take quite a while for the first time, while it
downloads packages. Packages are cached for the next push.</p>
<p>After it’s finished, the default Yesod application on Heroku:</p>
<p><a href="http://yesod-buildpack-demo.herokuapp.com/"><img src="http://brianmckenna.org/blog/static/heroku-buildpack-1.png" /></a></p>
<p>No compilation locally! How awesome is that!?</p>
<p>Turns out this could have worked 5 months ago if it wasn’t for this bug:</p>
<pre><code>$BUILD_DIR = $1</code></pre>
<p>Notice the typo? An extra <code>$</code>. Heroku doesn’t report errors from the
<code>bin/release</code> script in a Buildpack so Mark had no idea what was going
wrong. I only found out by running the Buildpack locally with
<a href="https://github.com/ddollar/mason">Mason</a>.</p>
<p>Anyway, give the Buildpack a try and let me know what you think:</p>
<p><a href="https://github.com/pufuwozu/heroku-buildpack-haskell">https://github.com/pufuwozu/heroku-buildpack-haskell</a></p>]]></summary>
</entry>
<entry>
    <title>bilby.js - QuickCheck</title>
    <link href="https://brianmckenna.org/blog/bilby_quickcheck" />
    <id>https://brianmckenna.org/blog/bilby_quickcheck</id>
    <published>2012-09-16T00:00:00Z</published>
    <updated>2012-09-16T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve added a <a href="http://www.haskell.org/haskellwiki/Introduction_to_QuickCheck">QuickCheck</a> implementation to <a href="https://github.com/pufuwozu/bilby.js">bilby.js</a>. The existing JavaScript implementations:</p>
<ul>
<li>Make it hard to create generators</li>
<li>Require a specific test runner</li>
</ul>
<p>bilby’s implementation fixes both problems.</p>
<p>You can register generators using the multimethod environment:</p>
<pre><code>λ = require(&#39;bilby&#39;)
    .method(&#39;arb&#39;, strictEquals(Boolean), function(a, s) {
        return Math.random() &lt; 0.5;
    })
    .method(&#39;shrink&#39;, isBoolean, function() {
        return b ? [False] : [];
    });</code></pre>
<p>Now, <code>λ.forAll</code> can be called with what property and argument types should be tested:</p>
<pre><code>console.log(λ.forAll(
    function(a) {
        return (a &amp;&amp; a) == a;
    },
    [Boolean]
).fold(
    &quot;OK&quot;,
    function(inputs, tries) {
        return &quot;Failed after &quot; + tries + &quot; tries: &quot; + inputs.toString();
    }
));</code></pre>
<p>The reporting API is really simple so it’s easy to mix this with the normal test runners, like I have with <a href="https://github.com/pufuwozu/bilby.js/blob/master/test/lib/test.js">nodeunit</a>.</p>]]></summary>
</entry>
<entry>
    <title>Introducing bilby.js</title>
    <link href="https://brianmckenna.org/blog/bilby" />
    <id>https://brianmckenna.org/blog/bilby</id>
    <published>2012-09-09T00:00:00Z</published>
    <updated>2012-09-09T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>While working on <a href="https://github.com/pufuwozu/roy">Roy</a>, I’ve been
coming up with some ideas and experiments on how to improve JavaScript
code.</p>
<p>The most important is a safer form of ad-hoc polymorphism. Currently,
JavaScript devs rely on duck typing and monkey patching to achieve
polymorphism. My idea is to use an immutable multimethod environment, like so:</p>
<pre><code>var env = λ.environment()
    .method(&#39;length&#39;, λ.isArray, function(a) {
        return a.length;
    })
    .method(&#39;length&#39;, λ.isString, function(s) {
        return s.length;
    })
    .property(&#39;empty&#39;, function(o) {
        return !this.length(o);
    });

env.empty([]) == true;
env.empty([1, 2, 3]) == false;</code></pre>
<p>Extending the environment is easy. We can supply a function to be
dispatched based on a predicate function (e.g. λ.isArray) or just a
property on the environment object.</p>
<p>Another idea is to encode Option and Either types; and add
implementations for common functional patterns like applicatives,
functors, semigroups and monads. I’ve found this to be very useful
while implementing the new Roy type system.</p>
<p>And I’ve been experimenting with some crazy operator overloading
hacks. I’ve managed to implement a notation that looks like this:</p>
<pre><code>// Monad:
λ.Do()(
    λ.some(1) &gt;= function(x) {
        return x &lt; 0 ? λ.none : λ.some(x + 2);
    }
).getOrElse(0) == 3;

// Semigroups:    
λ.Do()(
    λ.some(1) + λ.some(2)
).getOrElse(0) == 3;</code></pre>
<p>I didn’t think it’d be possible but actually turns out to be quite a
nice way to write complicated expressions. It’s a complete hack
underneath but I don’t think it has shown through too much.</p>
<p>Anyway, as of today I’ve collected all of these ideas into a new
library, <a href="https://github.com/pufuwozu/bilby.js">bilby.js</a>. Try it out
and let me know what you think.</p>
<p><img src="http://brianmckenna.org/files/bilby.png" /></p>]]></summary>
</entry>
<entry>
    <title>Roy - Constraint Typing</title>
    <link href="https://brianmckenna.org/blog/roy_constraint_typing" />
    <id>https://brianmckenna.org/blog/roy_constraint_typing</id>
    <published>2012-09-02T00:00:00Z</published>
    <updated>2012-09-02T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week I’ve been working on the new constraint-based type-system
for <a href="http://roy.brianmckenna.org/">Roy</a>. I’ve been working on it for a
few months but got a bit stuck recently with typing algebraic data
type definitions. I think I properly implemented that and I’m up to
pattern matching.</p>
<p>I’m basing the work off <a href="http://igitur-archive.library.uu.nl/math/2007-1122-200535/heeren_02_generalizinghindleymilner.pdf">Generalizing Hindley-Milner Type Inference
Algorithms</a>
(PDF) - a way of achieving Hindley-Milner via constraints; rather than
the environment in Algorithm W. The big benefit is that it delegates
unification until the end of constraint generation. My understanding
is that this will help with structural typing since I’ll be able to
generate proper subtype constraints - instead of the hacky, buggy
stuff I’ve done until now.</p>
<p>I’m probably a while away from finishing the core of the type-system
but then I can move onto Rank-2 types, hopefully allowing me to
implement Tony Morris’
<a href="https://github.com/tonymorris/lens-proposal">lens-proposal</a> work -
allowing automatic lens generation from Roy types!</p>]]></summary>
</entry>
<entry>
    <title>GLL Combinators - Whitespace Fix</title>
    <link href="https://brianmckenna.org/blog/gll_combinators_whitespace" />
    <id>https://brianmckenna.org/blog/gll_combinators_whitespace</id>
    <published>2012-08-26T00:00:00Z</published>
    <updated>2012-08-26T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This has been my second week at <a href="http://precog.com/">Precog</a>. During
my first week I wrote a
<a href="https://github.com/djspiewak/gll-combinators/commit/f996645096">patch</a>
for the gll-combinators project to fix a whitespace handling issue.</p>
<p>The issue occurred when using the <code>^#</code> (<code>mapWithTail</code>) combinator,
which passes column and line information to a function:</p>
<pre><code>case class A(loc: LineStream, x: String)
literal(&quot;daniel&quot;) ^# { (loc, x) =&gt; A(loc, x) }</code></pre>
<p>The symptom was that the <code>RegexParser</code> class wouldn’t strip
whitespace from the beginning of the location. So an input with
prefix whitespace like:</p>
<pre><code>    daniel</code></pre>
<p>Would be turned into:</p>
<pre><code>A(&quot;    daniel&quot;, 0, 0)</code></pre>
<p>But it should have been:</p>
<pre><code>A(&quot;daniel&quot;, 0, 4)</code></pre>
<p>I just refactored whitespace handling out of <code>RegexParser</code> and into
the generic <code>Parser</code> class. Merged into master this week.</p>
<p>Pretty trivial fix but it feels good to be able to work on an
open-source parser combinator library!</p>]]></summary>
</entry>
<entry>
    <title>Dripper git support</title>
    <link href="https://brianmckenna.org/blog/dripper_git" />
    <id>https://brianmckenna.org/blog/dripper_git</id>
    <published>2012-08-19T00:00:00Z</published>
    <updated>2012-08-19T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week had my first few days at <a href="http://precog.com/">Precog</a>. It’s
been awesome contributing to the <a href="http://quirrel-lang.org/">Quirrel
language</a> and working with insanely smart
people.</p>
<p>Last night I found out about a project called
<a href="https://github.com/fesplugas/dripper">Dripper</a>. It’s basically a
wrapper around <a href="http://www.gnu.org/software/stow/">stow</a> which makes
it easy to compile and link applications with predefined
scripts. Think of it as a Homebrew-like interface to stow.</p>
<p>I’ve always wanted to be able to take a git repository or a tarball
and automatically run <code>./configure --prefix=/usr/local/stow/$PACKAGE &amp;&amp; make &amp;&amp; make install</code> to get a safely installed package. Today I
made Dripper capable of doing that for git remotes.</p>
<p>Check <a href="https://github.com/pufuwozu/dripper">my fork</a>. Hopefully I’ll
be able to do the same for <code>.tar.gz</code> URLs soon. I’d also like to
abstract it to be able to have a list of “generic” make scripts so it
can detect things like CMake or gyp and do the right thing.</p>]]></summary>
</entry>
<entry>
    <title>ScalaSyd - Monad Transformers</title>
    <link href="https://brianmckenna.org/blog/scalasyd_monad_transformers" />
    <id>https://brianmckenna.org/blog/scalasyd_monad_transformers</id>
    <published>2012-08-12T00:00:00Z</published>
    <updated>2012-08-12T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>On Wednesday I gave a talk at ScalaSyd about monad transformers. I
tried to make it fairly introductory which is a bit tricky to
do. There’s a <a href="http://www.youtube.com/watch?v=S_l95GIDCM0">much better talk on the
subject</a> by Jordan West.</p>
<p>I’ve posted my slides up <a href="http://brianmckenna.org/files/presentations/monad-trans-scalasyd/">here</a>.</p>
<p><a href="http://brianmckenna.org/files/presentations/monad-trans-scalasyd/"><img src="http://brianmckenna.org/blog/static/monadtrans1.png" /></a></p>
<p><a href="http://brianmckenna.org/files/presentations/monad-trans-scalasyd/"><img src="http://brianmckenna.org/blog/static/monadtrans2.png" /></a></p>
<p><a href="http://brianmckenna.org/files/presentations/monad-trans-scalasyd/"><img src="http://brianmckenna.org/blog/static/monadtrans3.png" /></a></p>
<p><a href="http://brianmckenna.org/files/presentations/monad-trans-scalasyd/"><img src="http://brianmckenna.org/blog/static/monadtrans4.png" /></a></p>
<p><a href="http://brianmckenna.org/files/presentations/monad-trans-scalasyd/"><img src="http://brianmckenna.org/blog/static/monadtrans5.png" /></a></p>
<p>Some crazy news is coming up in the next few days.</p>]]></summary>
</entry>
<entry>
    <title>OSXMonad using StackSet</title>
    <link href="https://brianmckenna.org/blog/osxmonad_stacks" />
    <id>https://brianmckenna.org/blog/osxmonad_stacks</id>
    <published>2012-08-05T00:00:00Z</published>
    <updated>2012-08-05T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week I made OSXMonad use the internal XMonad StackSet data type
to have its windows managed. This means that eventually ordinary
XMonad Layouts will be able to work with OSXMonad. I’m getting close.</p>
<p>I’ve been having some trouble with the XMonad configurations and I’m
not able to run the code via GHCi.</p>]]></summary>
</entry>
<entry>
    <title>OSXMonad as an XMonad library</title>
    <link href="https://brianmckenna.org/blog/osxmonad_library" />
    <id>https://brianmckenna.org/blog/osxmonad_library</id>
    <published>2012-07-29T00:00:00Z</published>
    <updated>2012-07-29T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week I managed to get
<a href="https://bitbucket.org/puffnfresh/osxmonad/">OSXMonad</a> running as an
XMonad library.</p>
<p>That means you can write a <code>~/.xmonad/xmonad.hs</code> file like so:</p>
<pre><code>import XMonad
import OSXMonad.Core

main = osxmonad defaultConfig</code></pre>
<p>And the <code>xmonad</code> command will launch OSXMonad to manage Cocoa windows
using the default XMonad configuration. Hardly any XMonad features
work except some layouts at the moment, but it’s still pretty cool to
see:</p>
<p><img src="http://brianmckenna.org/blog/static/osxmonad_library.png" /></p>
<p>I’ve been working on support for key bindings. Things like this currently work:</p>
<pre><code>main = osxmonad defaultConfig {
         modMask = mod1Mask .|. mod4Mask,
         keys = \(XConfig {XMonad.modMask = modMask}) -&gt; M.fromList [
                 ((modMask, xK_a), io $ putStrLn &quot;Test&quot;)
                ]
       }</code></pre>
<p>Which means that when you press “⌥-⌘-a” then “Test” will be printed to
the command line. It’s a start.</p>
<p>I had to modify the XMonad source. The <code>xmonad</code> command usually calls
out to GHC like so:</p>
<pre><code>ghc --make xmonad.hs -i -ilib -fforce-recomp -v0 -o $binn</code></pre>
<p>But I needed to to be compiled with <code>-framework Cocoa</code> for my Cocoa
calls to be linked correctly. I just hard-coded the change and added a
Darcs patch to the OSXMonad repo. I’ll eventually turn it into a patch
to allow additional GHC flags to be given to the <code>xmonad</code> binary.</p>
<p>I’ve added a
<a href="https://bitbucket.org/puffnfresh/osxmonad/src/master/README.md">README</a>
for anyone interested in getting started.</p>]]></summary>
</entry>
<entry>
    <title>OS X Tiling Window Manager</title>
    <link href="https://brianmckenna.org/blog/osx_tiling_window_manager" />
    <id>https://brianmckenna.org/blog/osx_tiling_window_manager</id>
    <published>2012-07-22T00:00:00Z</published>
    <updated>2012-07-22T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This weekend was
<a href="http://www.haskell.org/pipermail/haskell-cafe/2012-June/101765.html">AusHac</a>. I
worked on an OS X tiling window manager in Haskell.</p>
<p>The idea was to get a prototype “shell” that can tile windows in a way
suitable for <a href="http://xmonad.org/">XMonad</a>. XMonad’s layout algorithms
could then be taken and strapped into the shell. Sadly the
XMonad.Layout module has a few dependencies on X11, so it’s not going
to be as easy as I’d like.</p>
<p>I couldn’t chuck in XMonad’s layout algorithms so I made a very simple
one. It just splits the space horizontally:</p>
<p><img src="http://brianmckenna.org/blog/static/osxmonad1.png" /></p>
<p><img src="http://brianmckenna.org/blog/static/osxmonad2.png" /></p>
<p>Next steps:</p>
<ul>
<li>Get some XMonad layouts working</li>
<li>Don’t use threadDelay, figure out a way to wait for window events</li>
<li>Add hotkeys for changing layouts</li>
<li>Make things configurable like XMonad</li>
</ul>
<p>I’ve tenatively called it osxmonad. You can clone it from
<a href="https://bitbucket.org/puffnfresh/osxmonad">Bitbucket</a> or
<a href="https://github.com/pufuwozu/osxmonad">GitHub</a>. You’ll need OS X 10.6
with Haskell platform 2012.2.0. Then it’s just <code>cabal configure &amp;&amp; cabal install</code>.</p>]]></summary>
</entry>
<entry>
    <title>JavaScript ad hoc single dispatch library</title>
    <link href="https://brianmckenna.org/blog/js_adhoc_single_dispatch" />
    <id>https://brianmckenna.org/blog/js_adhoc_single_dispatch</id>
    <published>2012-07-15T00:00:00Z</published>
    <updated>2012-07-15T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>The idea in ad hoc polymorphism is to separate functions from data,
in contrast to mutating prototypes or the data itself.</p>
<p>We can of course just define a function that uses duck typing but
that’s only if the data quacks the same. It also doesn’t allow open
extension of the function implementation.</p>
<p>Ad hoc polymorphism is very common in functional languages like Lisp
and Haskell.</p>
<p>I wrote a little library for ad hoc polymorphism in JavaScript. It’s
single dispatch, meaning it will only choose which function to execute
based off of the first argument. It’s trivial to extend the code below
to use mutliple dispatch.</p>
<p>Here’s what using the library looks like:</p>
<pre><code>var x = emptyEnvironment
    // Empty
    .addMethod(&#39;empty&#39;)
    .extend(&#39;empty&#39;, isArray, function() {
        return [];
    })
    .extend(&#39;empty&#39;, isString, function() {
        return &#39;&#39;;
    })
    // Append
    .addMethod(&#39;append&#39;)
    .extend(&#39;append&#39;, isArray, function(a) {
        return function(b) {
            return a.concat(b);
        };
    })
    .extend(&#39;append&#39;, isString, function(a) {
        return function(b) {
            return a + b;
        };
    });

console.log(x.append([1, 2, 3])([2, 3, 4])); // [1, 2, 3, 2, 3, 4]
console.log(x.append(&quot;TEST&quot;)(&quot;HELLO&quot;)); // TESTHELLO
console.log(x.empty([1, 2, 3])); // []</code></pre>
<p>Here’s the complete implementation:</p>
<pre><code>// ## Mutable functions
// Functions that use mutable state *only* belong here. They must
// provide an immutable API.
function extend(o, e) {
    var n = {}, i;
    for(i in o) {
        n[i] = o[i];
    }
    for(i in e) {
        n[i] = e[i];
    }
    return n;
}

function singletonObject(k, v) {
    var o = {};
    o[k] = v;
    return o;
}

function foldl(a, f, z) {
    var i;
    for(i = 0; i &lt; a.length; i++) {
        z = f(z, a[i]);
    }
    return z;
}

// ## Helper predicates
function isArray(a) {
    if(Array.isArray) return Array.isArray(a);
    return Object.prototype.toString.call(a) === &quot;[object Array]&quot;;
}

function isTypeOf(s) {
    return function(o) {
        return typeof o == s;
    };
}

var isString = isTypeOf(&#39;string&#39;);
var isNumber = isTypeOf(&#39;number&#39;);

// ## An environment holds all modules and methods.
var emptyEnvironment = {
    methods: {},
    addMethod: function(methodName) {
        return extend(
            extend(
                this,
                singletonObject(methodName, function(o) {
                    return foldl(this.methods[methodName], function(accum, method) {
                        if(method.predicate(o)) {
                            return method.implementation;
                        }
                        return accum;
                    }, function() {
                        throw new Error(&quot;Method not implemented for this input&quot;);
                    })(o);
                })
            ), {
                methods: extend(
                    this.methods,
                    singletonObject(methodName, [])
                )
            }
        );
    },
    extend: function(methodName, predicate, implementation) {
        return extend(this, {
            methods: extend(
                this.methods,
                singletonObject(
                    methodName,
                    this.methods[methodName].concat({
                        predicate: predicate,
                        implementation: implementation
                    })
                )
            )
        });
    }
};</code></pre>]]></summary>
</entry>
<entry>
    <title>SpainJS</title>
    <link href="https://brianmckenna.org/blog/spainjs_roy" />
    <id>https://brianmckenna.org/blog/spainjs_roy</id>
    <published>2012-07-08T00:00:00Z</published>
    <updated>2012-07-08T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I spent this week going to SpainJS. I had lots of fun in
Madrid and gave a talk on Roy. I put <a href="http://brianmckenna.org/files/presentations/spainjs-roy">the talk online here</a>.</p>]]></summary>
</entry>
<entry>
    <title>CraftyJS running character demo</title>
    <link href="https://brianmckenna.org/blog/craftyjs_runner" />
    <id>https://brianmckenna.org/blog/craftyjs_runner</id>
    <published>2012-07-01T00:00:00Z</published>
    <updated>2012-07-01T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This weekend I worked on a tiny demo for a browser-based game. The
idea was to experiment with some JavaScript game
engines. <a href="http://craftyjs.com/">CraftyJS</a> seemed the most complete for
what I wanted to do.</p>
<p>The demo has two running characters. One is controlled by repeatedly
pressing the spacebar. The other just moves foward constantly:</p>
<p><a href="http://brianmckenna.org/blog/static/crafty-running-character-demo/"><img src="http://brianmckenna.org/blog/static/running-game.png" /></a></p>
<p>CraftyJS can output to canvas and DOM nodes. This example uses only
DOM nodes (with background images).</p>
<p>If you’re interested in browser-based games or CraftyJS, you can <a href="http://brianmckenna.org/blog/static/crafty-running-character-demo/">try the online demo</a> or <a href="https://bitbucket.org/puffnfresh/crafty-running-character-demo">clone the code</a>.</p>]]></summary>
</entry>
<entry>
    <title>Foldable1/Traverse1 for scalaz</title>
    <link href="https://brianmckenna.org/blog/scalaz_foldable1" />
    <id>https://brianmckenna.org/blog/scalaz_foldable1</id>
    <published>2012-06-24T00:00:00Z</published>
    <updated>2012-06-24T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve started work on adding Foldable1 and Traverse1 to
<a href="https://github.com/scalaz/scalaz">scalaz</a>. Pretty similar to the
semigroupoids package:</p>
<p><a href="http://hackage.haskell.org/packages/archive/semigroupoids/1.3.2.1/doc/html/Data-Semigroup-Foldable.html">http://hackage.haskell.org/packages/archive/semigroupoids/1.3.2.1/doc/html/Data-Semigroup-Foldable.html</a></p>
<p>The idea is to move over the following from Foldable to Foldable1:</p>
<ul>
<li>foldMap1</li>
<li>foldr1</li>
<li>foldl1</li>
<li>maximum</li>
<li>minimum</li>
</ul>
<p>Those functions will then be total and won’t need to return
Option. Other methods can be defined in Foldable1 (e.g. suml1, sumr1)
which will only require a Semigroup instead of a Monoid.</p>
<p>I’m also creating Traverse1 which relaxes Traverse’s Applicative
restrictions to Apply.</p>
<p>My incomplete changes live <a href="https://github.com/pufuwozu/scalaz/commits/scalaz-seven">on my
fork</a>.</p>]]></summary>
</entry>
<entry>
    <title>Using ScalaCheck with Akka and Specs2</title>
    <link href="https://brianmckenna.org/blog/akka_scalacheck_specs2" />
    <id>https://brianmckenna.org/blog/akka_scalacheck_specs2</id>
    <published>2012-06-17T00:00:00Z</published>
    <updated>2012-06-17T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I spent some time this weekend playing around with
<a href="http://akka.io/">Akka</a>. It took me a while to get it to work nicely
with <a href="https://github.com/rickynils/scalacheck">ScalaCheck</a> and
<a href="etorreborre.github.com/specs2/">Specs2</a>.</p>
<p>My first attempt was to make the test create a new Akka <code>TestKit</code>:</p>
<pre><code>def e1 = new TestKit(system) with Scope with ImplicitSender {
  within(1 second) {
    system.actorOf(Props(new Actor {
      def receive = { case x ⇒ sender ! x }
    })) ! &quot;hallo&quot;

    expectMsgType[String] must be equalTo &quot;hallo&quot;
  }
}</code></pre>
<p>But I couldn’t get ScalaCheck to work inside of the <code>Scope</code>. Instead,
I had to move the <code>TestKit</code> up to the Specification class. Then I
could make a big trait with everything I needed:</p>
<pre><code>trait AkkaScalaCheck extends
  Specification with
  NoTimeConversions with
  ScalaCheck with
  ImplicitSender { self: TestKit =&gt; }</code></pre>
<p>Specs2 will automatically run tests in parallel (awesome feature) but
that broke my tests because actors were sending responses to queries
from other tests.</p>
<p>I just had to tell Specs2 to run tests sequentially:</p>
<pre><code>testOptions in Test += Tests.Argument(&quot;sequential&quot;)</code></pre>
<p>I tried just inserting <code>sequential</code> in the Specification but that
didn’t work for me. I’ll try to narrow down why soon.</p>
<p>The final code looks something like this:</p>
<pre><code>import org.specs2.{ Specification, ScalaCheck }
import org.specs2.specification.Step
import org.specs2.time.NoTimeConversions

import akka.actor.{ Props, ActorSystem }
import akka.testkit.{ TestKit, ImplicitSender }
import akka.util.duration._

trait AkkaScalaCheck extends
  Specification with
  NoTimeConversions with
  ScalaCheck with
  ImplicitSender { self: TestKit =&gt; }

class MySpec(system: ActorSystem) extends TestKit(system) with AkkaScalaCheck {
  def this() = this(ActorSystem(&quot;MySpec&quot;))

  def is =
    &quot;Test should&quot; ^
      p ^
      &quot;pass&quot; ! e1 ^
    Step(system.shutdown()) ^ end

  val ping = system.actorOf(Props[Ping])

  def message[A] = receiveOne(1 second).asInstanceOf[A]

  def e1 = check((a: Int) =&gt; {
    ping ! a
    message must be equalTo a
  })
}</code></pre>]]></summary>
</entry>
<entry>
    <title>Roy - IEEE Article</title>
    <link href="https://brianmckenna.org/blog/roy_ieee" />
    <id>https://brianmckenna.org/blog/roy_ieee</id>
    <published>2012-06-10T00:00:00Z</published>
    <updated>2012-06-10T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>A few weeks ago I had an article about Roy published in IEEE’s
<a href="http://www.computer.org/portal/web/computingnow/internetcomputing">Internet Computing
Magazine</a>. You
can download the final draft here:</p>
<p><a href="http://brianmckenna.org/files/IC-Roy.pdf">http://brianmckenna.org/files/IC-Roy.pdf</a></p>
<p>It’s on IEEE Xplore here:</p>
<p><a href="http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=6188583">http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=6188583</a></p>
<blockquote>
<p>© 2012 IEEE. Personal use of this material is permitted. Permission
from IEEE must be obtained for all other uses, in any current or
future media, including reprinting/republishing this material for
advertising or promotional purposes, creating new collective works,
for resale or redistribution to servers or lists, or reuse of any
copyrighted component of this work in other works.</p>
</blockquote>
<p>Brian McKenna, “Roy: A Statically Typed, Functional Language for JavaScript,” <em>IEEE Internet Computing</em>, vol. 16, no. 3, pp. 86-91, Apr. 2012, doi:10.1109/MIC.2012.56</p>]]></summary>
</entry>
<entry>
    <title>GovHack 2012</title>
    <link href="https://brianmckenna.org/blog/govhack_2012" />
    <id>https://brianmckenna.org/blog/govhack_2012</id>
    <published>2012-06-03T00:00:00Z</published>
    <updated>2012-06-03T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This weekend I went to Sydney’s <a href="http://www.govhack.org/">GovHack</a>. My
team decided to work on a new PhotoSearch for the <a href="http://www.naa.gov.au/">National Archives
of Australia</a>. Our README does a pretty good
job a describing what it is and does:</p>
<blockquote>
<p>The National Archives of Australia has amazing collection our countries vibrant history, with over 300,000 images collected from the past 200 years.Â Sadly the ability to <a href="http://recordsearch.naa.gov.au/scripts/PhotoSearchSearch.asp">search</a> these images on the official siteÂ is a little cumbersome, not to mention slow.</p>
</blockquote>
<blockquote>
<p><a href="http://i.imgur.com/eUxr8.jpg"><img src="http://i.imgur.com/eUxr8l.jpg" /></a></p>
</blockquote>
<blockquote>
<p>You should be able to be bask in the ocean of images this archive has locked away. Scroll past hundreds of images, without ever having to click ‘next’. Dynamically filter results on the fly by state and year with an intuitive interface, with updates the search results immediately. Tweet gems to your friends and followers. Access the images from your mobile - anywhere, anytime.</p>
</blockquote>
<blockquote>
<p>And now you can! We present to you: <a href="http://photosearch.us.to/">PhotoSearch</a></p>
</blockquote>
<blockquote>
<p><a href="http://i.imgur.com/Phu9b.jpg"><img src="http://i.imgur.com/Phu9bl.jpg" /></a></p>
</blockquote>
<blockquote>
<p>These images are more than just pretty pictures; they reveal to us our history and identity; where we come from and what makes us Australian. Discover this country through its’ history and through these awesome archive of images.</p>
</blockquote>
<blockquote>
<p>Some nifty features we managed to squeeze in over the weekend:</p>
</blockquote>
<blockquote>
<ul>
<li>Fast searching!</li>
<li>Magical continuous scrolling for more results</li>
<li>Background colour and image borders taken from the average of the colours of search results</li>
<li>Share awesome photos with your friends via twitter or <a href="http://photosearch.us.to/?q=dogs&amp;i=11674410">url</a></li>
<li>Filter and search results easily by date, state</li>
<li>Mobile friendly responsive design</li>
</ul>
</blockquote>
<blockquote>
<p>A few more screenshots of <a href="http://photosearch.us.to/">PhotoSearch</a>.</p>
</blockquote>
<blockquote>
<p><a href="http://i.imgur.com/jtHGm.jpg"><img src="http://i.imgur.com/jtHGml.jpg" /></a></p>
</blockquote>
<blockquote>
<p><a href="http://i.imgur.com/lCPki.jpg"><img src="http://i.imgur.com/lCPkil.jpg" /></a></p>
</blockquote>
<blockquote>
<p><a href="http://i.imgur.com/gf1FD.png"><img src="http://i.imgur.com/gf1FDl.png" /></a></p>
</blockquote>
<blockquote>
<p><img src="https://img.skitch.com/20120603-1fi5ehbqnt3cb37riadnr17sc4.png" /></p>
</blockquote>
<blockquote>
<p>That link again, just in case you missed it: <a href="http://photosearch.us.to/">PhotoSearch</a>.</p>
</blockquote>
<p>The code is <a href="https://bitbucket.org/cofarrell/govhack2012">on Bitbucket</a> and the <a href="http://photosearch.us.to/">site is live</a>.</p>]]></summary>
</entry>
<entry>
    <title>Naggly</title>
    <link href="https://brianmckenna.org/blog/naggly" />
    <id>https://brianmckenna.org/blog/naggly</id>
    <published>2012-05-27T00:00:00Z</published>
    <updated>2012-05-27T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>For the past month I’ve been working part-time on a small Yesod web
application.</p>
<p>The idea is to make daily blogging easy by asking a small
question. There’s questions like:</p>
<ol type="1">
<li>What are you grateful for?</li>
<li>How did you celebrate your last birthday?</li>
<li>What’s in your fridge today?</li>
</ol>
<p><a href="http://naggly.herokuapp.com/"><img src="http://brianmckenna.org/blog/static/naggly.png" /></a></p>
<p><a href="http://naggly.herokuapp.com/"><img src="http://brianmckenna.org/blog/static/naggly2.png" /></a></p>
<p>You can try it out <a href="http://naggly.herokuapp.com/">here</a>. Hosting thanks to Heroku!</p>]]></summary>
</entry>
<entry>
    <title>Haskell on Heroku</title>
    <link href="https://brianmckenna.org/blog/haskell_on_heroku" />
    <id>https://brianmckenna.org/blog/haskell_on_heroku</id>
    <published>2012-05-20T00:00:00Z</published>
    <updated>2012-05-20T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve been working on a <a href="http://www.yesodweb.com/">Yesod</a> webapp over the past few
weeks. I noticed that the skeleton contained a
<code>deploy/Procfile</code>. I also know of a couple of developers that
have managed to get Haskell running on Heroku.</p>
<p>Heroku Cedar is the polyglot platform which allows you to push
any binary that will run on their servers. I first tried using
Ubuntu 12.04 to compile the binary. Bad mistake; Heroku uses
10.04 so the shared libraries won’t match up.</p>
<p>After manually setting up a virtual machine just to be able to
push - I eventually got it. If I wanted to push, I just had to
get a copy of this special 6GB virtual machine.</p>
<p>I used Yesod’s <code>Procfile</code>, something like this:</p>
<pre><code>web: ./dist/build/my-haskell-project/my-haskell-project -p $PORT</code></pre>
<p>And for some reason, I needed to trick Heroku into thinking it’s
running node.js, I created a <code>package.json</code> containing:</p>
<pre><code>{ &quot;name&quot;: &quot;my-haskell-project&quot;, &quot;version&quot;: &quot;0.0.1&quot;, &quot;dependencies&quot;: {} }</code></pre>
<p>Then I realised that I should have made a <a href="http://vagrantup.com/">Vagrant</a> project instead of
manually setting up a virtual machine. That way anyone could easily
reproduce the deployment environment:</p>
<ul>
<li>Ubuntu 10.04</li>
<li>GHC 7.0.4</li>
<li>Haskell Platform 2011.4.0.0</li>
<li>Heroku Toolbelt</li>
</ul>
<p>It was actually very easy to make, thanks to John Bender’s <a href="http://johnbender.us/2011/03/05/snap-setup-from-scratch-the-vagrant-way/">Snap
blog post</a>. I’ve put it up on <a href="https://bitbucket.org/puffnfresh/vagrant-haskell-heroku">Bitbucket</a>.</p>
<p>To use it, you just need to connect:</p>
<pre><code>git clone https://bitbucket.org/puffnfresh/vagrant-haskell-heroku.git
cd vagrant-haskell-heroku
vagrant up
vagrant ssh</code></pre>
<p>After you’re in, you can build and push your GHC binary:</p>
<pre><code>git clone git@bitbucket.org:puffnfresh/my-haskell-project.git
cd my-haskell-project
git checkout -b deploy
cabal update
cabal install
git add -f dist/build/my-haskell-project/my-haskell-project
git commit -m &quot;Deploy `date`&quot;
git remote add heroku git@heroku.com:my-haskell-project.git
git push -f heroku deploy:master</code></pre>
<p>A much nicer solution would be to use Heroku’s <a href="https://devcenter.heroku.com/articles/buildpacks">Buildpack</a>
support. That way you wouldn’t need to push the binary; you could
just push your Cabal project and it would be compiled on
Heroku. Susan Potter started a <a href="https://github.com/mbbx6spp/cabal-heroku-buildpack">Cabal Buildpack</a> a while ago
and has started thinking about using Vulcan to get ready-made GHC
binaries. That’d be awesome.</p>]]></summary>
</entry>
<entry>
    <title>Roy - Jasmine tests</title>
    <link href="https://brianmckenna.org/blog/roy_jasmine_tests" />
    <id>https://brianmckenna.org/blog/roy_jasmine_tests</id>
    <published>2012-05-13T00:00:00Z</published>
    <updated>2012-05-13T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve rewritten Roy’s tests to be Jasmine specifications. Previously I
had written my own test runner which didn’t work very well.</p>
<p>The custom test runner only supported functional level tests; it just
executed Roy files and compared that with expected output.</p>
<p>I’ve now started writing finer grained tests. I’m really missing
<a href="http://en.wikipedia.org/wiki/QuickCheck">QuickCheck</a> for this stuff -
I might take a look at Crockford’s
<a href="https://github.com/douglascrockford/JSCheck">JSCheck</a>.</p>
<p>But as a bonus for switching, I now get nice looking test results:</p>
<p><img src="http://brianmckenna.org/blog/static/jasmine-runner.png" /></p>]]></summary>
</entry>
<entry>
    <title>Roy - Type-class function constraints</title>
    <link href="https://brianmckenna.org/blog/roy_type_classes_functions" />
    <id>https://brianmckenna.org/blog/roy_type_classes_functions</id>
    <published>2012-05-06T00:00:00Z</published>
    <updated>2012-05-06T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve gotten <a href="roy_type_classes">Roy’s type-classes</a> to propagate across
functions.</p>
<p>To show how it works I’ll define some Monoids:</p>
<pre><code>typeclass Monoid #a {
  append: Function(#a, #a, #a)
  empty: #a
}

instance stringMonoid = Monoid String {
  append: \x y -&gt; x ++ y
  empty: &quot;&quot;
}

instance productMonoid = Monoid {product: Number} {
  append: \x y -&gt; {product: x.product * y.product}
  empty: {product: 1}
}

instance sumMonoid = Monoid {sum: Number} {
  append: \x y -&gt; {sum: x.sum + y.sum}
  empty: {sum: 0}
}</code></pre>
<p>This is the JavaScript output:</p>
<pre><code>var stringMonoid = {
    &quot;append&quot;: function(x, y) {
        return x + y;
    },
    &quot;empty&quot;: &quot;&quot;
};
var productMonoid = {
    &quot;append&quot;: function(x, y) {
        return {
            &quot;product&quot;: x.product * y.product
        };
    },
    &quot;empty&quot;: {
        &quot;product&quot;: 1
    }
};
var sumMonoid = {
    &quot;append&quot;: function(x, y) {
        return {
            &quot;sum&quot;: x.sum + y.sum
        };
    },
    &quot;empty&quot;: {
        &quot;sum&quot;: 0
    }
};</code></pre>
<p>With the changes I’ve made this week, functions can use type-classes
without specifying an implementation. These functions can now be
<em>polymorphic</em> on type-class instances.</p>
<p>For example, implementations of the Monoid type-class are inferred
from the call site’s values:</p>
<pre><code>let f x = append empty x
let g x = f x

console.log (g &quot;TEST&quot;)
console.log (g {product: 10}).product
console.log (g {sum: 1}).sum</code></pre>
<p>In JavaScript, these functions are compiled to take the type-class
instance as an argument. The call site then figures out which instance
to pass in:</p>
<pre><code>var f = function(Monoid, x) {
    return Monoid.append(Monoid.empty, x);
};
var g = function(Monoid, x) {
    return f(Monoid, x);
};
console.log(g(stringMonoid, &quot;TEST&quot;));
console.log(g(productMonoid, {
    &quot;product&quot;: 10
}).product);
console.log(g(sumMonoid, {
    &quot;sum&quot;: 1
}).sum);</code></pre>
<p>The output is:</p>
<pre><code>TEST
10
1</code></pre>]]></summary>
</entry>
<entry>
    <title>Roy - Initial Source Maps</title>
    <link href="https://brianmckenna.org/blog/roy_sourcemaps" />
    <id>https://brianmckenna.org/blog/roy_sourcemaps</id>
    <published>2012-04-29T00:00:00Z</published>
    <updated>2012-04-29T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve started working on <a href="http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/">Source
Map</a>
support for Roy as a <a href="http://www.atlassian.com/company/careers/life">20%
time</a> project at
Atlassian.</p>
<p>At the moment it’s fairly limited. You can only set breakpoints at the
top level of a Roy file. That means nested functions, do-blocks,
definitions, etc, can’t be debugged.</p>
<p>But anyway, it’s pretty exciting to see Roy code being stepped
through:</p>
<p><img src="http://i.imgur.com/xU0GM.gif" /></p>]]></summary>
</entry>
<entry>
    <title>Roy - Type-classes and how they fix primitives</title>
    <link href="https://brianmckenna.org/blog/roy_type_classes" />
    <id>https://brianmckenna.org/blog/roy_type_classes</id>
    <published>2012-04-22T00:00:00Z</published>
    <updated>2012-04-22T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve managed to hack together an initial version of type-classes in
Roy. Here’s what’s compiling in master:</p>
<pre><code>typeclass Monoid #a {
  append: Function(#a, #a, #a)
  empty: #a
}

instance stringMonoid = Monoid String {
  append: \x y -&gt; x ++ y
  empty: &quot;&quot;
}

console.log (append (append &quot;Hello!&quot; empty) empty)</code></pre>
<p>Which compiles into:</p>
<pre><code>var stringMonoid = {
    &quot;append&quot;: function(x, y) {
        return x + y;
    },
    &quot;empty&quot;: &quot;&quot;
};
console.log(stringMonoid.append(stringMonoid.append(&quot;Hello!&quot;, stringMonoid.empty), stringMonoid.empty));</code></pre>
<p>I’m really excited about it because:</p>
<ol type="1">
<li>Type-classes are very cool</li>
<li>They’ve been surprisingly easy to implement</li>
<li>They’re going to fix many problems in Roy</li>
</ol>
<p>How are they going to fix problems in Roy?</p>
<p>At the moment there’s no built-in way to get a length of a String
(yes, I know). This is because the String type is not implemented as a
structural type. One obvious fix is to define a String like a
structural type:</p>
<pre><code>type String = {
  length: String
  indexOf: Function(String, Number)
  lastIndexOf: Function(String, Number)
  toLowerCase: String
  toUpperCase: String
  ...
}</code></pre>
<p>But that causes a couple of problems:</p>
<ol type="1">
<li>A String is not fully interchangable with a structural type - it has more information</li>
<li>It’s not just a “structure” in JS - so not easy to extend without mutation</li>
<li>What happens when we want to add ES6 support? Suddenly we have to change the compiler built-in String type to add something like <code>startsWith</code>…</li>
</ol>
<p>Here’s the type-class solution:</p>
<pre><code>typeclass WithLength #a {
  length: Function(#a, Number)
}

instance stringWithLength = WithLength String {
  length: \s -&gt; s.length
}

console.log (length &quot;TEST&quot;)</code></pre>
<p>This just compiles to:</p>
<pre><code>var stringWithLength = {
    &quot;length&quot;: function(s) {
        return s.length;
    }
};
console.log(stringWithLength.length(&quot;TEST&quot;));</code></pre>
<p>Easy. An obvious optimisation is to inline that
<code>stringWithLength.length</code> function call.</p>
<p>Other things to get working are type-classes with function
definitions:</p>
<pre><code>let appendEmptyIsEmpty x = (append x empty) == empty

console.log (appendEmptyIsEmpty &quot;TEST&quot;)</code></pre>
<p>Which should become:</p>
<pre><code>var appendEmptyIsEmpty = function(monoid, x) {
    return monoid.append(x, monoid.empty) == monoid.empty;
};

console.log(appendEmptyIsEmpty(stringMonoid, &quot;TEST&quot;));</code></pre>
<p>I’ll be spending <a href="http://atlassian.com/">Atlassian</a>’s 20% time on
Roy. Expect more exciting things soon.</p>
<p>If you want to play with the master version of Roy, clone the
repository from <a href="https://bitbucket.org/puffnfresh/roy">Bitbucket</a> or
<a href="https://github.com/pufuwozu/roy">GitHub</a>.</p>]]></summary>
</entry>
<entry>
    <title>Roy - Highlighting on Website</title>
    <link href="https://brianmckenna.org/blog/roy_site_highlighting" />
    <id>https://brianmckenna.org/blog/roy_site_highlighting</id>
    <published>2012-04-15T00:00:00Z</published>
    <updated>2012-04-15T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I was at <a href="http://2012.jsconf.us/">JSConf</a> almost 2 weeks ago, where I gave <a href="http://brianmckenna.org/files/presentations/jsconf-roy/">a talk about
Roy</a>. I then
went on holiday in San Francisco and met up with heaps of cool people.</p>
<p>On the flight back I was able to make a <a href="https://github.com/pufuwozu/roy/blob/master/site/codemirror2/mode/roy/roy.js">CodeMirror2 mode for Roy</a>. Then I added it to the <a href="http://roy.brianmckenna.org/">Roy website</a>:</p>
<p><a href="http://roy.brianmckenna.org/"><img src="http://brianmckenna.org/blog/static/highlighted-syntax.png" /></a></p>
<p>Another change (that I should have done a long time ago) is getting type errors to print out line numbers:</p>
<p><img src="http://brianmckenna.org/blog/static/type-errors-line-number.png" /></p>
<p>This was also initial work to getting <a href="http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/">Source Map</a> support.</p>]]></summary>
</entry>
<entry>
    <title>Roy - CLI Compile Browser Modules</title>
    <link href="https://brianmckenna.org/blog/roy_cli_browser_modules" />
    <id>https://brianmckenna.org/blog/roy_cli_browser_modules</id>
    <published>2012-03-25T00:00:00Z</published>
    <updated>2012-03-25T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve added support for compiling <a href="http://brianmckenna.org/blog/roy_browser_modules">browser modules</a> via the node.js
CLI. You can now run:</p>
<pre><code>./roy --browser examples/node_module.roy</code></pre>
<p>And you’ll get code just like the Roy compiler generates when running
in the browser:</p>
<pre><code>(function() {
console.log((structural.obj.x + structural.obj.y));
})();</code></pre>
<p>I’ve also cleaned up the module implementation. They are no longer
half-implemented as macros. This is mainly so I can add <a href="https://github.com/amdjs/amdjs-api/wiki/AMD">AMD</a>
support.</p>]]></summary>
</entry>
<entry>
    <title>Roy - Modules in master</title>
    <link href="https://brianmckenna.org/blog/roy_modules_master" />
    <id>https://brianmckenna.org/blog/roy_modules_master</id>
    <published>2012-03-18T00:00:00Z</published>
    <updated>2012-03-18T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I have just merged the <code>modules</code> branch of Roy into <code>master</code>. I’ve been implementing this feature since December and have finally got it working mostly the way I wanted.</p>
<p>Roy modules work for node.js:</p>
<pre><code>import &quot;./structural&quot;
console.log (structural.obj.x + structural.obj.y)
let hundred = 100
export hundred</code></pre>
<p>Which compiles to:</p>
<pre><code>var structural = require(&quot;./structural&quot;);
console.log((structural.obj.x + structural.obj.y));
var hundred = 100;
exports[&quot;hundred&quot;] = hundred;;</code></pre>
<p>Roy modules also work in the browser:</p>
<pre><code>// Roy modules have a descriptor format.
// The demo site manually supplies the &#39;dom&#39; descriptor.

import &quot;dom&quot;

let button = document.getElementById &quot;jsrun&quot;

console.log (button.getAttribute &quot;value&quot;)</code></pre>
<p>Which compiles to:</p>
<pre><code>(function() {
// Roy modules have a descriptor format.
// The demo site manually supplies the &#39;dom&#39; descriptor.
// Using browser module: &quot;dom&quot;
var button = document.getElementById(&quot;jsrun&quot;);
console.log((button.getAttribute(&quot;value&quot;)));
})();</code></pre>]]></summary>
</entry>
<entry>
    <title>Roy - Breaking Changes</title>
    <link href="https://brianmckenna.org/blog/roy_breaking_changes" />
    <id>https://brianmckenna.org/blog/roy_breaking_changes</id>
    <published>2012-03-11T00:00:00Z</published>
    <updated>2012-03-11T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve made some breaking changes to Roy. The first is changing the
grammar to use less parentheses. Before, you had to write:</p>
<pre><code>if (not true) then (id 100) else (10 - 1)</code></pre>
<p>Now you can write:</p>
<pre><code>if not true then id 100 else 10 - 1</code></pre>
<p>The problem is you can no longer do things like this:</p>
<pre><code>if true then if true then true else false else false</code></pre>
<p>But instead have to write:</p>
<pre><code>if true then (if true then true else false) else false</code></pre>
<p>Seems like a good trade-off to me.</p>
<p>The other breaking change is on the <code>modules</code> branch. I’ve decided to
make tags be typed and compiled to normal JavaScript function
calls. This is possible with a really cool JavaScript trick:</p>
<pre><code>var C = function() {
    if(!(this instanceof C)) {
        return new C();
    }
};</code></pre>
<p>The above code allows the construction of <code>C</code> from JavaScript with
either <code>C()</code> or <code>new C()</code>.</p>
<p>But this breaks nullary tags, which must now be called with empty
parens (just like nullary, external JavaScript functions):</p>
<pre><code>let c = C ()</code></pre>
<p>I’ve been making this change to unify the concepts of tags and
functions for module loading. I’ve also been able to remove a heap of
mutable state in doing so.</p>
<p>I’ll hopefully be able to merge in the <code>modules</code> branch very soon.</p>]]></summary>
</entry>
<entry>
    <title>Ray - Roy on Play</title>
    <link href="https://brianmckenna.org/blog/ray" />
    <id>https://brianmckenna.org/blog/ray</id>
    <published>2012-03-04T00:00:00Z</published>
    <updated>2012-03-04T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week I worked on a Play 2.0 plugin that automatically compiles
Roy files. I’ve named the plugin ‘Ray’.</p>
<p>With Ray enabled in your application, you can write a plain <code>.roy</code>
file and place it in the <code>app/assets/javascripts</code> directory:</p>
<p><img src="http://i.imgur.com/6JkOe.png" /></p>
<p>You can then include it in your page like a normal <code>.js</code> asset:</p>
<pre><code>&lt;script src=&quot;@routes.Assets.at(&quot;javascripts/main.js&quot;)&quot;&gt;&lt;/script&gt;</code></pre>
<p>Any compile errors will be shown when the page is requested:</p>
<p><img src="http://i.imgur.com/wJwAp.png" /></p>
<p>Change to your editor to fix up the error:</p>
<p><img src="http://i.imgur.com/lf5TW.png" /></p>
<p>Then refresh the page to have working JavaScript:</p>
<p><img src="http://i.imgur.com/G0qpG.png" /></p>
<p>Download Ray from <a href="https://github.com/pufuwozu/ray">GitHub</a> or <a href="https://bitbucket.org/puffnfresh/ray">Bitbucket</a>.</p>
<p>I couldn’t find any prior Play 2.0 plugins so a lot of this was trial
and error. In the end, I needed to make this an SBT plugin that is put
into the Play 2.0 local Ivy repository.</p>
<p>These were main lines in the <code>build.sbt</code> file:</p>
<pre><code>sbtPlugin := true

addSbtPlugin(&quot;play&quot; % &quot;sbt-plugin&quot; % playVersion)

publishTo := Some(playRepository)

publishMavenStyle := false</code></pre>
<p>The <code>playRepository</code> and <code>playVersion</code> values are calculated from
environment variables given on the command line:</p>
<pre><code>sbt -Dplay.path=../play-2.0-RC3 -Dplay.version=2.0-RC3 publish</code></pre>
<p>Then the plugin can be added in the application’s <code>plugins.sbt</code>:</p>
<pre><code>addSbtPlugin(&quot;org.brianmckenna&quot; % &quot;ray&quot; % &quot;0.1&quot;)</code></pre>
<p>And then imported in the application’s <code>Build.scala</code>:</p>
<pre><code>import org.brianmckenna.ray.RoyBuild</code></pre>
<p>Then your Play 2.0 plugin can add resource generators or other
build changes.</p>]]></summary>
</entry>
<entry>
    <title>Diabetes Fundraiser Poster</title>
    <link href="https://brianmckenna.org/blog/diabetes_poster" />
    <id>https://brianmckenna.org/blog/diabetes_poster</id>
    <published>2012-02-26T00:00:00Z</published>
    <updated>2012-02-26T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I spent some time this week creating some posters for family trying to fundraise for diabetes research. Feel free to <a href="http://www.teamcurediabetes.org.au/team_brew">sponsor</a> them.</p>
<p><a href="http://www.teamcurediabetes.org.au/team_brew"><img src="http://brianmckenna.org/blog/static/poster-general.png" /></a></p>
<p><a href="http://www.teamcurediabetes.org.au/team_brew"><img src="http://brianmckenna.org/blog/static/poster-school.png" /></a></p>]]></summary>
</entry>
<entry>
    <title>Roy - fp-syd</title>
    <link href="https://brianmckenna.org/blog/fpsyd_presentation_roy" />
    <id>https://brianmckenna.org/blog/fpsyd_presentation_roy</id>
    <published>2012-02-19T00:00:00Z</published>
    <updated>2012-02-19T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week I presented at <a href="http://fp-syd.ouroborus.net/">fp-syd</a>. I’ve put the <a href="http://brianmckenna.org/files/presentations/fp-syd-roy/">slides</a> online. I talked about why JavaScript needs to be improved for functional programming:</p>
<p><a href="http://brianmckenna.org/files/presentations/fp-syd-roy/"><img src="http://brianmckenna.org/blog/static/fp-syd-1.png" /></a></p>
<p>What options existed before I started Roy:</p>
<p><a href="http://brianmckenna.org/files/presentations/fp-syd-roy/"><img src="http://brianmckenna.org/blog/static/fp-syd-2.png" /></a></p>
<p>Why those options were suboptimal:</p>
<p><a href="http://brianmckenna.org/files/presentations/fp-syd-roy/"><img src="http://brianmckenna.org/blog/static/fp-syd-3.png" /></a></p>
<p>What I’m trying to achieve:</p>
<p><a href="http://brianmckenna.org/files/presentations/fp-syd-roy/"><img src="http://brianmckenna.org/blog/static/fp-syd-4.png" /></a></p>
<p>And what Roy currently is:</p>
<p><a href="http://brianmckenna.org/files/presentations/fp-syd-roy/"><img src="http://brianmckenna.org/blog/static/fp-syd-5.png" /></a></p>
<p>I got a lot of positive feedback which was motivating. I also heard some more news on using type inference in JavaScript engines for performance. It’d be great if we could figure out a way to use Roy’s type information within those engines.</p>]]></summary>
</entry>
<entry>
    <title>Roy - REPL Improvements</title>
    <link href="https://brianmckenna.org/blog/roy_repl_improvements" />
    <id>https://brianmckenna.org/blog/roy_repl_improvements</id>
    <published>2012-02-12T00:00:00Z</published>
    <updated>2012-02-12T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve added a few improvements to the Roy REPL.</p>
<p>You can now see the type of assigned identifiers with the <code>:t</code> directive:</p>
<pre><code>roy&gt; let x = 100
roy&gt; :t x
Number
roy&gt; let a = [1, 2, 3]
roy&gt; :t a
[Number]</code></pre>
<p>A structure’s values are printed instead of <code>[object Object]</code>:</p>
<pre><code>roy&gt; let x = {a: 1, b: true, c: &quot;three&quot;}
roy&gt; x
{&quot;a&quot;:1,&quot;b&quot;:true,&quot;c&quot;:&quot;three&quot;} : {a: Number, b: Boolean, c: String}</code></pre>
<p>A helpful message is now shown when the lexer fails:</p>
<pre><code>roy&gt; can&#39;t lex this
Couldn&#39;t tokenise: &#39;t lex this</code></pre>
<p>And you can choose not to include the prelude when running files:</p>
<pre><code>$ ./roy -p examples/option.roy 
{ _0: 6 }</code></pre>
<p>Hopefully this will make the REPL experience a bit nicer.</p>]]></summary>
</entry>
<entry>
    <title>Roy - DOM Tests</title>
    <link href="https://brianmckenna.org/blog/roy_dom" />
    <id>https://brianmckenna.org/blog/roy_dom</id>
    <published>2012-02-05T00:00:00Z</published>
    <updated>2012-02-05T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week I did minor work on making <a href="http://brianmckenna.org/blog/roy_browser_modules">browser modules</a> work more smoothly.</p>
<p>In the “modules” branch, the website will have a few “document” definitions in the “dom” module. For example, there’s a partial definition for “getElementById”:</p>
<p><img src="http://brianmckenna.org/blog/static/roy_dom.png" /></p>
<p>As you can see, passing a Number doesn’t work because it expects a String.</p>
<p>I manually defined parts of the “document” object. The next step would be to use something like IDL to automatically generate the Roy module.</p>]]></summary>
</entry>
<entry>
    <title>Roy - Browser Modules</title>
    <link href="https://brianmckenna.org/blog/roy_browser_modules" />
    <id>https://brianmckenna.org/blog/roy_browser_modules</id>
    <published>2012-01-29T00:00:00Z</published>
    <updated>2012-01-29T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week I started work on Roy browser modules. The code is the same as node.js modules. So this:</p>
<pre><code>let obj = {x: 1, y: 2, t: &quot;test&quot;}
export obj</code></pre>
<p>Will compile into this (in browser mode):</p>
<pre><code>var _obj;
(function() {
var obj = {
&quot;x&quot;: 1,
&quot;y&quot;: 2,
&quot;t&quot;: &quot;test&quot;
};
_obj = obj;
})();</code></pre>
<p>It currently prefixes the global variables with an underscore. This was just for the initial version and I hope to get rid of it soon.</p>]]></summary>
</entry>
<entry>
    <title>Roy - node.js Modules</title>
    <link href="https://brianmckenna.org/blog/roy_node_modules" />
    <id>https://brianmckenna.org/blog/roy_node_modules</id>
    <published>2012-01-22T00:00:00Z</published>
    <updated>2012-01-22T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week I was at <a href="http://linux.conf.au/">linux.conf.au 2012</a> in Ballarat. I talked about <a href="http://altjs.org/">altJS</a> (languages that compile to JavaScript). The video is <a href="http://www.youtube.com/watch?v=Grgz5yBhvRo">up on YouTube</a>.</p>
<p>During my off-time, I worked on Roy’s <a href="https://github.com/pufuwozu/roy/tree/modules">modules</a> branch and made it capable of importing and exporting node.js modules. The branch adds an “export” macro:</p>
<pre><code>let obj = {x: 1, y: 2, t: &quot;test&quot;}
export obj</code></pre>
<p>This will assign the identifier to the “exports” global specified by <a href="http://nodejs.org/docs/latest/api/modules.html">CommonJS Modules/1.0</a>:</p>
<pre><code>var obj = {
    &quot;x&quot;: 1,
    &quot;y&quot;: 2,
    &quot;t&quot;: &quot;test&quot;
};
exports[&quot;obj&quot;] = obj;</code></pre>
<p>My work on <a href="http://brianmckenna.org/blog/roy_separate_compilation">separate compilation</a> causes a “.roym” file to be written during compilation:</p>
<pre><code>obj: {x: Number, y: Number, t: String}</code></pre>
<p>On the other side, there’s an “import” macro:</p>
<pre><code>import &quot;./structural&quot;

let f o = o.x + o.y
f structural.obj</code></pre>
<p>Which loads the “.roym” file and assigns the types under the module name and compiles to node.js compatible requires:</p>
<pre><code>var structural = require(&quot;./structural&quot;);
var f = function(o) {
    return o.x + o.y;
}
f(structural.obj)</code></pre>
<p>That’s it. Type-safe node.js modules. Awesome.</p>
<p>I have a few things to continue with:</p>
<ul>
<li>Add flags to change macros to target browser globals and <a href="https://github.com/amdjs/amdjs-api/wiki/AMD">AMD</a> modules</li>
<li>Fix writing <em>all</em> top-level type information to the “.roym” file; only write exported values</li>
</ul>]]></summary>
</entry>
<entry>
    <title>Roy - Type System Documentation</title>
    <link href="https://brianmckenna.org/blog/roy_docs_types" />
    <id>https://brianmckenna.org/blog/roy_docs_types</id>
    <published>2012-01-15T00:00:00Z</published>
    <updated>2012-01-15T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week I wrote some simple documentation about Roy’s type system.</p>
<p><a href="http://readthedocs.org/docs/roy/en/latest/types.html"><img src="http://brianmckenna.org/blog/static/roy_types_docs.png" /></a></p>
<p>I’m going to write about functions in the next chapter.</p>]]></summary>
</entry>
<entry>
    <title>Type Errors as Warnings</title>
    <link href="https://brianmckenna.org/blog/type_errors_as_warnings" />
    <id>https://brianmckenna.org/blog/type_errors_as_warnings</id>
    <published>2012-01-11T00:00:00Z</published>
    <updated>2012-01-11T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I follow some programming language people on Twitter. Last week an interesting discussion broke out between David Pollak, James Iry and Paul Snively. Eventually Manuel Simoni, Daniel Spiewak and others got involved.</p>
<p>David Pollak (<a href="http://twitter.com/dpp"><span class="citation" data-cites="dpp">@dpp</span></a>) is working on a <a href="http://blog.visi.io/it-was-20-years-ago-today">new programming language</a>, he imagines it as a cross between Haskell and Excel. He asked:</p>
<blockquote>
<p>Should code fail to compile if tests/contract and documentation are missing for public functions/structures/methods?</p>
</blockquote>
<p>Paul Snively (<a href="http://twitter.com/psnively"><span class="citation" data-cites="psnively">@psnively</span></a>) mentioned that types are all of the above:</p>
<blockquote>
<p><span class="citation" data-cites="dpp">@dpp</span> Of course it should fail to compile if your types are wrong. ;-)</p>
</blockquote>
<p>James Iry (<a href="http://twitter.com/jamesiry"><span class="citation" data-cites="jamesiry">@jamesiry</span></a>) said maybe compile-time type errors could instead become warnings and emit runtime errors:</p>
<blockquote>
<p><span class="citation" data-cites="psnively">@psnively</span> It’s sometimes useful for an IDE to “warn” on type errors and generate exception code in place of the type problem.</p>
</blockquote>
<p>The <a href="http://james-iry.blogspot.com/2012/01/type-errors-as-warnings.html">Eclipse JDT compiler is one that does this</a>. I’m not sure why the Eclipse IDE needed this functionality but it seems like the <a href="http://www.playframework.org/">Play framework</a> uses it to present nice-looking compilation errors on page refresh:</p>
<p><a href="http://www.playframework.org/documentation/1.0.1/guide1"><img src="http://brianmckenna.org/blog/static/play-guide1-3-small.png" /></a></p>
<p>The compiler works by noticing type errors (amongst others) like this:</p>
<pre><code>int foo(String x) {
    return x * 2;
}</code></pre>
<p>But continues by emitting code like this:</p>
<pre><code>int foo(String x) {
    throw new TypeError(&quot;Expected an int but got a String at line 42 of Bar.java.&quot;);
}</code></pre>
<p>Play comes along, catches that runtime exception and turns it into a pretty screen.</p>
<h3 id="haskell">Haskell</h3>
<p>Interestingly, this is exactly what Simon Peyton-Jones talked to me about during a <a href="http://yownightsydneydec11.eventbrite.com/">YOW! Night</a> here in Sydney. His idea is that people want to be able to run programs, even when the compiler is telling them that parts are wrong. He wants to add a mode to the Glasgow Haskell Compiler so code like this:</p>
<pre><code>foo :: String -&gt; Int
foo x = x * 2</code></pre>
<p>Is transformed into:</p>
<pre><code>foo :: String -&gt; Int
foo x = error &quot;Expected an Int but got a String at line 2 of Foo.hs&quot;</code></pre>
<p>And the Haskell compiler will print a warning during compilation:</p>
<pre><code>WARNING: Foo.hs:2:8:
    Couldn&#39;t match expected type `Int&#39; against inferred type `String&#39;
    In the expression: x * 2
In the definition of `foo&#39;: foo x = x * 2</code></pre>
<p>The following program would execute fine with no command-line arguments but otherwise show the type error at <em>runtime</em>:</p>
<pre><code>import System (getArgs)

main = do
  args &lt;- getArgs
  print $ if length args &gt; 0 then foo [1, 2, 3] else 100</code></pre>
<p>This might be useful for incomplete refactoring during development. You can modify part of your program and still run that part’s tests while the types in other parts have become inconsistent.</p>
<p>Manuel Simoni (<a href="http://twitter.com/msimoni"><span class="citation" data-cites="msimoni">@msimoni</span></a>) says it’s also beneficial to go into inconsistency while redefining parts of your program, interactively:</p>
<blockquote>
<p>Without the ability to be inconsistent, you can’t support the Lisp Experience™</p>
</blockquote>
<p>In any case, you’d definitely want to turn on treating type warnings as errors in production code.</p>
<h3 id="questions">Questions</h3>
<p>Do you think this is a good option for statically-typed languages?</p>
<p>Simon seems to think this could attract fans of dynamic languages to Haskell. Would this sole feature satisfy them?</p>
<p>Temporary inconsistencies also <a href="http://www.unlimitednovelty.com/2011/03/distributed-systems-and-dynamic-typing.html">play a part in distributed systems</a>, could a similar idea be used?</p>]]></summary>
</entry>
<entry>
    <title>Roy - Documentation</title>
    <link href="https://brianmckenna.org/blog/roy_docs" />
    <id>https://brianmckenna.org/blog/roy_docs</id>
    <published>2012-01-08T00:00:00Z</published>
    <updated>2012-01-08T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week I wrote the first piece of documentation for Roy - an <a href="http://readthedocs.org/docs/roy/en/latest/introduction.html">introduction</a> to a guide through Roy. The project uses <a href="http://sphinx.pocoo.org/">Sphinx</a> and <a href="http://readthedocs.org/">Read the Docs</a> (thanks to <a href="http://www.distractable.net/">Damon Oehlman</a> for pointing me towards that).</p>
<p><a href="http://readthedocs.org/docs/roy/en/latest/introduction.html"><img src="http://brianmckenna.org/blog/static/roy_introduction.png" /></a></p>
<p>The introduction covers why JavaScript isn’t enough, the options that we have for not using JavaScript and the path that Roy takes. The next chapter will be on compile-time type-checking, one of the things that makes Roy unique for an altJS language.</p>]]></summary>
</entry>
<entry>
    <title>Roy - Literate Roy</title>
    <link href="https://brianmckenna.org/blog/literate_roy" />
    <id>https://brianmckenna.org/blog/literate_roy</id>
    <published>2012-01-01T00:00:00Z</published>
    <updated>2012-01-01T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I added some <a href="http://en.wikipedia.org/wiki/Literate_programming">literate programming</a> support to Roy. You can write Markdown files with an extension of <code>.lroy</code> and the <code>roy</code> executable will accept them.</p>
<p>I’ve also written a shell script that will run it through Pandoc to give you <a href="http://brianmckenna.org/blog/static/sqrt.htm">nice-looking HTML output</a>, using <a href="http://kev.inburke.com/">Kevin Burke’s</a> <a href="http://kevinburke.bitbucket.org/markdowncss/">Markdown.css</a>:</p>
<p><a href="http://brianmckenna.org/blog/static/sqrt.htm"><img src="http://brianmckenna.org/blog/static/literate_roy.png" /></a></p>
<p>The above was generated using the following Markdown:</p>
<pre><code>% Roy - Babylonian Square Root

This is a Markdown file. It&#39;s also literate Roy code!

We&#39;re going to define a `sqrt` function using the
[Babylonian method][] for approximation.

    let sqrt n =

Making a good initial guess helps reduce the amount of
iterations until convergence. One method is to find the
highest-bit (`b`) and use `2^(b/2)`.

      let highestBit n i =
        if (1 &lt;&lt; i) &gt; n then
          i
        else
          highestBit n (i + 1)

      let guess = 1 &lt;&lt; ((highestBit n 1) / 2)

Iteratively average the guess and the number divided by the guess
until convergence with a cut-off of 0.001. The guessing is started
from the initial value, calculated above.

      let nextGuess g =
        if (Math.abs (g - (n / g))) &lt; 0.001 then
          g
        else
          nextGuess ((g + (n / g)) / 2)

      nextGuess guess

Now we can calculate the square root of 314 and print it.

    console.log (sqrt 314)

We should get an answer of around 17.720.

[Babylonian method]: http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method</code></pre>
<p>Happy New Year!</p>]]></summary>
</entry>
<entry>
    <title>Rome - Roy as Chrome Extension</title>
    <link href="https://brianmckenna.org/blog/roy_chrome_rome" />
    <id>https://brianmckenna.org/blog/roy_chrome_rome</id>
    <published>2011-12-25T00:00:00Z</published>
    <updated>2011-12-25T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Rome is a Google Chrome Extension for compiling and editing Roy files. A developer can install <a href="https://github.com/pufuwozu/roy/tree/master/misc/chrome-extension">the unpacked extension</a> (currently only in the <a href="https://github.com/pufuwozu/roy">Roy repository</a>) then just drag a .roy file into the browser.</p>
<p>The file will be compiled and can be executed:</p>
<p><img src="http://brianmckenna.org/blog/static/roy_chrome_rome.png" /></p>
<p>I decided to steal this while watching a <a href="http://dartlang.org/">Dart</a> presentation at <a href="http://sydjs.com/">SydJS</a>. The presenter mentioned the general idea and I later found out it was called <a href="http://dartwatch.com/index.php/2011/12/frog-toss-tip-and-in-browser-compiling/">Dart Tip</a>. Rome tries to do exactly what Dart Tip does for Dart. Thanks for the idea, Dart team!</p>
<p>Merry Christmas!</p>]]></summary>
</entry>
<entry>
    <title>Roy - Separate Compilation</title>
    <link href="https://brianmckenna.org/blog/roy_separate_compilation" />
    <id>https://brianmckenna.org/blog/roy_separate_compilation</id>
    <published>2011-12-18T00:00:00Z</published>
    <updated>2011-12-18T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Up until now you’ve had to compile all Roy modules at once so that
type information would be kept around.</p>
<p>This week I started work on separate compilation Roy. With the latest
changes, a <code>.roym</code> file is generated on compilation that defines all
top level types, like so:</p>
<pre><code>even: Function(Number,Boolean)
odd: Function(Number,Boolean)
succ: Function(Number,Number)
pred: Function(Number,Number)</code></pre>
<p>Currently the compiler only reads lib/prelude.roym for type
information. I’m going to add a flag to specify where to read modules
from.</p>
<p>This should be a start to a few issues:</p>
<ul>
<li><a href="https://github.com/pufuwozu/roy/issues/17">Add a way to give types to JS globals</a></li>
<li><a href="https://github.com/pufuwozu/roy/issues/18">IDL binding generator</a></li>
</ul>]]></summary>
</entry>
<entry>
    <title>Roy - Pretty Printing</title>
    <link href="https://brianmckenna.org/blog/roy_pretty_printing" />
    <id>https://brianmckenna.org/blog/roy_pretty_printing</id>
    <published>2011-12-11T00:00:00Z</published>
    <updated>2011-12-11T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week I created an initial version of a <a href="http://en.wikipedia.org/wiki/Prettyprint">pretty printer</a> for Roy code. The REPL will now take a <code>:s</code> command pointing at a bound name, like so:</p>
<pre><code>roy&gt; let x= \a-&gt;   a+ 100
roy&gt; :s x
\a -&gt; a + 100</code></pre>
<p>Notice that it pads out the operators. It also works on things like arrays and objects:</p>
<pre><code>roy&gt; let y = [1,2,3]
roy&gt; :s y
[1, 2, 3]
roy&gt; let z = {a: 1   , b:true, c:   &quot;three&quot;}
roy&gt; :s z
{a: 1, b: true, c: &quot;three&quot;}</code></pre>
<p>I have futures plans to expand this into a standalone formatter so that Roy source will have something like <a href="http://golang.org/cmd/gofmt/">gofmt</a>.</p>
<p>In other Roy news:</p>
<ul>
<li>We have <a href="https://github.com/pufuwozu/roy/blob/master/examples/ajaxmonad.roy">some</a> <a href="https://github.com/pufuwozu/roy/blob/master/examples/deferredmonad.roy">better</a> monad examples</li>
<li>I <a href="https://github.com/pufuwozu/roy/commit/7ff4ac22b2d0a1ebdc80e162f1b1d64ced330c8f">fixed</a> a bug in recursive functions using data constructors</li>
<li>The Roy version that the site is based off has been added to the footer of <a href="http://roy.brianmckenna.org/">http://roy.brianmckenna.org/</a></li>
</ul>]]></summary>
</entry>
<entry>
    <title>Roy - Recursive Data</title>
    <link href="https://brianmckenna.org/blog/roy_recursive_data" />
    <id>https://brianmckenna.org/blog/roy_recursive_data</id>
    <published>2011-12-04T00:00:00Z</published>
    <updated>2011-12-04T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Last week I blogged that this wasn’t possible in Roy:</p>
<pre><code>data List a = Cons a (List a) | Nil</code></pre>
<p>My one goal for this week was to make that possible. I <a href="https://bitbucket.org/puffnfresh/roy/changeset/f8465a08756f">managed to succeed</a> and you can now even write fancier things like this:</p>
<pre><code>data Tree a = TEmpty | TBranch a (Tree a) (Tree a)

console.log (TBranch 100 TEmpty (TBranch 100 TEmpty TEmpty))

// Won&#39;t compile:
// console.log (TBranch 100 TEmpty (TBranch &quot;ASDF&quot; TEmpty TEmpty))</code></pre>
<p>I also fixed some simple problems with <a href="https://github.com/pufuwozu/roy/issues/24">multiple</a> <a href="https://github.com/pufuwozu/roy/issues/25">declarations</a> of things.</p>
<p>A very cool contribution has been a Roy TextMate/Sublime bundle:</p>
<p><a href="https://github.com/paulmillr/roy.tmbundle"><img src="http://brianmckenna.org/blog/static/roy-textmate.png" /></a></p>
<p>Other awesome contributions have been:</p>
<ul>
<li><a href="https://github.com/pufuwozu/roy/issues/33">Unicode operators</a></li>
<li><a href="https://github.com/pufuwozu/roy/pull/48">REPL improvements</a></li>
<li>New <a href="https://github.com/pufuwozu/roy/issues/34">bind</a> and <a href="https://github.com/pufuwozu/roy/issues/31">lambda syntax</a></li>
<li>New <a href="https://github.com/pufuwozu/roy/issues/14">example</a></li>
</ul>]]></summary>
</entry>
<entry>
    <title>Roy's Big Week</title>
    <link href="https://brianmckenna.org/blog/big_roy_news" />
    <id>https://brianmckenna.org/blog/big_roy_news</id>
    <published>2011-11-27T00:00:00Z</published>
    <updated>2011-11-27T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Roy was submitted to Hacker News about 2 days ago and received over 100 votes and 47 comments! Crazy.</p>
<p>This is after I created a <a href="https://github.com/pufuwozu/roy">GitHub mirror</a> where <a href="http://paulmillr.com/">Paul Miller</a> filled out the <a href="https://github.com/pufuwozu/roy/issues">issue tracker</a>. I’m trying to work through the biggest bugs and then move onto extra features. Currently the biggest issue is the lack of <a href="https://bitbucket.org/puffnfresh/roy/issue/1/recursive-data-type">recursive data types</a>. That issue is blocking being able to write things like the <a href="http://en.wikipedia.org/wiki/Cons#Lists">cons list</a>:</p>
<pre><code>data List a = Cons a (List a) | Nil</code></pre>
<p>(Which is also valid Haskell syntax)</p>
<p>This was actually part of a much bigger problem. Data constructors could only have generic parameters and not solid types specified in value constructors. For example, this wouldn’t work:</p>
<pre><code>data OptionN = SomeN Number | NoneN</code></pre>
<p>And that was also a problem with type aliases:</p>
<pre><code>type OptionS = Option String</code></pre>
<p>Both problems have now been <a href="https://bitbucket.org/puffnfresh/roy/changeset/2b6cf2d4a984">fixed</a>. Now I’m pretty close to fixing the original recursive data type issue.</p>
<p>In other news:</p>
<ul>
<li>Roy now <a href="https://bitbucket.org/puffnfresh/roy">uses Git</a> (clone this new repo if you have an old Mercurial version)</li>
<li>Roy is now in <a href="https://github.com/balupton/docpad">DocPad</a>!</li>
<li>Roy is now in <a href="http://search.npmjs.org/#/roy">npm</a></li>
<li>I fixed <code>do</code> notation not being typed correctly</li>
</ul>
<p>It’s been awesome to see such positive feedback. Thanks everyone.</p>]]></summary>
</entry>
<entry>
    <title>SydJS Presentation on altJS</title>
    <link href="https://brianmckenna.org/blog/sydjs_presentation_altjs" />
    <id>https://brianmckenna.org/blog/sydjs_presentation_altjs</id>
    <published>2011-11-20T00:00:00Z</published>
    <updated>2011-11-20T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>On Wednesday I gave a presentation about <a href="http://altjs.org/">altJS</a> to <a href="http://www.sydjs.com/">SydJS</a>. I focused on four languages:</p>
<ol type="1">
<li><a href="http://coffeescript.org/">CoffeeScript</a></li>
<li><a href="https://github.com/clojure/clojurescript">ClojureScript</a></li>
<li><a href="http://dartlang.org/">Dart</a></li>
<li><a href="http://roy.brianmckenna.org/">Roy</a></li>
</ol>
<p>I say “focused” but the only thing I said about Dart was that I don’t like it and I don’t see anything good about it. The next SydJS is going to have someone from Google talking about Dart. Interesting.</p>
<p>A few questions were asked. One was to clarify <a href="https://wiki.mozilla.org/DevTools/Features/SourceMap">source maps</a>. I don’t think I did a good job explaining them. They’re a way to map from compiled JavaScript to original source files for debugging. The <a href="https://wiki.mozilla.org/DevTools/Features/SourceMap">MozillaWiki</a> has much more detailed info.</p>
<p>Another question was if there were any domain-specific languages. Kind-of. There are languages that are ports of others, languages that target <a href="http://brianmckenna.org/blog/cps_transform_js">callback hell</a> and languages that target security. I don’t know of any with limited business domains.</p>
<p><a href="http://balupton.com/">Ben Lupton</a> later on asked me whether Roy was in <a href="http://npmjs.org/">npm</a> (so he could add it to <a href="http://docpad-kitchensink.herokuapp.com/">DocPad</a>). Answer was “no” but now it’s in both <a href="http://search.npmjs.org/#/roy">npm</a> and <a href="https://github.com/balupton/docpad/commit/b34d64e8f76e58bee6ddf0400dad07a573913bf8">DocPad</a>!</p>
<p>I’ve posted the presentation <a href="http://brianmckenna.org/files/presentations/sydjs-altjs/">slides online</a>. Sadly, they will only work in WebKit browsers (e.g. Chrome, Safari and Epiphany).</p>
<p><a href="http://brianmckenna.org/files/presentations/sydjs-altjs/"><img src="http://brianmckenna.org/blog/static/altjs-1.png" /></a></p>
<p><a href="http://brianmckenna.org/files/presentations/sydjs-altjs/"><img src="http://brianmckenna.org/blog/static/altjs-2.png" /></a></p>
<p><a href="http://brianmckenna.org/files/presentations/sydjs-altjs/"><img src="http://brianmckenna.org/blog/static/altjs-3.png" /></a></p>
<p><a href="http://brianmckenna.org/files/presentations/sydjs-altjs/"><img src="http://brianmckenna.org/blog/static/altjs-4.png" /></a></p>
<p><a href="http://brianmckenna.org/files/presentations/sydjs-altjs/"><img src="http://brianmckenna.org/blog/static/altjs-5.png" /></a></p>]]></summary>
</entry>
<entry>
    <title>BigText Slideshow</title>
    <link href="https://brianmckenna.org/blog/bigtext_slideshow" />
    <id>https://brianmckenna.org/blog/bigtext_slideshow</id>
    <published>2011-11-13T00:00:00Z</published>
    <updated>2011-11-13T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p><a href="http://www.sydjs.com/">SydJS</a> is on Wednesday and I’m giving a talk about <a href="http://altjs.org/">altJS</a> languages. I recently read Zach Holman’s <a href="http://zachholman.com/posts/slide-design-for-developers/">Slide Design for Developers</a> and my biggest enlightenments were:</p>
<ul>
<li>Make text huge</li>
<li>Words as shapes</li>
</ul>
<p>I wanted to experiment with the layout of my slides and focus completely on those. I tried doing it with Keynote and OpenOffice but they weren’t making it very easy to create the style I wanted.</p>
<p>I thought doing it in HTML5 and JavaScript would be much easier. There is an awesome library called <a href="http://www.zachleat.com/web/bigtext-makes-text-big/">BigText</a>, it resizes the CSS font-sizeuntil text fits to the container width - perfect for what I wanted.</p>
<p>I’ve been working on the SydJS slides for a while but tonight I extracted the skeleton and wrote a quick demo:</p>
<p><a href="http://brianmckenna.org/blog/static/bigtext-slideshow/"><img src="http://brianmckenna.org/blog/static/bigtext-slideshow-1.png" /></a></p>
<p><a href="http://brianmckenna.org/blog/static/bigtext-slideshow/"><img src="http://brianmckenna.org/blog/static/bigtext-slideshow-2.png" /></a></p>
<p><a href="http://brianmckenna.org/blog/static/bigtext-slideshow/"><img src="http://brianmckenna.org/blog/static/bigtext-slideshow-3.png" /></a></p>
<p>I’ve uploaded the <a href="http://brianmckenna.org/blog/static/bigtext-slideshow/">demo online</a>. If you want to create your own presentation, clone the skeleton from <a href="https://bitbucket.org/puffnfresh/bigtext-slideshow">Bitbucket</a>.</p>]]></summary>
</entry>
<entry>
    <title>S-expression Compiler in Scala</title>
    <link href="https://brianmckenna.org/blog/sexp_scala" />
    <id>https://brianmckenna.org/blog/sexp_scala</id>
    <published>2011-11-06T00:00:00Z</published>
    <updated>2011-11-06T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p><a href="http://en.wikipedia.org/wiki/John_McCarthy_(computer_scientist)">John McCarthy</a> passed away a few weeks ago. For those unfamiliar, he invented Lisp.</p>
<p>After I heard the news, I wondered how hard would it be to create a tiny Lisp in Scala. I imagined that Scala’s <a href="http://www.codecommit.com/blog/scala/the-magic-behind-parser-combinators">parser combinators</a> would make it very simple.</p>
<p>And then I remembered a project called <a href="https://github.com/qmx/jitescript">Jitescript</a>. Jitescript is a DSL inspired by Ruby’s <a href="https://github.com/headius/bitescript">BiteScript</a>. Both are very simple ways to output JVM bytecode.</p>
<p>So, I set out to write a Lisp to JVM bytecode compiler. I managed to fit it into 63 lines of code. Sure, it’s not going to compete with <a href="http://clojure.org/">Clojure</a> any time soon but I think it shows how easy it is to write a JVM language. I think we could make it even nicer by adding some Scala magic to Jitescript.</p>
<p>You put the S-expression as an argument to the <a href="https://github.com/harrah/xsbt/wiki">SBT</a> REPL:</p>
<pre><code>&gt; run (- (- (+ (- (+ 99 11) 10) 11) 10) 10)</code></pre>
<p>And then run the Lisp.class:</p>
<pre><code>$ java Lisp
91</code></pre>
<p>(Works out to <a href="http://en.wikipedia.org/wiki/McCarthy_91_function">the number 91</a>)</p>
<p>Here are the 63 lines of Scala:</p>
<pre><code>package scalispa

import util.parsing.combinator.RegexParsers

import java.io.{ File, FileOutputStream, PrintStream }

import me.qmx.jitescript.{ JiteClass, CodeBlock }
import me.qmx.jitescript.util.CodegenUtils.{ p, ci, sig }

import org.objectweb.asm.Opcodes._

sealed trait Node
case class SExp(l: List[Node]) extends Node
case class SInt(i: Int) extends Node
case class SIdent(s: String) extends Node

object Parser extends RegexParsers {
  def int = regex(&quot;&quot;&quot;[0-9]+&quot;&quot;&quot;.r) ^^ { (i: String) =&gt; SInt(i.toInt) }
  def ident = regex(&quot;&quot;&quot;[A-Za-z+-/\*]+&quot;&quot;&quot;.r) ^^ SIdent
  def sexp = &quot;(&quot; ~&gt; rep(node) &lt;~ &quot;)&quot; ^^ SExp
  def node: Parser[Node] = int | ident | sexp
  def apply(s: String) = parse(sexp, s)
}

object Evaluator {
  def compile(b: CodeBlock, n: Node) {
    n match {
      case SExp(Nil) =&gt; {}
      case SExp(x :: xs) =&gt; {
        xs.foreach(compile(b, _))
        compile(b, x)
      }
      case SInt(x) =&gt; b.pushInt(x)
      case SIdent(&quot;+&quot;) =&gt; b.iadd()
      case SIdent(&quot;-&quot;) =&gt; b.isub()
      case SIdent(&quot;*&quot;) =&gt; b.imul()
      case SIdent(&quot;/&quot;) =&gt; b.idiv()
    }
  }

  def apply(program: SExp) {
    val b = new CodeBlock
    compile(b, program)
    b.iprintln().voidreturn()

    val name = &quot;Lisp&quot;
    val c = new JiteClass(name)
    c.defineMethod(&quot;main&quot;, ACC_PUBLIC | ACC_STATIC, sig(classOf[Unit], classOf[Array[String]]), b)

    val stream = new FileOutputStream(new File(name + &quot;.class&quot;))
    stream.write(c.toBytes)
    stream.close()
  }
}

object Main {
  def main(args: Array[String]) {
    Parser(args mkString &quot; &quot;) match {
      case Parser.Success(p, _) =&gt; Evaluator(p)
      case a =&gt; println(a)
    }
  }
}</code></pre>
<p>The code is up on Bitbucket, under the unimaginative repo name of <a href="https://bitbucket.org/puffnfresh/scalispa">Scalispa</a>. Let me know what you think!</p>]]></summary>
</entry>
<entry>
    <title>Launch48 Sydney</title>
    <link href="https://brianmckenna.org/blog/launch48" />
    <id>https://brianmckenna.org/blog/launch48</id>
    <published>2011-10-30T00:00:00Z</published>
    <updated>2011-10-30T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I just finished 48 hours of <a href="http://sydney.launch48.com/">Launch48 Sydney</a>.</p>
<p>Friday night at 6pm we heard around 20 pitches, voted and then heard more from the top 8. We voted again and split up into 4 teams:</p>
<ul>
<li>Social pet sitting</li>
<li>Social trips</li>
<li>Social gifts</li>
<li>Social volunteer network</li>
</ul>
<p>Notice a social trend?</p>
<p>I chose to be part of the group working on the volunteer network. The idea was to create something a little bit like <a href="http://stackoverflow.com/">StackOverflow</a> but instead of questions/answers we have charities/volunteers.</p>
<p>Charities add their initiatives. Volunteers browse initiatives, choose to participate and receive points that are shown on their profile. The idea is to help get people hooked into contributing to charities.</p>
<p>Our group of 9 built an initial version, put it up on <a href="http://ninefold.com/">Ninefold</a> and made available at <a href="http://www.happytri.be/">HappyTri.be</a>. The main technology used was <a href="http://www.python.org/">Python</a>, <a href="https://www.djangoproject.com/">Django</a> and <a href="http://pinaxproject.com/">Pinax</a>.</p>
<p>Launch48 was a great way for me to get involved in a startup. I had fun, created something interesting, learned some new skills and uncovered something that I think is a big opportunity. I definitely recommend it.</p>]]></summary>
</entry>
<entry>
    <title>Roy - Type Aliases</title>
    <link href="https://brianmckenna.org/blog/roy_aliases" />
    <id>https://brianmckenna.org/blog/roy_aliases</id>
    <published>2011-10-23T00:00:00Z</published>
    <updated>2011-10-23T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Roy now has a form of type aliasing. You can give names to types, like so:</p>
<pre><code>type Name = String
type Animal = {name: Name, legs: Number}
let zebra: Animal = {name: &quot;Zebra&quot;, legs: 4}</code></pre>
<p>The benefits are mainly for structural types:</p>
<ol type="1">
<li>You don’t have to type out a long structure whenever you want to be explicit</li>
<li>Better error messages</li>
</ol>
<p>For example, this is a poorly typed program without an alias:</p>
<pre><code>let getName x = x.firstName ++ x.lastName
console.log (getName {})</code></pre>
<p>And this is the error message:</p>
<pre><code>Type error: {} is not {firstName: String, lastName: String}</code></pre>
<p>You can imagine the error would be kind of scary if the structure was heavily nested or had more than just a couple of elements.</p>
<p>This is a poorly typed program with an alias:</p>
<pre><code>type Person = {firstName: String, lastName: String}
let getName (x: Person) = x.firstName ++ x.lastName
console.log (getName {})</code></pre>
<p>And this is the nicer error message:</p>
<pre><code>Type error: {} is not Person</code></pre>
<p>I originally wanted inference to use the scope to check which aliases it could satisfy and use the most appropriate:</p>
<pre><code>type Person = {firstName: String, lastName: String}
// `x` is inferred to be Person from the scope
let getName x = x.firstName ++ x.lastName</code></pre>
<p>Which is something that <a href="http://mth.github.com/yeti/">Yeti</a> is <a href="https://groups.google.com/d/topic/yeti-lang/evblC5cnz5E/discussion">able to do</a>. Instead, I implemented a very simple version that will just propogate explicit aliases. Using the simple version might conflict with my future plans.</p>
<p>Later on I hope to be able to use the type aliases to output nicer JavaScript:</p>
<pre><code> // Roy: type Person = {firstName: String, lastName: String}
 var Person = function(firstName, lastName) {
     this.firstName = firstName;
     this.lastName = lastName;
 };</code></pre>
<p>And I might even be able to extend aliases to output information about the hierarchy:</p>
<pre><code>// Hypothetical Roy: type Employee = Person with {wage: Number}
var Employee = function(firstName, lastName, wage) {
    Person.call(this, firstName, lastName);
    this.wage = wage;
};
// Just for documentation:
Employee.prototype = new Person();</code></pre>
<p>But maybe not. I’ll have to try it out.</p>
<p>In adding aliases, I fixed something that I wanted to do for a while; using structural types for normal type annotations:</p>
<pre><code>let getName (x: {name: String}) = x.name
console.log (getName {name: &quot;TEST&quot;})</code></pre>
<p>Let me know what you think.</p>]]></summary>
</entry>
<entry>
    <title>Roy - Tuples</title>
    <link href="https://brianmckenna.org/blog/roy_tuples" />
    <id>https://brianmckenna.org/blog/roy_tuples</id>
    <published>2011-10-16T00:00:00Z</published>
    <updated>2011-10-16T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Tuples could be implemented in Roy a couple of different ways. The first way is using the ADT support:</p>
<pre><code>data Tuple a b = Tuple2 a b</code></pre>
<p>I could add some syntactic sugar on top to completely hide the data type.</p>
<p>The second way would be to use a structure, something like this:</p>
<pre><code>type Tuple2 a b = {0: a, 1: b}</code></pre>
<p>(The above isn’t valid Roy code, I don’t have type aliases in yet)</p>
<p>I could also add sugar to hide this method. Pretty similar to what ML does.</p>
<p>Because of JavaScript’s property access, I can actually compile tuples to JavaScript arrays very easily. That means this:</p>
<pre><code>let x = (1, true, &quot;three&quot;)</code></pre>
<p>Can compile to this:</p>
<pre><code>var x = [1, true, &quot;three&quot;];</code></pre>
<p>And still compile down as if it was a structure with numeric keys:</p>
<pre><code>x[0] == 1
x[1] == true
x[2] == &quot;three&quot;</code></pre>
<p>An interesting part of the structural approach is that higher-arity tuples are subtypes of lesser-arity tuples. For example <code>(1, 2, 3)</code> is a subtype of <code>(4, 5)</code>. I’m not sure if this is good or bad thing but ML seems to get away with it.</p>
<p>I’m currently running with the structural way of implementing tuples. I think that having two different possibilities shows a problem with Roy - it doesn’t make sense to have two ways of constructing product types. I should just go the ML way and have ADT options only take up to a single parameter.</p>]]></summary>
</entry>
<entry>
    <title>Roy - Deep Pattern Matching</title>
    <link href="https://brianmckenna.org/blog/roy_deep_matching" />
    <id>https://brianmckenna.org/blog/roy_deep_matching</id>
    <published>2011-10-09T00:00:00Z</published>
    <updated>2011-10-09T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Roy now has deep pattern matching. That means you can write things like:</p>
<pre><code>let xor e = match e
  case (Left (Left n)) = 0
  case (Left (Right n)) = n
  case (Right (Left n)) = n
  case (Right (Right n)) = 0

console.log (xor (Left (Left 100)))
console.log (xor (Left (Right 100)))
console.log (xor (Right (Left 100)))
console.log (xor (Right (Right 100)))</code></pre>
<p>Which wil output:</p>
<pre><code>0
100
100
0</code></pre>
<p>Here’s some code I wrote while trying to break it:</p>
<pre><code>let x a = match a
  case (Some (Some (Some s))) = s
  case (Some (Some None)) = 0
  case (Some None) = 0
  case None = 0

// Doesn&#39;t compile:
// console.log (x (Some (Some (Some None))))

console.log (x (Some (Some (Some 42))))
console.log (x (Some (Some None)))
console.log (x (Some None))
console.log (x None)


data Tuple a b c = Tuple2 a b | Tuple3 a b c

let addTuple t = match t
  case (Tuple3 a (Tuple3 b c d) e) = b + c + d
  case (Tuple3 a (Tuple2 b c) d) = b + c
  case (Tuple2 a (Tuple3 b c d)) = b + c + d
  case (Tuple2 a (Tuple2 b c) d) = b + c

console.log (addTuple (Tuple3 &quot;addTuple&quot; (Tuple2 1 2) &quot;addTuple&quot;))
console.log (addTuple (Tuple3 &quot;addTuple&quot; (Tuple3 1 2 3) &quot;adsf&quot;))
console.log (addTuple (Tuple2 &quot;addTuple&quot; (Tuple2 1 2)))
console.log (addTuple (Tuple2 &quot;addTuple&quot; (Tuple3 1 2 3)))</code></pre>
<p>Both functions broke the type checking but now work.</p>
<p>I’ve been working on just deep matching for the past week. I really need to start proving parts of Roy’s type system instead of just writing it in JavaScript and hoping it works (and makes sense).</p>]]></summary>
</entry>
<entry>
    <title>Roy Improvements</title>
    <link href="https://brianmckenna.org/blog/roy_improvements" />
    <id>https://brianmckenna.org/blog/roy_improvements</id>
    <published>2011-10-02T00:00:00Z</published>
    <updated>2011-10-02T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>A few people expressed interest in Roy this week. One person had some feature requests so I started working on it again after a delay of over 2 months.</p>
<h3 id="the-with-keyword">The <code>with</code> keyword</h3>
<p>Roy is built on the idea of <a href="roy_structural">structural typing</a>. Up until now Roy didn’t have a nice way of extending structures - users had to do this:</p>
<pre><code>let addWorldField o = {hello: o.hello, world: false}

// type is: Function({hello: Boolean},{hello: Boolean, world: Boolean})

console.log (addWorldField {hello: true})</code></pre>
<p>Pretty ugly. My solution was steal the <code>with</code> keyword from <a href="http://mth.github.com/yeti/">Yeti</a>:</p>
<pre><code>console.log (addWorldField {hello: true} with {world: false})</code></pre>
<h3 id="bug-fixes">Bug fixes</h3>
<p>Along with implementing the <code>with</code> keyword, I fixed some more bugs.</p>
<p>A huge one that had been annoying me for a long time, was a problem with type-checking tags:</p>
<pre><code>// Fixed bug with unification over tags
console.log (Some 1)
console.log (Some &quot;Test&quot;)</code></pre>
<p>When using the REPL or running .roy files with the ‘-r’ flag, the standard library wasn’t imported.</p>
<h3 id="future">Future</h3>
<p>Coming up next in Roy:</p>
<ul>
<li>Mutable references</li>
<li>Deep pattern matching</li>
</ul>
<p>Hopefully I’ll have even more to show next week!</p>]]></summary>
</entry>
<entry>
    <title>Time Lapse</title>
    <link href="https://brianmckenna.org/blog/time_lapse" />
    <id>https://brianmckenna.org/blog/time_lapse</id>
    <published>2011-09-25T00:00:00Z</published>
    <updated>2011-09-25T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I took a screenshot every minute while I was working on last week’s <a href="pyweek_13">PyWeek entry</a>. I used those screenshots to create a time-lapse video:</p>
<iframe width="640" height="360" src="http://www.youtube.com/embed/VDThwoRWk7o" frameborder="0" allowfullscreen>
</iframe>
<p>The above video is made up of about 20 hours worth of screenshots, compressed down to 2 minutes.</p>
<p>I cleaned up the scripts I wrote and pushed them to <a href="https://bitbucket.org/puffnfresh/timelapser">Bitbucket</a>. Works on both Linux and Mac OS X.</p>]]></summary>
</entry>
<entry>
    <title>PyWeek #13</title>
    <link href="https://brianmckenna.org/blog/pyweek_13" />
    <id>https://brianmckenna.org/blog/pyweek_13</id>
    <published>2011-09-18T00:00:00Z</published>
    <updated>2011-09-18T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Today was the last day of PyWeek #13. I entered in a team that included four other graduate developers from <a href="http://www.atlassian.com/">work</a>.</p>
<p>The theme was “Mutate!” - we got together and came up with the concept of a tower defence game that used a genetic algorithm to evolve.</p>
<p>We named the game “Smooth Jazz Tower Defence”. Here are the instructions form the README:</p>
<blockquote>
<p>This is a tower defence game with a twist: creeps mutate! The game uses a
genetic algorithm to select the best creeps and breed them together. A little
bit of mutation is thrown in for a bit of spice, just like in evolution.</p>
<p>For both creeps and turrets, colours signify the specialties:</p>
</blockquote>
<blockquote>
<ul>
<li>Red: health</li>
<li>Blue: armour</li>
<li>Green: speed</li>
</ul>
</blockquote>
<blockquote>
<p>A good first strategy is to place one of each turret at the start of the map.</p>
</blockquote>
<blockquote>
<p>To place a turret, click its icon from the right side of the screen. Hover your
cursor over a bright red square and click.</p>
</blockquote>
<blockquote>
<p>Sit back, relax and let the smooth jazz sooth your soul.</p>
</blockquote>
<p>I’ve uploaded a video of the game <a href="http://www.youtube.com/watch?v=UcnVr_XKv3M">to YouTube</a>:</p>
<p><a href="http://www.youtube.com/watch?v=UcnVr_XKv3M"><img src="http://i1.ytimg.com/vi/UcnVr_XKv3M/0.jpg" /></a></p>
<p>The game runs on Windows, Mac, Linux and anything else that supports Pyglet. Download links are on our <a href="http://pyweek.org/e/gradlassians/">PyWeek page</a>.</p>]]></summary>
</entry>
<entry>
    <title>JReversePro</title>
    <link href="https://brianmckenna.org/blog/jrevpro" />
    <id>https://brianmckenna.org/blog/jrevpro</id>
    <published>2011-09-11T00:00:00Z</published>
    <updated>2011-09-11T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve always wanted Emacs to be able to open Java class files. This week I picked up the development of <a href="http://github.com/pufuwozu/jreversepro">JReversePro</a> and wrote a little Emacs interface to it.</p>
<p>I started by looking around for an open-source, command-line Java decompiler. Almost all had no activity since 2004-2008. JReversePro was last touched in January, 2010 so seemed like a good candidate to pick up and continue.</p>
<p>I updated the run scripts, made changes to the spacing, started work on JSR-14 (Adding Generics to the Java Programming Language) and wrote an Emacs script for automatically decompiling .class files.</p>
<p>If you want to try it out, build JReversePro:</p>
<pre><code>git clone https://github.com/pufuwozu/jreversepro.git
cd jreversepro
mvn package</code></pre>
<p>In Emacs, use <code>M-x load-file</code> to load the jrevpro.el file under the scripts directory. Use <code>M-x set-variable jrevpro-script</code> to change the location to the jrevpro script under the same directory. You should now be able to open a .class file and have it automatically decompiled to Java.</p>]]></summary>
</entry>
<entry>
    <title>Cloud9 User Script</title>
    <link href="https://brianmckenna.org/blog/cloud9_user_script" />
    <id>https://brianmckenna.org/blog/cloud9_user_script</id>
    <published>2011-09-04T00:00:00Z</published>
    <updated>2011-09-04T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week I created a user script extension for <a href="http://cloud9ide.com/">Cloud9</a>. The idea is to add something like the Emacs <a href="http://www.emacswiki.org/emacs/InitFile">init file</a>. It could also be thought of something like <a href="https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/">Greasemonkey</a>.</p>
<p>You write some JavaScript and it is executed whenever Cloud9 is loaded. My idea behind this was to be able to extend the editor without changing anything server-side.</p>
<p><a href="https://github.com/pufuwozu/cloud9-userscript/blob/master/README.md">See the README</a> for installation instructions. Once installed, a button will appear on the right dock:</p>
<p><img src="http://brianmckenna.org/blog/static/userscript.png" /></p>
<p>Clicking it will present a code editor. This is where you type in your user script. When you’re ready, press Control+Shift+E to evaluate and save the script.</p>
<p><a href="https://github.com/pufuwozu/cloud9-userscript">Clone the repository</a> and try it out!</p>]]></summary>
</entry>
<entry>
    <title>PyWeek - 8 pixels and Python reloading</title>
    <link href="https://brianmckenna.org/blog/pyweek_8px_reload" />
    <id>https://brianmckenna.org/blog/pyweek_8px_reload</id>
    <published>2011-08-28T00:00:00Z</published>
    <updated>2011-08-28T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’m organising a team entry into <a href="http://pyweek.org/13/">next month’s PyWeek</a> (#13)
- this week I did a bit of preparation.</p>
<h3 id="walk-cycle-in-low-resolution-pixel-art">Walk cycle in low resolution pixel art</h3>
<p>Time is always limited during PyWeek. To make a nice looking game, you
have to be able to rapidly create art. I’ve been working on minimising
the amount of pixels used. I think this has two direct benefits:</p>
<ul>
<li>Low resolution graphics look nice</li>
<li>They are very quick and fairly easy to create</li>
</ul>
<p>Ideally I want less than 8x8 pixel characters but I’ve found that it’s
hard to create a nice looking walk animation with limited pixels. My
first take was to create characters with 1px high legs:</p>
<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle3.gif" /></p>
<p>It’s not very obvious that the character is walking. I thought that
some shading might improve the situation:</p>
<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle4.gif" /></p>
<p>Only a little. Next thought was that the legs just don’t have enough
definition. Adding a knee helped a bit:</p>
<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle2.gif" /></p>
<p>Adding some shading to the legs helped even more:</p>
<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle7.gif" /></p>
<p>But I wanted something more fluent. I wasn’t sure how to create it with
the platformer side/front on view like above but I had an idea of how
I wanted it to look side on:</p>
<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle1Sheet.png" /></p>
<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle1.gif" /></p>
<p>Looks nice! I took the animations of each leg and added it back to the
platformer angle:</p>
<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle5.gif" /></p>
<p>The legs look like a mess half-way into the animation. I thought it
might be caused by the legs being too close together. I moved them
apart by a pixel:</p>
<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle6.gif" /></p>
<p>It actually looks pretty good! But then I thought, is it really much
of an improvement to one of the simpler ones?</p>
<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle7.gif" /> <img src="http://brianmckenna.org/blog/static/8bit/Cycle6.gif" /></p>
<p>In the end, I’m not sure if it’s worth the extra work when you’re
under heavy time constraints.</p>
<h3 id="reloading-python-modules">Reloading Python modules</h3>
<p>This PyWeek I want to try to write the game in a style that will allow
for reloading of parts while it’s running. It turns out that Python
has a <code>reload</code> built-in that’s makes this really simple!</p>
<p>I made a small proof of concept. I created a file called
“constants.py” that included a single constant:</p>
<pre><code>SPEED = 10</code></pre>
<p>I then wrote some game code. Pressing the right key will move the
player to the right by SPEED pixels. Pressing ‘r’ will reload the
constants.py file. Using Pyglet:</p>
<pre><code>#!/usr/bin/env python
import pyglet
import constants

window = pyglet.window.Window()

animation = pyglet.image.load_animation(&#39;Cycle7.gif&#39;)
sprite = pyglet.sprite.Sprite(animation)

@window.event
def on_draw():
    window.clear()
    sprite.draw()

@window.event
def on_key_press(symbol, modifiers):
    if symbol == pyglet.window.key.RIGHT:
        sprite.x += constants.SPEED
    elif symbol == pyglet.window.key.R:
        reload(constants)

pyglet.app.run()</code></pre>
<p>So while running, I can modify constants.py:</p>
<pre><code>SPEED = 100</code></pre>
<p>Then switch back to the game, press ‘r’ and then press the right
button to move the character by 100 pixels! Hopefully this will let
us rapidly play with game values without having to exit and restart
the game.</p>]]></summary>
</entry>
<entry>
    <title>Odd Odd Even Agda Proof</title>
    <link href="https://brianmckenna.org/blog/plus_equals_even" />
    <id>https://brianmckenna.org/blog/plus_equals_even</id>
    <published>2011-08-21T00:00:00Z</published>
    <updated>2011-08-21T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’m reading a book titled “<a href="http://homepages.cwi.nl/~jve/HR/">The Haskell Road to Logic, Maths and Programming</a>”, it teaches Haskell by using logic and logic by using Haskell. I’m using the book to get better at reading and writing proofs. I’m also trying to learn languages like <a href="http://coq.inria.fr/">Coq</a> and <a href="http://wiki.portal.chalmers.se/agda/pmwiki.php">Agda</a> to solve exercises in the book.</p>
<p>One of the first exercises in Chapter 3 (The Use of Logic: Proof) is 3.4:</p>
<ul>
<li>Assume that n and m belong to the set of natural numbers</li>
<li>Show that: if m is odd and n is odd then m + n is even</li>
</ul>
<p>My proof involved:</p>
<ul>
<li>n-1 is even</li>
<li>m-1 is even</li>
<li>2 is even</li>
<li>Thus <code>n-1 + m-1 + 2 = n + m</code> is even</li>
</ul>
<p>I decided to try Agda on this proof. First I needed to define a data type for even and odd numbers. I eventually came up with a mutually recursive definition:</p>
<pre><code>mutual
  data Even : Set where
    zeroE : Even
    succE : Odd -&gt; Even
  data Odd : Set where
    succO : Even -&gt; Odd</code></pre>
<p>The base case is even zero. Every number after is built like so:</p>
<pre><code>succE (succO (succE (succO zeroE)))</code></pre>
<p>This example represents 4 and belongs to the even set.</p>
<p>The above problem has this type signature:</p>
<pre><code>_odd+_ : Odd -&gt; Odd -&gt; Even</code></pre>
<p>That is, an odd plus an odd always equals an even.</p>
<p>The first two cases for this function are easy. If either side is one (succO zeroE), then we just increment the other side, which makes it even:</p>
<pre><code>succO zeroE     odd+ n               = succE n
n               odd+ succO zeroE     = succE n</code></pre>
<p>The last case is a bit confusing. We take 2 off each side to get to the previous odd number, recurse and then add back on the 4 that we subtracted:</p>
<pre><code>succO (succE n) odd+ succO (succE m) = succE (succO (succE (succO (n odd+ m))))</code></pre>
<p>I started writing the proof in Agda but didn’t end up using any dependent types - a unique feature to languages like Agda. My solution could have easily been made by using another language. For example, here is a direct Haskell translation:</p>
<pre><code>data Even = ZeroE | SuccE Odd
data Odd  = SuccO Even

oddPlus :: Odd -&gt; Odd -&gt; Even
oddPlus (SuccO ZeroE) n = SuccE n
oddPlus n (SuccO ZeroE) = SuccE n
oddPlus (SuccO (SuccE n)) (SuccO (SuccE m)) = SuccE $ SuccO $ SuccE $ SuccO $ oddPlus n m</code></pre>
<p>Maybe I’m not familiar enough with dependent types to use them in my solution. I imagine that a larger chunk of the problem could have been encoded into the type system. Hopefully I’ll figure out some tricks as I work through the book.</p>]]></summary>
</entry>
<entry>
    <title>GDD HTML5 Challenge</title>
    <link href="https://brianmckenna.org/blog/html5xgdd" />
    <id>https://brianmckenna.org/blog/html5xgdd</id>
    <published>2011-08-14T00:00:00Z</published>
    <updated>2011-08-14T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week I entered the <a href="https://sites.google.com/site/opencallforgdd/the-challenge-1">Google Developer Day HTML5 challenge</a>. The goal was to use HTML5 to do something interesting with the <a href="http://www.google.com/events/developerday/2011/">Google Developer Day</a> logo (a <a href="http://en.wikipedia.org/wiki/Dymaxion_map">dymaxion map</a>):</p>
<p><img src="http://brianmckenna.org/blog/static/html5xgdd/OpenCallVisual.png" /></p>
<p>Some restrictions:</p>
<ul>
<li>Only HTML5; no plugins</li>
<li>Related to the location of the Developer Day</li>
<li>Licensed under the <a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 Unported License</a></li>
</ul>
<p>I came up with the idea of using WebGL to transform the logo into the <a href="http://en.wikipedia.org/wiki/Sydney_Opera_House">Sydney Opera House</a>. This is what I made:</p>
<p><a href="http://brianmckenna.org/files/html5xgdd/"><img src="http://brianmckenna.org/blog/static/html5xgdd/HTML5xGDD.png" /></a></p>
<h3 id="implementation">Implementation</h3>
<p>I first looked at <a href="https://github.com/mrdoob/three.js/">three.js</a> to see what options there were for using 3D data and animating it. I found that morph animation was added to three.js as part of the <a href="http://ro.me/">RO.ME</a> project. Perfect!</p>
<p>I imported the SVG logo into <a href="http://blender.org/">Blender</a>. I had some troubles at first but it imported nicely after deleting the text from the vector. The next problem was that each edge had many unnecessary vertices.</p>
<p><img src="http://brianmckenna.org/blog/static/html5xgdd/vertices.gif" /></p>
<p>I tried extruding the mesh but the polycount increased to about 5,000 - not very acceptable for morphing. I minimised the original polycount largely by using the <a href="http://wiki.blender.org/index.php/Doc:Manual/Modifiers/Mesh/Decimate">Decimate</a> modifier. Decimate would close up a few of the small holes so I decreased the polycount there by manually merging vertices. I eventually got the extruded polycount down to about 300.</p>
<p><img src="http://brianmckenna.org/blog/static/html5xgdd/decimate.gif" /></p>
<p>For animation, I added a photo of the Opera House as a background for reference. I used shape keys to transform the triangles to corresponding positions/sizes.</p>
<p><img src="http://brianmckenna.org/blog/static/html5xgdd/animation.gif" /></p>
<p>To export, I just had to step through the timeline and export each frame separately. This created 10 obj files that I could use with the three.js conversion script:</p>
<pre><code>python convert_obj_three.py -i frame_00.obj -o Visual.js -m &quot;frame*.obj&quot;</code></pre>
<p>The model could then be used with three.js:</p>
<pre><code>var loader = new THREE.JSONLoader(true);
loader.load({
  model: &quot;Visual.js&quot;,
  callback: function(geometry) {
    // Create material and add to scene
  }
});</code></pre>
<p>I wanted animation to be achieved through “scrubbing” the mouse across the X axis. That was pretty easy to implement using three.js morph targets:</p>
<pre><code>var currentFrame = Math.floor(ratio * framesCount);
var transitionAmount = (ratio * framesCount) % 1;

mesh.morphTargetInfluences[currentFrame] = 1 - transitionAmount;
mesh.morphTargetInfluences[currentFrame + 1] = transitionAmount;</code></pre>
<p>To finish it off, I added some animated three.js particles, a CSS3 gradient for the background and some simple visual cues. I’ve put <a href="http://brianmckenna.org/files/html5xgdd/">my entry</a> live and pushed <a href="https://bitbucket.org/puffnfresh/html5xgdd">the code</a> to Bitbucket.</p>]]></summary>
</entry>
<entry>
    <title>Ringneck - PASM to JS</title>
    <link href="https://brianmckenna.org/blog/ringneck" />
    <id>https://brianmckenna.org/blog/ringneck</id>
    <published>2011-08-07T00:00:00Z</published>
    <updated>2011-08-07T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p><a href="http://parrot.org/">Parrot</a> is designed to be a general purpose virtual machine for dynamic languages. It started as the virtual machine for Perl 6 but <a href="http://trac.parrot.org/parrot/wiki/Languages">many languages</a> are able to target it. I really love that it’s high level enough to have awesome interoperability - for example, you should be able to write a class in Python but subclass it in Ruby.</p>
<p>December of last year I started work on a <a href="http://en.wikipedia.org/wiki/Parrot_assembly_language">Parrot Assembly Language</a> (PASM) to JavaScript compiler called Ringneck. Last week I found it again and now I’m releasing it. The idea was that if many languages compile to PASM, I could get many languages to compile to the web just by compiling PASM to JavaScript.</p>
<p>Ringneck takes PASM like this:</p>
<pre><code>  set     I1, 1
  if      I1, TRUE
  print   &quot;False!\n&quot;

  branch  END
TRUE:
  print   &quot;True!\n&quot;
END:
  end</code></pre>
<p>And compiles to something like this:</p>
<pre><code>var label;
while(true) {
switch(label) {
default:
    opcodes.core.set.apply(null, [{&quot;type&quot;:1,&quot;text&quot;:&quot;I1&quot;,&quot;reg&quot;:&quot;I&quot;,&quot;index&quot;:1},{&quot;type&quot;:2,&quot;text&quot;:&quot;1&quot;,&quot;value&quot;:1}]);
    if(regs[&quot;I&quot;][1].value != 0) {label = &quot;TRUE&quot;; break;}
    opcodes.io.print.apply(null, [{&quot;type&quot;:4,&quot;text&quot;:&quot;\&quot;False!\\n\&quot;&quot;,&quot;value&quot;:&quot;False!\n&quot;}]);
    label = &quot;END&quot;; break;
case &quot;TRUE&quot;:
    opcodes.io.print.apply(null, [{&quot;type&quot;:4,&quot;text&quot;:&quot;\&quot;True!\\n\&quot;&quot;,&quot;value&quot;:&quot;True!\n&quot;}]);
case &quot;END&quot;:
    flush(); return;
}
}</code></pre>
<p>I’ve put a <a href="http://brianmckenna.org/blog/static/ringneck/">demo</a> up. Feel free to <a href="https://bitbucket.org/puffnfresh/ringneck">clone the Bitbucket repo</a>.</p>
<p><img src="http://brianmckenna.org/blog/static/monkey.jpg" /></p>]]></summary>
</entry>
<entry>
    <title>Climacs</title>
    <link href="https://brianmckenna.org/blog/climacs" />
    <id>https://brianmckenna.org/blog/climacs</id>
    <published>2011-07-31T00:00:00Z</published>
    <updated>2011-07-31T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week I tried creating an application with ClojureScript and Google Closure. One idea I’ve had for a while is an extensible HTML5 text editor.</p>
<p>I’m an avid Emacs user because Emacs is extremely extensible; I’m able to write some Lisp to make Emacs work exactly as I like. I wanted the same concept to be core to my toy editor, you write some JavaScript and extend the editor at runtime.</p>
<p>I didn’t get very far because I was constantly running into problems with DOM Ranges. What I did achieve was syntax highlighting (via parse-js.js in UglifyJS) and JavaScript evaluation:</p>
<p><img src="http://brianmckenna.org/blog/static/climacs/screenshot.png" /></p>
<p>I’ve put a <a href="http://brianmckenna.org/blog/static/climacs/">demo up</a> and <a href="https://bitbucket.org/puffnfresh/climacs">the code</a> is on Bitbucket. Only tested in Chrome. Editing is very limited and will only work on a single line. Evaluate your JavaScript with CTRL/CMD+J.</p>]]></summary>
</entry>
<entry>
    <title>Escaping Callback Hell with ClojureScript macros</title>
    <link href="https://brianmckenna.org/blog/cps_transform_js" />
    <id>https://brianmckenna.org/blog/cps_transform_js</id>
    <published>2011-07-24T00:00:00Z</published>
    <updated>2011-07-24T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p><a href="http://meta2.tumblr.com/post/787368639/javascript-needs-macros">JavaScript needs macros</a>. I’ve thought this for a long time. This week <a href="http://en.wikipedia.org/wiki/Rich_Hickey">Rich Hickey</a> announced and released <a href="https://github.com/clojure/clojurescript">ClojureScript</a>, a version of <a href="http://clojure.org/">Clojure</a> that compiles to JavaScript! I’m going to try and use ClojureScript’s macro system to overcome one of my JavaScript frustrations.</p>
<p>I like the fact that JavaScript is highly event based but code can easily become <em>callback hell</em>. Take this for example:</p>
<pre><code>app.get(&#39;/index&#39;, function(req, res, next) {
    User.get(req.params.userId, function(err, user) {
        if(err) next(err);
        db.find({user: user.name}, function(err, cursor) {
            if(err) next(err);
            cursor.toArray(function(err, items) {
                if(err) next(err);
                res.send(items);
            });
        });
    });
});</code></pre>
<p>Yuck! Let’s try to fix this with a simpler example. Here are the goals:</p>
<ul>
<li>Write a sequence of function calls</li>
<li>Have each call be wrapped with an asynchronous timeout callback</li>
</ul>
<p>In the end, I want to be able to write code like this:</p>
<pre><code>(timeout/timeout-macro
   (pn &quot;Hello&quot;)
   (pn &quot;World&quot;)
   (p &quot;Hello&quot;)
   (p &quot; &quot;)
   (p &quot;world&quot;)
   (p &quot;!&quot;)
   (p &quot;!&quot;)
   (pn &quot;!&quot;)
   (pn (+ 1 2 3))
   (pn &quot;Done&quot;))</code></pre>
<p>Lisps are great at solving this problem because they are <a href="http://en.wikipedia.org/wiki/Homoiconicity">homoiconic</a>. They can have powerful macro systems because code can be transformed exactly the same as data. Here is the macro I wrote for this problem:</p>
<pre><code>(defmacro timeout-macro [&amp; body]
  (reduce
   (fn [x y]
     `(timer/callOnce (fn [] ~x ~y) 1000))
   `(fn [])
   (reverse body)))</code></pre>
<p>With the macro, ClojureScript transforms the function calls above into some awesomely ugly JavaScript:</p>
<pre><code>callOnce.call(null, (function () {
  callOnce.call(null, (function () {
    callOnce.call(null, (function () {
      callOnce.call(null, (function () {
        callOnce.call(null, (function () {
          callOnce.call(null, (function () {
            callOnce.call(null, (function () {
              callOnce.call(null, (function () {
                callOnce.call(null, (function () {
                  callOnce.call(null, (function () {
                    return pn.call(null, &quot;Done&quot;);
                  }), 1000);
                  return pn.call(null, cljs.core._PLUS_.call(null, 1, 2, 3));
                }), 1000);
                return pn.call(null, &quot;!&quot;);
              }), 1000);
              return p.call(null, &quot;!&quot;);
            }), 1000);
            return p.call(null, &quot;!&quot;);
          }), 1000);
          return p.call(null, &quot;world&quot;);
        }), 1000);
        return p.call(null, &quot; &quot;);
      }), 1000);
      return p.call(null, &quot;Hello&quot;);
    }), 1000);
    return pn.call(null, &quot;World&quot;);
  }), 1000);
  return pn.call(null, &quot;Hello&quot;);
}), 1000);</code></pre>
<p>This is known as an automatic <a href="http://en.wikipedia.org/wiki/Continuation-passing_style">continuation-passing style</a> (CPS) transform. I’ve put the <a href="http://brianmckenna.org/blog/static/clojurescript-timeout-cps/">demo up here</a> and posted the <a href="https://bitbucket.org/puffnfresh/clojurescript-timeout-cps">code up on Bitbucket</a>.</p>]]></summary>
</entry>
<entry>
    <title>Roy - Tests (finally)</title>
    <link href="https://brianmckenna.org/blog/roy_tests" />
    <id>https://brianmckenna.org/blog/roy_tests</id>
    <published>2011-07-17T00:00:00Z</published>
    <updated>2011-07-17T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Anybody following along could probably tell that I’m not practising <a href="http://en.wikipedia.org/wiki/Test-driven_development">TDD</a> with Roy. Only this week I started writing some tests. As expected, I’m finding lots of bugs!</p>
<p>I’m going to work on cleaning it up but the test runner currently stands at 24 lines of Roy code:</p>
<pre><code>let fs = require &#39;fs&#39;
let path = require &#39;path&#39;
let child_process = require &#39;child_process&#39;

let dir = &quot;test&quot;
let files = fs.readdirSync dir

let tests = files.filter (fn x =
  (x.lastIndexOf &#39;.roy&#39;) == (x.length - 4)
)

tests.forEach (fn t =
  let name = path.join dir t
  let outFile = (path.join dir (path.basename t &#39;.roy&#39;)) ++ &#39;.out&#39;
  child_process.exec &#39;./roy -r &#39; ++ name (fn error stdout stderr =
    if error then
      console.log &quot;Error:&quot; error.message
    else
      let expected = fs.readFileSync outFile &#39;utf8&#39;
      let actual = stdout.toString ()
      console.assert actual == expected &quot;Output of &quot; ++ t ++ &quot;: &quot; ++ (JSON.stringify actual) ++ &quot; does not match &quot; ++ (JSON.stringify expected)
      console.log &quot;Pass:&quot; name
  )
)</code></pre>
<p>Not too ugly. It seems like some standard library functions could make it nicer.</p>]]></summary>
</entry>
<entry>
    <title>Learn Nintendo DS a Haskell</title>
    <link href="https://brianmckenna.org/blog/learn_nintendo_ds_a_haskell" />
    <id>https://brianmckenna.org/blog/learn_nintendo_ds_a_haskell</id>
    <published>2011-07-10T00:00:00Z</published>
    <updated>2011-07-10T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This weekend was <a href="http://www.haskell.org/haskellwiki/AusHac2011">AusHac 2011</a>. I spent my time getting Haskell to compile to the Nintendo DS.</p>
<p>I remember reading a while ago about someone using <a href="http://repetae.net/computer/jhc/">JHC</a> to compile a Haskell executable for the iPhone. JHC is a Haskell compiler that outputs fairly sane C code. I figured that it’d be fairly easy to get it to output code to work with <a href="http://devkitpro.org/">devkitPro</a>.</p>
<p>I had <a href="http://twitter.com/puffnfresh/status/17348921600778240">a quick version</a> of this project working in December but I lost the patches and wanted to make a better version.</p>
<p>After a days work I had something compiling and I spent another day playing around with it. I think I created the world’s most annoying Haskell program:</p>
<p><img src="http://brianmckenna.org/blog/static/haskell-nds/screenshot.gif" /></p>
<p>It is much more annoying running on a physical DS:</p>
<p><img src="http://brianmckenna.org/blog/static/haskell-nds/20110710_210754.jpg" /></p>
<p>I’ve uploaded <a href="http://brianmckenna.org/blog/static/haskell-nds/haskell-nds.nds">the binary</a> for people to try out. I’ve put <a href="https://bitbucket.org/puffnfresh/haskell-nds">the example project</a> up on Bitbucket. The main Haskell for the example is:</p>
<pre><code>printFreq freq = do
  consoleClear
  print freq

setSound sound freq = do
  soundSetFreq sound freq
  printFreq freq

keyLoop sound = do
  x &lt;- keyboardUpdate
  scanKeys
  if x &gt; 0 then do
    setSound sound $ x * 100
    putChar $ chr x
  else if isTouching then do
    if getTouchY &lt; 110 then do
      setSound sound $ getTouchY * 100
      print getTouchY
    else
      return ()
    r &lt;- randomRIO (0, 31)
    oamMainColor r 0 0
    oamMainSet getTouchX getTouchY
  else
    return ()

  swiWaitForVBlank
  oamMainUpdate
  keyLoop sound

main = do
  consoleDemoInit
  keyboardDemoInit
  keyboardShow
  soundEnable
  sound &lt;- soundPlayPSG dutyCycle_50 10000 127 64
  oamMainInit
  keyLoop sound</code></pre>
<p>To compile you have to <a href="http://devkitpro.org/wiki/Getting_Started/devkitARM">setup devkitARM</a> with my <a href="http://sourceforge.net/tracker/download.php?group_id=114505&amp;atid=668551&amp;file_id=417645&amp;aid=3361239">patch to libnds</a>. You then need to <a href="http://repetae.net/computer/jhc/development.shtml">setup JHC</a> with my <a href="http://www.haskell.org/pipermail/jhc/attachments/20110710/11fc461d/attachment.obj">DARCS patch</a>. I’ve forwarded the patches on so hopefully it will just work in the future!</p>
<p>Before this project, it was possible to run <a href="http://blog.closuretohome.com/2007/12/hugs-for-nintendo-ds.html">Hugs</a> on the DS. While I think that is really awesome, I took the JHC approach for a few reasons:</p>
<ol type="1">
<li>I couldn’t figure out an easy way to access C libraries from Hugs.</li>
<li>I wasn’t sure how to make Hugs jump straight to executing custom Haskell code.</li>
<li>Hugs is interpreted. I had a feeling that compiling to C and using GCC would give better performance.</li>
</ol>
<p>Although the above example code is fairly ugly, I’m very confident that a nice DSL could be created for writing games. I’d love to see this happen.</p>]]></summary>
</entry>
<entry>
    <title>Roy - Meta-programming and a REPL</title>
    <link href="https://brianmckenna.org/blog/roy_repl_macros" />
    <id>https://brianmckenna.org/blog/roy_repl_macros</id>
    <published>2011-07-03T00:00:00Z</published>
    <updated>2011-07-03T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Roy now has a limited, <a href="http://en.wikipedia.org/wiki/Metaprogramming">compile-time meta-programming</a> system. Simple example:</p>
<pre><code>macro printArgLength =
  console.log &quot;Compiling to:&quot; arguments.length
  [| console.log &amp;(arguments.length) |]

printArgLength 1
printArgLength 1 2
printArgLength 1 2 3</code></pre>
<p>The code above will output messages during compilation. This is the JavaScript output:</p>
<pre><code>console.log(1)
console.log(2)
console.log(3)</code></pre>
<p>I’d really like to make Roy’s meta-programming work more like <a href="http://www.haskell.org/ghc/docs/7.0.2/html/users_guide/template-haskell.html">Template Haskell</a> or <a href="http://convergepl.org/documentation/1.2/ctmp/">Converge</a>. Unfortunately I have only skimmed papers on both and used neither. My goal is to make the meta-programming powerful enough to express <a href="http://meta2.tumblr.com/post/787368639/javascript-needs-macros">modules</a> and <a href="roy_monad_syntax">do notation</a>.</p>
<p>I also built a <a href="http://en.wikipedia.org/wiki/Read-eval-print_loop">REPL</a> for Roy in about 20 minutes. Amazing how simple it is to create a nice REPL in <a href="http://nodejs.org/">node.js</a> by using the readline module.</p>
<pre><code>$ ./roy
roy&gt; 10 * 2 - 5
15 : Number
roy&gt; </code></pre>]]></summary>
</entry>
<entry>
    <title>Roy - Standard Library</title>
    <link href="https://brianmckenna.org/blog/roy_standard_library" />
    <id>https://brianmckenna.org/blog/roy_standard_library</id>
    <published>2011-06-26T00:00:00Z</published>
    <updated>2011-06-26T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I spent a large chunk of this week trying to create modules in <a href="http://roy.brianmckenna.org/">Roy</a>. I’ve thought of countless ways to try and implement them but none of the solutions have been very good. I have two fundamental problems:</p>
<ol type="1">
<li>JavaScript itself doesn’t support modules</li>
<li>Roy needs static type information to be useful</li>
</ol>
<p>To illustrate the problem, in CommonJS we do this:</p>
<pre><code>var x = require(&#39;./x&#39;);
exports.a = x.y;
exports.b = 1;</code></pre>
<p>In the browser we do this:</p>
<pre><code>window.m = {a: window.x.y, b: 1};</code></pre>
<p>How do we create a solution that imports/exports type information across both?</p>
<p>I don’t think it’s possible. I might have to resort to making the Roy compiler modal (CommonJS or bowser modes).</p>
<p>That problem aside. I did commit something this week - the start of a standard library:</p>
<pre><code>console.log (id 1) // 1
console.log (odd 2) // false

console.log (maybe 0 id None) // 0

console.log (head (tail (replicate 10 &#39;a&#39;))) // a</code></pre>
<p>While writing the standard library I’ve found a lot of holes in the type system. I’ll try to fix them for next week!</p>]]></summary>
</entry>
<entry>
    <title>Roy - Monad Syntax</title>
    <link href="https://brianmckenna.org/blog/roy_monad_syntax" />
    <id>https://brianmckenna.org/blog/roy_monad_syntax</id>
    <published>2011-06-19T00:00:00Z</published>
    <updated>2011-06-19T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I added monad syntax to <a href="http://roy.brianmckenna.org/">Roy</a>. It is very close to <a href="http://en.wikipedia.org/wiki/Monad_(functional_programming)#do-notation">do-notation</a>, with the exception that the monad implementation is explicit:</p>
<pre><code>data Option a =
  Some a | None

let optionMonad = {
  return: fn x =
    Some x
  bind: fn x f = match x
    case (Some a) = f a
    case None = None
}

console.log (do optionMonad
  bind x = Some 1
  let y = 2
  bind z = Some 3
  return x + y + z
)</code></pre>
<p>Note the <code>do optionMonad</code>. Explicitness is only necessary because Roy doesn’t have any form of interfaces or type classes. An upside is that a single datatype could have multiple monad implementations, something not allowed in most other languages.</p>
<p>I also worked on prettying up the JS output. It now looks like this:</p>
<pre><code>&quot;use strict&quot;;
var Some = function(a){this._0 = a};
var None = function(){};
var optionMonad = {
    &quot;return&quot;: function(x) {
        return new Some(x);
    },
    &quot;bind&quot;: function(x, f) {
        return (function() {
            if(x instanceof Some) {
                var a = x._0;
                return f(a)
            } else if(x instanceof None) {
                return new None()
            }
        })();
    }
};
console.log((function(){
    var __monad__ = optionMonad;
    return __monad__[&quot;bind&quot;](new Some(1), function(x) {
        var y = 2;
        return __monad__[&quot;bind&quot;](new Some(3), function(z) {
            return __monad__[&quot;return&quot;](x + y + z);
        });
    });
})())</code></pre>]]></summary>
</entry>
<entry>
    <title>Roy - Structural Typing</title>
    <link href="https://brianmckenna.org/blog/roy_structural" />
    <id>https://brianmckenna.org/blog/roy_structural</id>
    <published>2011-06-12T00:00:00Z</published>
    <updated>2011-06-12T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week I implemented very simple <a href="http://en.wikipedia.org/wiki/Structural_type_system">structural typing</a> in Roy and <a href="http://roy.brianmckenna.org/">created a website for the project</a>.</p>
<p>Structural typing is a really awesome type system feature. Here’s an example:</p>
<pre><code>let obj = {x: 1, y: 2, t: &quot;test&quot;}

let getX a = a.x + 2

console.log (getX obj)
console.log (obj.x + obj.y)

let plusXY a = a.x + a.y
console.log (plusXY obj)
console.log (plusXY {x: 2, y: 1})

let makeXY x y = {x: x, y: y}
console.log (plusXY (makeXY 1 2))
console.log (makeXY 1 2)

// Won&#39;t compile
// plusXY {x: 1, z: 2}

console.log ((fn obj = obj.a.a + obj.a.b) {a: {a: 1, b: 2}})

let makeFun a = {f: fn b = a.x + b.y}
console.log ((makeFun {x: 1}).f {y: 2})</code></pre>
<p>The idea is that an object is a subtype if it can satisfy all of another object’s properties.</p>
<p><a href="http://roy.brianmckenna.org/">Visit Roy’s website</a> to give the language a try from your browser. I’ve only tested it in Chrome and Safari. It definitely won’t work in IE.</p>]]></summary>
</entry>
<entry>
    <title>Roy - Simple Pattern Matching</title>
    <link href="https://brianmckenna.org/blog/roy_pattern_matching" />
    <id>https://brianmckenna.org/blog/roy_pattern_matching</id>
    <published>2011-06-05T00:00:00Z</published>
    <updated>2011-06-05T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p><a href="http://projectaweek.heroku.com/">This week</a> I worked on adding simple <a href="http://en.wikipedia.org/wiki/Tagged_union">tagged unions</a> (sum types) and <a href="http://en.wikipedia.org/wiki/Pattern_matching">pattern matching</a> to <a href="roy">Roy</a>. The <a href="https://bitbucket.org/puffnfresh/roy/changeset/205a1d95d1fe">diff is fairly disgusting</a> but I’m happy that it works. Here is the example I committed:</p>
<pre><code>data Maybe a =
  Some a | None

let printSomething m = match m
  case (Some x) = console.log x
  case None = console.log &quot;Empty&quot;

printSomething (Some 1)
printSomething None

data Either a b =
  Left a | Right b

let printString (s : String) =
  console.log s

let printResult e = match e
  case (Left x) = console.log x
  case (Right x) = printString x

printResult (Left 10)
printResult (Right &quot;Error&quot;)

// Won&#39;t compile:
// printResult (Right 10)

data Bool =
  True | False

let getBool b ifTrue ifFalse = match b
  case True = ifTrue
  case False = ifFalse

console.log (getBool True 1 2)
console.log (getBool False 1 2)</code></pre>
<p>Running the above example (with <code>./roy examples/data.roy &amp;&amp; node examples/data.js</code>) will print the following:</p>
<pre><code>1
Empty
10
Error
1
2</code></pre>
<p>The current version of pattern matching has no exhaustiveness check. I’ll try to figure out how to do that later on.</p>]]></summary>
</entry>
<entry>
    <title>Roy</title>
    <link href="https://brianmckenna.org/blog/roy" />
    <id>https://brianmckenna.org/blog/roy</id>
    <published>2011-05-29T00:00:00Z</published>
    <updated>2011-05-29T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This week I’m releasing a toy functional language that compiles to JavaScript. I’ve named it “Roy” and you can <a href="https://bitbucket.org/puffnfresh/roy">find it on Bitbucket</a>. It’s just over 1000 lines of JavaScript.</p>
<p>It uses my past two projects from <a href="http://projectaweek.heroku.com/">projectaweek</a>:</p>
<ul>
<li><a href="js_type_inference">Type inference</a></li>
<li><a href="js_lexer">Whitespace lexer</a></li>
</ul>
<p>Here’s an example of the language:</p>
<pre><code>let gcd a b =
  if b == 0 then
    a
  else
    gcd b (a % b)

console.log (gcd 49 35)</code></pre>
<p>And here’s the (ugly) JavaScript output:</p>
<pre><code>&quot;use strict&quot;;
var gcd = function(a, b) {return (function(){if(b == 0){return a}else{return gcd(b, a % b)}})();;};
console.log(gcd(49, 35))</code></pre>
<p>Roy will serve as the basis for a new language I’m working on. The next language will:</p>
<ul>
<li>Improve JavaScript interop</li>
<li>Structural typing</li>
<li>Tail recursion</li>
<li>Algebraic data types</li>
<li>Pattern matching</li>
<li>Prettify the JavaScript output</li>
</ul>]]></summary>
</entry>
<entry>
    <title>Simple Lexer in JavaScript</title>
    <link href="https://brianmckenna.org/blog/js_lexer" />
    <id>https://brianmckenna.org/blog/js_lexer</id>
    <published>2011-05-22T00:00:00Z</published>
    <updated>2011-05-22T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I haven’t had much time but I’m trying to continue with <a href="http://www.shimweasel.com/2011/05/08/the-stewart-method-how-not-to-suck">releasing a project every week</a>. This week I’ve worked on a whitespace-significant lexer for use with <a href="http://jison.org/">Jison</a>.</p>
<p>The <a href="https://bitbucket.org/puffnfresh/js-whitespace-lexer">code</a> is up on Bitbucket. It analyses a small, ML-like language.</p>]]></summary>
</entry>
<entry>
    <title>Type Inference in JavaScript</title>
    <link href="https://brianmckenna.org/blog/js_type_inference" />
    <id>https://brianmckenna.org/blog/js_type_inference</id>
    <published>2011-05-15T00:00:00Z</published>
    <updated>2011-05-15T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Last week I read about <a href="http://donsbot.wordpress.com/">Don Stewart</a>’s method for productivity: <a href="http://www.shimweasel.com/2011/05/08/the-stewart-method-how-not-to-suck">releasing a project every week</a>. I’ve been working on a language that <a href="http://altjs.org/">compiles to JavaScript</a> and thought that I could release it in modular parts.</p>
<p>This week I am releasing my JavaScript implementation of <a href="http://en.wikipedia.org/wiki/Type_inference#Hindley.E2.80.93Milner_type_inference_algorithm">Hindley-Milner type inference</a> (a.k.a. Algorithm W).</p>
<p>The <a href="https://bitbucket.org/puffnfresh/js-type-inference/src">source is on Bitbucket</a> and I’ve generated some literate-style code docs using <a href="http://jashkenas.github.com/docco/">Docco</a>. Check them out here:</p>
<ul>
<li><a href="http://brianmckenna.org/files/js-type-inference/docs/typeinference.html">typeinference.js</a></li>
<li><a href="http://brianmckenna.org/files/js-type-inference/docs/types.html">types.js</a></li>
</ul>]]></summary>
</entry>
<entry>
    <title>Minimalist Android Scala Environment</title>
    <link href="https://brianmckenna.org/blog/minimalist_android_scala_env" />
    <id>https://brianmckenna.org/blog/minimalist_android_scala_env</id>
    <published>2010-12-28T00:00:00Z</published>
    <updated>2010-12-28T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I managed to get Scala working on Android after the SDK was first released. I also found <a href="https://review.source.android.com/10724">a little problem with the Dalvik virtual machine</a> in the process.</p>
<p>A year and a half went by and I’ve come back to try Scala on Android. There’s now a few resources on the topic, <a href="http://www.assembla.com/wiki/show/scala-ide/Developing_for_Android">even one from ScalaIDE</a>. I haven’t been completely satisfied with the solutions I’ve read so I came up with the following.</p>
<h3 id="instructions">Instructions</h3>
<p>Install <a href="http://www.scala-ide.org/">ScalaIDE</a> in Eclipse and create a new Android project.</p>
<p>Make sure there is a directory called libs and copy in scala-library.jar. Make a new directory called tools and copy in scala-compiler.jar.</p>
<p>Generate an Ant build.xml file:</p>
<pre><code>$ ~/android-sdk-linux_86/tools/android update project --target 1 --path .</code></pre>
<p>Define a pre-compile stage in build.xml and add a Scala task:</p>
<pre><code>&lt;target name=&quot;-pre-compile&quot; depends=&quot;-resource-src&quot;&gt;
    &lt;taskdef resource=&quot;scala/tools/ant/antlib.xml&quot;
             classpath=&quot;tools/scala-compiler.jar:libs/scala-library.jar&quot; /&gt;

    &lt;scalac force=&quot;changed&quot; deprecation=&quot;on&quot; destdir=&quot;${out.classes.absolute.dir}&quot;
            bootclasspathref=&quot;android.target.classpath&quot;&gt;
        &lt;src path=&quot;${source.absolute.dir}&quot; /&gt;
        &lt;src path=&quot;${gen.absolute.dir}&quot; /&gt;
        &lt;src refid=&quot;project.libraries.src&quot; /&gt;
        &lt;classpath&gt;
            &lt;fileset dir=&quot;${jar.libs.absolute.dir}&quot; includes=&quot;*.jar&quot; /&gt;
        &lt;/classpath&gt;
    &lt;/scalac&gt;
&lt;/target&gt;</code></pre>
<p>Android doesn’t work very well when converting a huge amount of Java bytecode to Dalvik bytecode. To get around this, we can use Proguard to remove all unused parts of the Scala library. Enable Proguard for debug releases by adding the following to build.xml:</p>
<pre><code>&lt;target name=&quot;-debug-obfuscation-check&quot;&gt;
    &lt;property name=&quot;proguard.enabled&quot; value=&quot;true&quot; /&gt;
    &lt;path id=&quot;out.dex.jar.input.ref&quot; /&gt;
&lt;/target&gt;</code></pre>
<p>Make the <code>install</code> target local to our build.xml instead of importing it. This will make it easier for Eclipse later on:</p>
<pre><code>&lt;target name=&quot;install&quot; depends=&quot;debug&quot;&gt;
    &lt;install-helper /&gt;
&lt;/target&gt;</code></pre>
<p>Add the following line to default.properties:</p>
<pre><code>proguard.config=proguard.cfg</code></pre>
<p>The Scala library will cause warnings and make Proguard stop. Make it continue by adding the following to proguard.cfg:</p>
<pre><code>-dontwarn</code></pre>
<p>Remove the default run configuration from Eclipse and add a new external run configuration. The buildfile should be <code>${project_loc}/build.xml</code> and the base directory should be <code>${project_loc}</code>. Go to the “Targets” tab and tick the “install” target.</p>
<p>Delete the default Java source file and recreate it using Scala:</p>
<pre><code>package org.brianmckenna.helloandroid

import android.app.Activity
import android.os.Bundle

class HelloAndroid extends Activity {
  override def onCreate(savedInstanceState: Bundle): Unit = {
    super.onCreate(savedInstanceState)
    setContentView(List(R.layout.main) head)
  }
}</code></pre>
<p>After starting the emulator and running Ant, Scala should now run on Android!</p>]]></summary>
</entry>
<entry>
    <title>Haskell: From a Parallel Perspective</title>
    <link href="https://brianmckenna.org/blog/haskell_parallel_perspective" />
    <id>https://brianmckenna.org/blog/haskell_parallel_perspective</id>
    <published>2010-10-13T00:00:00Z</published>
    <updated>2010-10-13T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>For class today, I presented some popular parallel libraries for Haskell (using GHC). It covered topics suchs as:</p>
<ul>
<li><code>par</code> and <code>pseq</code></li>
<li><code>parList</code>, <code>parListChunk</code>, <code>parMap</code>, <code>r0</code>, <code>rwhnf</code> and <code>rnf</code></li>
<li>Data Parallel Haskell</li>
<li>Intel CnC</li>
<li><code>forkIO</code> with <code>MVar</code>, <code>Chan</code>, <code>QSemN</code> and <code>STM</code></li>
</ul>
<p>The presentation is online here:</p>
<p><a href="http://brianmckenna.org/files/presentations/haskell-parallel/">http://brianmckenna.org/files/presentations/haskell-parallel/</a></p>
<p>On Bitbucket here:</p>
<p><a href="https://bitbucket.org/puffnfresh/presentations">https://bitbucket.org/puffnfresh/presentations</a></p>
<p>Downloadable as a zip here:</p>
<p><a href="http://brianmckenna.org/files/presentations/haskell-parallel.zip">http://brianmckenna.org/files/presentations/haskell-parallel.zip</a></p>
<figure>
<img src="http://brianmckenna.org/blog/static/lyah_random.png" alt="Random" />
<figcaption aria-hidden="true">Random</figcaption>
</figure>
<p><em>Illustration from <a href="http://learnyouahaskell.com/">LYAH</a> by <a href="https://twitter.com/bonus500">bonus500</a></em></p>]]></summary>
</entry>
<entry>
    <title>When I was 3...</title>
    <link href="https://brianmckenna.org/blog/3yr_old_brian" />
    <id>https://brianmckenna.org/blog/3yr_old_brian</id>
    <published>2010-09-06T00:00:00Z</published>
    <updated>2010-09-06T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p><img src="http://brianmckenna.org/blog/static/computer_photo_small.jpg" /></p>]]></summary>
</entry>
<entry>
    <title>Wanted: Unparallel project in need of good optimisation</title>
    <link href="https://brianmckenna.org/blog/wanted_unparallel_project" />
    <id>https://brianmckenna.org/blog/wanted_unparallel_project</id>
    <published>2010-07-29T00:00:00Z</published>
    <updated>2010-07-29T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve just started a Parallel Programming class at <a href="http://qut.edu.au/">QUT</a>. Our major assessment (worth 50%) is to manually parallelise some software.</p>
<p>I’m looking for something that:</p>
<ul>
<li>Is interesting</li>
<li>Takes skill and effort</li>
<li>Has some potential barriers</li>
<li>Would be appreciated</li>
<li>Is preferably open-source</li>
</ul>
<p>Do you use any software could use a speed up? Do you have a project that could use some parallelisation?</p>]]></summary>
</entry>
<entry>
    <title>node.js WebGL</title>
    <link href="https://brianmckenna.org/blog/nodejs_webgl" />
    <id>https://brianmckenna.org/blog/nodejs_webgl</id>
    <published>2010-06-09T00:00:00Z</published>
    <updated>2010-06-09T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’m about to present something I’ve been working on recently. Something I’m really happy about!</p>
<h2 id="a-webgl-implementation-for-node.js1">A WebGL implementation for <a href="http://nodejs.org/">node.js</a>!</h2>
<p>Here’s a screenshot of it next to WebGL in Chromium (even running the same JavaScript):</p>
<p><img src="http://brianmckenna.org/blog/static/nodejs_webgl.png" /></p>
<p>I’ve <a href="http://github.com/pufuwozu/node-webgl">chucked it up on GitHub</a> but if you’re having a go, be aware that I’ve only implemented enough OpenGL calls to run my example. I’d really appreciate any help implementing the other functions.</p>
<p>This project is part of something much bigger. Imagine easily writing games or multimedia applications that run in the browser and on the desktop without changes. Stay tuned.</p>]]></summary>
</entry>
<entry>
    <title>GSoC Introduction</title>
    <link href="https://brianmckenna.org/blog/gsoc_introduction" />
    <id>https://brianmckenna.org/blog/gsoc_introduction</id>
    <published>2010-05-19T00:00:00Z</published>
    <updated>2010-05-19T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p><em>This post has been taken from <a href="http://gsoc2010.wordpress.com/2010/05/17/introduction/">the WordPress GSoC 2010 blog</a>.</em></p>
<p>I work part-time as a web developer at a marketing and advertising agency which heavily uses WordPress as a CMS. Like many developers, we use local development machines to add new functionality and fix bugs, we then migrate those websites onto our client’s web servers. If you’re very familiar with WordPress you’ll probably know that migrating an install is fairly horrible. That’s what I plan to fix.</p>
<p>I’ll try to put an easy to use interface (hopefully with some help from the WordPress UI/UX team) that will let the user type in their new URL, new FTP credentials and new database server credentials. The blog will then be able to use all of those details and move itself over, automatically. I’m not a UI designer so please forgive my mock-up:</p>
<p><img src="http://gsoc2010.files.wordpress.com/2010/05/migrate_sceenshot.png" /></p>
<p>I’ll be posting a revised project proposal to this blog soon. It will be at the following URL when it’s ready:</p>
<p><a href="http://gsoc2010.wordpress.com/brian-mckenna-automatic-migration/">http://gsoc2010.wordpress.com/brian-mckenna-automatic-migration/</a></p>
<p>This has been a brief overview of my project. What do you think of the idea? What would you like to see implemented?</p>]]></summary>
</entry>
<entry>
    <title>PyWeek 2010</title>
    <link href="https://brianmckenna.org/blog/pyweek_2010" />
    <id>https://brianmckenna.org/blog/pyweek_2010</id>
    <published>2010-04-29T00:00:00Z</published>
    <updated>2010-04-29T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>At the beginning of the month I was finishing off a little game I helped make for <a href="http://www.pyweek.org/">PyWeek</a>. PyWeek is a game programming competition where you must create a whole game within a week and use Python.</p>
<p>I was the sole programmer on the team, there were two other people working on art and music. I was really happy with the end product (even though it was rushed). The reviews of our game <a href="http://www.pyweek.org/e/blank_page/ratings/">are public</a>, here are a few choice ones:</p>
<p>Anonymous:</p>
<blockquote>
<p>Excellent concept. Hard and tricky game - had to think to get through this game (that’s good) and it doesn’t repeat “puzzles” much. Well executed, the jumping/bouncing feels nice and bouncy. Great graphics and nice music. Intro video was neat, although I think it could’ve taken the whole screen. Excellent work on this game, I just wish it was longer. You should really give some thought into making this a full game, with more levels, a tutorial, a better storyline and everything (maybe some new features would be nice too, like different types of jelly). I really think it has potential for a great “full game”. :)</p>
</blockquote>
<p>Anonymous:</p>
<blockquote>
<p>I was extremely impressed by this entry! Great job! However, the learning curve level was way too hard for me to really enjoy it. If there were more tutorial parts and less mid-air precision shots, I would have had a lot of fun with it.</p>
</blockquote>
<p>Anonymous:</p>
<blockquote>
<p>Retro look. Platforming with jelly bouncing. What’s not to like? Apart from the fact that I ran out of goo that is.</p>
</blockquote>
<p>Anonymous:</p>
<blockquote>
<p>I was amazed by the production values of this game. Really cool art style.
The gameplay is nice… but i couldn’t figure out how to cross beyond the first obstacle :(</p>
</blockquote>
<p>I’ve posted some videos of the game to YouTube:</p>
<p><a href="http://www.youtube.com/watch?v=Pxsv6aG3En4"><img src="http://i1.ytimg.com/vi/Pxsv6aG3En4/0.jpg" /></a></p>
<p><a href="http://www.youtube.com/watch?v=i5pGKABDgx4"><img src="http://i1.ytimg.com/vi/i5pGKABDgx4/0.jpg" /></a></p>
<p><a href="http://www.youtube.com/watch?v=ukPlFI9kCF8"><img src="http://i1.ytimg.com/vi/ukPlFI9kCF8/0.jpg" /></a></p>
<p>I have created a <a href="http://brianmckenna.org/files/blank_page-1.0-py2exe.zip">Windows package</a> for anyone who wants to try it out. There is also a <a href="http://media.pyweek.org/dl/10/blank_page/blank_page-1.0.zip">Python source version</a> for people on other systems - the only problem is that the source version requires <a href="http://www.pyglet.org/">Pyglet</a>.</p>
<p>I’m planning on working on this game a bit further and entering into the <a href="http://pyggy.pyweek.org/">Pyggy Awards</a>.</p>]]></summary>
</entry>
<entry>
    <title>JavaScript as a Functional Language</title>
    <link href="https://brianmckenna.org/blog/javascript_as_a_functional_language" />
    <id>https://brianmckenna.org/blog/javascript_as_a_functional_language</id>
    <published>2010-04-28T00:00:00Z</published>
    <updated>2010-04-28T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p><em>This post has been modified from an <a href="http://stackoverflow.com/questions/2677532/how-is-a-functional-programming-based-javascript-app-laid-out/2695594#2695594">answer I posted on Stack Overflow</a>.</em></p>
<p>A lot of people <a href="http://javascript.crockford.com/javascript.html">misunderstand JavaScript</a>, possibly because its syntax looks like most other programming languages (where Lisp/Haskell/OCaml behave and look completely different).</p>
<p>JavaScript is sometimes called object-oriented. It is a loosely-typed dynamic language and doesn’t have classes nor classical inheritance. This means that when JavaScript is compared to Java or C++, the concepts just don’t match up.</p>
<p>I find that JavaScript can be better compared to a Lisp; it has closures and first-class functions. Using them you can create other functional programming techniques, such as <a href="http://ejohn.org/blog/partial-functions-in-javascript/">partial application</a> (currying).</p>
<p>Today’s aim is to make a piece of JavaScript act more functional. Let’s take an example (using <code>sys.puts</code> from node.js):</p>
<pre><code>var external;
function foo() {
    external = Math.random() * 1000;
}
foo();

sys.puts(external);</code></pre>
<p>To get rid of global side effects, we can wrap it in a closure:</p>
<pre><code>(function() {
    var external;
    function foo() {
        external = Math.random() * 1000;
    }
    foo();

    sys.puts(external);
})();</code></pre>
<p>Notice that we can’t actually do anything with <code>external</code> or <code>foo</code> outside of the scope. They’re completely wrapped up in their own closure, untouchable.</p>
<p>Now, to get rid of the <code>external</code> side-effect:</p>
<pre><code>(function() {
    function foo() {
        return Math.random() * 1000;
    }

    sys.puts(foo());
})();</code></pre>
<p>That’s as far as we’ll get. In the end, the example is not purely-functional because it <strong>can’t</strong> be. Using a random number reads from the global state (to get a seed) and printing to the console is a side-effect.</p>
<p>I also want to point out that mixing functional programming with objects is perfectly fine. Take this for example:</p>
<pre><code>var Square = function(x, y, w, h) {
   this.x = x;
   this.y = y;
   this.w = w;
   this.h = h;
};

function getArea(square) {
    return square.w * square.h;
}

function sum(values) {
    var total = 0;
    
    values.forEach(function(value) {
        total += value;
    });

    return total;
}

sys.puts(sum([new Square(0, 0, 10, 10), new Square(5, 2, 30, 50), new Square(100, 40, 20, 19)].map(function(square) {
    return getArea(square);
})));</code></pre>
<p>Some Lisps even have things called property lists which can be thought of as objects.</p>
<p>The real trick to using objects in a functional style is to make sure that you don’t rely on their side effects but instead treat them as immutable. An easy way is whenever you want to change a property, just create a <em>new</em> object with the new details and pass that one along, instead (this is the approach often used in Clojure and Haskell).</p>
<p>I strongly believe that functional aspects can be very useful in JavaScript but ultimately, you should use whatever makes the code more readable and what works for <strong>you</strong>.</p>]]></summary>
</entry>
<entry>
    <title>node.js via CGI</title>
    <link href="https://brianmckenna.org/blog/nodejs_via_cgi" />
    <id>https://brianmckenna.org/blog/nodejs_via_cgi</id>
    <published>2010-04-27T00:00:00Z</published>
    <updated>2010-04-27T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Hi everyone! I’ve decided to create a new blog for myself. As many programmers do, I used this blog as an excuse to learn a new platform.</p>
<p>I wrote this blog engine from scratch using <a href="http://nodejs.org/">node.js</a>. What makes this site different to the others running node.js is that this one is running completely off of a shared server (<a href="http://dreamhost.com/">DreamHost</a>, specifically).</p>
<p>When I was looking into using node.js, I found that most developers are deploying it by using the built-in web server and then optionally proxying it to Apache or Nginx. Those options just aren’t possible when using cheap shared hosting. At this point I could:</p>
<ol type="1">
<li>Rent a virtual machine to deploy a node.js website (costs money)</li>
<li>Hack up a custom solution to make node.js server on a shared server (takes time)</li>
</ol>
<p>I chose the latter and now I am the proud creator of the <a href="http://github.com/pufuwozu/node-cgi">node-cgi</a> monster. It’s a CGI adaptor for node.js that mimmicks the node.js <code>http</code> library.</p>
<p>To use the adaptor you must create a <code>.htaccess</code> file that redirects paths to a CGI script. This blog uses:</p>
<pre><code>Options +ExecCGI
AddHandler cgi-script cgi

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) server.cgi</code></pre>
<p>Where server.cgi contains:</p>
<pre><code>#!/usr/bin/env node

var blog = require(&#39;./blog&#39;),
    cgi = require(&#39;./cgi&#39;);

var server = cgi.createServer(blog.requestListener);
server.listen();</code></pre>
<p>For people not familiar with node.js, using this library is very similar to the standard way of creating a HTTP server:</p>
<pre><code>var blog = require(&#39;./blog&#39;),
    http = require(&#39;http&#39;);

var server = http.createServer(exports.requestListener);
server.listen(5000, &quot;localhost&quot;);</code></pre>
<p>This means that some applications will only have to change <code>require('http')</code> to <code>require('cgi')</code> to create a CGI version!</p>
<p>The library is <a href="http://github.com/pufuwozu/node-cgi">up on GitHub</a> for those that want to take a look. I’d like to know if anyone finds it useful!</p>
<script type="text/javascript">
var disqus_identifier = 'nodejs_via_cgi';
</script>]]></summary>
</entry>

</feed>
