<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>λ Tony's blog λ</title>
  <link href="http://blog.tmorris.net/atom.xml" rel="self"/>
  <link href="http://blog.tmorris.net"/>
  <id>http://blog.tmorris.net/atom.xml</id>
  <author>
    <name>Tony Morris</name>
  </author>
  <updated>2013-04-24T20:00:00Z</updated>
  <entry>
  <title>Obturator Entrapment Neuropathy (update)</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/obturator-neuropathy-update/index.html"/>
  <id>http://blog.tmorris.net/posts/obturator-neuropathy-update/index.html</id>
  <published>2013-04-24T20:00:00Z</published>
  <updated>2013-04-24T20:00:00Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>After a subsequent meeting with an specialist inter-state, the diagnosis of <a href="http://blog.tmorris.net/posts/obturator-neuropathy/">obturator neuropathy</a> has been revised. Obturator neuropathy rarely occasions in isolation[1]. The true diagnosis is more sinister, with the obturator neuropathy occurring as one of many symptoms.</p>
<p>Reconstructive surgery is required.</p>
<hr />
<ol style="list-style-type: decimal">
<li>Tipton, John Sison. “Obturator neuropathy.” <em>Current reviews in musculoskeletal medicine</em> 1.3-4 (2008): 234-237. <a href="https://github.com/tonymorris/obturator-neuropathy-papers/blob/master/obturator-neuropathy-tipton.pdf?raw=true"><em>(link)</em></a></li>
</ol>
    </div>
  </content>
</entry>
<entry>
  <title>List Folds at BFPG</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/list-folds-bfpg/index.html"/>
  <id>http://blog.tmorris.net/posts/list-folds-bfpg/index.html</id>
  <published>2013-04-24T15:00:00Z</published>
  <updated>2013-04-24T15:00:00Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>A talk on the list fold functions (fold left and fold right), delivered to <a href="http://www.bfpg.org/events/96368322/?eventId=96368322&amp;action=detail">Brisbane Functional Programming Group on Tuesday 23 April 2013</a>.</p>
<ul>
<li><p><a href="http://dl.dropbox.com/u/7810909/media/doc/list-folds.pdf">Slides</a> <em>(pdf)</em></p></li>
<li><p><a href="https://vimeo.com/64673035">Video</a> <em>(vimeo)</em></p></li>
</ul>
<div class="embed-vimeo">
  <iframe src="http://player.vimeo.com/video/64673035" width="688" height="387" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen>
  </iframe>
</div>


    </div>
  </content>
</entry>
<entry>
  <title>Obturator Entrapment Neuropathy</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/obturator-neuropathy/index.html"/>
  <id>http://blog.tmorris.net/posts/obturator-neuropathy/index.html</id>
  <published>2013-04-11T19:00:00Z</published>
  <updated>2013-04-11T19:00:00Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>After 19 surgeries<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup> and 5 years of searching for the source of my chronic pain syndrome, which started with a sporting injury in 2007, I have been found to have a condition called Obturator Neuropathy — a source of chronic pain affecting athletes.</p>
<p>Unfortunately, many specialists are unaware of this condition and so may not recognise the correct diagnosis, which has been my case. Obturator Neuropathy typically affects those engaged in kicking sports and especially, Australian Rules football. Although I was playing Australian Rules football at the time of my injury, I live in Brisbane, where the sport is less popular than in other cities such as Melbourne and Sydney, where the condition is more recognised. I have recently learned that many more specialists in these cities are aware of this insidious disease, while I have yet to find anyone in Brisbane who even know it exists — I suppose this set of circumstances came together to delay my correct diagnosis for many years.</p>
<p>This article is the first of my writings on this condition, as at this time, it is still currently unresolved. I am planning to meet with many specialists in the next few days to discuss surgical management. Later, I intend to raise greater awareness of this condition in the hope that other athletes, professional or otherwise, needn’t go through the dramas that I have done in these last few years.</p>
<p>My pain is now so severe that I am unable to perform my normal duties for my employer. Thankfully, my employer is awesome and understanding of my plight and I am committed to resolving this matter as soon as possible so that I can contribute back my highest level of performance. I am thankful to others in their understanding and I apologise to those who have sometimes been on “the wrong end of the stick” of my frustrations especially when I am having a “bad day” with pain. I am also usually taking narcotic medication during these times, so my recollection of the events is typically blurry to me.</p>
<p>If you are ever inflicted with this condition, I highly recommend these publications, with most recommended appearing first:</p>
<div style="font-family: Courier, 'Courier New', monospace">

<ol style="list-style-type: decimal">
<li><p>Bradshaw, Chris, et al. “Obturator Nerve Entrapment A Cause of Groin Pain in Athletes.” <em>The American journal of sports medicine</em> 25.3 (1997): 402-408. <a href="https://github.com/tonymorris/obturator-neuropathy-papers/blob/master/obturator-nerve-entrapment-a-cause-of-groin-pain.pdf?raw=true"><em>(link)</em></a></p></li>
<li><p>Bradshaw, Chris, and Paul McCrory. “Obturator nerve entrapment.” <em>Clinical Journal of Sport Medicine</em> 7.3 (1997): 217-219. <a href="https://github.com/tonymorris/obturator-neuropathy-papers/blob/master/obturator-nerve-entrapment.pdf?raw=true"><em>(link)</em></a></p></li>
<li><p>Tipton, John Sison. “Obturator neuropathy.” <em>Current reviews in musculoskeletal medicine</em> 1.3-4 (2008): 234-237. <a href="https://github.com/tonymorris/obturator-neuropathy-papers/blob/master/obturator-neuropathy-tipton.pdf?raw=true"><em>(link)</em></a></p></li>
<li><p>Harvey, Gregory, and Simon Bell. “Obturator neuropathy: an anatomic perspective.” <em>Clinical orthopaedics and related research</em> 363 (1999): 203-211. <a href="https://github.com/tonymorris/obturator-neuropathy-papers/blob/master/obturator-neuropathy-an-anatomic-perspective.pdf?raw=true"><em>(link)</em></a></p></li>
<li><p>Busis, Neil A. “Femoral and obturator neuropathies.” <em>Neurologic clinics</em> 17.3 (1999): 633-653. <a href="https://github.com/tonymorris/obturator-neuropathy-papers/blob/master/femoral-and-obturator-neuropathies.pdf?raw=true"><em>(link)</em></a></p></li>
<li><p>Koulouris, George. “Imaging review of groin pain in elite athletes: an anatomic approach to imaging findings.” <em>American Journal of Roentgenology</em> 191.4 (2008): 962-972. <a href="https://github.com/tonymorris/obturator-neuropathy-papers/blob/master/imaging-review-of-groin-pain.pdf?raw=true"><em>(link)</em></a></p></li>
<li><p>Sorenson, Eric J., Joseph J. Chen, and Jasper R. Daube. “Obturator neuropathy: causes and outcome.” <em>Muscle &amp; nerve</em> 25.4 (2002): 605-607. <a href="https://github.com/tonymorris/obturator-neuropathy-papers/blob/master/obturator-neuropathy-causes-and-outcome.pdf?raw=true"><em>(link)</em></a></p></li>
<li><p>Kitagawa, Ryan, et al. “Surgical management of obturator nerve lesions.” <em>Neurosurgery</em> 65.4 (2009): A24-A28. <a href="https://github.com/tonymorris/obturator-neuropathy-papers/blob/master/surgical-management-of-obturator-nerve-lesions.pdf?raw=true"><em>(link)</em></a></p></li>
<li><p>Arnold, William David, and Bakri H. Elsheikh. “Entrapment Neuropathies.” <em>Neurologic Clinics</em> (2013). <a href="https://github.com/tonymorris/obturator-neuropathy-papers/blob/master/entrapment-neuropathies.pdf?raw=true"><em>(link)</em></a></p></li>
<li><p>Orchard, John, et al. “Pathophysiology of chronic groin pain in the athlete.” <em>Int J Sports Med</em> 1.1 (2000). <a href="https://github.com/tonymorris/obturator-neuropathy-papers/blob/master/pathophysiology-of-chronic-groin-pain.pdf?raw=true"><em>(link)</em></a></p></li>
<li><p>Anagnostopoulou, Sofia, et al. “Anatomic variations of the obturator nerve in the inguinal region: implications in conventional and ultrasound regional anesthesia techniques.” <em>Regional anesthesia and pain medicine</em> 34.1 (2009): 33-39. <a href="https://github.com/tonymorris/obturator-neuropathy-papers/blob/master/anatomic-variations-of-the-obturator-nerve.pdf?raw=true"><em>(link)</em></a></p></li>
<li>Falvey, Eanna Cian, Andrew Franklyn-Miller, and P. R. McCrory. “The groin triangle: a patho-anatomical approach to the diagnosis of chronic groin pain in athletes.” <em>British journal of sports medicine</em> 43.3 (2009): 213-220. <a href="https://github.com/tonymorris/obturator-neuropathy-papers/blob/master/the-groin-triangle.pdf?raw=true"><em>(link)</em></a>
</div>



</li>
</ol>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>21 surgeries under a strict definition of the term “surgery” but let’s stick with 19 :)<a href="#fnref1">↩</a></p></li>
</ol>
</div>
    </div>
  </content>
</entry>
<entry>
  <title>Teaching a Man to Fish …and all that</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/teaching-a-man-to-fish/index.html"/>
  <id>http://blog.tmorris.net/posts/teaching-a-man-to-fish/index.html</id>
  <published>2013-04-10T13:00:00Z</published>
  <updated>2013-04-10T13:00:00Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>One of the very nice properties of type-safe, functional source code or API is that “an example usage of that API …” can almost always be answered with “anything that type-checks.” Now for some people and for some libraries, this answer is unsatisfactory, offensive even — they demand an example dammit!</p>
<p>But what they think I am going to do? Do they really think I have a library of examples in my head that I am holding hostage? Do they think that I am being spiteful toward them by withholding this library of knowledge that I possess and they do not? No, what I would do here is exactly what they are very capable of doing — they can find any type-checking program. In fact, this is the tool support that I aspire to so that I do not have to maintain a “library of examples” in my own head.</p>
<p>By appeasing their demand for “example usages of …”, if I were to do such an unfortunate thing, I am disservicing them. I am taking away their opportunity to develop the skills to answer this question for themselves. I am not even giving a good answer to the specifics of the question. It is not “a good example” of anything at all. It is the <em>process</em> by which the example is derived that is useful and nothing else.</p>
<p>So go on, try it. Create yourself a type-checking program. You may be a bit uncomfortable with the much higher degree of tool support in this environment. All I can say is, embrace it, cherish it even. Go.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Lane-Splitting in Australia.</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/lane-splitting/index.html"/>
  <id>http://blog.tmorris.net/posts/lane-splitting/index.html</id>
  <published>2013-03-10T20:00:00Z</published>
  <updated>2013-03-10T20:00:00Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>The subject of lane-splitting on a motorcycle often comes up in discussion. In Australia, the legality of lane-splitting is not absolute. For example, under some circumstances, such as two (or even three) motorcycles sharing a lane, this manouvre may be legal (further specifics apply). Under some other circumstances, lane-splitting is illegal.</p>
<p>Below are verbatim excerpts of Transport Operations (Road Use Management) Act 1995; Transport Operations (Road Use Management-Road Rules) Regulation 1999 that are relevant to lane-splitting. The name of this legislation is sometimes abbreviated to <em>TORUM</em>. TORUM applies to the state of Queensland and is derived from the Australian Road Rules (ARR).</p>
<p>Other Australian state and territory road use legislation is also derived from the ARR. Although these sections have been excerpted directly from TORUM, they can also be found in the ARR (under the same sections) and also in the road use legislation for each Australian state/territory.</p>
<h1 id="no-overtaking-etc-to-the-left-of-a-vehicle">141 No overtaking etc to the left of a vehicle</h1>
<ol style="list-style-type: decimal">
<li>A driver (except the rider of a bicycle) must not overtake a vehicle to the left of the vehicle unless–
<ul>
<li>the driver is driving on a multi-lane road and the vehicle can be safely overtaken in a marked lane to the left of the vehicle; or</li>
<li>the vehicle is turning right, or making a U–turn from the centre of</li>
<li>the road, and is giving a right change of direction signal.</li>
</ul></li>
<li>The rider of a bicycle must not ride past, or overtake, to the left of a vehicle that is turning left and is giving a left change of direction signal.</li>
<li>In this section–
<ul>
<li>“turning right” does not include making a hook turn.</li>
<li>“vehicle” does not include a bus travelling along tram tracks, or any vehicle displaying a do not overtake turning vehicle sign.</li>
</ul></li>
</ol>
<h1 id="no-overtaking-to-the-right-of-a-vehicle-turning-right-etc">142 No overtaking to the right of a vehicle turning right etc</h1>
<ol style="list-style-type: decimal">
<li>A driver must not overtake to the right of a vehicle if the vehicle is–
<ul>
<li>turning right or making a U-turn from the centre of the road; and</li>
<li>giving a right change of direction signal.</li>
</ul></li>
<li>In this section–
<ul>
<li>“turning right” does not include making a hook turn.</li>
<li>“vehicle” does not include a bus travelling along tram tracks, or any vehicle displaying a do not overtake turning vehicle sign.</li>
</ul></li>
</ol>
<h1 id="driving-within-a-single-marked-lane-or-line-of-traffic">146 Driving within a single marked lane or line of traffic</h1>
<ol style="list-style-type: decimal">
<li>A driver on a multi-lane road must drive so the driver’s vehicle is completely in a marked lane, unless the driver is–
<ul>
<li>entering a part of the road of 1 kind from a part of the road of another kind (for example, moving to or from a service road, a shoulder of the road or emergency stopping lane); or</li>
<li>entering or leaving the road; or</li>
<li>moving from 1 marked lane to another marked lane; or</li>
<li>avoiding an obstruction; or</li>
<li>obeying a traffic control device applying to the marked lane; or</li>
<li>permitted to drive in more than 1 marked lane under this regulation.</li>
</ul></li>
<li>A driver on a road with 2 or more lines of traffic travelling in the same direction as the driver, but without marked lanes, must drive so the driver’s vehicle is completely in a single line of traffic unless–
<ul>
<li>it is not practicable to drive completely in a single line of traffic; or</li>
<li>the driver is entering a part of the road of 1 kind from a part of the road of another kind (for example, moving to or from a service road, a shoulder of the road or an emergency stopping lane); or</li>
<li>the driver is entering or leaving the road; or</li>
<li>the driver is moving from 1 line of traffic to another line of traffic; or</li>
<li>the driver is avoiding an obstruction.</li>
</ul></li>
</ol>
<h1 id="moving-from-1-marked-lane-to-another-marked-lane-across-a-continuous-line-separating-the-lanes">147 Moving from 1 marked lane to another marked lane across a continuous line separating the lanes</h1>
<p>A driver on a multi-lane road must not move from 1 marked lane to another marked lane by crossing a continuous line separating the lanes unless–</p>
<ul>
<li>the driver is avoiding an obstruction; or</li>
<li>the driver is obeying a traffic control device applying to the first marked lane; or</li>
<li>the driver is permitted to drive in both marked lanes under this regulation; or</li>
<li>either of the marked lanes is a special purpose lane in which the driver is permitted to drive under this regulation and the driver is moving to or from the special purpose lane.</li>
</ul>
<h1 id="driving-on-or-across-a-continuous-white-edge-line">150 Driving on or across a continuous white edge line</h1>
<ol style="list-style-type: decimal">
<li>A driver must not drive on or over a continuous white edge line on a road unless the driver is–
<ul>
<li>turning at an intersection; or</li>
<li>entering or leaving the road; or</li>
<li>entering a part of the road of 1 kind from a part of the road of another kind (for example, moving to or from a service road, a shoulder of the road or an emergency stopping lane); or</li>
<li>overtaking a vehicle that is–
<ul>
<li>turning right or making a U-turn from the centre of the road; and</li>
<li>giving a right change of direction signal; or</li>
</ul></li>
<li>driving a slow-moving vehicle; or</li>
<li>stopping at the side of the road (including any shoulder of the road); or</li>
<li>driving a vehicle that is too wide, or too long, to drive on the road without driving on or over the edge line.</li>
</ul></li>
<li>This section does not apply to the rider of a bicycle or animal.</li>
</ol>
<h1 id="riding-a-motor-bike-or-bicycle-alongside-more-than-1-other-rider">151 Riding a motor bike or bicycle alongside more than 1 other rider</h1>
<ol style="list-style-type: decimal">
<li>The rider of a motor bike or bicycle must not ride on a road that is not a multi-lane road alongside more than 1 other rider, unless subsection (3) applies to the rider.</li>
<li>The rider of a motor bike or bicycle must not ride in a marked lane alongside more than 1 other rider in the marked lane, unless subsection (3) applies to the rider.</li>
<li>The rider of a motor bike or bicycle may ride alongside more than 1 other rider if the rider is overtaking the other riders.</li>
<li>If the rider of a motor bike or bicycle is riding on a road that is not a multi-lane road alongside another rider, or in a marked lane alongside another rider in the marked lane, the rider must ride not over 1.5 m from the other rider.</li>
<li>In this section–</li>
</ol>
<ul>
<li>“road” does not include a road-related area, but includes a bicycle path, a shared path and any shoulder of the road.</li>
</ul>
    </div>
  </content>
</entry>
<entry>
  <title>Functors and things using Scala</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/functors-and-things-using-scala/index.html"/>
  <id>http://blog.tmorris.net/posts/functors-and-things-using-scala/index.html</id>
  <published>2013-03-01T00:00:00Z</published>
  <updated>2013-03-01T00:00:00Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <h2 id="types-of-functors">Types of Functors</h2>
<p>There are many types of functors. They can be expressed using the Scala programming language.</p>
<ul>
<li>covariant functors — defines the operation commonly known as <code>map</code> or <code>fmap</code>.</li>
</ul>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// covariant functor</span>
<span class="kw">trait</span> Functor[F[_]] {
  <span class="kw">def</span> fmap[A, B](f: A =&gt; B): F[A] =&gt; F[B]
}</code></pre>
<ul>
<li>contravariant functors — defines the operation commonly known as <code>contramap</code>.</li>
</ul>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// contravariant functor</span>
<span class="kw">trait</span> Contravariant[F[_]] {
  <span class="kw">def</span> contramap[A, B](f: B =&gt; A): F[A] =&gt; F[B]
}</code></pre>
<ul>
<li>exponential functors — defines the operation commonly known as <code>xmap</code>. Also known as <em>invariant functors</em>.</li>
</ul>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// exponential functor</span>
<span class="kw">trait</span> Exponential[F[_]] {
  <span class="kw">def</span> xmap[A, B](f: (A =&gt; B, B =&gt; A)): F[A] =&gt; F[B]
}</code></pre>
<ul>
<li>applicative functor<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup> — defines the operation commonly known as <code>apply</code> or <code>&lt;*&gt;</code>.</li>
</ul>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// applicative functor (abbreviated)</span>
<span class="kw">trait</span> Applicative[F[_]] {
  <span class="kw">def</span> apply[A, B](f: F[A =&gt; B]): F[A] =&gt; F[B]
}</code></pre>
<ul>
<li>monad<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup> — defines the operation commonly known as <code>bind</code>, <code>flatMap</code> or <code>=&lt;&lt;</code>.</li>
</ul>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// monad (abbreviated)</span>
<span class="kw">trait</span> Monad[F[_]] {
  <span class="kw">def</span> flatMap[A, B](f: A =&gt; F[B]): F[A] =&gt; F[B]
}</code></pre>
<ul>
<li>comonad<sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup> — defines the operation commonly known as <code>extend</code>, <code>coflatMap</code> or <code>&lt;&lt;=</code>.</li>
</ul>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// comonad (abbreviated)</span>
<span class="kw">trait</span> Comonad[F[_]] {
  <span class="kw">def</span> coflatMap[A, B](f: F[A] =&gt; B): F[A] =&gt; F[B]
}</code></pre>
<h2 id="remembering-the-different-types">Remembering the different types</h2>
<p>Sometimes I am asked how to remember all of these and/or determine which is appropriate. There are many answers to this question, but there is a common feature of all of these different types of functor:</p>
<blockquote>
<p>They all take an argument that is some arrangement of three type variables and then return a function with the type F[A] =&gt; F[B].</p>
</blockquote>
<p>I memorise the table that is the type of the different argument arrangements to help me to determine which abstraction might be appropriate. Of course, I use other methods, but this particular technique is elegant and short. Here is that table:</p>
<table>
<col width="20%" />
<col width="25%" />
<thead>
<tr class="header">
<th align="left">functor</th>
<th align="left">argument arrangement</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">covariant</td>
<td align="left"><code class="sourceCode scala">A =&gt; B</code></td>
</tr>
<tr class="even">
<td align="left">contravariant</td>
<td align="left"><code class="sourceCode scala">B =&gt; A</code></td>
</tr>
<tr class="odd">
<td align="left">exponential</td>
<td align="left"><code class="sourceCode scala">(A =&gt; B, B =&gt; A)</code></td>
</tr>
<tr class="even">
<td align="left">applicative</td>
<td align="left"><code class="sourceCode scala">F[A =&gt; B]</code></td>
</tr>
<tr class="odd">
<td align="left">monad</td>
<td align="left"><code class="sourceCode scala">A =&gt; F[B]</code></td>
</tr>
<tr class="even">
<td align="left">comonad</td>
<td align="left"><code class="sourceCode scala">F[A] =&gt; B</code></td>
</tr>
</tbody>
</table>
<p>We can see from this table that there is not much reason to emphasise one over the other. For example, monads get <em>lots</em> of attention and associated stigma, but it’s undeserved. It’s rather boring when put in the context of a bigger picture. It’s just a different arrangement of its argument (<code>A =&gt; F[B]</code>).</p>
<p>Anyway, this table is a good way to keep a check on the different types of abstraction and how they might apply. There are also ways of deriving some from others, but that’s for another rainy day. That’s all, hope it helps!</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>applicative functors also define an identity operation (<code>def insert[A]: A =&gt; F[A]</code>) however, it is omitted.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>monads also define an identity operation (<code>def insert[A]: A =&gt; F[A]</code>) however, it is omitted.<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>comonads also define an identity operation (<code>def extract[A]: F[A] =&gt; A</code>) however, it is omitted.<a href="#fnref3">↩</a></p></li>
</ol>
</div>
    </div>
  </content>
</entry>
<entry>
  <title>Memoisation with State using Scala</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/memoisation-with-state-using-scala/index.html"/>
  <id>http://blog.tmorris.net/posts/memoisation-with-state-using-scala/index.html</id>
  <published>2013-02-22T00:00:00Z</published>
  <updated>2013-02-22T00:00:00Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Everyone has seen a naïve fibonacci implementation</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> FibNaïve {
  <span class="kw">def</span> fibnaïve(n: BigInt): BigInt =
    <span class="kw">if</span>(n &lt;= <span class="dv">1</span>)
      n
    <span class="kw">else</span> {
      <span class="kw">val</span> r = fibnaïve(n - <span class="dv">1</span>)
      <span class="kw">val</span> s = fibnaïve(n - <span class="dv">2</span>)
      r + s
    }
}</code></pre>
<p>While this implementation is elegant, it is exponential in time with respect to <code>n</code>. For example, computing the result of <code>fibnaïve(4)</code> will result in the unnecessary re-computation of values less than <code>4</code>. If we unravel the recursion, computation occurs as follows:</p>
<pre><code>  fibnaïve(4)
= fibnaïve(3) + fibnaïve(2)
= (fibnaïve(2) + fibnaïve(1)) + (fibnaïve(1) + fibnaïve(0))
= ((fibnaïve(1) + fibnaïve(0)) + fibnaïve(1)) + (fibnaïve(1) + fibnaïve(0))</code></pre>
<p>This algorithm calculates for <code>fibnaïve(2)</code> twice, which ultimately results in a lot of repeated calculations, especially as <code>n</code> grows. What we would like to do is trade some space to store previous stored values for a given <code>n</code>. We can achieve this by looking up the argument value in a table and if it has already been computed, we return it then carry on, but if it hasn’t, we compute the result by calling <code>fibnaïve</code>, store it in the table, then return it. This technique is called <em>memoisation</em>.</p>
<p>As a first cut, let’s solve fibonacci with a helper function that passes a <code>Map[BigInt, BigInt]</code> around in the recursion. This map will serve at the memoisation table.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> FibMemo1 {
  <span class="kw">type</span> Memo = Map[BigInt, BigInt]

  <span class="kw">def</span> <span class="fu">fibmemo1</span>(n: BigInt): BigInt = {
    <span class="kw">def</span> <span class="fu">fibmemoR</span>(z: BigInt, memo: Memo): (BigInt, Memo) =
      <span class="kw">if</span>(z &lt;= <span class="dv">1</span>)
        (z, memo)
      <span class="kw">else</span> memo get z <span class="kw">match</span> {
        <span class="kw">case</span> None =&gt; {
          <span class="kw">val</span> (r, memo0) = <span class="fu">fibmemoR</span>(z - <span class="dv">1</span>, memo)
          <span class="kw">val</span> (s, memo1) = <span class="fu">fibmemoR</span>(z - <span class="dv">2</span>, memo0)
          (r + s, memo1)
        }
        <span class="kw">case</span> Some(v) =&gt; (v, memo)
      }

    <span class="fu">fibmemoR</span>(n, Map()).<span class="fu">_1</span>
  }
}</code></pre>
<p>We have traded space (the memoisation table) for speed; the algorithm is more efficient by not recomputing values. However, we have sacrificed the elegance of the code. How can we achieve both elegance and efficiency?</p>
<h2 id="the-state-monad">The State Monad</h2>
<p>The previous code (<code>fibmemo1</code>) has <em>passed state through the computation</em>. In other words, where we once returned a value of the type <code>A</code>, we are accepting an argument of the type <code>Memo</code> and returning the pair <code>(A, Memo)</code>. The state in this case is a value of the type <code>Memo</code>. We can represent this as a data structure:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">case</span> <span class="kw">class</span> State[S, A](run: S =&gt; (A, S))</code></pre>
<p>Our <code>fibmemoR</code> function which once had this type:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">def</span> <span class="fu">fibmemoR</span>(z: BigInt, memo: Memo): (BigInt, Memo)</code></pre>
<p>…can be transformed to this type:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">def</span> <span class="fu">fibmemoR</span>(z: BigInt): State[Memo, BigInt]</code></pre>
<p>Let’s write our new fibonacci function:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> FibMemo2 {
  <span class="kw">type</span> Memo = Map[BigInt, BigInt]

  <span class="kw">def</span> <span class="fu">fibmemo2</span>(n: BigInt): BigInt = {
    <span class="kw">def</span> <span class="fu">fibmemoR</span>(z: BigInt): State[Memo, BigInt] =
      State(memo =&gt;
        <span class="kw">if</span>(z &lt;= <span class="dv">1</span>)
          (z, memo)
        <span class="kw">else</span> memo get z <span class="kw">match</span> {
          <span class="kw">case</span> None =&gt; {
            <span class="kw">val</span> (r, memo0) = <span class="fu">fibmemoR</span>(z - <span class="dv">1</span>) run memo
            <span class="kw">val</span> (s, memo1) = <span class="fu">fibmemoR</span>(z - <span class="dv">2</span>) run memo
            (r + s, memo1)
          }
          <span class="kw">case</span> Some(v) =&gt; (v, memo)
        })

    <span class="fu">fibmemoR</span>(n).<span class="fu">run</span>(Map()).<span class="fu">_1</span>
  }
}</code></pre>
<p>Ew! This code is still rather clumsy as it manually passes the memo table around. What can we do about it? This is where the state monad is going to help us out. The state monad is going to take care of passing the state value around for us. The monad itself is implemented by three functions:</p>
<ol style="list-style-type: decimal">
<li><p>The <code>map</code> method on <code>State[S, A]</code>.</p></li>
<li><p>The <code>flatMap</code> method on <code>State[S, A]</code>.</p></li>
<li><p>The <code>insert</code> function on the <code>object State</code> that <em>inserts a value while leaving the state unchanged</em>.</p></li>
</ol>
<p>I will also add three convenience functions:</p>
<ol style="list-style-type: decimal">
<li><p><code>eval</code> method for running the <code>State</code> value and dropping the resulting state value.</p></li>
<li><p><code>get</code> function for taking the current state to a value. <code>(S =&gt; A) =&gt; State[S, A]</code></p></li>
<li><p><code>mod</code> function for modifying the current state. <code>(S =&gt; S) =&gt; State[S, Unit]</code></p></li>
</ol>
<p>Here goes:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">case</span> <span class="kw">class</span> State[S, A](run: S =&gt; (A, S)) {
  <span class="co">// 1. the map method</span>
  <span class="kw">def</span> map[B](f: A =&gt; B): State[S, B] =
    State(s =&gt; {
      <span class="kw">val</span> (a, t) = <span class="fu">run</span>(s)
      (<span class="fu">f</span>(a), t)
    })

  <span class="co">// 2. the flatMap method</span>
  <span class="kw">def</span> flatMap[B](f: A =&gt; State[S, B]): State[S, B] =
    State(s =&gt; {
      <span class="kw">val</span> (a, t) = <span class="fu">run</span>(s)
      <span class="fu">f</span>(a) run t
    })

  <span class="co">// Convenience function to drop the resulting state value</span>
  <span class="kw">def</span> <span class="fu">eval</span>(s: S): A =
    <span class="fu">run</span>(s).<span class="fu">_1</span>
}

<span class="kw">object</span> State {
  <span class="co">// 3. The insert function</span>
  <span class="kw">def</span> insert[S, A](a: A): State[S, A] =
    State(s =&gt; (a, s))

  <span class="co">// Convenience function for taking the current state to a value</span>
  <span class="kw">def</span> get[S, A](f: S =&gt; A): State[S, A] =
    State(s =&gt; (<span class="fu">f</span>(s), s))

  <span class="co">// Convenience function for modifying the current state</span>
  <span class="kw">def</span> mod[S](f: S =&gt; S): State[S, Unit] =
    State(s =&gt; ((), <span class="fu">f</span>(s)))
}</code></pre>
<p>We can see that the <code>flatMap</code> method takes care of passing the state value through a given function. This is the ultimate purpose of the state monad. Specifically, the state monad allows the programmer to pass a state (<code>S</code>) value through a computation (<code>A</code>) without us having to manually handle it. The <code>map</code> and <code>insert</code> methods complete the state monad.</p>
<p>How does our fibonacci implementation look now?</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> FibMemo3 {
  <span class="kw">type</span> Memo = Map[BigInt, BigInt]

  <span class="kw">def</span> <span class="fu">fibmemo3</span>(n: BigInt): BigInt = {
    <span class="kw">def</span> <span class="fu">fibmemoR</span>(z: BigInt): State[Memo, BigInt] =
      <span class="kw">if</span>(z &lt;= <span class="dv">1</span>)
        State.<span class="fu">insert</span>(z)
      <span class="kw">else</span>
        <span class="kw">for</span> {
          u &lt;- State.<span class="fu">get</span>((m: Memo) =&gt; m get z)
          v &lt;- u map State.<span class="fu">insert</span>[Memo, BigInt] getOrElse
                 <span class="fu">fibmemoR</span>(z - <span class="dv">1</span>) <span class="fu">flatMap</span> (r =&gt;
                 <span class="fu">fibmemoR</span>(z - <span class="dv">2</span>) <span class="fu">flatMap</span> (s =&gt; {
                 <span class="kw">val</span> t = r + s
                 State.<span class="fu">mod</span>((m: Memo) =&gt; m + ((z, t))) <span class="fu">map</span> (_ =&gt;
                 t)
                 }))
        } <span class="kw">yield</span> v

    <span class="fu">fibmemoR</span>(n) eval Map()
  }
}</code></pre>
<p>Now we have used the three state monad methods to pass the memo table through the computation for us - no more manual handling of passing that memo table through to successive recursive calls.</p>
<p>Scala provides syntax for the type of computation that chains calls to <code>flatMap</code> and <code>map</code>. It is implemented using the <code>for</code> and <code>yield</code> keywords in what is called a <em>for-comprehension</em>. The for-comprehension syntax will make the calls to <code>flatMap</code> and <code>map</code>, while allowing a more imperative-looking style. For example, where we once wrote code such as <code>x flatMap (r =&gt;</code>, we will now write <code>r &lt;- x</code> inside the for-comprehension.</p>
<p>How does this look?</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> FibMemo4 {
  <span class="kw">type</span> Memo = Map[BigInt, BigInt]

  <span class="kw">def</span> <span class="fu">fibmemo4</span>(n: BigInt): BigInt = {
    <span class="kw">def</span> <span class="fu">fibmemoR</span>(z: BigInt): State[Memo, BigInt] =
      <span class="kw">if</span>(z &lt;= <span class="dv">1</span>)
        State.<span class="fu">insert</span>(z)
      <span class="kw">else</span>
        <span class="kw">for</span> {
          u &lt;- State.<span class="fu">get</span>((m: Memo) =&gt; m get z)
          v &lt;- u map State.<span class="fu">insert</span>[Memo, BigInt] <span class="fu">getOrElse</span> (<span class="kw">for</span> {
                 r &lt;- <span class="fu">fibmemoR</span>(z - <span class="dv">1</span>)
                 s &lt;- <span class="fu">fibmemoR</span>(z - <span class="dv">2</span>)
                 t = r + s
                 _ &lt;- State.<span class="fu">mod</span>((m: Memo) =&gt; m + ((z, t)))
               } <span class="kw">yield</span> t)
        } <span class="kw">yield</span> v

    <span class="fu">fibmemoR</span>(n) eval Map()
  }
}</code></pre>
<p>This is a lot neater as the memoisation table is handled by the state monad. In fact, it is starting to look like the original naïve solution. We are no longer manually handling the state transitions, which allows us to express the essence of the problem and without the calculation speed blow-out.</p>
<p>Where you once may have use <code>var</code>, consider if the state monad is instead more appropriate.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Refactoring filter</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/refactoring-filter/index.html"/>
  <id>http://blog.tmorris.net/posts/refactoring-filter/index.html</id>
  <published>2013-01-12T00:00:00Z</published>
  <updated>2013-01-12T00:00:00Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <h2 id="the-filter-function">The <code>filter</code> function</h2>
<p>The <code>filter</code> function is one that accepts a list as an argument, keeping all elements that satisfy a given predicate, discarding all others and returns the resulting list. For example, I might use the <code>filter</code> function in Haskell to keep all <strong>even</strong> elements in a list:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">λ&gt; <span class="fu">filter</span> <span class="fu">even</span> [<span class="dv">2</span>,<span class="dv">3</span>,<span class="dv">6</span>,<span class="dv">2</span>,<span class="dv">4</span>,<span class="dv">7</span>,<span class="dv">6</span>,<span class="dv">75</span>,<span class="dv">22</span>]
[<span class="dv">2</span>,<span class="dv">6</span>,<span class="dv">2</span>,<span class="dv">4</span>,<span class="dv">6</span>,<span class="dv">22</span>]</code></pre>
<p>or perhaps using Scala:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">scala&gt; List(<span class="dv">2</span>,<span class="dv">3</span>,<span class="dv">6</span>,<span class="dv">2</span>,<span class="dv">4</span>,<span class="dv">7</span>,<span class="dv">6</span>,<span class="dv">75</span>,<span class="dv">22</span>) <span class="fu">filter</span> (_ % <span class="dv">2</span> == <span class="dv">0</span>)
res0: List[Int] = List(<span class="dv">2</span>, <span class="dv">6</span>, <span class="dv">2</span>, <span class="dv">4</span>, <span class="dv">6</span>, <span class="dv">22</span>)</code></pre>
<p>In both cases, the list structure under examination is a <a href="http://en.wikipedia.org/wiki/Cons">cons list</a>.</p>
<p>When I teach functional programming, we are usually implementing the <code>filter</code> function on <a href="https://github.com/tonymorris/course/blob/master/src/L02/List.hs#L80">our own cons list using Haskell</a><sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup> on the first day. Having done this enough times now, with both Haskell and Scala, I observe a recurring pattern.</p>
<p>The usual solutions are given either with explicit pattern-matching along with explicit recursion:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">fiilter _ [] <span class="fu">=</span> []
fiilter p (h<span class="fu">:</span>t) <span class="fu">=</span> <span class="kw">if</span> p h <span class="kw">then</span> h<span class="fu">:</span>fiilter p t <span class="kw">else</span> fiilter p t</code></pre>
<p>…or by using the provided <code>foldRight</code> function, which abstracts the pattern-matching and recursion for cons lists:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">fiilter p x <span class="fu">=</span> foldRight (\a b <span class="ot">-&gt;</span> <span class="kw">if</span> p a <span class="kw">then</span> a<span class="fu">:</span>b <span class="kw">else</span> b) [] x</code></pre>
<h2 id="re-implementing-filter-as-an-exercise">Re-implementing <code>filter</code> as an exercise</h2>
<p>Whichever solution is given, they are both correct. However, almost invariably, at this stage in the exercise, there is a developing suspicion that this solution can be <em>done better</em>. I am usually quizzed about how to improve the solution. For example, in the pattern-matching solution, both sides of the <code>if</code> branch repeat the code <code>fiilter p t</code>. Indeed, even in the <code>foldRight</code> solution, there is application to the value <code>b</code> on both sides of the <code>if</code> branch – a classic example of repetitive code (we functional programmers take the DRY principle seriously, even obsess over it!).</p>
<p>So let’s get on with the refactor. Since we are using pure functional programming, we are able to deploy <em>equational reasoning</em>. In other words, we are able to shuffle our expressions around, so long as we have an equivalent expression, because we are void of side-effects.</p>
<h2 id="denying-equational-reasoning">Denying equational reasoning</h2>
<p>Let’s take a quick diversion for a minute and imagine if we did not have this guarantee and suppose we were to tidy up this code:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">if</span> p <span class="kw">then</span> f x <span class="kw">else</span> f y</code></pre>
<p>This code can be refactored to remove the repetition of application of the function <code>f</code>:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">f (<span class="kw">if</span> p <span class="kw">then</span> x <span class="kw">else</span> y)</code></pre>
<p>However, imagine if <code>f</code> performed a side-effect! For example, if <code>f</code> printed its argument to standard output, then our refactoring would have altered the way the program runs.</p>
<p>Thankfully, in our context, we are guaranteed that this is not the case, so we can go right ahead.</p>
<h2 id="refactoring-fiilter">Refactoring <code>fiilter</code></h2>
<p>I am going to demonstrate a refactoring of <code>fiilter</code> at every intermediate step. Some people skip these steps when they do this for themselves, but I will specify each step that I usually see. The first step in refactoring the pattern-matching solution is to use <code>foldRight</code> as has already been given:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">fiilter p x <span class="fu">=</span> foldRight (\a b <span class="ot">-&gt;</span> <span class="kw">if</span> p a <span class="kw">then</span> a<span class="fu">:</span>b <span class="kw">else</span> b) [] x</code></pre>
<p>Once we get to this step (or perhaps we started here), we move on to removing the repetition in the lambda expression – specifically, the application to the value <code>b</code> appearing on each branch of the <code>if</code>.</p>
<p>First, let’s introduce the <code>id</code> function, perhaps the easiest function to understand ever!</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="fu">id</span><span class="ot"> ::</span> a <span class="ot">-&gt;</span> a
<span class="fu">id</span> a <span class="fu">=</span> a</code></pre>
<p>That’s right, the <code>id</code> function takes one argument and simply returns it. That means I can refactor the above code to this, without changing the way the function behaves:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">fiilter p x <span class="fu">=</span> foldRight (\a b <span class="ot">-&gt;</span> <span class="kw">if</span> p a <span class="kw">then</span> a<span class="fu">:</span>b <span class="kw">else</span> <span class="fu">id</span> b) [] x</code></pre>
<p>All I have done here is use <code>id</code> on one side of the <code>if</code> branch. Next I am going to do a purely syntactic transformation. I am going to move the use of <code>(:)</code> into prefix position. I am doing this to help make the next step a bit more obvious :)</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">fiilter p x <span class="fu">=</span> foldRight (\a b <span class="ot">-&gt;</span> <span class="kw">if</span> p a <span class="kw">then</span> (<span class="fu">:</span>) a b <span class="kw">else</span> <span class="fu">id</span> b) [] x</code></pre>
<p>Now we apply the true side to <code>b</code> using <code>(:) a</code> and the false side using <code>id</code>. We can refactor that away by returning a function on each branch, then applying that result to <code>b</code>:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">fiilter p x <span class="fu">=</span> foldRight (\a b <span class="ot">-&gt;</span> (<span class="kw">if</span> p a <span class="kw">then</span> ((<span class="fu">:</span>) a) <span class="kw">else</span> <span class="fu">id</span>) b) [] x</code></pre>
<p>Great! The application to the value <code>b</code> occurs only once. Next we can remove the explicit value <code>b</code> that is declared for the lambda expression, then we merely apply a function to it. Let’s just return that function! In other words, since this:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">\x <span class="ot">-&gt;</span> f x</code></pre>
<p>…can be replaced with this:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">f</code></pre>
<p>…and this:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">\x y <span class="ot">-&gt;</span> f x y</code></pre>
<p>…can be replaced with this:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">\x <span class="ot">-&gt;</span> f x</code></pre>
<p>…then this:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">fiilter p x <span class="fu">=</span> foldRight (\a b <span class="ot">-&gt;</span> (<span class="kw">if</span> p a <span class="kw">then</span> ((<span class="fu">:</span>) a) <span class="kw">else</span> <span class="fu">id</span>) b) [] x</code></pre>
<p>…can be replaced with:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">fiilter p <span class="fu">=</span> foldRight (\a <span class="ot">-&gt;</span> <span class="kw">if</span> p a <span class="kw">then</span> ((<span class="fu">:</span>) a) <span class="kw">else</span> <span class="fu">id</span>) []</code></pre>
<p>OK, this is great! We are simply replacing each cons cell with the given function<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup> and we needn’t specify the list in the argument list only to apply to it on the far right. But are we finished?</p>
<h2 id="final-housekeeping">Final housekeeping</h2>
<p>Unfortunately, Haskell (and most languages) provide <code>if</code> as syntax. Since Haskell is a non-strict language, we can easily write it ourselves as a library function:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="ot">if&#39; ::</span> <span class="dt">Bool</span> <span class="ot">-&gt;</span> x <span class="ot">-&gt;</span> x <span class="ot">-&gt;</span> x
if&#39; p t f <span class="fu">=</span> <span class="kw">if</span> p <span class="kw">then</span> t <span class="kw">else</span> f</code></pre>
<p>So how does our code look?</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">fiilter p <span class="fu">=</span> foldRight (\a <span class="ot">-&gt;</span> if&#39; (p a) ((<span class="fu">:</span>) a) <span class="fu">id</span>) []</code></pre>
<p>No real improvement.</p>
<p>However, for consistency with other <em>catamorphisms</em><sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup> in the Haskell library, we should shuffle the argument order<sup><a href="#fn4" class="footnoteRef" id="fnref4">4</a></sup>. I will also move the false branching argument to the <em>first position</em>. There is an underlying theoretical reason for this, but run with me for now!</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="ot">if&#39; ::</span> x <span class="ot">-&gt;</span> x <span class="ot">-&gt;</span> <span class="dt">Bool</span> <span class="ot">-&gt;</span> x
if&#39; f t p <span class="fu">=</span> <span class="kw">if</span> p <span class="kw">then</span> t <span class="kw">else</span> f</code></pre>
<p>Great, we have a branching function with arguments in appropriate order :)</p>
<p>OK so what about now?</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">fiilter p <span class="fu">=</span> foldRight (\a <span class="ot">-&gt;</span> if&#39; <span class="fu">id</span> ((<span class="fu">:</span>) a) (p a)) []</code></pre>
<p>Still no real difference :( However, there is a very regular pattern to be observed here, perhaps a little too advanced for day one, but it is here nonetheless!</p>
<h3 id="function-composition">Function composition</h3>
<p>Let’s first do a small refactor on our expression using function composition. Any expression of the form:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">\x <span class="ot">-&gt;</span> f (g x)</code></pre>
<p>can be written using function composition:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">f <span class="fu">.</span> g</code></pre>
<p>Therefore, our expression <code>\a -&gt; if' id ((:) a) (p a)</code> can be written:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">\a <span class="ot">-&gt;</span> ((if&#39; <span class="fu">id</span> <span class="fu">.</span> (<span class="fu">:</span>)) a) (p a)</code></pre>
<p>Although, this is a somewhat messy step, it allows us to get to the next one, where the purpose becomes a bit more apparent.</p>
<h3 id="the-ski-combinator-calculus">The SK(I) combinator calculus</h3>
<p>We have an expression of this form:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">\x <span class="ot">-&gt;</span> f x (g x)</code></pre>
<p>This is known as <em>the S combinator of <a href="http://en.wikipedia.org/wiki/SKI_combinator_calculus">the SK(I) combinator calculus</a></em><sup><a href="#fn5" class="footnoteRef" id="fnref5">5</a></sup>. The S combinator generalises to an applicative functor<sup><a href="#fn6" class="footnoteRef" id="fnref6">6</a></sup> and we can exploit this to take our refactoring further. The S combinator (generalised) in Haskell is written with <code>(&lt;*&gt;)</code><sup><a href="#fn7" class="footnoteRef" id="fnref7">7</a></sup> and you will need to <code>import Control.Applicative</code> to use it.</p>
<p>The expression <code>\x -&gt; f x (g x)</code> can be written <code>f &lt;*&gt; g</code> and we have an expression of precisely this form:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">\a <span class="ot">-&gt;</span> ((if&#39; <span class="fu">id</span> <span class="fu">.</span> (<span class="fu">:</span>)) a) (p a)</code></pre>
<p>which can be refactored to:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">if&#39; <span class="fu">id</span> <span class="fu">.</span> (<span class="fu">:</span>) <span class="fu">&lt;*&gt;</span> p</code></pre>
<p>This is great! So now our solution for <code>fiilter</code> looks like this:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">fiilter p <span class="fu">=</span> foldRight (if&#39; <span class="fu">id</span> <span class="fu">.</span> (<span class="fu">:</span>) <span class="fu">&lt;*&gt;</span> p) []</code></pre>
<h2 id="finally">Finally</h2>
<p>This is how I might express a final solution. Taking the refactoring this far is questionable to begin with, however, it is at least a great exercise in the application of equational reasoning and pattern recognition.</p>
<p>The readability of this code might also be questioned, however, it is very important to properly follow the process of pattern recognition before developing opinions about readability. I usually cannot address this concern quickly or in a helpful way. so I smile at this point and move on to the next exercise. Let’s do that :)</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>The function names have been altered to prevent clashing with those built-in.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>I emphasise and develop a very specific intuition of <code>foldRight</code> (and <code>foldLeft</code>) before attempting this exercise, so I be sure to use terminology that is specific to this explanation.<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p><code>foldRight</code>, <code>either</code>, <code>maybe</code> are all functions on which the final argument is the structure that is being <em>folded</em>. There is a very good reason for this, but let’s get on with it!<a href="#fnref3">↩</a></p></li>
<li id="fn4"><p>Since <code>if</code> is the fold (catamorphism) for the <code>Bool</code> structure, we will move the <code>Bool</code> to the final argument position.<a href="#fnref4">↩</a></p></li>
<li id="fn5"><p>Note the definition on the wiki, <code>Sxyz = xz(yz)</code> or in haskell syntax, <code class="sourceCode haskell">s x y z <span class="fu">=</span> x z (y z)</code>.<a href="#fnref5">↩</a></p></li>
<li id="fn6"><p>The <code>((-&gt;) t)</code> applicative functor is the S combinator.<a href="#fnref6">↩</a></p></li>
<li id="fn7"><p>I am often asked if this has a pronunciation and although I don’t know of an agreed term, I have heard: “spaceship operator”, “starship operator”, “angle bum.”<a href="#fnref7">↩</a></p></li>
</ol>
</div>
    </div>
  </content>
</entry>
<entry>
  <title>How to Find Thinking People</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/how-to-find-thinking-people/index.html"/>
  <id>http://blog.tmorris.net/posts/how-to-find-thinking-people/index.html</id>
  <published>2012-09-19T12:02:44Z</published>
  <updated>2012-09-19T12:02:44Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Here is how you find thinking people.</p>
<ul>
<li><p>You give them a <strong>really</strong> good answer to a problem they are having, spend some effort on it, have it reviewed, etc…</p></li>
<li><p>…then insert the word “fuck.”</p></li>
<li><p>If they talk about the word fuck, they are losers.</p></li>
<li><p>If they continue on learning, they are winners.</p></li>
<li><p>Discard losers.</p></li>
<li><p>Try to turn the thinking people into really good winners…</p></li>
<li><p>…then steal their good ideas.</p></li>
<li><p>The losers were never going to give you good ideas anyway.</p></li>
</ul>
    </div>
  </content>
</entry>
<entry>
  <title>SIP-18 is just another bad idea serving nobody</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/sip-18-is-just-another-bad-idea-serving-nobody/index.html"/>
  <id>http://blog.tmorris.net/posts/sip-18-is-just-another-bad-idea-serving-nobody/index.html</id>
  <published>2012-05-11T13:12:10Z</published>
  <updated>2012-05-11T13:12:10Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>SIP-18 is a bad idea because it makes awful assumptions about what is in the interest of language newcomers. I have had no shortage of unsolicited advice of how to teach, most of it in layers of wrongness, so I am acutely aware of the sheer quantity of this kind of advice. Please refrain for now. This is only my opinion, because it has been asked of me more than twice.</p>
<p>SIP-18 (and the Scala collections library for that matter) is no different to Haskell’s (dreaded) monomorphism restriction (DMR). The DMR was introduced specifically because of another chronically bold over-estimate of one’s ability to understand the process of learning. It is now an undesired language issue that hinders all users, <strong>especially newcomers</strong>. In other words, it serves nobody’s interest, hinders everyone’s interest and especially, the interest of those for whom it was meant to serve. You need only spend a short period of time with newcomers to Haskell to be overwhelmed by the prominence of this fact.</p>
<p>I can hear the pragmatists in the background muttering something about trade-offs, not being so extreme and keeping it relevant to the real world and blah blah blah, <em>insert the usual pragmatist bullshit here</em>. There is nothing to be traded off when you offer to take $5 from me for the low cost of $10. Now stop it and get your head out of the clouds so I can talk to you sensibly.</p>
<p>Not only does SIP-18 not help newcomers at all, it helps nobody, hinders everybody and <strong>especially newcomers</strong>. It is not a trade-off, it is not a good idea; it is simply a bold, severely misguided assertion about how learning takes place – it’s not even an approximation. I have seen only scant pseudo-psychology to support its existence, which obviates its predictable failure.</p>
<p>Hopefully, the Scala guys will work this out, but if Scala’s remarkable precision to repeat historical mistakes is anything to go by, I do not hold high hopes.</p>
<p>Thanks for asking.</p>
    </div>
  </content>
</entry>
<entry>
  <title>CAT (3D enhanced) Lumbosacral 2011-11-02 (24 hours post-op)</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/cat-3d-enhanced-lumbosacral-2011-11-02-24-hours-post-op/index.html"/>
  <id>http://blog.tmorris.net/posts/cat-3d-enhanced-lumbosacral-2011-11-02-24-hours-post-op/index.html</id>
  <published>2011-11-11T09:41:04Z</published>
  <updated>2011-11-11T09:41:04Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <h4 id="l4l5s1sacro-iliac-fusion">L4/L5/S1/Sacro-iliac fusion</h4>
<ul>
<li><p>L4/L5/S1 fusion performed 15 March 2011</p></li>
<li><p>Sacro-iliac fusion performed 01 November 2011</p></li>
</ul>
<ol style="list-style-type: decimal">
<li><p><a href="http://i.imgur.com/MwVxP.png"><img src="http://i.imgur.com/MwVxP.png" alt="1" /></a></p></li>
<li><p><a href="http://i.imgur.com/TQQMK.png"><img src="http://i.imgur.com/TQQMK.png" alt="2" /></a></p></li>
<li><p><a href="http://i.imgur.com/Zx34w.png"><img src="http://i.imgur.com/Zx34w.png" alt="3" /></a></p></li>
<li><p><a href="http://i.imgur.com/Dur1v.png"><img src="http://i.imgur.com/Dur1v.png" alt="4" /></a></p></li>
<li><p><a href="http://i.imgur.com/4Q3oc.png"><img src="http://i.imgur.com/4Q3oc.png" alt="5" /></a></p></li>
<li><p><a href="http://i.imgur.com/SeAhg.png"><img src="http://i.imgur.com/SeAhg.png" alt="6" /></a></p></li>
<li><p><a href="http://i.imgur.com/4HXHd.png"><img src="http://i.imgur.com/4HXHd.png" alt="7" /></a></p></li>
<li><p><a href="http://i.imgur.com/S5AoC.png"><img src="http://i.imgur.com/S5AoC.png" alt="8" /></a></p></li>
<li><p><a href="http://i.imgur.com/Uw0KC.png"><img src="http://i.imgur.com/Uw0KC.png" alt="9" /></a></p></li>
<li><p><a href="http://i.imgur.com/BPoBt.png"><img src="http://i.imgur.com/BPoBt.png" alt="10" /></a></p></li>
</ol>
    </div>
  </content>
</entry>
<entry>
  <title>I cannot use language X</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/i-cannot-use-language-x/index.html"/>
  <id>http://blog.tmorris.net/posts/i-cannot-use-language-x/index.html</id>
  <published>2011-10-27T11:27:35Z</published>
  <updated>2011-10-27T11:27:35Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I often hear people complain to me that they cannot use some superior programming language in their environment. Is it the right programming language to use? You sure? Great, now toughen up and use it.</p>
<p>You’re being told that you cannot? What is the reason given? Because “blah blah fucking said so blah blah.” There’s your problem – you subscribe to the illusion of authority and attribute it to the claimant. Abandon the illusion. No; actually abandon it to the extent of total non-existence. “Yeah but blah blah blah…” – I totally didn’t hear what you just said, intentionally. The consequences are not what you think they are.</p>
<p>“Oh but how come you get to use Haskell in your job?” Because I refuse to be bullied by fools proclaiming their authority with disregard for the common goal of getting the job done. Don’t give them the leverage – by way of believing it even exists – it doesn’t. I use whatever is appropriate and Haskell is often appropriate. It’s as simple as that.</p>
<p>HTFU and just do it properly. Unicorns do not exist. Deal with it accordingly. HTH.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Data Parallelism in Haskell</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/data-parallelism-in-haskell/index.html"/>
  <id>http://blog.tmorris.net/posts/data-parallelism-in-haskell/index.html</id>
  <published>2011-09-03T12:17:56Z</published>
  <updated>2011-09-03T12:17:56Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <h3 id="manuel-m-t-chakravarty-university-of-new-south-wales">Manuel M T Chakravarty – University of New South Wales</h3>
<h3 id="brisbane-functional-programming-group"><a href="http://bfpg.org/">Brisbane Functional Programming Group</a></h3>
<p>01 September 2011</p>
<p><a href="http://vimeo.com/28477220">Data Parallelism in Haskell</a> from <a href="http://vimeo.com/user8218847">Rob Manthey</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Lifting (Haskell addendum)</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/lifting-haskell-addendum/index.html"/>
  <id>http://blog.tmorris.net/posts/lifting-haskell-addendum/index.html</id>
  <published>2011-08-19T11:03:38Z</published>
  <updated>2011-08-19T11:03:38Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>A follow-on from <a href="http://blog.tmorris.net/lifting/">Lifting</a>. A port of the Scala code to Haskell follows.</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">class</span> <span class="dt">Lift</span> f <span class="kw">where</span>
  lift0 <span class="ot">::</span>
    a <span class="ot">-&gt;</span> f a

  lift1 <span class="ot">::</span>
    (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> f a <span class="ot">-&gt;</span> f b
  lift1 <span class="fu">=</span>
    ap <span class="fu">.</span> lift0

  lift2 <span class="ot">::</span>
    (a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> c) <span class="ot">-&gt;</span> f a <span class="ot">-&gt;</span> f b <span class="ot">-&gt;</span> f c
  lift2 f <span class="fu">=</span>
    ap <span class="fu">.</span> lift1 f

  lift3 <span class="ot">::</span>
    (a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> c <span class="ot">-&gt;</span> d) <span class="ot">-&gt;</span> f a <span class="ot">-&gt;</span> f b <span class="ot">-&gt;</span> f c <span class="ot">-&gt;</span> f d
  lift3 f a <span class="fu">=</span>
    ap <span class="fu">.</span> lift2 f a

  ap <span class="ot">::</span>
    f (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> f a <span class="ot">-&gt;</span> f b

<span class="co">-- scala.List</span>
<span class="kw">instance</span> <span class="dt">Lift</span> [] <span class="kw">where</span>
  lift0 <span class="fu">=</span>
    <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

  ap <span class="fu">=</span>
    <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- scala.Option</span>
<span class="kw">instance</span> <span class="dt">Lift</span> <span class="dt">Maybe</span> <span class="kw">where</span>
  lift0 <span class="fu">=</span>
    <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

  ap <span class="fu">=</span>
    <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- scala.Either[R, _]</span>
<span class="kw">instance</span> <span class="dt">Lift</span> (<span class="dt">Either</span> r) <span class="kw">where</span>
  lift0 <span class="fu">=</span>
    <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

  ap <span class="fu">=</span>
    <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- scala.Functior1[R, _]</span>
<span class="kw">instance</span> <span class="dt">Lift</span> ((<span class="ot">-&gt;</span>) r) <span class="kw">where</span>
  lift0 <span class="fu">=</span>
    <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

  ap <span class="fu">=</span>
    <span class="fu">error</span> <span class="st">&quot;todo&quot;</span></code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Java 7</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/java-7/index.html"/>
  <id>http://blog.tmorris.net/posts/java-7/index.html</id>
  <published>2011-08-18T21:06:13Z</published>
  <updated>2011-08-18T21:06:13Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Java 7 has proposed syntax for what Scala calls two methods:</p>
<p>1. <code class="sourceCode scala">Option.<span class="fu">flatMap</span></code> In Scala where we would normally write:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">(a, b, c, d) =&gt; <span class="kw">for</span> {
  aa &lt;- <span class="fu">a</span>(argsa)
  bb &lt;- <span class="fu">b</span>(argsb)
  cc &lt;- <span class="fu">c</span>(argsc)
  dd &lt;- <span class="fu">d</span>(argsd)
} <span class="kw">yield</span> <span class="fu">f</span>(aa, bb, cc, dd)</code></pre>
<p>While in Java we write:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="co">// ceremony in the absence of closures</span>
<span class="co">// has been omitted (and altered slightly) for brevity</span>
<span class="fu">a</span>(argsa)?.<span class="fu">b</span>(argsb)?.<span class="fu">c</span>(argsc)?.<span class="fu">d</span>(argsd).<span class="fu">f</span>();</code></pre>
<p>This syntax denotes the bind operation of <code>Option</code> monad, while Scala’s for-comprehension works for <em>any</em> monad. A pedantic point of note is that, from a particular perspective, Java’s syntax is slightly weaker than monad syntax, in that it is in fact, an applicative functor comprehension (not monad), since subsequent computations do not have access to previously computed values along the chain (if this is confuzzling, never mind – it’s important point otherwise, but not so much here). Scala’s for-comprehensions allow this, but it hasn’t been demonstrated above.</p>
<ol start="2" style="list-style-type: decimal">
<li><code class="sourceCode scala">Option.<span class="fu">getOrElse</span></code></li>
</ol>
<p>Java calls this <code>?:</code>, so while in Scala we might write <code>value getOrElse k</code>, or if you prefer Scalaz, <code>value | k</code>, in Java we’d write <code>value ?: k</code>. The Java version maintains the usual lack of safety of <code>null</code>, while Scala uses an algebraic data type.</p>
<p>Among many differences between Scala and Java here, one is that Scala does not introduce syntax for these two specific functions – after all, why would you? Further, what about the zillions of other useful functions? Java has no user-defined call-by-need unification, which means it is not possible to write <code>?:</code> yourself (even with a different valid Java identifier as a name). <a href="http://blog.tmorris.net/a-fling-with-lazy-evaluation/">I wrote about this once before</a>. I expect this is the reason for introduction of syntax for representing individual functions.</p>
<p>Scala’s representation is also safer, in that it uses a data structure to denote <em>a list with a maximum length of one</em>, rather than <em>a value with type T, oh wait, just kidding, it might be null!</em></p>
<p>My favourite part of Java’s proposed introduction of syntax for two very specific functions (among hundreds of others), watered down to be not-quite-as-useful, is the assurance that I am still going to hear about how Scala is complex, while Java is not. Fun times.</p>
<p><em>Edit: Proposed Java syntax.</em></p>
    </div>
  </content>
</entry>
<entry>
  <title>Lifting</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/lifting/index.html"/>
  <id>http://blog.tmorris.net/posts/lifting/index.html</id>
  <published>2011-07-17T10:57:29Z</published>
  <updated>2011-07-17T10:57:29Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Below is a compileable Scala source file. If you read it from top to bottom, it may help with some insights regarding applicative functors. It was partially inspired by Eric’s rendition of <a href="http://etorreborre.blogspot.com/2011/06/essence-of-iterator-pattern.html">The Essence of the Iterator Pattern</a>.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> Lift[F[_]] {
  <span class="co">// Spot the pattern in these type signatures</span>
  <span class="co">// of increasing arity.</span>

  <span class="kw">def</span> lift0[A]:
    A =&gt; F[A]

  <span class="kw">def</span> lift1[A, B]:
    (A =&gt; B) =&gt; (F[A] =&gt; F[B])

  <span class="kw">def</span> lift2[A, B, C]:
    (A =&gt; B =&gt; C) =&gt; (F[A] =&gt; F[B] =&gt; F[C])

  <span class="kw">def</span> lift3[A, B, C, D]:
    (A =&gt; B =&gt; C =&gt; D) =&gt; (F[A] =&gt; F[B] =&gt; F[C] =&gt; F[D])

  <span class="co">// ... and so on</span>

  <span class="co">// The relationship between lift&lt;n&gt; and lift&lt;n-1&gt;</span>
  <span class="co">// can be given by a function,</span>

  <span class="kw">def</span> ap[A, B]:
    F[A =&gt; B] =&gt; (F[A] =&gt; F[B])
}

<span class="kw">trait</span> LiftImpl[F[_]] <span class="kw">extends</span> Lift[F] {
  <span class="co">// Each lift function uses</span>
  <span class="co">// the previous lift function and ap.</span>

  <span class="kw">def</span> lift1[A, B]:
    (A =&gt; B) =&gt; (F[A] =&gt; F[B])
    = ap compose lift0

  <span class="kw">def</span> lift2[A, B, C]:
    (A =&gt; B =&gt; C) =&gt; (F[A] =&gt; F[B] =&gt; F[C])
    = f =&gt; ap compose <span class="fu">lift1</span>(f)

  <span class="kw">def</span> lift3[A, B, C, D]:
    (A =&gt; B =&gt; C =&gt; D) =&gt; (F[A] =&gt; F[B] =&gt; F[C] =&gt; F[D])
    = f =&gt; a =&gt; ap compose <span class="fu">lift2</span>(f)(a)
}

<span class="co">// Notes</span>
<span class="co">// * lift0 is often called: unit, return, pure, point, η</span>
<span class="co">// * lift1 is often called: fmap, map, ∘</span>
<span class="co">// * lift&lt;n&gt; is often called: liftA&lt;n&gt;, liftM&lt;n&gt;</span></code></pre>
<p>All that is left to do is to implement the <code>LiftImpl</code> trait! You can do this by implementing the <code>ap</code> and <code>lift0</code> functions.</p>
<p>Examples of implementations that I know will work out if you try to implement them:</p>
<ul>
<li><p><code class="sourceCode scala"><span class="kw">class</span> ListLift <span class="kw">extends</span> LiftImpl[List]</code></p></li>
<li><p><code class="sourceCode scala"><span class="kw">class</span> OptionLift <span class="kw">extends</span> LiftImpl[Option]</code></p></li>
<li><p><code class="sourceCode scala"><span class="kw">class</span> EitherLift[R] <span class="kw">extends</span> LiftImpl[({<span class="kw">type</span> λ[α] = Either[R, α]})#λ]</code></p></li>
<li><p><code class="sourceCode scala"><span class="kw">class</span> Function1Lift[R] <span class="kw">extends</span> LiftImpl[({<span class="kw">type</span> λ[α] = R =&gt; α})#λ]</code></p></li>
</ul>
<p>Those last couple are a bit funky, but a lot of that is syntax noise rather than anything too complicated. Fill out the body of those classes!</p>
    </div>
  </content>
</entry>
<entry>
  <title>Three and a half friggin years later</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/three-and-a-half-friggin-years-later/index.html"/>
  <id>http://blog.tmorris.net/posts/three-and-a-half-friggin-years-later/index.html</id>
  <published>2011-04-30T20:24:03Z</published>
  <updated>2011-04-30T20:24:03Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>The result of:</p>
<ul>
<li><p>The purchase and consumption of 31 medical text books on lower limb orthopaedics, neurology, neuro and spinal surgery and radiology.</p></li>
<li><p>Uncountable subscriptions to medical journals.</p></li>
<li><p>18 MRIs, 4 CAT scans, 3 XRAY scans, 3 bone scans.</p></li>
<li><p>12 surgical procedures; 8 to the lower limb, 3 to the lumbar spine. 1 (successfully) minor procedure performed by myself for a medical emergency for which acknowledgement was initially refused and later accepted after surgical extraction of foreign body.</p></li>
<li><p>29 doctors</p></li>
<li><p>AU$130K <em>(total estimated)</em></p></li>
<li><p>Having been misdiagnosed by a not-so-clever person named Dr Leigh Atkinson, including the suggestion that my chronic pain is “caused by the holy ghost.” Yes, seriously, he said this – while also in the room with a qualified medical professional (whom he called delusional in the same rant). He also claimed that I did not have Entrapment Neuropathy of SPN when I told him I strongly suspected it. I did – surgically verified by lower limb orthopaedic specialist (November 2009).</p></li>
<li><p>Having been repeatedly told for nearly two years by Dr Michael McEniery, who would threaten to sue me again if I was to call him incompetent or dangerous (even though this might be my genuinely held opinion based on substantiated fact and so he would lose) that I am obsessing about a minor condition, requiring no medical intervention, and that this obsession is because of the athletic demands of myself and my coach.</p></li>
<li><p>Having executed a partially-successful mission to demand immediate medical attention in March 2009 at significant expense.</p></li>
</ul>
<p>I have successfully and single-handedly diagnosed:</p>
<ul>
<li><p>Entrapment Neuropathy of the Superficial Peroneal Nerve, 10cm proximal to lateral malleolus (unilateral).</p></li>
<li><p>Foraminal Stenosis of the Fifth Lumbar (L5) Nerve Root (unilateral).</p></li>
<li><p>Spinal instability (Spondylolisthesis) at Fifth Lumbar (L5).</p></li>
<li><p>Withdrawal from morphine and oxycodone after immediate cessation.</p></li>
</ul>
<p>These conditions were caused by a single acute sporting injury in July 2007. I have been treated for all.</p>
<p>L4,L5,S1 fusion 15 March 2011 <img src="http://i.imgur.com/t0InY.jpg" alt="L4,L5,S1 Image" /></p>
<p>PS: This is why I sometimes demonstrate low tolerance for stupidity and/or failure or refusal to entertain the possibility of thinking. People get hurt. No, I am not sorry.</p>
    </div>
  </content>
</entry>
<entry>
  <title>A brief point on static typing</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/a-brief-point-on-static-typing/index.html"/>
  <id>http://blog.tmorris.net/posts/a-brief-point-on-static-typing/index.html</id>
  <published>2011-03-26T12:29:47Z</published>
  <updated>2011-03-26T12:29:47Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>This post also incidentally attempts to justify my answer to a question that I regularly encounter, <em>what is your favourite programming language?</em></p>
<blockquote>
<p>It’s not possible to write bug-free programs.</p>
</blockquote>
<p>This particular myth is quite popular, and its recent inclusion in a discussion I had has prompted me to write this post. The profound fact of this matter is that this statement is “as false as you can get.” In other words, there exists a formal proof of its negation, and subsequent counter-examples. It has also been my experience that belief in this myth has degenerative practical implications.</p>
<p>To emphasise the point, there exist programming languages for which <em>it is impossible to write an incorrect program</em>. What does it mean for a program to be correct? It means the program <em>terminates</em>. Such languages include (in order of my decreasing experience with them): Coq, Agda, Epigram, Isabelle.</p>
<p>Some people like to think “correctness” includes the thoughts of one or more persons in order to make the assessment. For example, one might proclaim, “sure you have a proof of program termination, but that is not the program that I asked for!” I think this is a poor use of the term “correctness” and I am not considering it any further here.</p>
<p>There is a problem with the aforementioned programming languages. A big one. While you always have correct programs in these languages, <em>you cannot have all general programs</em>. This is a well-documented contention. So you might say that these languages set out to achieve the objective of emphasising correctness, but at the expense of generality – in other words, they are exploring the question: “just how general and practical can we get, without sacrificing absolute correctness?” In my opinion, this is a very important question and worthy of further research.</p>
<p>Other programming languages sacrifice correctness for generality. In my typical work (I work for a product company), this includes languages such as Haskell, Scala and even Scala’s type system (which can be used as an embedded language). I expect most of my readers fall into this category of usage of languages. That is, we are all using languages that explore the question: “just how correct and practical can we get, without sacrificing generality?” In my opinion, this is a very important question too.</p>
<p>In the pursuit of answering both of the above questions, there are a number of contentions that arise. This means that there is not a <em>holy grail</em> programming language. It also means that there is a lot to understand before even starting to talk about the merits of correctness (aka static typing). This is unfortunate given the strong compulsion for, and quality of, popular commentary – we spend too much time clearing up myths. I digress.</p>
<p>However, this issue of contentions and trade-offs does not preclude the existence of questions of dismissal of programming languages. That is, it is possible to ask, and even answer, the question of whether or not there are programming languages that offer nothing toward resolving all of these (meaningful) contentions with respect to peer programming languages. These programming languages may be dismissed as offering nothing toward the goals of computability. It may be said that they are “universally impractical” with respect to the goals of computability (I am explicitly distinguishing here from social objectives). This may seem pessimistic, but it’s just a fact of the matter.</p>
<p>I hope that helps.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Anti-intellectual Euphemisms</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/anti-intellectual-euphemisms/index.html"/>
  <id>http://blog.tmorris.net/posts/anti-intellectual-euphemisms/index.html</id>
  <published>2011-03-13T08:49:26Z</published>
  <updated>2011-03-13T08:49:26Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I see this a lot, especially in programming forums.</p>
<ul>
<li><p>Using the word <em>simple</em>, <em>natural</em>, <em>pragmatic</em>, <em>real world</em> or <em>intuitive</em> to mean <strong>“I am able to understand this.”</strong></p></li>
<li><p>Conversely, using the word <em>complex</em>, <em>unnatural</em>, <em>academic</em>, <em>“your world”</em> or <em>unintuitive</em> to mean <strong>“I am not able nor am I willing to invest the effort to come to understand this.”</strong></p></li>
</ul>
<p>If someone does this, I will politely request that it stops, since it crushes any potential useful discussion.</p>
<p><em>–By request from Viktor. You don’t wanna mess with Viktor.</em></p>
    </div>
  </content>
</entry>
<entry>
  <title>Configuration Without the Bugs and Gymnastics</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/configuration-without-the-bugs-and-gymnastics/index.html"/>
  <id>http://blog.tmorris.net/posts/configuration-without-the-bugs-and-gymnastics/index.html</id>
  <published>2011-03-06T20:49:30Z</published>
  <updated>2011-03-06T20:49:30Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>…an introduction to the reader monad</p>
<ul>
<li><p><a href="http://vimeo.com/20674558">Video</a></p></li>
<li><p><a href="http://docs.tmorris.net/reader-monad/reader-monad.html">Slides</a></p></li>
</ul>
    </div>
  </content>
</entry>
<entry>
  <title>Understanding Practical API Design, Static Typing and Functional Programming</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/understanding-practical-api-design-static-typing-and-functional-programming/index.html"/>
  <id>http://blog.tmorris.net/posts/understanding-practical-api-design-static-typing-and-functional-programming/index.html</id>
  <published>2011-03-05T13:39:16Z</published>
  <updated>2011-03-05T13:39:16Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><em>…and how a marriage to a particular programming language is only indirectly and barely relevant</em></p>
<p>I was really tempted to title this post, “What to Solve Before Expecting Me to Take Your Opinions of Static Typing Seriously”, however, I figured this would be a bit too controversial and might detract from the points I wish to make. Nevertheless, I just want to make note, I think it is a very appropriate title.</p>
<p>The reason I think it’s a very appropriate title, is because of certain events that have happened recently. I teach advanced programming techniques to programmers. I do this voluntarily for the most part, and I occasionally deliver guest lectures to universities and other sporadic occurrences. I also teach at my place of employment, where I use these techniques for product development. I used to do university lecturing, until I came to the conclusion that the tertiary institution is in direct contention with the goal of education; the latter of which is important to me.</p>
<p>I have constructed the course material myself, predicting what would be useful, too difficult or too easy and so on and revising over time as these predictions fell out of place. Recently I set a task, predicted how difficult it would be, then was astonished to find that it appears to be <em>significantly more difficult than I had originally predicted</em>. I’m still not sure what is going on here, however, I think there are some lessons to be taken. One of which is a lesson about approaches to teaching advanced concepts of programming – something I am constantly learning about (and yearning for more solid research and experimental results!).</p>
<p>I asked students to write an API for the game tic-tac-toe. No need for the computer to tactically play tic-tac-toe – just an API that you can use to model the game itself. You can use any programming language you like, however, I think you will find certain environments to be lacking in the available tools, so I will guide you so that you’re not off somewhere “shaving yaks” so to speak.</p>
<p>If I’d left the requirement there, I can predict what I would have ended up with. Probably something similar to the API that I used to support at L3 for IBM where the number of bugs coming in was at a rate faster than I could fix them – and we don’t want that. Worse still, every time I fixed one bug gave rise to several new ones, no matter what I did! The whole point of this exercise is to avoid this scenario, once and for all, and without all that nonsense that gives false promise to deliver on this objective (Agile, XP, Scrum and all that silliness).</p>
<p>So I set some rules, but without further explanation of why these rules existed:</p>
<ul>
<li><p>If you write a function, I must be able to call it with the same arguments and always get the same results, forever.</p></li>
<li><p>If I, as a client of your API, call one of your functions, I should always get a sensible result. Not <code>null</code> or an exception or other backdoors that cause the death of millions of kittens worldwide.</p></li>
<li><p>If I call <code>move</code> on a tic-tac-toe board, but the game has finished, I should get a <strong>compile-time type-error</strong>. In other words, calling <code>move</code> on inappropriate game states (i.e. move doesn’t make sense) is disallowed by the types.</p></li>
<li><p>If I call <code>takeMoveBack</code> on a tic-tac-toe board, but no moves have yet been made, I get a <strong>compile-time type-error</strong>.</p></li>
<li><p>If I call <code>whoWonOrDraw</code> on a tic-tac-toe board, but the game hasn’t yet finished, I get a <strong>compile-time type-error</strong>.</p></li>
<li><p>I should be able to call various functions on a game board that is in any state of play e.g. <code>isPositionOccupied</code> works for in-play and completed games.</p></li>
<li><p>It is not possible to play out of turn.</p></li>
</ul>
<p>Now, why these rules? Well, because if you can achieve the goal of enforcing these rules, then the next phone call that I get in L3 support from an upset client, I can be guaranteed that one of the following are true:</p>
<ul>
<li><p>I have a bug in my code, in which case, the sooner the call, the better! …unless of course, fixing the bug results in only more bugs – but we have avoided that possibility – hopefully you can see why.</p></li>
<li><p>The client has misused the API and circumvented the type system. The client has used <code>null</code>, thrown an exception or performed a side-effect within the API or perhaps even used such things as Java reflection or even type-casting or type-casing. Unfortunately, in some environments, there’s not much I can do about enforcing that except impose a de facto rule where you assume non-existence of these possibilities (Just don’t do that!). Hopefully you haven’t yet jumped to the conclusion that any of these things are necessary or even useful – they aren’t.</p></li>
<li><p>The client is simply mistaken about the merits of their complaint.</p></li>
</ul>
<p>That’s it. There is nothing more to add to the list. <strong>Importantly, this list is significantly shorter than the list that I once had when supporting a typical Java application in IBM L3 support.</strong> How did I achieve this narrow list of possibilities before the phone even rang?</p>
<p>I have actually solved this problem using various programming languages:</p>
<ul>
<li><p>Haskell</p></li>
<li><p>Scala</p></li>
<li><p>C#</p></li>
<li><p>Java</p></li>
</ul>
<p>In order to take the emphasis off programming-language-centric issues, I will focus now on the Java solution (the most challenging environment in which to achieve the goal) and then I am going to invite you to conduct a thought experiment.</p>
<p>Let’s take a look at <a href="http://dl.dropbox.com/u/7810909/TicTacToe/javadoc/index.html">the javadoc for the Java solution</a>. Ignore the <code>Main</code> class for now, which simply gives you a 2-player console application that uses the API (feel free to run it!) – it depends on the rest of the API and so could be deleted without breaking anything.</p>
<p>If I asked you to be the most malicious user you can be, so long as you followed the rules (which I will assume you have done from here on), I want you to get an instance of the <code>FinishedBoard</code> class. If you rang me up in L3 support, even hiding your malicious intent from me, and said you had such an instance, then <em>I am absolutely guaranteed that you obtained that instance by playing a legitimate game of tic-tac-toe and ended up with a game that is in the position of a player winning or a draw</em>. Consider the implications of this for a moment.</p>
<p>For another example, suppose you rang and said that you called the <code>move</code> function and when you ran it, something-or-rather happened at run-time, <em>I can be guaranteed that you called that function on a game that was in-play and so had the ability to move, since otherwise it would not have compiled, let alone run</em>.</p>
<p>There are many more examples of these types of guarantees – invariants that I am certain have been met before I even start listening to you on the phone. I think this is an enormous advantage to real-world software tasks, don’t you? And all this done with Java and its overwhelmingly impractical type system. How about that!?</p>
<p>Now, producing an API of this nature seems to be more difficult for programmers than I originally predicted. Why is this? I can only conjecture and given my already-disproportionate prediction, I am hesitant to do so. Nevertheless, what you are looking at is <em>an extremely robust API for a relatively trivial problem</em>. This API robustness was achieved by exploiting techniques available from static typing and functional programming.</p>
<p>So let’s summarise. A robust API for a trivial game was written using several programming languages in such a way that appears to be difficult for many programmers to reproduce and using techniques such as exploiting static typing and functional programming. This was even done with a popular programming language that is not particularly amenable to achieving this degree of robustness.</p>
<p>In other words, many programmers have difficulty solving a trivial problem using techniques that many programmers are compelled to offer their comment on – no wonder there is a lot of outrageous hype! On the topic of why I expect you to be able to solve this problem before I take you seriously – it’s not because I have high standards, they’re incredibly low – it’s just that while these standards are very low, they are rarely satisfied. This is not a high-horse-motivated rant (as many insecure people might hastily conclude), the point I am making here is that I think it’s important to set standards of scepticism – maybe you should too!</p>
<p>It’s not just support issues where you will see an advantage to this programming technique. You might be writing an API for the guy sitting next to you. Those types are machine-checked documentation – he won’t have to keep bothering you about which function to call when – it’s obvious, since it’s specified in the type! You might even be your own client – suppose you hit a bug in your own code – you can rule out a huge number of possibilities of where that bug is, before you even start looking for it.</p>
<p>All these advantages of robust API design for less expense than the contrary and yet robust API design seems to be overwhelmingly rare. I am left only with questions, aren’t you? Come on guys, we can do a whole lot better. It’s an invitation!</p>
<p>It’s possible to take this particular API problem further using a language such as Agda or Coq and enforce the invariant that it’s not possible to make a move to a position on a board if that position has already been moved to. I know of one person who is attempting to achieve this. Godspeed.</p>
<p>I haven’t shown you the source to any of these solutions because I figure you might want to take a crack at it yourself. Give it a go! If you really want the source let me know and I’ll send you a link.</p>
<p>Hopefully this helps!</p>
    </div>
  </content>
</entry>
<entry>
  <title>Monads do not compose</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/monads-do-not-compose/index.html"/>
  <id>http://blog.tmorris.net/posts/monads-do-not-compose/index.html</id>
  <published>2011-02-24T11:32:16Z</published>
  <updated>2011-02-24T11:32:16Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>On the Scala mailing list, I said “monads do not compose.” What does this mean exactly? Hopefully the following answers it.</p>
<p>Let us first state the <code>Functor</code>, <code>Applicative</code> and <code>Monad</code> interfaces:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> Functor[F[_]] {
  <span class="kw">def</span> fmap[A, B](f: A =&gt; B, a: F[A]): F[B]
}

<span class="kw">trait</span> Applicative[F[_]] <span class="kw">extends</span> Functor[F] {
  <span class="kw">def</span> ap[A, B](f: F[A =&gt; B], a: F[A]): F[B]
  <span class="kw">def</span> point[A](a: A): F[A]
  <span class="kw">override</span> <span class="kw">final</span> <span class="kw">def</span> fmap[A, B](f: A =&gt; B, a: F[A]) =
    <span class="fu">ap</span>(<span class="fu">point</span>(f), a)
}

<span class="kw">trait</span> Monad[F[_]] <span class="kw">extends</span> Applicative[F] {
  <span class="kw">def</span> flatMap[A, B](f: A =&gt; F[B], a: F[A]): F[B]
  <span class="kw">override</span> <span class="kw">final</span> <span class="kw">def</span> ap[A, B](f: F[A =&gt; B], a: F[A]) =
    <span class="fu">flatMap</span>((ff: A =&gt; B) =&gt; <span class="fu">fmap</span>((aa: A) =&gt; <span class="fu">ff</span>(aa), a), f)
}</code></pre>
<p>Let’s now restate our claims:</p>
<ol style="list-style-type: decimal">
<li><p>Functors compose</p></li>
<li><p>Applicatives compose</p></li>
<li><p>Monads do not compose</p></li>
</ol>
<p>I will now address points 1) and 2). What does it mean for X to compose in this context? Let us now answer that question more succinctly:</p>
<p>It means that we can write a function with this signature (for some X):</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">def</span> XCompose[M[_], N[_]](<span class="kw">implicit</span> mx: X[M], nx: X[N]):
  X[({<span class="kw">type</span> λ[α]=M[N[α]]})#λ]</code></pre>
<p>This return type may look like gobbledy, but it’s just a fancy way of doing partial type constructor application in Scala. It is essentially the X type constructor applied to the composition of M and N and followed by a type variable just like M and N itself (kind * -&gt; *). Let us now test our claims.</p>
<p>Functors compose. That is to say, we can write:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">def</span> FunctorCompose[M[_], N[_]]
    (<span class="kw">implicit</span> mx: Functor[M], nx: Functor[N]):
       Functor[({<span class="kw">type</span> λ[α]=M[N[α]]})#λ]</code></pre>
<p>Let’s do it!</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">new</span> Functor[({<span class="kw">type</span> λ[α]=M[N[α]]})#λ] {
  <span class="kw">def</span> fmap[A, B](f: A =&gt; B, a: M[N[A]]) =
      mx.<span class="fu">fmap</span>((na: N[A]) =&gt; nx.<span class="fu">fmap</span>(f, na), a)
}</code></pre>
<p>Here we are composing two Functors. Claim 1) is demonstrated. What about claim 2)? Here we go. Hold your breath!</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">def</span> ApplicativeCompose[M[_], N[_]]
    (<span class="kw">implicit</span> ma: Applicative[M], na: Applicative[N]):
        Applicative[({<span class="kw">type</span> λ[α]=M[N[α]]})#λ] =
  <span class="kw">new</span> Applicative[({<span class="kw">type</span> λ[α]=M[N[α]]})#λ] {
  <span class="kw">def</span> ap[A, B](f: M[N[A =&gt; B]], a: M[N[A]]) = {
    <span class="kw">def</span> liftA2[X, Y, Z](f: X =&gt; Y =&gt; Z, a: M[X], b: M[Y]): M[Z] =
      ma.<span class="fu">ap</span>(ma.<span class="fu">fmap</span>(f, a), b)
    <span class="fu">liftA2</span>((ff: N[A =&gt; B]) =&gt; (aa: N[A]) =&gt; na.<span class="fu">ap</span>(ff, aa), f, a)
  }
  <span class="kw">def</span> point[A](a: A) =
    ma <span class="fu">point</span> (na point a)
}</code></pre>
<p>Have fun untangling that! It’s a bit noisy but this is mostly because Scala requires a lot of boilerplate. Hopefully you can get to the essence of what it means to compose two Applicative functors.</p>
<p>Now let’s move to Monad. Essentially, I am saying that you won’t be able to write such a function for Monad. I really encourage you to try to write it so you can see the twist that you will get into.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">def</span> MonadCompose[M[_], N[_]](<span class="kw">implicit</span> ma: Monad[M], na: Monad[N]):
    Monad[({<span class="kw">type</span> λ[α]=M[N[α]]})#λ]</code></pre>
<p>Here is a compilable version <a href="http://paste.pocoo.org/show/343606/">http://paste.pocoo.org/show/343606/</a></p>
<p>Hope that helps!</p>
    </div>
  </content>
</entry>
<entry>
  <title>List with O(1) cons and snoc in Scala</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/list-with-o1-cons-and-snoc-in-scala/index.html"/>
  <id>http://blog.tmorris.net/posts/list-with-o1-cons-and-snoc-in-scala/index.html</id>
  <published>2011-02-20T10:40:48Z</published>
  <updated>2011-02-20T10:40:48Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>A pseudo difference list with constant time prepend (cons) and append (snoc).</p>
<p><a href="http://code.google.com/p/scalaz/issues/detail?id=19">There is an efficiency issue</a> with respect to Scala’s TCO implementation (making this data structure untenable?), however, I have forgotten the details of that.</p>
<p>In any case, a finger-tree is often more appropriate, but it would be nice to revive the <code>Endo[List[A]]</code>!</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">sealed</span> <span class="kw">trait</span> DiffList[A] {
  <span class="kw">val</span> endo: List[A] =&gt; List[A]

  <span class="kw">import</span> DiffList.<span class="fu">_</span>

  <span class="co">// cons O(1)</span>
  <span class="kw">def</span> &lt;::(a: A): DiffList[A] = <span class="kw">new</span> DiffList[A] {
    <span class="kw">val</span> endo = (z: List[A]) =&gt; a :: DiffList.<span class="fu">this</span>.<span class="fu">endo</span>(z)
  }

  <span class="co">// snoc O(1)</span>
  <span class="kw">def</span> ::&gt;(a: A): DiffList[A] = <span class="kw">new</span> DiffList[A] {
    <span class="kw">val</span> endo = (z: List[A]) =&gt; DiffList.<span class="fu">this</span>.<span class="fu">endo</span>(a :: z)
  }

  <span class="co">// append O(1)</span>
  <span class="kw">def</span> :::&gt;(a: DiffList[A]): DiffList[A] = <span class="kw">new</span> DiffList[A] {
    <span class="kw">val</span> endo = (z: List[A]) =&gt; DiffList.<span class="fu">this</span>.<span class="fu">endo</span>(a.<span class="fu">endo</span>(z))
  }

  <span class="co">// O(n)</span>
  <span class="kw">def</span> toList = <span class="fu">endo</span>(Nil)
}

<span class="kw">object</span> DiffList {
  <span class="kw">def</span> empty[A]: DiffList[A] = <span class="kw">new</span> DiffList[A] {
    <span class="kw">val</span> endo = (z: List[A]) =&gt; z
  }

  <span class="kw">def</span> single[A](a: A): DiffList[A] = a &lt;:: empty[A]
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>A fine example...</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/a-fine-example/index.html"/>
  <id>http://blog.tmorris.net/posts/a-fine-example/index.html</id>
  <published>2011-02-06T15:11:07Z</published>
  <updated>2011-02-06T15:11:07Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>…of <a href="http://dancres.wordpress.com/2011/02/05/links-for-2011-02-05/">a whinging cunt with nothing useful to say</a>. How fucking sad. At least try, at least, for fuck’s sake.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Critique of Odersky's Scala levels</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/critique-of-oderskys-scala-levels/index.html"/>
  <id>http://blog.tmorris.net/posts/critique-of-oderskys-scala-levels/index.html</id>
  <published>2011-01-17T11:37:29Z</published>
  <updated>2011-01-17T11:37:29Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Martin Odersky, creator of the Scala programming language, recently wrote <a href="http://www.scala-lang.org/node/8610">a brief article describing levels of Scala expertise</a>. Martin labelled the levels in increasing order: [A1, A2, A3, L1, L2, L3].</p>
<p>I wish to register a small objection here, with recognition of otherwise sound judgement. While the objection is small, I think the consequences of what I believe is an error, are quite detrimental.</p>
<p>I will repost Martin’s specification for L3, the highest:</p>
<blockquote>
<p>Level L3: Expert library designer</p>
</blockquote>
<blockquote>



</blockquote>
<blockquote>
<ul>
<li>Early initializers</li>
</ul>
</blockquote>
<blockquote>
<ul>
<li>Abstract types</li>
</ul>
</blockquote>
<blockquote>
<ul>
<li>Implicit definitions</li>
</ul>
</blockquote>
<blockquote>
<ul>
<li>Higher-kinded types</li>
</ul>
</blockquote>
<p>First, I will get a couple of nitpicks out of the way. Martin’s L2 specifies that variance annotations will be used at this level. I (we: scalaz) propose that there is another level again, where you come to the realisation that variance annotations are not worth their use in the context of Scala’s limited type-inferencing abilities and other details. Instead, prefer a short-hand version of <code>fmap</code> and <code>contramap</code> functions. Scalaz calls these ∘ and ∙. The details of why this is more appropriate are beside the point here. Nevertheless, Edward Kmett has set out to prove this hypothesis wrong. Many of us have and failed. As far as I know, there is nothing compelling yet but I wish Ed luck with his unique insights.</p>
<p>Second, the suggestion that L3 requires the use of early initializers boggles my mind a little. The idea that these details exist at all is a symptom of a lot of nasty language and interoperability issues. Ultimately, if you are relying on the language-specified initialization order in your library code, then you are doing something disastrously wrong. Long-time users of Scala will recall the number of changes this behaviour went through. There is a gremlin at every turn and (much) more disciplined approaches to library design.</p>
<p>To the point.</p>
<p>If L3 is the highest level attainable, where we are using higher-kinded values and implicits, then what about other levels that are <em>way higher</em> in the level of required understanding? Let’s be clear, the use of these features has been part of Scalaz for a few years now. I started Scalaz in 2007, when I learned that Scala had these two features (which are extremely important to library design). These features have enabled the encoding of much more advanced concepts – what about those?</p>
<p>Some concepts that belong way higher than Martin’s L3 specification are:</p>
<ul>
<li><p>encoding type-level transformations</p></li>
<li><p>advanced purely-functional data structures</p></li>
<li><p>automated specification-based testing and associated library authoring requirements to effectively achieve it</p></li>
<li><p>encoding algebraic structures of category theory and <em>ensuring these are available for practical use</em></p></li>
<li><p>understanding type theory, its goals and (truly understanding, for real) the benefits and trade-offs of static program verification</p></li>
<li><p>attempting a high (read: extremely high) degree of abstraction in the context of Scala’s limited laziness abilities.</p></li>
</ul>
<p>I take issue here because keen learners may be fooled into believing that as they are confident in understanding all concepts at L3, then they are qualified to be an “expert library designer.” I put it to you that there is an extraordinary leap from L3 to an API designer of any considerable merit. Indeed, in my opinion, L3 is just enough knowledge to even begin practical library design. Before I attract a charge of shooting too high or the usual anti-intellectual nonsense, I like to remind others that I like to aim high, very high. I encourage you to do so too. Nothing more.</p>
<p>I recently gave <a href="http://blog.tmorris.net/scala-exercise-with-types-and-abstraction/">a beginner API design quiz</a>. I use it in programming classes that I teach, where many people struggle with it. When these students eventually break through, they are equipped with a reasonable fundamental understanding of writing practical libraries and APIs. However, note the triviality of the problem and the observation (if you’ll trust me), that many programmers have difficulty. This leaves open a huge opportunity for improvement in problem-solving skills – let’s take it!</p>
<p>I’d hate to believe that L3 is “expert.” I’d be saddened to think others have been tricked into settling there too. Surely we can shoot higher than that Martin.</p>
<h2 id="edit">Edit</h2>
<p>A case in point, I was directed to <a href="http://www.reddit.com/r/programming/comments/f38z4/scala_levels_beginner_to_expert_application/c1cyp2j">this comment</a>:</p>
<blockquote>
<p>If it [scala] is a failure, why has the language - for exaple [sic] - the best collection library of all languages currently out there?</p>
</blockquote>
<p>Honestly and without any intention to exaggerate, it boggles my mind with fascination as to what could cause such a rapid and extreme departure from reality. Working with both Scala and Haskell in depth for many years, there is nothing more disheartening than putting Haskell aside and dealing with the underwhelming practicalities of Scala’s (and therefore, Java’s) libraries. Indeed, this Great Big Hole That Is Still Gaping Wide was one of the primary motivations for the creation of Scalaz when I was working on a commercial application yearning for useful libraries. That was many years ago. Nothing has changed.</p>
<p>That’s just Haskell. There are other examples of programming environments that completely annihilate Scala/Java in terms of useful libraries.</p>
<p>To believe the aforementioned statement is perhaps a symptom of shooting so disastrously low as purported by “L3, the highest level of expertise.” In other words, there are serious and observable consequences for having such low standards, to such an extent that one may even fall under the illusion presented in this statement. I hope you’ll agree that there are practical implications for believing these things.</p>
<p>Then I witnessed <a href="http://www.reddit.com/r/programming/comments/f38z4/scala_levels_beginner_to_expert_application/c1czlg9">this comment</a>, which completely misses the point. Specifically, this commenter is not at what Odersky would call L3, since the comment demonstrates lack of understanding of higher-order polymorphism (aka higher-kinds). I don’t wish to pull apart every naive comment, but I do wish to point out that we can aim much higher than this.</p>
<p><strong>MUCH MUCH HIGHER</strong></p>
<p>I lament, but fight on, for the encouragement of setting a higher standard. Sorry guys, but you’re way off base. We can do a fuck-load better than this and we have done exactly that, elsewhere.</p>
<p><em>– a former contributor to the Scala collection libraries with high hopes</em></p>
    </div>
  </content>
</entry>
<entry>
  <title>Today's ride following natural disaster</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/todays-ride-following-natural-disaster/index.html"/>
  <id>http://blog.tmorris.net/posts/todays-ride-following-natural-disaster/index.html</id>
  <published>2011-01-14T23:46:08Z</published>
  <updated>2011-01-14T23:46:08Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I went looking for my grandmother today, who lives on the bank of the Brisbane River in Wivenhoe Pocket. I didn’t find her, but I’ve been assured she is safe.</p>
<p>* <a href="http://www.vimeo.com/18780944">Video</a></p>
<p>Fernvale bridge 32 hours after peaking during major flood. The edge of the water is 830 metres from the bridge which is typically used to traverse the river. The width of the river is estimated to be over 1.5km.</p>
<p>The dried mud on the bitumen road indicates the peak height that was reached.</p>
<p>Note the street sign indicating a side street ahead. Coominya State School lies completely submerged in the water ahead.</p>
<p><a href="http://www.openstreetmap.org/?mlat=-27.43818&amp;mlon=152.63681&amp;zoom=14&amp;layers=M">Map location</a> The marker denotes the edge of the water as seen in the video to within a few metres.</p>
<p>* <a href="http://www.vimeo.com/18782012">Video</a></p>
<p>Alice Street and Queen Street, Goodna, Brisbane 32 hours after Brisbane River peaks in major flood disaster.</p>
<p>The peak height of the river can be seen at 0:01 when the road changes to a dirty colour.</p>
<p><a href="http://www.openstreetmap.org/?lat=-27.6139&amp;lon=152.90214&amp;zoom=17&amp;layers=">Map location</a></p>
<p>* <a href="http://www.vimeo.com/18782516">Video</a></p>
<p>Schmidt Road, Fernvale 32 hours after Brisbane River peaks in major flood disaster.</p>
<p>The peak height of the river can be seen in the debris that hangs in the fences.</p>
<p><a href="http://www.openstreetmap.org/?mlat=-27.44542&amp;mlon=152.65106&amp;zoom=15&amp;layers=M">Map location</a></p>
    </div>
  </content>
</entry>
<entry>
  <title>Java is pass by value</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/java-is-pass-by-value/index.html"/>
  <id>http://blog.tmorris.net/posts/java-is-pass-by-value/index.html</id>
  <published>2011-01-13T16:02:38Z</published>
  <updated>2011-01-13T16:02:38Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I was linked to <a href="http://www.theserverside.com/news/thread.tss?track=NL-461&amp;ad=808081&amp;thread_id=61622&amp;asrc=EM_NLN_13145929&amp;uid=2780877">this silly thread</a> today. I didn’t read much of it and I recommend you don’t either.</p>
<p>Instead, take note, it’s yet another example of Java programmers knowing one language and knowing it poorly. This consistent observation is not particularly interesting, but this particular misunderstanding was cleared up <em>years</em> ago. I went through an old Java FAQ database that I had written while I was working on the IBM implementation <em>in 2000</em> where I explained all this. It was even asked in one of my wanky Java certifications back then. There were surely other explanations around at the time too. <em>Sigh</em>, Java guys, please… do yourself a favour and at least understand the shitty language that you hold so dear.</p>
<p>Java has two possible parameter types</p>
<ol style="list-style-type: decimal">
<li><p>Object references</p></li>
<li><p>primitives (restricted to 8 in total)</p></li>
</ol>
<p>Note here that Java never passes objects, ever. They do not appear in the list above, double-check to make sure. Now, you don’t have to take my word for it; after all, I’m just a former implementer of the language and API specification and I assure you, that doesn’t change a thing with regard to credibility. However, just what was I implementing back then? It was a number of specifications; one of which was called The Java Virtual Machine Specification (VMS).</p>
<p>Here is <a href="http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#26454">section 2.10.1 of the VMS</a>. I will quote the whole section to make sure this point sinks in. If you are unsure whether Java passes by reference or value or some variation, then please read it again. Repeat this until you comprehend the important part. Here goes:</p>
<blockquote>
<p>The formal parameters of a method, if any, are specified by a list of comma-separated parameter specifiers. Each parameter specifier consists of a type and an identifier that specifies the name of the parameter. When the method is invoked, the values of the actual argument expressions initialize newly created parameter variables (§2.5), each of the declared type, before execution of the body of the method.</p>
</blockquote>
<p>A method parameter of type float always contains an element of the float value set (§2.4.3); similarly, a method parameter of type double always contains an element of the double value set. It is not permitted for a method parameter of type float to contain an element of the float-extended-exponent value set that is not also an element of the float value set, nor for a method parameter of type double to contain an element of the double-extended-exponent value set that is not also an element of the double value set.</p>
<p>Where an actual argument expression corresponding to a parameter variable is not FP-strict (§2.18), evaluation of that actual argument expression is permitted to use values drawn from the appropriate extended-exponent value sets. Prior to being stored in the parameter variable, the result of such an expression is mapped to the nearest value in the corresponding standard value set by method invocation conversion (§2.6.8).</p>
<p>Let me extract a really important part:</p>
<blockquote>
<p>_…initialize newly created parameter variables (§2.5), each of the declared type, before execution of the body of the method. _</p>
</blockquote>
<p>Did you see that? Java is pass by value, without reservation. It says so in the specification. It is even observable by writing a trivial program.</p>
<pre class="sourceCode Java"><code class="sourceCode java">Object o = <span class="kw">new</span> Object();</code></pre>
<p>Now I know you may be accustomed to calling ‘o’ an object here, and it may even be the source of confusion, but it’s not an object. It’s an object reference. The object referred to by ‘o’ has no name.</p>
<p>When you pass ‘o’, it is copied, as per the <strong>specification</strong>, to a new reference, specified by the method being called. This means that if you reassign that reference, it cannot be observed outside of that method. Of course, since <strong>it is a copy of the method parameter</strong>.</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="dt">void</span> <span class="fu">method</span>(Object o) {
  o = x; <span class="co">// not observable outside local scope</span>
}</code></pre>
<p>If you were to dereference ‘o’ you may be able to execute some effect that may be outside of the method. Note the adjective here, <strong>dereference</strong>. What are we dereferencing? An object reference of course! Surely you have seen a <code>NullPointerException</code>. Know what this means? You dereferenced a reference which held no object!</p>
<p>I don’t know how else to make this clear, so I won’t continue trying.</p>
<p><strong>Java is pass by value.</strong></p>
    </div>
  </content>
</entry>
<entry>
  <title>Scala exercise with types and abstraction</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/scala-exercise-with-types-and-abstraction/index.html"/>
  <id>http://blog.tmorris.net/posts/scala-exercise-with-types-and-abstraction/index.html</id>
  <published>2011-01-09T09:44:27Z</published>
  <updated>2011-01-09T09:44:27Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Write an API for playing tic-tac-toe. There should be no side-effects (or variables), at all, for real. The <code>move</code> function will take a game state, a <code>Position</code> and it will return a data type that you write yourself.</p>
<p>The following functions (at least) must be supported:</p>
<ol style="list-style-type: decimal">
<li><p><code>move</code> (as mentioned)</p></li>
<li><p><code>whoseTurn</code> (returns which player’s turn it is)</p></li>
<li><p><code>whoWon</code> (returns who won or if a draw)</p></li>
<li><p><code>playerAt</code> (returns which player, if any, is at a given position)</p></li>
</ol>
<p><strong>Importantly</strong>, the following must be true:</p>
<ol style="list-style-type: decimal">
<li><p>It is a <strong>compile-time error</strong> to call <code>move</code> or <code>whoseTurn</code> on a game that has been completed</p></li>
<li><p>It is a <strong>compile-time error</strong> to call <code>whoWon</code> on a game that has <strong>not</strong> been completed</p></li>
<li><p>The <code>playerAt</code> function must be supported on both complete and in-play games</p></li>
</ol>
<p>Good luck and may the types be with you.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Configuration versus Code</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/configuration-versus-code/index.html"/>
  <id>http://blog.tmorris.net/posts/configuration-versus-code/index.html</id>
  <published>2011-01-09T07:28:34Z</published>
  <updated>2011-01-09T07:28:34Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Sometimes I’ll be working away when a colleague will make some distinction between “that which is configuration” and “that which is code.” In all cases, it turns out that this distinction is premised on a having a very narrow understanding of solving software problems. That can’t be good.</p>
<p>When we write compositional code using techniques such as <em>referential transparency</em>, the distinction between configuration and code completely evaporates. I wish to emphasise this evaporation, so I will restate it: <strong>it is not possible to determine which is configuration and which is code, except when using very sloppy problem solving habits, no matter how much we wish to save the thesis</strong>. I made this emphasis because I have even seen people accept that the delineation disappears, then in the very next breath say something to the effect as if it were still there. Brains are fascinating machines. I digress.</p>
<p>Let us suppose a Haskell program, though, the language is unimportant to this point. We only need to examine the type signature:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="ot">application ::</span> <span class="dt">IO</span> ()</code></pre>
<p>If we need some form of “configuration”, such as a possible <code>String</code> value with a “default”, we pass it as such:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="ot">application ::</span> <span class="dt">Maybe</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> ()</code></pre>
<p>Then the body of <code>application</code> will apply the default: <code>fromMaybe &quot;default string&quot;</code>. Easy right?</p>
<p>You might have multiple configuration values and not necessarily with the type <code>String</code>. Now of course, since we are using Haskell (and not XML!), we can give our configuration values a type! Here is an example:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Initialisation</span> <span class="fu">=</span> <span class="dt">Initialisation</span> {
<span class="ot">  ioWait ::</span> <span class="dt">Int</span>
,<span class="ot"> performance ::</span> <span class="dt">Speed</span>
,<span class="ot"> password ::</span> <span class="dt">String</span>
}</code></pre>
<p>then your application becomes:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="ot">application ::</span> <span class="dt">Initialisation</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> ()</code></pre>
<p>With Haskell you also get record selector syntax with this data structure. This means that setting say, 2 of these values can be done with effort proportional to the size of 2. With languages such as Java, achieving this goal results in a quadratic blow-out, requiring n^2 methods with overloads where n is the number of record fields.</p>
<p>Now, notice how doing this is simply, <strong>using a function</strong>. Let’s be clear, I am using a function, like any other, a function, code. It is not special and does not deserve any elevated status above other functions. No more useless ceremony here.</p>
<p>A good example of an application, that I use each day, is <a href="http://xmonad.org/">xmonad</a>, which I “configure” by writing Haskell. OK, now let’s be honest, I just write a program and take advantage of the comprehensive libraries.</p>
<p>In some cases that make the distinction between configuration and code, it’s often that an inappropriate language has been chosen to write code in, such as XML. There is a direct mapping between the XML and whatever programming language they are using. However, the XML will often exhibit properties that programming languages such as Haskell exhibit universally e.g. reordering statements does not affect the observable outcome of the program. In other words, this is just functional programming with XML (yeah, my thoughts exactly).</p>
<p>Any effort that delineates between configuration and code is nothing more than a very reliable indicator of sloppy thinking. Think again.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Nothing returns anything, ever!</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/nothing-returns-anything-ever/index.html"/>
  <id>http://blog.tmorris.net/posts/nothing-returns-anything-ever/index.html</id>
  <published>2010-12-28T19:39:08Z</published>
  <updated>2010-12-28T19:39:08Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I once had the following discussion with someone regarding a Java project:</p>
<blockquote>
<p>Him: Once we did a project and we didn’t return anything from a method, ever (i.e. <code>void</code>) It went very well. Me: So everything was in CPS transform then so that you could simulate it? Him: No, we didn’t ever return anything ever! Me: So uh, it was uh, in CPS transform then, since er… you know… Him: No! Nothing. Return. Nothing. Ever. Void. Always! Me: Er yeah right uh huh.</p>
</blockquote>
<p>This person operates under the illusion that I am in an intellectual battle with him, so I can excuse the somewhat awkward discussion. My efforts to destroy this destructive illusion have been repeated failure to date. That’s a side-story.</p>
<p>It occurred to me later, thanks to Edward Kmett, that perhaps it wasn’t a CPS transform but using exceptions instead! I doubt that was the case :) I’m also reasonably confident this discussion was <em>argumentum ad ignorantiam</em> – my converser doesn’t know what CPS transform means (so it can’t possibly be true!), but that’s cool – let’s not dwell on it. Instead, let’s have a look how you can simulate returning a value without actually returning a value using continuation-passing style (CPS)!</p>
<p>We may conjure up both simple and elaborate examples of functions that actually return a value:</p>
<pre class="sourceCode Java"><code class="sourceCode java">Integer <span class="fu">wibble</span>(String s, <span class="dt">double</span> d)
Swizzler <span class="fu">function1</span>(<span class="dt">int</span> i, String s, Swazzle z)</code></pre>
<p>I am going to use the trivial example (top one), but I hope you’ll be able to extrapolate to swizzlier cases.</p>
<p>First, note that Java methods may perform side-effects willy-nilly. Passing in a <code>String</code> and a <code>double</code> are not the only values that the function may access. The function may print to standard output, use variables in any scope, read/write files, the network and so on. This changes things a little (read: a lot) with regard to how we look at a function, so perhaps this is why this technique has apparent (read: apparent) merit.</p>
<p>Suppose a very simple interface:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> To&lt;a&gt; {
  <span class="dt">void</span> <span class="fu">to</span>(A a);
}</code></pre>
<p>Quite simply, this function takes a polymorphic (aka generic) value and performs a side-effect, perhaps using this value. It is important to point out that this polymorphic interface may be modelled differently e.g. it may not be polymorphic:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> Stringer {
  <span class="dt">void</span> <span class="fu">stringer</span>(String s);
}</code></pre>
<p>This interface is exactly equivalent to <code>To&lt;String&gt;</code> so I’m also trusting that you’ll extrapolate my generic example to other possibilities.</p>
<p>Now, instead of returning a type e.g. <code>Integer</code> in the <code>wibble</code> function, we may return <code>void</code> with an additional <code>To&lt;Integer&gt;</code> argument. We can do this for every single function that would otherwise return a value!</p>
<p>How does that work then? Simple really. We compute the <code>Integer</code> as we normally would in the body of <code>wibble</code> and instead of returning it (we can’t of course), we pass it to the <code>to</code> method of the given <code>To&lt;Integer&gt;</code> instance.</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="dt">void</span> <span class="fu">wibble</span>(String s, <span class="dt">double</span> d, To&lt;integer&gt; t)</code></pre>
<p>And so on it goes, for every method.</p>
<p>Essentially, this results in a function that, instead of returning a value of type T, returns a value of the type <code>(T =&gt; void) =&gt; void</code> where <code>(T =&gt; void)</code> is represented by the <code>To</code> interface and is of course, in the position of a method argument where that method returns <code>void</code>. This is exactly equivalent to a specific example of a continuation. We are doing a CPS transform to simulate returning a value!</p>
<p>To summarise the formula:</p>
<blockquote>
<p>For a method that would normally return a type T, we can transform it in such a way to accept an argument of type <code>To&lt;T&gt;</code> and returns void.</p>
</blockquote>
<p>As for the merits of doing this, well I’ll leave that for another battle :) Further, there are some interesting properties about continuations, in particular, <a href="http://blog.tmorris.net/continuation-monad-in-scala/">they are a monad</a>, perhaps even <a href="http://blog.sigfpe.com/2008/12/mother-of-all-monads.html">the mother of all monads</a>, but we’ll leave all that for another day too.</p>
<p>Edit: Per comments, I think a clarification is in order. Doing this is a <strong>very very bad idea</strong> on the JVM (without tail-call elimination – note that the IBM implementation only does direct TCE). Doing this results in a significant performance degradation and increased syntax <strong>for zero benefit</strong>. I didn’t bring this up because I was never going to get that far in the original conversation that I mention. <strong>Beware.</strong></p>
    </div>
  </content>
</entry>
<entry>
  <title>Bye Reddit</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/bye-reddit/index.html"/>
  <id>http://blog.tmorris.net/posts/bye-reddit/index.html</id>
  <published>2010-12-28T14:37:46Z</published>
  <updated>2010-12-28T14:37:46Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>With idiotic shit like <a href="http://symbo1ics.com/blog/?p=788">this</a>, followed by overwhelmingly stupid commentary like <a href="http://www.reddit.com/r/programming/comments/es29o/the_air_on_which_haskell_programmers_seem_to/">this</a> and <a href="http://www.reddit.com/user/grauenwolf">the most ignorant and intellectually under-equipped programmer on the internet</a> (prove me wrong, but not now, in my moment of lament), I have cancelled my reddit account.</p>
<p>Fool is me for not doing it sooner. Bye.</p>
    </div>
  </content>
</entry>
<entry>
  <title>The Writer Monad using Scala (example)</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/the-writer-monad-using-scala-example/index.html"/>
  <id>http://blog.tmorris.net/posts/the-writer-monad-using-scala-example/index.html</id>
  <published>2010-12-12T20:54:06Z</published>
  <updated>2010-12-12T20:54:06Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Prompted by <a href="http://permalink.gmane.org/gmane.comp.lang.scala.user/34094">a question on the scala mailing list</a>, I have produced below a minimal library representing a data type called <code>Logger</code> and its monad implementation (see the <code>map</code> and <code>flatMap</code> methods).</p>
<p>This data type represents logging in a pure functional environment where you maintain compositionality of your code (i.e. no side-effects) and also, brevity of code – see the example usage below using a for-comprehension demonstrating this.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> Monoid[A] {
  <span class="kw">def</span> <span class="fu">append</span>(a1: A, a2: A): A
  <span class="kw">def</span> empty: A
}

<span class="kw">object</span> Monoid {
  <span class="kw">implicit</span> <span class="kw">def</span> ListMonoid[A]: Monoid[List[A]] = <span class="kw">new</span> Monoid[List[A]] {
    <span class="kw">def</span> <span class="fu">append</span>(a1: List[A], a2: List[A]) = a1 ::: a2
    <span class="kw">def</span> empty = Nil
  }
}

<span class="kw">case</span> <span class="kw">class</span> Logger[LOG, A](log: LOG, value: A) {
  <span class="kw">def</span> map[B](f: A =&gt; B) =
    Logger(log, <span class="fu">f</span>(value))

  <span class="kw">def</span> flatMap[B](f: A =&gt; Logger[LOG, B])(<span class="kw">implicit</span> m: Monoid[LOG]) = {
    <span class="kw">val</span> x = <span class="fu">f</span>(value)
    Logger(m.<span class="fu">append</span>(log, x.<span class="fu">log</span>), x.<span class="fu">value</span>)
  }

  <span class="co">// insert much more</span>
}

<span class="kw">object</span> Logger {
  <span class="kw">def</span> unital[LOG, A](value: A)(<span class="kw">implicit</span> m: Monoid[LOG]) =
    Logger(m.<span class="fu">empty</span>, value)

  <span class="co">// insert much more</span>
}

<span class="kw">object</span> Util {
  <span class="co">// utility</span>
  <span class="kw">implicit</span> <span class="kw">def</span> ListLogUtil[A](a: A) = <span class="kw">new</span> {
    <span class="kw">def</span> ~&gt;[B](b: B) = Logger(List(a), b)

    <span class="kw">def</span> &lt;|~[B](k: A =&gt; B) = Logger(List(<span class="fu">k</span>(a)), a)
  }

  <span class="kw">def</span> noLog[A](a: A) =
    Logger.<span class="fu">unital</span>[List[String], A](a)
}

<span class="co">// begin example</span>

<span class="co">/*</span>
<span class="co">$ scala Main 456</span>
<span class="co">RESULT: 7000</span>

<span class="co">LOG</span>
<span class="co">---</span>
<span class="co">adding one to 456</span>
<span class="co">converting int to string 457</span>
<span class="co">checking length of 457 for evenness</span>
<span class="co">multiplying 1000 by 7 to produce 7000</span>
<span class="co">*/</span>
<span class="kw">object</span> Main {
  <span class="kw">import</span> Util.<span class="fu">_</span>

  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]) {
    <span class="kw">val</span> x = <span class="fu">args</span>(<span class="dv">0</span>).<span class="fu">toInt</span> <span class="co">// parse int from command line</span>

    <span class="kw">val</span> r =
      <span class="kw">for</span>(a &lt;- <span class="fu">addOne</span>(x);
          b &lt;- <span class="fu">intString</span>(a);
          c &lt;- <span class="fu">lengthIsEven</span>(b);
          d &lt;- <span class="fu">noLog</span>(<span class="fu">hundredOrThousand</span>(c));
          e &lt;- <span class="fu">times7</span>(d)
         ) <span class="kw">yield</span> e

    <span class="fu">println</span>(<span class="st">&quot;RESULT: &quot;</span> + r.<span class="fu">value</span>)
    println
    <span class="fu">println</span>(<span class="st">&quot;LOG&quot;</span>)
    <span class="fu">println</span>(<span class="st">&quot;---&quot;</span>)
    r.<span class="fu">log</span> foreach println
  }

  <span class="kw">def</span> <span class="fu">addOne</span>(n: Int) =
    (<span class="st">&quot;adding one to &quot;</span> + n) ~&gt; (n + <span class="dv">1</span>)

  <span class="kw">def</span> <span class="fu">intString</span>(n: Int) =
    (<span class="st">&quot;converting int to string &quot;</span> + n) ~&gt; n.<span class="fu">toString</span>

  <span class="kw">def</span> <span class="fu">lengthIsEven</span>(s: String) =
    (<span class="st">&quot;checking length of &quot;</span> + s + <span class="st">&quot; for evenness&quot;</span>) ~&gt; (s.<span class="fu">length</span> % <span class="dv">2</span> == <span class="dv">0</span>)

  <span class="kw">def</span> <span class="fu">hundredOrThousand</span>(b: Boolean) = <span class="co">// no logging</span>
    <span class="kw">if</span>(b) <span class="dv">100</span> <span class="kw">else</span> <span class="dv">1000</span>

  <span class="kw">def</span> <span class="fu">times7</span>(n: Int) =
    (n * <span class="dv">7</span>) &lt;|~ (<span class="st">&quot;multiplying &quot;</span> + n + <span class="st">&quot; by 7 to produce &quot;</span> + _)
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Medileaks</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/medileaks/index.html"/>
  <id>http://blog.tmorris.net/posts/medileaks/index.html</id>
  <published>2010-12-08T22:02:01Z</published>
  <updated>2010-12-08T22:02:01Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Keeping with <a href="http://scienceblogs.com/pharyngula/2010/12/i_get_mail_3.php">the spirit of recent topics</a>, here is a letter I recently received:</p>
<blockquote>
<p>08 October 2010</p>
</blockquote>
<p>Dear Mr Morris,</p>
<p>DR MICHAEL MCENIERY</p>
<p>We act on behalf of Dr Michael McEniery.</p>
<p>Our client has provided us with a copy of your letter to Dr Lachlan Steffen dated 15 September 2010.</p>
<p>A number of comments within your letter are grossly inappropriate and contain defamatory imputations about our client, suggesting that he is dangerous and incompetent.</p>
<p>The publication of defamatory material in Queensland is actionable under section 7 of The Defamation Act 2005. Please understand that our client takes strong objection to your conduct and reserves his right to claim damages.</p>
<p>Our client demands that you immediately cease making any negative or derogatory comments or publications which may cause injury or loss to him. If you do not cease such conduct our client may take such action as he is advised without further notice to you.</p>
<p>Yours faithfully,</p>
<p>David Watt</p>
<p>…and a response…</p>
<blockquote>
<p>29 October 2010</p>
</blockquote>
<p>Dear Mr David Watt,</p>
<p>Re: DR MICHAEL MCENIERY (08 October 2010)</p>
<p>No.</p>
<p>Sincerely,</p>
<p>I might just leave this here:</p>
<blockquote>
<p>DEFAMATION ACT 2005 - SECT 25</p>
</blockquote>
<p>Defence of justification</p>
<p>It is a defence to the publication of defamatory matter if the defendant proves that the defamatory imputations carried by the matter of which the plaintiff complains are substantially true.</p>
<p>…and this too…</p>
<blockquote>
<p>DEFAMATION ACT 2005 - SECT 31</p>
</blockquote>
<p>Defences of honest opinion</p>
<pre><code>  (1) It is a defence to the publication of defamatory matter if the defendant proves that –

(a) the matter was an expression of opinion of the defendant rather than a statement of fact; and

(b) the opinion related to a matter of public interest; and

(c) the opinion is based on proper material. </code></pre>
<p>Just sayin’ :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>Dear Java library guy</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/dear-java-library-guy/index.html"/>
  <id>http://blog.tmorris.net/posts/dear-java-library-guy/index.html</id>
  <published>2010-11-24T10:57:15Z</published>
  <updated>2010-11-24T10:57:15Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">import java.io.File;</span>
<span class="kw">import java.util.Calendar;</span>

<span class="kw">import static java.util.Calendar.DAY_OF_WEEK;</span>
<span class="kw">import static java.util.Calendar.THURSDAY;</span>
<span class="kw">import static java.util.Calendar.TUESDAY;</span>
<span class="kw">import static java.util.Calendar.WEDNESDAY;</span>

<span class="kw">public</span> <span class="kw">class</span> ThreeAdder {
  <span class="co">// Convenience method to add the two given numbers, then adds 3.</span>
  <span class="co">// It&#39;s really convenient, promise.</span>
  <span class="co">// It even has tests and they passed! See below.</span>
  <span class="kw">public</span> <span class="dt">static</span> <span class="dt">int</span> <span class="fu">addThen3</span>(<span class="dt">int</span> a, <span class="dt">int</span> b) {
    <span class="kw">if</span>(<span class="kw">new</span> File(<span class="st">&quot;/etc/passwd&quot;</span>).<span class="fu">exists</span>() &amp;&amp; a &lt; <span class="dv">100</span>) {
      <span class="kw">return</span> a + b + <span class="dv">3</span>;
    } <span class="kw">else</span> <span class="kw">if</span> (b == <span class="dv">2</span>) {
      <span class="dt">int</span> day = Calendar.<span class="fu">getInstance</span>().<span class="fu">get</span>(DAY_OF_WEEK);
      <span class="kw">if</span> (day == TUESDAY || day == WEDNESDAY || day == THURSDAY)
        <span class="kw">return</span> <span class="dv">5</span> + a;
      <span class="kw">else</span>
        <span class="kw">return</span> <span class="dv">9</span>;
    } <span class="kw">else</span> <span class="kw">if</span>(a == <span class="dv">0</span>) {
      <span class="kw">return</span> b + <span class="dv">3</span>;
    } <span class="kw">else</span> <span class="kw">if</span>(b == <span class="dv">0</span>) {
      <span class="kw">return</span> a + <span class="dv">3</span>;
    } <span class="kw">else</span> {
      <span class="kw">return</span> <span class="dv">8</span>;
    }
  }

  <span class="kw">public</span> <span class="dt">static</span> &lt;a&gt; String <span class="fu">assertEq</span>(String name, A x, A y) {
    <span class="kw">return</span> name + (x.<span class="fu">equals</span>(y) ?
      <span class="st">&quot; [PASSED]&quot;</span> :
      <span class="st">&quot; [FAILED] {&quot;</span> + x + <span class="st">&quot;}  {&quot;</span> + y + &#39;}&#39;);
  }

  <span class="kw">public</span> <span class="dt">static</span> <span class="dt">void</span> <span class="fu">main</span>(String[] args) {
    String[] out = {
        <span class="fu">assertEq</span>(<span class="st">&quot;adding to zero&quot;</span>, <span class="fu">addThen3</span>(<span class="dv">0</span>, <span class="dv">0</span>), <span class="dv">3</span>)
    ,   <span class="fu">assertEq</span>(<span class="st">&quot;adding to zero&quot;</span>, <span class="fu">addThen3</span>(<span class="dv">0</span>, <span class="dv">4</span>), <span class="dv">7</span>)
    ,   <span class="fu">assertEq</span>(<span class="st">&quot;adding to zero&quot;</span>, <span class="fu">addThen3</span>(<span class="dv">4</span>, <span class="dv">0</span>), <span class="dv">7</span>)
    ,   <span class="fu">assertEq</span>(<span class="st">&quot;adding to zero&quot;</span>, <span class="fu">addThen3</span>(<span class="dv">1</span>, <span class="dv">0</span>), <span class="dv">4</span>)
    ,   <span class="fu">assertEq</span>(<span class="st">&quot;adding to zero&quot;</span>, <span class="fu">addThen3</span>(<span class="dv">0</span>, <span class="dv">1</span>), <span class="dv">4</span>)
    ,   <span class="fu">assertEq</span>(<span class="st">&quot;adding to zero&quot;</span>, <span class="fu">addThen3</span>(<span class="dv">0</span>, <span class="dv">1</span>), <span class="dv">4</span>)
    ,   <span class="fu">assertEq</span>(<span class="st">&quot;small numbers&quot;</span>,  <span class="fu">addThen3</span>(<span class="dv">2</span>, <span class="dv">4</span>), <span class="dv">9</span>)
    ,   <span class="fu">assertEq</span>(<span class="st">&quot;small numbers&quot;</span>,  <span class="fu">addThen3</span>(<span class="dv">2</span>, <span class="dv">3</span>), <span class="dv">8</span>)
    ,   <span class="fu">assertEq</span>(<span class="st">&quot;small numbers&quot;</span>,  <span class="fu">addThen3</span>(<span class="dv">3</span>, <span class="dv">3</span>), <span class="dv">9</span>)
    ,   <span class="fu">assertEq</span>(<span class="st">&quot;small numbers&quot;</span>,  <span class="fu">addThen3</span>(<span class="dv">3</span>, <span class="dv">2</span>), <span class="dv">8</span>)
    };

    <span class="kw">for</span>(String o : out) {
      System.<span class="fu">out</span>.<span class="fu">println</span>(o);
    }
  }
}</code></pre>
<p>No.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Safari Fuel Tanks -- Husqvarna TE510</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/safari-fuel-tanks-husqvarna-te510/index.html"/>
  <id>http://blog.tmorris.net/posts/safari-fuel-tanks-husqvarna-te510/index.html</id>
  <published>2010-10-26T19:57:36Z</published>
  <updated>2010-10-26T19:57:36Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://www.safaritanks.com.au/home/">Safari Tanks</a> recently released a long range fuel tank for the Husqvarna TE250/310/450/510 4-stroke enduro motorcycle. These bikes come standard with a 7.2 litre fuel tank, which simply does not cut the mustard, particularly for the thirsty 510.</p>
<p>I own a 2009 TE510 and a few weeks ago, I purchased <a href="http://www.safaritanks.com.au/home/14-Husqvarna/55-Husqvarna-TE250-310-450-510/flypage.tpl.html">this tank</a>. I was given the option of four colours: red, white, black or translucent. I chose white and I am happy with this choice. At this time, my bike had only done a few road kilometres and had not yet completed run-in.</p>
<p>Prior to my current TE510, I have owned other Husqvarna four stroke enduro motorcycles, but the TE510 is my first fuel-injected Husky. Below, I will attempt to write a balanced report of my experience with this product. Comments or questions are appreciated.</p>
<p>When it came time to fit the fuel tank, I found that the fuel pump did not install as specified and instead, could only fit in a 180 degree position. This is fine, except the supplied fuel line now did not reach the fuel tap outlet. Safari Tanks were quick to help me with this problem, spending a lot of time on the phone to resolve it (I live in Brisbane, about 1400km from Safari headquarters). Safari supplied me (express postage) with a suitable fuel line for the altered fuel pump fitting after I provided the measurements. This fuel line met my specifications and fit perfectly.</p>
<p>The <a href="http://safaritanksusa.com/Husqvarna%20Front.pdf">supplied instructions</a> did not mention that the side radiator guards (not the fins) must be removed, however this was pretty obvious since the tank was not going on otherwise. The fuel tank appears to provide better protection from side impact than the original guards as well. The stock radiator fins did not require any modification at all.</p>
<p>I had trouble fitting the seat since the seat post was a little too far posterior, so I removed the seat post. This allowed the seat to install perfectly.</p>
<p>As for the performance of the tank I cannot speak highly enough. After recently spending a 3-day weekend riding in a <a href="http://osm.org/go/ueGXNhZb-">massive state forest</a>, I didn’t once come even close to hitting reserve on the 510, nor did I ever fill the tank (to keep weight down). The tank is simply enormous and this attracted comments from other riders, even though it blends well with the bike’s styling.</p>
<p>However, aside from the extra weight of carrying more fuel, the ergonomics of the tank are indistinguishable from the original tank and it allows you to adopt a correct riding position even in aggressive riding. I was quite impressed with this obviously clever design given the massive increase in fuel range. I expect this is because the extra fuel capacity is below the typical fuel tank position.</p>
<p>The (supplied) fittings and mountings for the tank are very strong, particularly for the frame mount, and even after some hard riding (to give you an idea, I wrote off the stock tyre in 15 minutes) there was no sign of fatigue.</p>
<p>After going riding with my mates on a 510 race-style enduro with a 7.2 litre tank, it’s usually me who is the first to complain of the need to return to a fuel supply. Not anymore, not even close. I’m very happy with the purchase of the Safari fuel tank and I would recommend it to anyone. After dealing with some minor fitting issues and the obvious attention given to my complaints, I have no doubt that Safari will have sorted out those issues by now. I would recommend this fuel tank to any fellow enthusiast of Husqvarna high-performance motorcycles.</p>
<p>Some pictures of the bike fitted with the tank follow.</p>
<div class="figure">
<img src="http://i.imgur.com/0eWAR.jpg" alt="Husqvarna TE510 Safari Fuel Tank" /><p class="caption">Husqvarna TE510 Safari Fuel Tank</p>
</div>
<div class="figure">
<img src="http://i.imgur.com/YFZ09.jpg" alt="Husqvarna TE510 Safari Fuel Tank" /><p class="caption">Husqvarna TE510 Safari Fuel Tank</p>
</div>
<div class="figure">
<img src="http://i.imgur.com/uJybZ.jpg" alt="Husqvarna TE510 Safari Fuel Tank" /><p class="caption">Husqvarna TE510 Safari Fuel Tank</p>
</div>
<div class="figure">
<img src="http://i.imgur.com/ns6ZD.jpg" alt="Husqvarna TE510 Safari Fuel Tank" /><p class="caption">Husqvarna TE510 Safari Fuel Tank</p>
</div>
<div class="figure">
<img src="http://i.imgur.com/Qp61g.jpg" alt="Husqvarna TE510 Safari Fuel Tank" /><p class="caption">Husqvarna TE510 Safari Fuel Tank</p>
</div>
<div class="figure">
<img src="http://i.imgur.com/WSDmo.jpg" alt="Husqvarna TE510 Safari Fuel Tank" /><p class="caption">Husqvarna TE510 Safari Fuel Tank</p>
</div>
    </div>
  </content>
</entry>
<entry>
  <title>Brad's original post</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/brads-original-post/index.html"/>
  <id>http://blog.tmorris.net/posts/brads-original-post/index.html</id>
  <published>2010-10-19T11:08:16Z</published>
  <updated>2010-10-19T11:08:16Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://bradclow.blogspot.com/2009/03/tonys-letter-to-medical-board-of.html">A friend of mine, Brad Clow, has received demands to remove one of his blog posts by a lawyer.</a> This post contains a letter that I wrote to the Medical Health Board of Queensland in March 2009. The letter mentions the name of a doctor, from whom I have also received recent threats of legal action; specifically allegations of defamation. Brad has removed the name of this doctor.</p>
<p>These threats are without any legal basis at all and a cursory read of <a href="http://www.austlii.edu.au/au/legis/nsw/consol_act/da200599/">The Defamation Act 2005</a> makes this really quite apparent. Specifically, sections <a href="http://www.austlii.edu.au/au/legis/nsw/consol_act/da200599/s25.html">25</a> and <a href="http://www.austlii.edu.au/au/legis/nsw/consol_act/da200599/s31.html">31</a>. Neither myself nor Brad have made any defamatory claims against Dr Michael McEniery, however, I do have <em>honestly held opinions</em> which are based on <em>facts which are substantially true</em>. These opinions and facts will be made available for public viewing after I have sought advice from legal experts. Advice in this regard is most welcome and I promise a remarkable and quite alarming story.</p>
<p>It took me a little over a year longer to finally determine the correct diagnosis. I had an entrapment neuropathy of the superficial peroneal nerve 10cm proximal to the lateral malleolus causing traction injury and subsequent foraminal stenosis at the right L5 nerve root, resulting in severe neurological deficit. I also had anteromedial osseous impingement syndrome (caused by tibia/talus collision from foot drop) and four improperly installed screws causing (painful) interference in the talar joint. It is now 6 months since surgical resolution and I am left with some neurological deficit. It is not known if I will fully recover, though the treating surgeon is hopeful.</p>
<p>Brad’s original post, before he yielded to the legal demands, follows.</p>
<p>We received a copy of this yesterday evening. Please note Tony is a friend of mine and this is genuine.</p>
<blockquote>
<pre><code>
To The Medical Board of Queensland,</code></pre>
</blockquote>
<pre><code>My complaint is rather lengthy. It relates to an injury and subsequent treatment of that injury by various doctors and surgeons. I am not primarily complaining about any particular individual of the medical institution, rather, that I still have not been diagnosed and treated for my condition. I am desperately seeking diagnosis and a treatment. Some doctors may believe they have diagnosed my condition, but they have been wrong and this has been proven surgically. The best diagnosis available today is my own humble conjecture, which is terrifyingly inadequate.

On 28 July 2007, I suffered a severe inversion sprain to my right ankle. I&#39;d suffered a few previous sprains, but this one was much worse than others. I was kicking a football rather hard when I landed incorrectly. I was not weight-bearing for about 5-6 days. During that time I was a very fit athlete playing A1-grade tournament squash and was very active with many other hobbies.

Over the following months after the injury, I tried returning to sport and I could feel I had something wrong in my ankle. I hoped it would resolve, but it didn&#39;t. I could not put my joint into dorsiflexion due to a mechanical impingement and this resulted in muscle atrophy. Subsequently, I became very ill. Nevertheless, I pushed on with my sporting endeavours expecting my body to overcome the problem like it had many others in the past.

Eventually I conceded in January 2008 and sought help from Dr. Michael McEniery. We tried various treatments including a cortico-steroid injection and obtained MRI radiographs. Over time, this condition worsened to the point where I was forced to discontinue sport in May 2008. I have not been active since. I sought help from an orthopaedic surgeon, Dr. Greg Sterling, who prescribed a Broestrom Repair and medial arthroscopy since my complaint was mostly anteromedial.

At the time, I was very medically-illiterate and put much faith in medical doctors. I assumed a positive outcome from surgery, simply because I&#39;d had surgery in the past for various conditions and I was always better afterward. The procedure was performed on 15 September 2008 and the medial arthroscopy revealed deltoid ligament damage which was also repaired along with the ATFL and CFL.

I wore a cast for 2 weeks and an orthodic boot thereafter. Although I was in pretty intense pain, I&#39;d attributed this to the recent surgery and thought it would resolve. It didn&#39;t. In October 2008, I knew I was in big trouble – I had similar symptoms to pre-operative but they were now much worse. I immediately sought help from Dr. Greg Sterling who requested another MRI but in November 2008, could see nothing wrong. He said “see you in January 2009”. The prospect of waiting so long in agony was traumatising.

Around the same time, I&#39;d sought help from Dr. McEniery who claimed I was exaggerating my symptoms and attributing too much attention to my condition. This blatant oversight added further to my trauma – and he&#39;d almost convinced a member of my family of these falsehoods. I was suffering psychologically and I sought immediate help from Prince Charles Mental Health Unit.

I was discharged as an outpatient but I knew I was not mentally ill – I was in incredible pain and agony from a misdiagnosis by an orthopaedic surgeon. I set out to conquer the problem myself – scared and ill-educated on the subject matter – and was faced by the foreign medical protocols and language.

As my stress levels grew, I was admitted to the Prince Charles Mental Health Unit by Dr. John Reinders under a de facto ITO. I was also forced to take anti-psychotic medication. This is because of some of the desperate language I was using, for example, “do I have to operate on myself?” and Dr. Reinders felt I may be a harm to myself.

I&#39;d never been so low in my life. When taking anti-psychotic medication, you are very much unaware of your surroundings. It was only during a lull in the effect of the medication, that I decided I needed to get out of the hospital and do what I can for my ankle – I was convinced the doctors had erred and that this was a huge mistake. I requested a Psychiatric evaluation and was declared “in severe distress, but mentally healthy” and I was discharged.

I set about understanding ankle anatomy, conditions of the ankle and general medical protocols. I quickly learned that I had at least soft tissue impingement. Indeed, I had tissue trapped in the joint that was under permanent pressure due to the recent surgery – even when not weight bearing. This is as painful as you might imagine it to be and a little more given multiple pathologies.

I sought help from Dr. Andrew Wines (Foot &amp; Ankle Orthopaedic Surgeon) in Sydney who prescribed an arthroscopic debridement. This was performed under GA on 11 December 2008. To quote his remark, “you had a chunk of tissue about the size of my finger in there”. I was immediately weight bearing post-operative and the local aneasthetic provided some relief. As a result of this anaesthesis, I was under the false impression that my troubles were over. They weren&#39;t.

After a few days I knew I still had a severe and painful problem though I no longer had the problem of tissue impingement. It felt like I had bone impingement on dorsiflexion and I sought answers from medical literature. I eventually stumbled on Anteromedial Osseous Impingement Syndrome for which MRI radiography is inconclusive for diagnosis. I used my January 2009 appointment with Dr. Sterling to ask for a request form for a CAT radiograph and weight-bearing Xray. Dr. Sterling also made an appointment with Dr. Michael Lutz to determine if he could unravel this mysterious problem of mine.

Upon obtaining these radiographs, I saw immediately that I had a bone spur in the location of my pain. I sought assistance from Dr. Andrew Wines (again in Sydney) who agreed with me to some extent but wanted a second opinion in order to ensure he was not suffering a bias. I applaud this decision. I used my upcoming appointment with Dr. Lutz to achieve this second opinion. Dr. Lutz agreed that an open incision to excise osteophytes on my tibia may be appropriate and I was informed of the risks .

Dr. Wines performed an arthrotomic tibial ostectomy on 04 March 2009 under GA at Royal North Shore Hospital. I flew home the next day – I was weight bearing without assistance. Again, the anaesthetic provided a false belief that my problems were over.

Unfortunately, I still have the same problem I started with – I cannot put my ankle into dorsiflexion. Many doctors might attribute this to the recent surgery, but I know I am experiencing precisely the same symptoms that I have done for the last 18 months. Although the localised and extreme pain caused by a bone spur has been resolved, I still have bone impingement on dorsiflexion that is not localised. I also know that this is due to a very definite mechanical limitation, since I have had a Physiotherapist in the past attempt to push my joint past this point with intense force to no avail.

As a result of this inability for dorsiflexion, my muscles have atrophied up to my thoracic spine. Subsequently, I find breathing difficult and any position uncomfortable except for lying down. This has caused immense stress especially while I have maintained a full-time job (Computing Science Researcher) and I am considering indefinite unpaid sick leave. Unfortunately, a consequence of this is that I will no longer be able to afford regular flights to Sydney for treatment, radiographs and so on, therefore, I must continue the battle under all circumstances and despite exhaustion.

I have long maintained that my symptoms are only observable while I am weight-bearing and in an attempt at dorsiflexion. This means that surgeons who operate cannot check for resolution of these symptoms, MRI and CAT radiographs cannot exhibit them and the only weight-bearing Xray I have was not in dorsiflexion because the Radiographer would not allow it (images only per requesting doctor instructions).

Unfortunately, I still have quite a large battle ahead but I am at a complete loss with respect to how I should go about it and that is why I have written to you, my state medical authority.

Is there a radiographic machine available in Queensland that will exhibit my bone impingement while in dorsiflexion and while weight-bearing? Better still, is there a doctor who is prepared to do the hard work of figuring this problem out? I am more than willing to make many sacrifices to ensure it. These are rhetorical questions – I don&#39;t know what the right questions are.

I am desperately seeking a diagnosis and treatment, 19 months after an initial injury and I know that my time is limited with regard to the amount of stress and pain that I can continue to endure. This is simply unsustainable.

Please advise.

Thank you for your time. Confidentiality is not requested and you may share this information with whoever you see fit.</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>reverse.jar</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/reversejar/index.html"/>
  <id>http://blog.tmorris.net/posts/reversejar/index.html</id>
  <published>2010-09-29T21:13:04Z</published>
  <updated>2010-09-29T21:13:04Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>There was once a programming language called Jolly. It was exactly like what would become Java, except for a couple of differences.</p>
<ol style="list-style-type: decimal">
<li><p>The language did not have parametric polymorphism of any kind. No generics, nadda. In fact, the inventors of Jolly had never even heard of it.</p></li>
<li><p>The language did not have a common supertype. No <code>java.lang.Object</code></p></li>
</ol>
<p>The Jolly language was incredibly popular, especially among enterprise programmers. There were massive open source contributions written in Jolly, including one library, which was called <strong>list.reverse</strong>.</p>
<p>The <strong>list.reverse</strong> library had about 140 developers (and getting stronger!) across the world all working away. You see, since Jolly had no parametric polymorphism, every time you wanted to reverse a list of say, <code>Banana</code>s, you had to check if reverse was already written for Bananas in the library, or if not, write it and commit to HEAD.</p>
<p>An academic, Robin, was chuffing on a joint rolled in some bark on which he had scribbled the thesis for the pi-calculus, after having invented an advanced ML programming language (with generics), spent a few years launching a space probe with it, found the challenge uninteresting, then decided to take on the harder stuff, made the effort to let the Jolly developers in on a little secret, “Hey guys, parametric polymorphism – it was invented decades ago, has been formalised and shown to be useful in many domains, including this one.”</p>
<p>“Who <em>was</em> this guy!? How dare he interrupt us on our pursuit to solve real-world list reversing with this academic nonsense!” was the first post to the mailing list. The Jolly contributors were <em>furious</em> at the careless remark of this Robin guy who, as far as they were concerned, had never written a line of industry-grade software in his life.</p>
<p>“Guys, just saying. You don’t need to keep writing this library over and over. I thought you might like to know. Just introduce this language feature and you’re done. I’ve attached a patch.”</p>
<p>Well now didn’t this get under the nose of the Jolly contributors. All that hard work had just been undermined in a short email by this person who had never written a single line of Jolly in his entire life. What would he know about list reversing anyway!? We have years of experience!</p>
<p>The academic finished off his joint and visited his colleague down the hall, Hermann, who was about to publish a thesis on new findings in the Lie Algebra, “those guys really got upset eh?”, Hermann remarked. Robin, not giving much of a shit, made a noise through his nose then asked, “So what’s new?”</p>
<p>It’s now a few years since that email. The patch to Jolly was never looked at. The list.reverse developers recently released a version 5.0 of their library, which implements reverse for lists of every single class in the Jolly library, and includes a plug-in for every type in the most popular ORM library for Jolly. The project was also forked to include reverse for both arrays and lists and is now more popular than list.reverse.</p>
<p>Robin and Hermann have since forgotten that Jolly even exists. Their colleagues have advanced computational theory well beyond what will soon become Java.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Even Further Understanding scala.Option (part 2)</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/even-further-understanding-scalaoption-part-2/index.html"/>
  <id>http://blog.tmorris.net/posts/even-further-understanding-scalaoption-part-2/index.html</id>
  <published>2010-09-01T15:45:27Z</published>
  <updated>2010-09-01T15:45:27Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>As a follow-on to <a href="http://blog.tmorris.net/further-understanding-scalaoption/">Further Understanding scala.Option</a>, following are another 10 exercises (numbered 16 to 25). Included are solutions to the original 1 to 15 exercises. Instructions are in the comments.</p>
<pre><code>// Scala version 2.8.0.final
// http://scala-tools.org/repo-releases/org/scala-tools/testing/scalacheck_2.8.0/1.7/scalacheck_2.8.0-1.7.jar</code></pre>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">/*</span>

<span class="co">  PART 1</span>
<span class="co">  ======</span>
<span class="co">  Below are 15 exercises numbered 1 to 15. The task is to emulate the scala.Option API</span>
<span class="co">  without using Some/None subtypes, but instead using a fold (called a</span>
<span class="co">  catamorphism).</span>

<span class="co">  A couple of functions are already done (map, get)</span>
<span class="co">  to be used as an example. ScalaCheck tests are given below to</span>
<span class="co">  verify the work. The desired result is to have all tests passing.</span>

<span class="co">  The 15th exercise is not available in the existing Scala API so</span>
<span class="co">  instructions are given in the comments.</span>


<span class="co">  Part 2</span>
<span class="co">  ======</span>

<span class="co">  Below are 10 exercises numbered 16 to 25. The task is to implement additional</span>
<span class="co">  methods for the Optional data type. These methods are not provided in the</span>
<span class="co">  scala.Option API so to determine the correct result requires reading the method</span>
<span class="co">  type signature and ensuring that the tests pass.</span>

<span class="co">  The 25th exercise is notable in that its signature says nothing about</span>
<span class="co">  scala.Option yet it is usable for Option (see the test for example).</span>


<span class="co">  Revision History</span>
<span class="co">  ================</span>

<span class="co">  23/08/2010</span>
<span class="co">  * Initial revision</span>

<span class="co">  ----------------</span>

<span class="co">  23/08/2010</span>
<span class="co">  * Fixed prop_getOrElse. Thanks Michael Bayne.</span>

<span class="co">  ----------------</span>

<span class="co">  26/08/2010</span>
<span class="co">  * Add lazy annotation to orElse method.</span>

<span class="co">  ----------------</span>

<span class="co">  01/09/2010</span>
<span class="co">  Added Part 2</span>

<span class="co">  02/09/2010</span>
<span class="co">  * Fixed mapOptionals test (why wasn&#39;t it failing?). Thanks Alec Zorab.</span>
<span class="co">  * Added comments including *** special note ***</span>

<span class="co">*/</span>


<span class="kw">trait</span> Optional[A] {
  <span class="co">// single abstract method</span>
  <span class="kw">def</span> fold[X](some: A =&gt; X, none: =&gt; X): X

  <span class="kw">import</span> Optional.<span class="fu">_</span>

  <span class="co">// Done for you.</span>
  <span class="kw">def</span> map[B](f: A =&gt; B): Optional[B] =
    <span class="fu">fold</span>(f andThen some, none[B])

  <span class="co">// Done for you.</span>
  <span class="co">// WARNING: undefined for None</span>
  <span class="kw">def</span> get: A =
    <span class="fu">fold</span>(a =&gt; a, <span class="fu">error</span>(<span class="st">&quot;None.get&quot;</span>))

  <span class="co">// Exercise 1</span>
  <span class="kw">def</span> flatMap[B](f: A =&gt; Optional[B]): Optional[B] =
    <span class="fu">fold</span>(f, none)

  <span class="co">// Exercise 2</span>
  <span class="co">// Rewrite map but use flatMap, not fold.</span>
  <span class="kw">def</span> mapAgain[B](f: A =&gt; B): Optional[B] =
    <span class="fu">flatMap</span>(f andThen some)

  <span class="co">// Exercise 3</span>
  <span class="kw">def</span> <span class="fu">getOrElse</span>(e: =&gt; A): A =
    <span class="fu">fold</span>(s =&gt; s, e)

  <span class="co">// Exercise 4</span>
  <span class="kw">def</span> <span class="fu">filter</span>(p: A =&gt; Boolean): Optional[A] =
    <span class="fu">fold</span>(a =&gt; <span class="kw">if</span>(<span class="fu">p</span>(a)) <span class="fu">some</span>(a) <span class="kw">else</span> none, none)

  <span class="co">// Exercise 5</span>
  <span class="kw">def</span> <span class="fu">exists</span>(p: A =&gt; Boolean): Boolean =
    <span class="fu">fold</span>(p, <span class="kw">false</span>)

  <span class="co">// Exercise 6</span>
  <span class="kw">def</span> <span class="fu">forall</span>(p: A =&gt; Boolean): Boolean =
    <span class="fu">fold</span>(p, <span class="kw">true</span>)

  <span class="co">// Exercise 7</span>
  <span class="kw">def</span> <span class="fu">foreach</span>(f: A =&gt; Unit): Unit =
    <span class="fu">fold</span>(f, ())

  <span class="co">// Exercise 8</span>
  <span class="kw">def</span> isDefined: Boolean =
    <span class="fu">fold</span>(_ =&gt; <span class="kw">true</span>, <span class="kw">false</span>)

  <span class="co">// Exercise 9</span>
  <span class="kw">def</span> isEmpty: Boolean =
    <span class="fu">fold</span>(_ =&gt; <span class="kw">false</span>, <span class="kw">true</span>)

  <span class="co">// Exercise 10</span>
  <span class="kw">def</span> <span class="fu">orElse</span>(o: =&gt; Optional[A]): Optional[A] =
    <span class="fu">fold</span>(_ =&gt; <span class="kw">this</span>, o)

  <span class="co">// Exercise 11</span>
  <span class="kw">def</span> toLeft[X](right: =&gt; X): Either[A, X] =
    <span class="fu">fold</span>(<span class="fu">Left</span>(_), <span class="fu">Right</span>(right))

  <span class="co">// Exercise 12</span>
  <span class="kw">def</span> toRight[X](left: =&gt; X): Either[X, A] =
    <span class="fu">fold</span>(<span class="fu">Right</span>(_), <span class="fu">Left</span>(left))

  <span class="co">// Exercise 13</span>
  <span class="kw">def</span> toList: List[A] =
    <span class="fu">fold</span>(List(_), Nil)

  <span class="co">// Exercise 14</span>
  <span class="kw">def</span> iterator: Iterator[A] =
    <span class="fu">fold</span>(Iterator.<span class="fu">single</span>(_), Iterator.<span class="fu">empty</span>)

  <span class="co">// Exercise 15 The Clincher!</span>
  <span class="co">// Return a none value if either this or the argument is none.</span>
  <span class="co">// Otherwise apply the function to the argument in some.</span>
  <span class="co">// Don&#39;t be afraid to use functions you have written.</span>
  <span class="co">// Better style, more points!</span>
  <span class="kw">def</span> applic[B](f: Optional[A =&gt; B]): Optional[B] =
    f flatMap map

  <span class="co">// Utility</span>
  <span class="kw">def</span> toOption: Option[A] = <span class="fu">fold</span>(Some(_), None)

  <span class="co">// Utility</span>
  <span class="kw">override</span> <span class="kw">def</span> toString =
    <span class="fu">fold</span>(<span class="st">&quot;some[&quot;</span> + _ + <span class="st">&quot;]&quot;</span>, <span class="st">&quot;none&quot;</span>)

  <span class="co">// Utility</span>
  <span class="kw">override</span> <span class="kw">def</span> <span class="fu">equals</span>(o: Any) =
    o.<span class="fu">isInstanceOf</span>[Optional[_]] &amp;&amp; {
      <span class="kw">val</span> q = o.<span class="fu">asInstanceOf</span>[Optional[_]]
      <span class="fu">fold</span>(a =&gt; q.<span class="fu">exists</span>(a == _),
           q.<span class="fu">isEmpty</span>)
    }
}

<span class="kw">object</span> Optional {
  <span class="co">// Done for you</span>
  <span class="kw">def</span> none[A]: Optional[A] = <span class="kw">new</span> Optional[A] {
    <span class="kw">def</span> fold[X](some: A =&gt; X, none: =&gt; X) = none
  }

  <span class="co">// Done for you</span>
  <span class="kw">def</span> some[A](a: A): Optional[A] = <span class="kw">new</span> Optional[A] {
    <span class="kw">def</span> fold[X](some: A =&gt; X, none: =&gt; X) = <span class="fu">some</span>(a)
  }

  <span class="co">// Utility</span>
  <span class="kw">def</span> fromOption[A](o: Option[A]): Optional[A] = o <span class="kw">match</span> {
    <span class="kw">case</span> None    =&gt; none
    <span class="kw">case</span> Some(a) =&gt; <span class="fu">some</span>(a)
  }

  <span class="co">// *** Special note ***</span>
  <span class="co">// Some of these functions are likely to be familiar List functions,</span>
  <span class="co">// but with one specific distinction: in every covariant value appearing in</span>
  <span class="co">// the type signature, this value is wrapped in Optional.</span>
  <span class="co">// For example, the unwrapped:</span>
  <span class="co">// filter:          (A =&gt; Boolean) =&gt; List[A] =&gt; List[A]</span>
  <span class="co">// and the wrapped:</span>
  <span class="co">// filterOptionals: (A =&gt; Optional[Boolean]) =&gt; List[A] =&gt; Optional[List[A]]</span>
  <span class="co">//</span>
  <span class="co">// There are other functions of a similar nature below.</span>

  <span class="co">// Exercise 16</span>
  <span class="co">// If a none is encountered, then return a none, otherwise,</span>
  <span class="co">// accumulate all the values in Optional.</span>
  <span class="kw">def</span> mapOptionals[A, B](f: A =&gt; Optional[B], a: List[A]): Optional[List[B]] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 17</span>
  <span class="co">// If a none is encountered, then return a none, otherwise,</span>
  <span class="co">// accumulate all the values in Optional.</span>
  <span class="kw">def</span> sequenceOptionals[A](a: List[Optional[A]]): Optional[List[A]] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 18</span>
  <span class="co">// Use sequenceOptionals</span>
  <span class="kw">def</span> mapOptionalsAgain[A, B](f: A =&gt; Optional[B], a: List[A]): Optional[List[B]] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 19</span>
  <span class="co">// Use mapOptionals</span>
  <span class="kw">def</span> sequenceOptionalsAgain[A](a: List[Optional[A]]): Optional[List[A]] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 20</span>
  <span class="co">// If a none is encountered, return none, otherwise,</span>
  <span class="co">// flatten/join by one level.</span>
  <span class="kw">def</span> joinOptionals[A](a: Optional[Optional[A]]): Optional[A] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 21</span>
  <span class="kw">def</span> filterOptionals[A](p: A =&gt; Optional[Boolean], a: List[A]): Optional[List[A]] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 22</span>
  <span class="kw">def</span> fillOptionals[A](n: Int, a: Optional[A]): Optional[List[A]] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 23</span>
  <span class="co">// Use sequenceOptionals</span>
  <span class="kw">def</span> fillOptionalsAgain[A](n: Int, a: Optional[A]): Optional[List[A]] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 24</span>
  <span class="co">// Methods mentioning Optional in the type signature are prohibited, except applic and map</span>
  <span class="kw">def</span> mapOptionalsYetAgain[A, B](f: A =&gt; Optional[B], a: List[A]): Optional[List[B]] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Consider: def joinOptional[A](a: Optional[Optional[A]]): Optional[A]</span>
  <span class="co">// This function &quot;flattens&quot; the Optional into a Some value if possible.</span>
  <span class="co">// It is not possible to write this using only applic and map (try it!).</span>

  <span class="co">// Bye bye Option-specificity!</span>
  <span class="co">// (setting up for Exercise 25)</span>
  <span class="kw">trait</span> Applic[F[_]] {
    <span class="kw">def</span> point[A](a: A): F[A]
    <span class="kw">def</span> applic[A, B](f: F[A =&gt; B], a: F[A]): F[B]

    <span class="kw">final</span> <span class="kw">def</span> map[A, B](f: A =&gt; B, a: F[A]): F[B] =
      <span class="fu">applic</span>(<span class="fu">point</span>(f), a)
  }

  <span class="kw">object</span> Applic {
    <span class="kw">implicit</span> <span class="kw">val</span> OptionalApplic: Applic[Optional] = <span class="kw">new</span> Applic[Optional] {
      <span class="kw">def</span> point[A](a: A): Optional[A] = <span class="fu">some</span>(a)
      <span class="kw">def</span> applic[A, B](f: Optional[A =&gt; B], a: Optional[A]): Optional[B] = a applic f
    }
  }

  <span class="co">// Exercise 25</span>
  <span class="co">// The Double-Clincher!</span>
  <span class="kw">def</span> mapWhatever[A, B, F[_]](f: A =&gt; F[B], a: List[A])(<span class="kw">implicit</span> z: Applic[F]): F[List[B]] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)
}

<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">_</span>
<span class="kw">import</span> Arbitrary.<span class="fu">arbitrary</span>
<span class="kw">import</span> Prop.<span class="fu">_</span>

<span class="kw">object</span> TestOptional <span class="kw">extends</span> Properties(<span class="st">&quot;Optional&quot;</span>) {
  <span class="kw">import</span> Optional.<span class="fu">_</span>

  <span class="kw">implicit</span> <span class="kw">def</span> ArbitraryOptional[A](<span class="kw">implicit</span> a: Arbitrary[A]): Arbitrary[Optional[A]] =
    <span class="fu">Arbitrary</span>(arbitrary[Option[A]] map fromOption)

  <span class="fu">property</span>(<span class="st">&quot;map&quot;</span>) = <span class="fu">forAll</span> ((o: Optional[Int], f: Int =&gt; String) =&gt;
    (o map f).<span class="fu">toOption</span> == (o.<span class="fu">toOption</span> map f))

  <span class="fu">property</span>(<span class="st">&quot;get&quot;</span>) = <span class="fu">forAll</span>((o: Optional[Int]) =&gt;
    o.<span class="fu">isDefined</span> ==&gt;
      (o.<span class="fu">get</span> == o.<span class="fu">toOption</span>.<span class="fu">get</span>))

  <span class="fu">property</span>(<span class="st">&quot;flatMap&quot;</span>) = <span class="fu">forAll</span>((o: Optional[Int], f: Int =&gt; Optional[String]) =&gt;
    (o flatMap f).<span class="fu">toOption</span> == (o.<span class="fu">toOption</span> <span class="fu">flatMap</span> (<span class="fu">f</span>(_).<span class="fu">toOption</span>)))

  <span class="fu">property</span>(<span class="st">&quot;mapAgain&quot;</span>) = <span class="fu">forAll</span> ((o: Optional[Int], f: Int =&gt; String) =&gt;
    (o mapAgain f).<span class="fu">toOption</span> == (o map f).<span class="fu">toOption</span>)

  <span class="fu">property</span>(<span class="st">&quot;getOrElse&quot;</span>) = <span class="fu">forAll</span> ((o: Optional[Int], n: Int) =&gt;
    (o getOrElse n) == (o.<span class="fu">toOption</span> getOrElse n))

  <span class="fu">property</span>(<span class="st">&quot;filter&quot;</span>) = <span class="fu">forAll</span> ((o: Optional[Int], f: Int =&gt; Boolean) =&gt;
    (o filter f).<span class="fu">toOption</span> == (o.<span class="fu">toOption</span> filter f))

  <span class="fu">property</span>(<span class="st">&quot;exists&quot;</span>) = <span class="fu">forAll</span> ((o: Optional[Int], f: Int =&gt; Boolean) =&gt;
    (o exists f) == (o.<span class="fu">toOption</span> exists f))

  <span class="fu">property</span>(<span class="st">&quot;forall&quot;</span>) = <span class="fu">forAll</span> ((o: Optional[Int], f: Int =&gt; Boolean) =&gt;
    (o forall f) == (o.<span class="fu">toOption</span> forall f))

  <span class="fu">property</span>(<span class="st">&quot;foreach&quot;</span>) = <span class="fu">forAll</span> ((o: Optional[Int], f: Int =&gt; Unit, n: Int) =&gt; {
    <span class="kw">var</span> x: Int = n
    <span class="kw">var</span> y: Int = x

    o <span class="fu">foreach</span> (t =&gt; x = x + t)
    o.<span class="fu">toOption</span> <span class="fu">foreach</span> (t =&gt; y = y + t)

    x == y
  })

  <span class="fu">property</span>(<span class="st">&quot;isDefined&quot;</span>) = <span class="fu">forAll</span> ((o: Optional[Int]) =&gt;
    (o.<span class="fu">isDefined</span>) == (o.<span class="fu">toOption</span>.<span class="fu">isDefined</span>))

  <span class="fu">property</span>(<span class="st">&quot;isEmpty&quot;</span>) = <span class="fu">forAll</span> ((o: Optional[Int]) =&gt;
    o.<span class="fu">isEmpty</span> == o.<span class="fu">toOption</span>.<span class="fu">isEmpty</span>)

  <span class="fu">property</span>(<span class="st">&quot;orElse&quot;</span>) = <span class="fu">forAll</span> ((o: Optional[Int], p: Optional[Int]) =&gt;
    (o orElse p).<span class="fu">toOption</span> == (o.<span class="fu">toOption</span> orElse p.<span class="fu">toOption</span>))

  <span class="fu">property</span>(<span class="st">&quot;toLeft&quot;</span>) = <span class="fu">forAll</span> ((o: Optional[Int], n: Int) =&gt;
    (o toLeft n) == (o.<span class="fu">toOption</span> toLeft n))

  <span class="fu">property</span>(<span class="st">&quot;toRight&quot;</span>) = <span class="fu">forAll</span> ((o: Optional[Int], n: Int) =&gt;
    (o toRight n) == (o.<span class="fu">toOption</span> toRight n))

  <span class="fu">property</span>(<span class="st">&quot;toList&quot;</span>) = <span class="fu">forAll</span> ((o: Optional[Int]) =&gt;
    o.<span class="fu">toList</span> == o.<span class="fu">toOption</span>.<span class="fu">toList</span>)

  <span class="fu">property</span>(<span class="st">&quot;iterator&quot;</span>) = <span class="fu">forAll</span> ((o: Optional[Int]) =&gt;
    o.<span class="fu">iterator</span> sameElements o.<span class="fu">toOption</span>.<span class="fu">iterator</span>)

  <span class="co">// *** READ THIS COMMENT FIRST ***</span>
  <span class="co">// Note that scala.Option has no such equivalent to this method</span>
  <span class="co">// Therefore, reading this test may give away clues to how it might be solved.</span>
  <span class="co">// If you do not wish to spoil it, look away now and follow the</span>
  <span class="co">// instruction in the Exercise comment.</span>
  <span class="fu">property</span>(<span class="st">&quot;applic&quot;</span>) = <span class="fu">forAll</span> ((o: Optional[Int =&gt; String], p: Optional[Int]) =&gt;
    (p applic o).<span class="fu">toOption</span> ==
    (<span class="kw">for</span>(f &lt;- o.<span class="fu">toOption</span>;
         n &lt;- p.<span class="fu">toOption</span>)
    <span class="kw">yield</span> <span class="fu">f</span>(n)))

  <span class="kw">def</span> trace[A](a: A) = {
    <span class="fu">println</span>(a)
    a
  }

  <span class="fu">property</span>(<span class="st">&quot;mapOptionals&quot;</span>) = <span class="fu">forAll</span>((f: Int =&gt; Optional[String], o: List[Int]) =&gt;
  {
    <span class="kw">val</span> i = o map f
    <span class="fu">mapOptionals</span>(f, o) == (<span class="kw">if</span>(i <span class="fu">forall</span> (_.<span class="fu">isDefined</span>)) <span class="fu">some</span>(i <span class="fu">map</span> (_.<span class="fu">get</span>)) <span class="kw">else</span> none)
  })

  <span class="fu">property</span>(<span class="st">&quot;sequenceOptionals&quot;</span>) = <span class="fu">forAll</span>((o: List[Optional[String]]) =&gt;
      <span class="fu">sequenceOptionals</span>(o) == (<span class="kw">if</span>(o <span class="fu">exists</span> (_.<span class="fu">isEmpty</span>)) none <span class="kw">else</span> <span class="fu">some</span>(o <span class="fu">map</span> (_.<span class="fu">get</span>))))

  <span class="fu">property</span>(<span class="st">&quot;mapOptionalsAgain&quot;</span>) = <span class="fu">forAll</span>((f: Int =&gt; Optional[String], o: List[Int]) =&gt;
      <span class="fu">mapOptionalsAgain</span>(f, o) == <span class="fu">mapOptionals</span>(f, o))

  <span class="fu">property</span>(<span class="st">&quot;sequenceOptionalsAgain&quot;</span>) = <span class="fu">forAll</span>((o: List[Optional[String]]) =&gt;
      <span class="fu">sequenceOptionalsAgain</span>(o) == <span class="fu">sequenceOptionals</span>(o))

  <span class="fu">property</span>(<span class="st">&quot;joinOptionals&quot;</span>) = <span class="fu">forAll</span>((o: Optional[Optional[String]]) =&gt;
      <span class="fu">joinOptionals</span>(o) == (<span class="kw">if</span>(o.<span class="fu">isDefined</span> &amp;&amp; o.<span class="fu">get</span>.<span class="fu">isDefined</span>) o.<span class="fu">get</span> <span class="kw">else</span> none))

  <span class="fu">property</span>(<span class="st">&quot;filterOptionals&quot;</span>) = <span class="fu">forAll</span>((f: Int =&gt; Optional[Boolean], o: List[Int]) =&gt;
      <span class="fu">filterOptionals</span>(f, o) == (<span class="kw">if</span>(o <span class="fu">exists</span> (<span class="fu">f</span>(_).<span class="fu">isEmpty</span>)) none <span class="kw">else</span> <span class="fu">some</span>(o <span class="fu">filter</span> (<span class="fu">f</span>(_).<span class="fu">get</span>))))

  <span class="fu">property</span>(<span class="st">&quot;fillOptionals&quot;</span>) = <span class="fu">forAll</span>((n: Int, o: Optional[String]) =&gt;
      (n &lt; <span class="dv">1000</span>) ==&gt; <span class="co">// prevent stack consumption</span>
      (<span class="fu">fillOptionals</span>(n, o) == (<span class="kw">if</span>(n &lt;= <span class="dv">0</span>) <span class="fu">some</span>(Nil) <span class="kw">else</span> (o <span class="fu">map</span> (List.<span class="fu">fill</span>(n)(_))))))

  <span class="fu">property</span>(<span class="st">&quot;fillOptionalsAgain&quot;</span>) = <span class="fu">forAll</span>((n: Int, o: Optional[String]) =&gt;
      (n &lt; <span class="dv">1000</span>) ==&gt; <span class="co">// prevent stack consumption</span>
      (<span class="fu">fillOptionalsAgain</span>(n, o) == <span class="fu">fillOptionals</span>(n, o)))

  <span class="fu">property</span>(<span class="st">&quot;mapOptionalsYetAgain&quot;</span>) = <span class="fu">forAll</span>((f: Int =&gt; Optional[String], o: List[Int]) =&gt;
      <span class="fu">mapOptionalsYetAgain</span>(f, o) == <span class="fu">mapOptionals</span>(f, o))

  <span class="fu">property</span>(<span class="st">&quot;mapWhatever&quot;</span>) = <span class="fu">forAll</span>((f: Int =&gt; Optional[String], o: List[Int]) =&gt;
      <span class="fu">mapWhatever</span>(f, o) == <span class="fu">mapOptionals</span>(f, o))

  <span class="co">/*</span>
<span class="co">  $ scala -classpath .:scalacheck_2.8.0-1.7.jar TestOptional</span>
<span class="co">  + Optional.map: OK, passed 100 tests.</span>
<span class="co">  + Optional.get: OK, passed 100 tests.</span>
<span class="co">  + Optional.flatMap: OK, passed 100 tests.</span>
<span class="co">  + Optional.mapAgain: OK, passed 100 tests.</span>
<span class="co">  + Optional.getOrElse: OK, passed 100 tests.</span>
<span class="co">  + Optional.filter: OK, passed 100 tests.</span>
<span class="co">  + Optional.exists: OK, passed 100 tests.</span>
<span class="co">  + Optional.forall: OK, passed 100 tests.</span>
<span class="co">  + Optional.foreach: OK, passed 100 tests.</span>
<span class="co">  + Optional.isDefined: OK, passed 100 tests.</span>
<span class="co">  + Optional.isEmpty: OK, passed 100 tests.</span>
<span class="co">  + Optional.orElse: OK, passed 100 tests.</span>
<span class="co">  + Optional.toLeft: OK, passed 100 tests.</span>
<span class="co">  + Optional.toRight: OK, passed 100 tests.</span>
<span class="co">  + Optional.toList: OK, passed 100 tests.</span>
<span class="co">  + Optional.iterator: OK, passed 100 tests.</span>
<span class="co">  + Optional.applic: OK, passed 100 tests.</span>
<span class="co">  + Optional.mapOptionals: OK, passed 100 tests.</span>
<span class="co">  + Optional.sequenceOptionals: OK, passed 100 tests.</span>
<span class="co">  + Optional.mapOptionalsAgain: OK, passed 100 tests.</span>
<span class="co">  + Optional.sequenceOptionalsAgain: OK, passed 100 tests.</span>
<span class="co">  + Optional.joinOptionals: OK, passed 100 tests.</span>
<span class="co">  + Optional.filterOptionals: OK, passed 100 tests.</span>
<span class="co">  + Optional.fillOptionals: OK, passed 100 tests.</span>
<span class="co">  + Optional.fillOptionalsAgain: OK, passed 100 tests.</span>
<span class="co">  + Optional.mapOptionalsYetAgain: OK, passed 100 tests.</span>
<span class="co">  + Optional.mapWhatever: OK, passed 100 tests.</span>
<span class="co">  */</span>
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Can an entrapment neuropathy of the superficial peroneal nerve cause foot drop?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/can-an-entrapment-neuropathy-of-the-superficial-peroneal-nerve-cause-foot-drop/index.html"/>
  <id>http://blog.tmorris.net/posts/can-an-entrapment-neuropathy-of-the-superficial-peroneal-nerve-cause-foot-drop/index.html</id>
  <published>2010-08-29T07:04:53Z</published>
  <updated>2010-08-29T07:04:53Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Of the 26 medical doctors I have met in the last couple of years, about 10 of them had this question before them in some way. All of them answered “no.” I am very confident this tiny sample set extrapolates – I doubt there is a doctor who would not say no.</p>
<p><strong>They are all wrong.</strong></p>
<p>Entrapment neuropathy of the superficial peroneal nerve is not a common condition, but one which I had after an ankle inversion sprain. The entrapment was 10cm proximal to the lateral malleolus at the deep fascia exit behind the peroneal muscles.</p>
<p>In order to achieve resolution of this problem, I had to publish an essay with citations and present it to several surgeons. My citations include every case study of this condition that currently exists and several orthopaedic text books.</p>
<p>My insistence that this was causing a significant problem and that I also had incomplete foot drop was met with deep scepticism. After all, the superficial peroneal nerve (SPN) is a cutaneous nerve that does not supply motor control. I knew this too of course, but I had no explanation. It is the deep peroneal nerve (DPN) which supplies motor control – the guy next door. Foot drop is often caused by an entrapment below and behind the knee before the nerve splits into these two branches, but I knew this was not the cause.</p>
<p>A marcaine/steroid injection into the SPN entrapment site immediately (within seconds) relieved some amount of foot drop. This too, was met with scepticism (?placebo), but I was adamant – there was an effect including a functional improvement.</p>
<p><strong>An entrapment neuropathy of the superficial peroneal can cause foot drop by extending the nerve, and placing traction on the L5 nerve root. This will result in the expected fibrillation of the foot extensor muscles. Further, this is an extremely painful and distressing condition resulting in symptoms that can be very distracting from the actual etiology.</strong></p>
<p>_I am not a medical expert, just an independent thinker who owns too many medical text books. _</p>
    </div>
  </content>
</entry>
<entry>
  <title>Further understanding scala.Option</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/further-understanding-scalaoption/index.html"/>
  <id>http://blog.tmorris.net/posts/further-understanding-scalaoption/index.html</id>
  <published>2010-08-23T11:46:56Z</published>
  <updated>2010-08-23T11:46:56Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Below are 15 (probably fun) exercises for anyone interested in obtaining a deeper understanding of <code>scala.Option</code> and algebraic data types in general. I could write the same in Haskell but this will require either type-classes or rank-n types (GHC extension), so I thought I’d give that a miss.</p>
<p>Instructions are in the comments. Let me know if there are any questions.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// Scala version 2.8.0.final</span>
<span class="co">// http://scalacheck.googlecode.com/files/scalacheck_2.8.0-1.8-SNAPSHOT.jar</span>


<span class="co">/*</span>

<span class="co">  Below are 15 exercises. The task is to emulate the scala.Option API</span>
<span class="co">  without using Some/None subtypes, but instead using a fold (called a</span>
<span class="co">  catamorphism).</span>

<span class="co">  A couple of functions are already done (map, get)</span>
<span class="co">  to be used as an example. ScalaCheck tests are given below to</span>
<span class="co">  verify the work. The desired result is to have all tests passing.</span>

<span class="co">  The 15th exercise is not available in the existing Scala API so</span>
<span class="co">  instructions are given in the comments.</span>

<span class="co">  Revision History</span>
<span class="co">  ================</span>

<span class="co">  23/08/2010</span>
<span class="co">  Initial revision</span>

<span class="co">  ----------------</span>

<span class="co">  23/08/2010</span>
<span class="co">  Fixed prop_getOrElse. Thanks Michael Bayne.</span>

<span class="co">  ----------------</span>

<span class="co">  26/08/2010</span>
<span class="co">  Add lazy annotation to orElse method.</span>

<span class="co">*/</span>


<span class="kw">trait</span> Optional[A] {
  <span class="co">// single abstract method</span>
  <span class="kw">def</span> fold[X](some: A =&gt; X, none: =&gt; X): X

  <span class="kw">import</span> Optional.<span class="fu">_</span>

  <span class="co">// Done for you.</span>
  <span class="kw">def</span> map[B](f: A =&gt; B): Optional[B] =
    <span class="fu">fold</span>(f andThen some, none[B])

  <span class="co">// Done for you.</span>
  <span class="co">// WARNING: undefined for None</span>
  <span class="kw">def</span> get: A =
    <span class="fu">fold</span>(a =&gt; a, <span class="fu">error</span>(<span class="st">&quot;None.get&quot;</span>))

  <span class="co">// Exercise 1</span>
  <span class="kw">def</span> flatMap[B](f: A =&gt; Optional[B]): Optional[B] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 2</span>
  <span class="co">// Rewrite map but use flatMap, not fold.</span>
  <span class="kw">def</span> mapAgain[B](f: A =&gt; B): Optional[B] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 3</span>
  <span class="kw">def</span> <span class="fu">getOrElse</span>(e: =&gt; A): A =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 4</span>
  <span class="kw">def</span> <span class="fu">filter</span>(p: A =&gt; Boolean): Optional[A] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 5</span>
  <span class="kw">def</span> <span class="fu">exists</span>(p: A =&gt; Boolean): Boolean =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 6</span>
  <span class="kw">def</span> <span class="fu">forall</span>(p: A =&gt; Boolean): Boolean =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 7</span>
  <span class="kw">def</span> <span class="fu">foreach</span>(f: A =&gt; Unit): Unit =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 8</span>
  <span class="kw">def</span> isDefined: Boolean =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 9</span>
  <span class="kw">def</span> isEmpty: Boolean =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 10</span>
  <span class="kw">def</span> <span class="fu">orElse</span>(o: =&gt; Optional[A]): Optional[A] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 11</span>
  <span class="kw">def</span> toLeft[X](right: =&gt; X): Either[A, X] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 12</span>
  <span class="kw">def</span> toRight[X](left: =&gt; X): Either[X, A] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 13</span>
  <span class="kw">def</span> toList: List[A] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 14</span>
  <span class="kw">def</span> iterator: Iterator[A] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 15 The Clincher!</span>
  <span class="co">// Return a none value if either this or the argument is none.</span>
  <span class="co">// Otherwise apply the function to the argument in some.</span>
  <span class="co">// Don&#39;t be afraid to use functions you have written.</span>
  <span class="co">// Better style, more points!</span>
  <span class="kw">def</span> applic[B](f: Optional[A =&gt; B]): Optional[B] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Utility</span>
  <span class="kw">def</span> toOption: Option[A] = <span class="fu">fold</span>(Some(_), None)
}

<span class="kw">object</span> Optional {
  <span class="co">// Done for you</span>
  <span class="kw">def</span> none[A]: Optional[A] = <span class="kw">new</span> Optional[A] {
    <span class="kw">def</span> fold[X](some: A =&gt; X, none: =&gt; X) = none
  }

  <span class="co">// Done for you</span>
  <span class="kw">def</span> some[A](a: A): Optional[A] = <span class="kw">new</span> Optional[A] {
    <span class="kw">def</span> fold[X](some: A =&gt; X, none: =&gt; X) = <span class="fu">some</span>(a)
  }

  <span class="co">// Utility</span>
  <span class="kw">def</span> fromOption[A](o: Option[A]): Optional[A] = o <span class="kw">match</span> {
    <span class="kw">case</span> None    =&gt; none
    <span class="kw">case</span> Some(a) =&gt; <span class="fu">some</span>(a)
  }
}

<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">_</span>
<span class="kw">import</span> Arbitrary.<span class="fu">arbitrary</span>
<span class="kw">import</span> Prop.<span class="fu">_</span>

<span class="kw">object</span> TestOptional {
  <span class="kw">import</span> Optional.<span class="fu">_</span>

  <span class="kw">implicit</span> <span class="kw">def</span> ArbitraryOptional[A](<span class="kw">implicit</span> a: Arbitrary[A]): Arbitrary[Optional[A]] =
    <span class="fu">Arbitrary</span>(arbitrary[Option[A]] map fromOption)

  <span class="kw">val</span> prop_map = <span class="fu">forAll</span> ((o: Optional[Int], f: Int =&gt; String) =&gt;
    (o map f).<span class="fu">toOption</span> == (o.<span class="fu">toOption</span> map f))

  <span class="kw">val</span> prop_get = <span class="fu">forAll</span>((o: Optional[Int]) =&gt;
    o.<span class="fu">isDefined</span> ==&gt;
      (o.<span class="fu">get</span> == o.<span class="fu">toOption</span>.<span class="fu">get</span>))

  <span class="kw">val</span> prop_flatMap = <span class="fu">forAll</span>((o: Optional[Int], f: Int =&gt; Optional[String]) =&gt;
    (o flatMap f).<span class="fu">toOption</span> == (o.<span class="fu">toOption</span> <span class="fu">flatMap</span> (<span class="fu">f</span>(_).<span class="fu">toOption</span>)))

  <span class="kw">val</span> prop_mapAgain = <span class="fu">forAll</span> ((o: Optional[Int], f: Int =&gt; String) =&gt;
    (o mapAgain f).<span class="fu">toOption</span> == (o map f).<span class="fu">toOption</span>)

  <span class="kw">val</span> prop_getOrElse = <span class="fu">forAll</span> ((o: Optional[Int], n: Int) =&gt;
    (o getOrElse n) == (o.<span class="fu">toOption</span> getOrElse n))

  <span class="kw">val</span> prop_filter = <span class="fu">forAll</span> ((o: Optional[Int], f: Int =&gt; Boolean) =&gt;
    (o filter f).<span class="fu">toOption</span> == (o.<span class="fu">toOption</span> filter f))

  <span class="kw">val</span> prop_exists = <span class="fu">forAll</span> ((o: Optional[Int], f: Int =&gt; Boolean) =&gt;
    (o exists f) == (o.<span class="fu">toOption</span> exists f))

  <span class="kw">val</span> prop_forall = <span class="fu">forAll</span> ((o: Optional[Int], f: Int =&gt; Boolean) =&gt;
    (o forall f) == (o.<span class="fu">toOption</span> forall f))

  <span class="kw">val</span> prop_foreach = <span class="fu">forAll</span> ((o: Optional[Int], f: Int =&gt; Unit, n: Int) =&gt; {
    <span class="kw">var</span> x: Int = n
    <span class="kw">var</span> y: Int = x

    o <span class="fu">foreach</span> (t =&gt; x = x + t)
    o.<span class="fu">toOption</span> <span class="fu">foreach</span> (t =&gt; y = y + t)

    x == y
  })

  <span class="kw">val</span> prop_isDefined = <span class="fu">forAll</span> ((o: Optional[Int]) =&gt;
    (o.<span class="fu">isDefined</span>) == (o.<span class="fu">toOption</span>.<span class="fu">isDefined</span>))

  <span class="kw">val</span> prop_isEmpty = <span class="fu">forAll</span> ((o: Optional[Int]) =&gt;
    o.<span class="fu">isEmpty</span> == o.<span class="fu">toOption</span>.<span class="fu">isEmpty</span>)

  <span class="kw">val</span> prop_orElse = <span class="fu">forAll</span> ((o: Optional[Int], p: Optional[Int]) =&gt;
    (o orElse p).<span class="fu">toOption</span> == (o.<span class="fu">toOption</span> orElse p.<span class="fu">toOption</span>))

  <span class="kw">val</span> prop_toLeft = <span class="fu">forAll</span> ((o: Optional[Int], n: Int) =&gt;
    (o toLeft n) == (o.<span class="fu">toOption</span> toLeft n))

  <span class="kw">val</span> prop_toRight = <span class="fu">forAll</span> ((o: Optional[Int], n: Int) =&gt;
    (o toRight n) == (o.<span class="fu">toOption</span> toRight n))

  <span class="kw">val</span> prop_toList = <span class="fu">forAll</span> ((o: Optional[Int]) =&gt;
    o.<span class="fu">toList</span> == o.<span class="fu">toOption</span>.<span class="fu">toList</span>)

  <span class="kw">val</span> prop_iterator = <span class="fu">forAll</span> ((o: Optional[Int]) =&gt;
    o.<span class="fu">iterator</span> sameElements o.<span class="fu">toOption</span>.<span class="fu">iterator</span>)

  <span class="co">// *** READ THIS COMMENT FIRST ***</span>
  <span class="co">// Note that scala.Option has no such equivalent to this method</span>
  <span class="co">// Therefore, reading this test may give away clues to how it might be solved.</span>
  <span class="co">// If you do not wish to spoil it, look away now and follow the</span>
  <span class="co">// instruction in the Exercise comment.</span>
  <span class="kw">val</span> prop_applic = <span class="fu">forAll</span> ((o: Optional[Int =&gt; String], p: Optional[Int]) =&gt;
    (p applic o).<span class="fu">toOption</span> ==
    (<span class="kw">for</span>(f &lt;- o.<span class="fu">toOption</span>;
        n &lt;- p.<span class="fu">toOption</span>)
    <span class="kw">yield</span> <span class="fu">f</span>(n)))

  <span class="kw">val</span> props =
    List(
      prop_map,
      prop_get,
      prop_flatMap,
      prop_mapAgain,
      prop_getOrElse,
      prop_filter,
      prop_exists,
      prop_forall,
      prop_foreach,
      prop_isDefined,
      prop_isEmpty,
      prop_orElse,
      prop_toLeft,
      prop_toRight,
      prop_toList,
      prop_iterator,
      prop_applic
    )

  <span class="co">/*</span>
<span class="co">  $ scala -classpath .:scalacheck_2.8.0-1.8-SNAPSHOT.jar TestOptional</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  + OK, passed 100 tests.</span>
<span class="co">  */</span>
  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]) {
    props <span class="fu">foreach</span> (_.<span class="fu">check</span>)
  }
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Java and Practicality</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/java-and-practicality/index.html"/>
  <id>http://blog.tmorris.net/posts/java-and-practicality/index.html</id>
  <published>2010-07-23T09:27:10Z</published>
  <updated>2010-07-23T09:27:10Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I have found that those who advocate for the practicality of Java as a programming language for solving software problems invariably have an incredibly poor understanding of programming language theory and poor general problem solving skills. However, almost always, an even poorer understanding of the Java programming language itself is most prominent.</p>
<p>Consequently, one cannot have a reasonable discussion about the merits of problem solving, using the Java programming language, or programming languages in general. However, one hopes that this sample set is biased and so one continues the search for a counter-example.</p>
<p>This is lamentable.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Functional Java 3.0</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/functional-java-30/index.html"/>
  <id>http://blog.tmorris.net/posts/functional-java-30/index.html</id>
  <published>2010-06-25T21:09:02Z</published>
  <updated>2010-06-25T21:09:02Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://functionaljava.org/">Functional Java 3.0</a> is released. As usual, requires any Java 1.5 (or above) runtime and the source can be compiled with any Java 1.5 compiler.</p>
<p>Support for Java 7 BGGA closures is dropped, since the function interfaces are now classes with abstract methods. Other useful additions abound. Have fun!</p>
    </div>
  </content>
</entry>
<entry>
  <title>Understanding Monads using Scala (Part 1)</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/understanding-monads-using-scala-part-1/index.html"/>
  <id>http://blog.tmorris.net/posts/understanding-monads-using-scala-part-1/index.html</id>
  <published>2010-06-22T16:51:23Z</published>
  <updated>2010-06-22T16:51:23Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Below are three exercises using Scala. The instructions for each are in the comments. Exercises 1 and 2 must be completed before Exercise 3 (which is just a thinking exercise – no code).</p>
<p>A follow-on to these exercises will be coming.</p>
<p>Hope this helps!</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// A typical data type with a single abstract method</span>
<span class="kw">case</span> <span class="kw">class</span> Inter[A](f: Int =&gt; A) {
  <span class="co">// which is a functor</span>
  <span class="kw">def</span> map[B](g: A =&gt; B): Inter[B] =
    <span class="fu">Inter</span>(n =&gt; <span class="fu">g</span>(<span class="fu">f</span>(n)))

  <span class="co">// and a monad (see unital below)</span>
  <span class="kw">def</span> flatMap[B](g: A =&gt; Inter[B]): Inter[B] =
    <span class="fu">Inter</span>(n =&gt; <span class="fu">g</span>(<span class="fu">f</span>(n)).<span class="fu">f</span>(n))
}

<span class="co">// unital: A =&gt; F[A]</span>
<span class="co">// Implementations for F=Option and F=Inter</span>
<span class="kw">object</span> Unitals {
  <span class="kw">def</span> unitalOption[A](a: A): Option[A] =
    Some(a)

  <span class="kw">def</span> unitalInter[A](a: A): Inter[A] =
    <span class="fu">Inter</span>(_ =&gt; a)
}

<span class="co">// Exercises</span>
<span class="co">//</span>
<span class="co">// It is recommended to use only map, flatMap and unital* for</span>
<span class="co">// Option or Inter when implementing the exercises below.</span>
<span class="co">// Any other libraries are acceptable (e.g. List functions).</span>
<span class="kw">object</span> Sequencing {
  <span class="kw">import</span> Unitals.<span class="fu">_</span>

  <span class="co">// Exercise 1 of 3</span>
  <span class="co">// ===============</span>
  <span class="co">// Implement a function that returns None if the given list</span>
  <span class="co">// contains any None values, otherwise, all the Some values.</span>
  <span class="kw">def</span> sequenceOption[A](x: List[Option[A]]): Option[List[A]] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

    <span class="co">// SOLUTIONx2 (ROT-13)</span>
    <span class="co">/*</span>
<span class="co">    1)</span>
<span class="co">    k.sbyqEvtug(havgnyBcgvba(Avy: Yvfg[N]))((n, o) =&gt; n syngZnc (k =&gt; o znc (k :: _)))</span>

<span class="co">    2)</span>
<span class="co">    k zngpu {</span>
<span class="co">      pnfr Avy  =&gt; havgnyBcgvba(Avy)</span>
<span class="co">      pnfr u::g =&gt; u syngZnc (k =&gt; frdhraprBcgvba(g) znc (k :: _))</span>
<span class="co">    }</span>
<span class="co">    */</span>

  <span class="co">// Exercise 2 of 3</span>
  <span class="co">// ===============</span>
  <span class="co">// Implement a function that returns an Inter that applies an Int</span>
  <span class="co">// to all the Inter implementations in the List of Inters and returns</span>
  <span class="co">// all the results.</span>
  <span class="kw">def</span> sequenceInter[A](x: List[Inter[A]]): Inter[List[A]] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

    <span class="co">// SOLUTIONx2 (ROT-13)</span>
    <span class="co">/*</span>
<span class="co">    1)</span>
<span class="co">    k.sbyqEvtug(havgnyVagre(Avy: Yvfg[N]))((n, o) =&gt; n syngZnc (k =&gt; o znc (k :: _)))</span>

<span class="co">    2)</span>
<span class="co">    k zngpu {</span>
<span class="co">      pnfr Avy  =&gt; havgnyVagre(Avy)</span>
<span class="co">      pnfr u::g =&gt; u syngZnc (k =&gt; frdhraprVagre(g) znc (k :: _))</span>
<span class="co">    }</span>
<span class="co">    */</span>

  <span class="co">// Exercise 3 of 3</span>
  <span class="co">// ===============</span>
  <span class="co">// There is repetition in the above exercises.</span>
  <span class="co">// How might we be rid of it?</span>
  <span class="co">// That is for Part 2.</span>

  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]) {
    <span class="kw">def</span> assertEquals[A](a1: A, a2: A) {
      <span class="kw">if</span>(a1 != a2)
        <span class="fu">error</span>(<span class="st">&quot;Assertion error. Expected: &quot;</span> + a1 + <span class="st">&quot; Actual: &quot;</span> + a2)
    }

    <span class="kw">def</span> assertInterEquals[A](a1: Inter[A], a2: Inter[A]) {
      <span class="kw">val</span> testInts = List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">0</span>, -<span class="dv">7</span>, -<span class="dv">9</span>, <span class="dv">113</span>, -<span class="dv">2048</span>)
      <span class="fu">assertEquals</span>(testInts.<span class="fu">map</span>(a1.<span class="fu">f</span>(_)), testInts.<span class="fu">map</span>(a2.<span class="fu">f</span>(_)))
    }

    <span class="co">// sequenceOption</span>
    <span class="fu">assertEquals</span>(<span class="fu">sequenceOption</span>(List(Some(<span class="dv">7</span>),
        Some(<span class="dv">8</span>), Some(<span class="dv">9</span>))), Some(List(<span class="dv">7</span>, <span class="dv">8</span>, <span class="dv">9</span>)))
    <span class="fu">assertEquals</span>(<span class="fu">sequenceOption</span>(List(Some(<span class="dv">7</span>), None, Some(<span class="dv">9</span>))),
        None)
    <span class="fu">assertEquals</span>(<span class="fu">sequenceOption</span>(List()),
      Some(List()))

    <span class="co">// sequenceInter</span>
    <span class="fu">assertInterEquals</span>(<span class="fu">sequenceInter</span>(List()),
      <span class="fu">Inter</span>(_ =&gt; List()))
    <span class="fu">assertInterEquals</span>(<span class="fu">sequenceInter</span>(List(<span class="fu">Inter</span>(<span class="dv">1</span>+),
        <span class="fu">Inter</span>(<span class="dv">2</span>*))), <span class="fu">Inter</span>(n =&gt; List(<span class="dv">1</span>+n, <span class="dv">2</span>*n)))
  }
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Optional a -> a (negative proof)</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/optional-a-negative-proof/index.html"/>
  <id>http://blog.tmorris.net/posts/optional-a-negative-proof/index.html</id>
  <published>2010-06-20T13:57:14Z</published>
  <updated>2010-06-20T13:57:14Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><em>A loose follow-on from <a href="http://blog.tmorris.net/java-trivia/">Java Trivia</a>.</em></p>
<p>I run a weekly Haskell session at my place of employment. We are just beginning. The intention is not so much to learn Haskell, but to learn deeper programming concepts so that we can apply them regardless of language – though to the extent that various languages permit.</p>
<p>Recently, we were discussing algebraic data types and we invented our own:</p>
<pre><code>data Optional a = Full a | Empty deriving (Eq, Show)</code></pre>
<p>This is equivalent to:</p>
<ul>
<li><p><a href="http://functionaljava.googlecode.com/svn/artifacts/2.23/javadoc/fj/data/Option.html">fj.data.Option</a> for Java</p></li>
<li><p><a href="http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Data-Maybe.html">Data.Maybe</a> for Haskell</p></li>
<li><p><a href="http://www.scala-lang.org/docu/files/api/scala/Option.html">scala.Option</a> for Scala</p></li>
<li><p><a href="http://msdn.microsoft.com/en-us/library/dd233245.aspx">option</a> for F#</p></li>
<li><p><a href="http://ocaml-lib.sourceforge.net/doc/Option.html">module Option</a> for OCaml</p></li>
<li><p><a href="http://www.standardml.org/Basis/option.html">Option</a> for SML</p></li>
<li><p><a href="http://www.lix.polytechnique.fr/coq/stdlib/Coq.Init.Datatypes.html#option">option</a> for Coq</p></li>
</ul>
<p>We were writing a function with this type</p>
<pre><code>Optional a -&gt; a -&gt; a</code></pre>
<p>when a member of the audience said, “Why not just use <code>Optional a -&gt; a</code>?” to which I responded, “That’s not possible to do in a consistent way.” That is, not only we shouldn’t, but we cannot do it, no matter what! By consistent here, I mean a total, terminating function. Telling programmers that something is not possible is often a little hasty, even if it is true, so I side-stepped any further discussion on this matter and carried on, promising further explanation, which follows.</p>
<p>Here I will prove it is not possible by exploiting the Curry-Howard Isomorphism. It is not intended to be deep or technical, only to display some of the possibilities of using “types as propositions, programs as proof” – to paraphrase the intention of C-H Isomorphism.</p>
<p>The essence of C-H is quite simple. If you write a type signature, you have also written a logical proposition. If you find at least one function that satisfies this signature, you have proven that proposition. Conversely, if you have a program, its existence proves its type (whether the programming language explicitly supplies that type or not). This program for a type is called an <em>inhabitant</em> of the type. Some types are uninhabited, for example: <code>a -&gt; b</code>. That’s because this proposition is not true.</p>
<p>To state it logically, <code>forall a b. a implies b</code> is a false statement. You can determine this by a simple truth table:</p>
<pre><code>a b a-&gt;b
0 0 1
0 1 1
1 0 0 &lt;-- inconsistency
1 1 1</code></pre>
<p>In <a href="http://blog.tmorris.net/java-trivia/">a previous post</a>, I demonstrated a function that was <em>once-inhabited</em> using (a subset of – <em>see the rules</em>) Java. I knew it was once-inhabited before I gave the puzzle, meaning that every answer given should be the same (extensionally equivalent). Once-inhabited functions are very interesting, but not here – since we are looking for either:</p>
<ul>
<li><p>At least one inhabitant (proof which I have claimed does not exist)</p></li>
<li><p>The absence of an inhabitant (proof negative)</p></li>
</ul>
<p>So how can we prove or disprove <code>Optional a -&gt; a</code>?</p>
<p>My claim is that it is uninhabited. You can disprove this claim by finding an inhabitant. However, the inability to find an inhabitant does not disprove the proposition – after all, we might just be having an unimaginative day! I am assuring you for now, that you will find no such inhabitant. Now I will prove that you won’t.</p>
<p>We first ask the question, what exactly is <code>Optional a</code>? We can provide a data structure of equivalence by exploiting the <a href="http://en.wikipedia.org/wiki/Catamorphism">catamorphism</a> for the data type:</p>
<pre><code>type Optional a = forall x. (a -&gt; x) -&gt; x -&gt; x</code></pre>
<p>This data type is isomorphic (of the same one form) to our previous one and you can determine this by passing in the two constructors of the earlier data type to this isomorphic data type to produce an identity function:</p>
<pre><code>let cata :: (a -&gt; x) -&gt; x -&gt; x
cata Full Empty == id</code></pre>
<p>Side note: if you’re interested in doing the same for a Haskell list, see the <code>foldr</code> function denoting the list catamorphism (<code>foldr (:) [] == id</code>).</p>
<p>Therefore, our proposition to prove/disprove is now rewritten <em>(remember that <code>-&gt;</code> is right-associative)</em>:</p>
<pre><code>forall a x. ((a -&gt; x) -&gt; x -&gt; x) -&gt; a)</code></pre>
<p>Using this, and the truth table for logical implication, we can find an answer by another truth table. Let us first assign some of the parts of this proposition to values for brevity (s being the proposition under investigation):</p>
<pre><code>p = a -&gt; x
q = x -&gt; x
r = p -&gt; q
s = r -&gt; a</code></pre>
<p>Let us now draw the truth table:</p>
<pre><code>a x p q r s
0 0 1 1 1 0 &lt;-- inconsistency
0 1 1 1 1 0 &lt;-- inconsistency
1 0 0 1 1 1
1 1 1 1 1 1</code></pre>
<p>We have now disproven the proposition <code>Optional a -&gt; a</code>. It is not possible to inhabit this type signature consistently.</p>
<p>Further Reading:</p>
<ul>
<li><p><a href="http://en.wikipedia.org/wiki/Curry%E2%80%93Howard_correspondence">The Curry-Howard Correspondence</a></p></li>
<li><p><a href="http://en.wikibooks.org/wiki/Haskell/The_Curry-Howard_isomorphism">The Curry-Howard Isomorphism with a crash course in formal logic</a></p></li>
</ul>
<p>As always, I hope this helps!</p>
    </div>
  </content>
</entry>
<entry>
  <title>Java Trivia</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/java-trivia/index.html"/>
  <id>http://blog.tmorris.net/posts/java-trivia/index.html</id>
  <published>2010-05-31T20:19:54Z</published>
  <updated>2010-05-31T20:19:54Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Implement the missing function body. These rules must be followed:</p>
<ul>
<li><p>No using <code>null</code></p></li>
<li><p>No throwing an exception/error</p></li>
<li><p>Function must terminate</p></li>
<li><p>No side-effecting</p></li>
<li><p>No type-casing (<code>instanceof</code>)</p></li>
<li><p>No type-casting</p></li>
</ul>
<p>How many different ways of achieving the objective?</p>
<pre class="sourceCode Java"><code class="sourceCode java">  <span class="kw">interface</span> Function&lt;A, B&gt; {
    B <span class="fu">apply</span>(A a);
  }

  <span class="kw">class</span> C {
    <span class="dt">static</span> &lt;A, B, C&gt; Function&lt;A, C&gt; <span class="fu">c</span>(<span class="dt">final</span> Function&lt;A, B&gt; f,
                                      <span class="dt">final</span> Function&lt;B, C&gt; g) {
        .<span class="kw">... </span>todo
    }
  }</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Beginner Java Exercise with Data Types</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/beginner-java-exercise-with-data-types/index.html"/>
  <id>http://blog.tmorris.net/posts/beginner-java-exercise-with-data-types/index.html</id>
  <published>2010-05-12T11:27:14Z</published>
  <updated>2010-05-12T11:27:14Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Below is a data type that represents a list that has a maximum length of one. It is often useful in cases where <code>null</code> would otherwise be used.</p>
<p>Consider for example, <a href="http://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/http/HttpServletRequest.html#getHeader%28java.lang.String%29">the <code>getHeaders</code> method</a> on <code>HttpServletRequest</code> which returns a <code>String</code> but might return <code>null</code> if there is no such header. Instead, a new API might return <code>NoneOrOne&lt;String&gt;</code> and do away with the use of <code>null</code>.</p>
<p>The idea of this exercise is to fill out the method bodies (remove the thrown <code>Error</code>) according to the comments without altering the method type. It is not permitted to use <code>null</code> or throw any exception. The tests at the bottom (see <code>main</code> method) should produce the specified results. At the moment, the code compiles, but will not execute successfully.</p>
<p>There are nine methods that need filling out. The tests are not exhaustive (use some intuition). Have fun! Questions are welcome.</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="co">// A list that is either empty or has one element.</span>
<span class="kw">public</span> <span class="kw">abstract</span> <span class="kw">class</span> NoneOrOne&lt;a&gt; {
  <span class="co">// The key abstract method (catamorphism).</span>
  <span class="kw">public</span> <span class="kw">abstract</span> &lt;x&gt; X <span class="fu">fold</span>(Thunk&lt;x&gt; none, Func&lt;A, X&gt; one);

  <span class="co">// Produces an empty list.</span>
  <span class="kw">public</span> <span class="dt">static</span> &lt;a&gt; NoneOrOne&lt;a&gt; <span class="fu">none</span>() {
    <span class="kw">throw</span> <span class="kw">new</span> Error(<span class="st">&quot;todo&quot;</span>);
  }

  <span class="co">// Produces a list with the given element.</span>
  <span class="kw">public</span> <span class="dt">static</span> &lt;a&gt; NoneOrOne&lt;a&gt; <span class="fu">one</span>(<span class="dt">final</span> A a) {
    <span class="kw">throw</span> <span class="kw">new</span> Error(<span class="st">&quot;todo&quot;</span>);
  }

  <span class="co">// Returns true if this list is empty.</span>
  <span class="kw">public</span> <span class="dt">boolean</span> <span class="fu">isEmpty</span>() {
    <span class="kw">throw</span> <span class="kw">new</span> Error(<span class="st">&quot;todo&quot;</span>);
  }

  <span class="co">// Maps the given function on each element of this list.</span>
  <span class="kw">public</span> &lt;b&gt; NoneOrOne&lt;b&gt; <span class="fu">map</span>(<span class="dt">final</span> Func&lt;A, B&gt; f) {
    <span class="kw">throw</span> <span class="kw">new</span> Error(<span class="st">&quot;todo&quot;</span>);
  }

  <span class="co">// Filters the list on the given predicate.</span>
  <span class="co">// The element is retained if the predicate satisfies.</span>
  <span class="kw">public</span> NoneOrOne&lt;a&gt; <span class="fu">filter</span>(<span class="dt">final</span> Func&lt;A, Boolean&gt; p) {
    <span class="kw">throw</span> <span class="kw">new</span> Error(<span class="st">&quot;todo&quot;</span>);
  }

  <span class="co">// Applies the possible function on this list.</span>
  <span class="kw">public</span> &lt;b&gt; NoneOrOne&lt;b&gt; <span class="fu">app</span>(<span class="dt">final</span> NoneOrOne&lt;Func&lt;A, B&gt;&gt; f) {
    <span class="kw">throw</span> <span class="kw">new</span> Error(<span class="st">&quot;todo&quot;</span>);
  }

  <span class="co">// Binds the given function on this list.</span>
  <span class="kw">public</span> &lt;b&gt; NoneOrOne&lt;b&gt; <span class="fu">bind</span>(<span class="dt">final</span> Func&lt;A, NoneOrOne&lt;b&gt;&gt; f) {
    <span class="kw">throw</span> <span class="kw">new</span> Error(<span class="st">&quot;todo&quot;</span>);
  }

  <span class="co">// Returns the value held in this list.</span>
  <span class="co">// However, if it is empty, return the given default value.</span>
  <span class="kw">public</span> A <span class="fu">get</span>(<span class="dt">final</span> Thunk&lt;a&gt; def) {
    <span class="kw">throw</span> <span class="kw">new</span> Error(<span class="st">&quot;todo&quot;</span>);
  }

  <span class="co">// If this list is empty, return the given one.</span>
  <span class="co">// Otherwise, return this list.</span>
  <span class="kw">public</span> NoneOrOne&lt;a&gt; <span class="fu">orElse</span>(<span class="dt">final</span> NoneOrOne&lt;a&gt; els) {
    <span class="kw">throw</span> <span class="kw">new</span> Error(<span class="st">&quot;todo&quot;</span>);
  }

  <span class="co">// For debugging</span>
  <span class="kw">public</span> String <span class="fu">toString</span>() {
    <span class="dt">final</span> StringBuilder s = <span class="kw">new</span> StringBuilder();
    s.<span class="fu">append</span>(&#39;[&#39;);
    <span class="fu">fold</span>(<span class="kw">new</span> Thunk&lt;object&gt;() {
      <span class="kw">public</span> Object <span class="fu">value</span>() {
        <span class="kw">return</span> <span class="kw">null</span>; <span class="co">// Java has no suitable unit type.</span>
      }
    }, <span class="kw">new</span> Func&lt;A, Object&gt;() {
      <span class="kw">public</span> Object <span class="fu">apply</span>(<span class="dt">final</span> A a) {
        s.<span class="fu">append</span>(a);
        <span class="kw">return</span> <span class="kw">null</span>; <span class="co">// Java has no suitable unit type.</span>
      }
    });
    <span class="kw">return</span> s.<span class="fu">append</span>(&#39;]&#39;).<span class="fu">toString</span>();
  }

  <span class="co">// TEST</span>
  <span class="kw">public</span> <span class="dt">static</span> <span class="dt">void</span> <span class="fu">main</span>(<span class="dt">final</span> String[] args) {
    <span class="dt">final</span> NoneOrOne&lt;integer&gt; s = NoneOrOne.<span class="fu">one</span>(Integer.<span class="fu">parseInt</span>(args[<span class="dv">0</span>]));

    <span class="dt">final</span> NoneOrOne&lt;string&gt; t = s.<span class="fu">map</span>(<span class="kw">new</span> Func&lt;Integer, String&gt;() {
      <span class="kw">public</span> String <span class="fu">apply</span>(<span class="dt">final</span> Integer i) {
        <span class="kw">return</span> <span class="kw">new</span> StringBuilder(Integer.<span class="fu">valueOf</span>(i * <span class="dv">123</span>).<span class="fu">toString</span>()).<span class="fu">reverse</span>().<span class="fu">toString</span>();
      }
    });

    <span class="dt">final</span> NoneOrOne&lt;integer&gt; u = s.<span class="fu">filter</span>(<span class="kw">new</span> Func&lt;Integer, Boolean&gt;() {
      <span class="kw">public</span> Boolean <span class="fu">apply</span>(<span class="dt">final</span> Integer i) {
        <span class="kw">return</span> i &lt; <span class="dv">100</span>;
      }
    });

    <span class="dt">final</span> NoneOrOne&lt;string&gt; v = s.<span class="fu">app</span>(NoneOrOne.&lt;Func&lt;Integer, String&gt;&gt;<span class="fu">one</span>(
      <span class="kw">new</span> Func&lt;Integer, String&gt;() {
      <span class="kw">public</span> String <span class="fu">apply</span>(<span class="dt">final</span> Integer i) {
        <span class="kw">return</span> String.<span class="fu">valueOf</span>(Math.<span class="fu">pow</span>(i, i));
      }
    }));

    <span class="dt">final</span> NoneOrOne&lt;string&gt; w = s.<span class="fu">bind</span>(<span class="kw">new</span> Func&lt;Integer, NoneOrOne&lt;string&gt;&gt;() {
      <span class="kw">public</span> NoneOrOne&lt;string&gt; <span class="fu">apply</span>(<span class="dt">final</span> Integer i) {
        <span class="kw">return</span> i % <span class="dv">2</span> == <span class="dv">0</span> ?
          <span class="fu">one</span>(<span class="st">&quot;it&#39;s even&quot;</span>) :
          i % <span class="dv">3</span> == <span class="dv">0</span> ?
            <span class="fu">one</span>(<span class="st">&quot;it&#39;s divisible by 3 but not 6&quot;</span>) :
            NoneOrOne.&lt;string&gt;<span class="fu">none</span>();
      }
    });

    <span class="dt">final</span> Integer x = s.<span class="fu">get</span>(<span class="kw">new</span> Thunk&lt;integer&gt;() {
      <span class="kw">public</span> Integer <span class="fu">value</span>() {
        <span class="kw">return</span> <span class="dv">42</span>;
      }
    });

    <span class="dt">final</span> NoneOrOne&lt;integer&gt; y = NoneOrOne.&lt;integer&gt;<span class="fu">none</span>().<span class="fu">orElse</span>(s);

    <span class="co">/*</span>
<span class="co">    $ java NoneOrOne 122</span>
<span class="co">    [122]</span>
<span class="co">    [60051]</span>
<span class="co">    []</span>
<span class="co">    [3.4347832971354663E254]</span>
<span class="co">    [it&#39;s even]</span>
<span class="co">    122</span>
<span class="co">    [122]</span>

<span class="co">    $ java -classpath /tmp/ NoneOrOne 12</span>
<span class="co">    [12]</span>
<span class="co">    [6741]</span>
<span class="co">    [12]</span>
<span class="co">    [8.916100448256E12]</span>
<span class="co">    [it&#39;s even]</span>
<span class="co">    12</span>
<span class="co">    [12]</span>
<span class="co">    */</span>
    System.<span class="fu">out</span>.<span class="fu">println</span>(s);
    System.<span class="fu">out</span>.<span class="fu">println</span>(t);
    System.<span class="fu">out</span>.<span class="fu">println</span>(u);
    System.<span class="fu">out</span>.<span class="fu">println</span>(v);
    System.<span class="fu">out</span>.<span class="fu">println</span>(w);
    System.<span class="fu">out</span>.<span class="fu">println</span>(x);
    System.<span class="fu">out</span>.<span class="fu">println</span>(y);
  }
}

<span class="co">// Laziness</span>
<span class="kw">interface</span> Thunk&lt;t&gt; {
  T <span class="fu">value</span>();
}

<span class="co">// Takes an A and produces a B</span>
<span class="kw">interface</span> Func&lt;A, B&gt; {
  B <span class="fu">apply</span>(A a);
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Haskell Beginner Exercises with Tests</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/haskell-beginner-exercises-with-tests/index.html"/>
  <id>http://blog.tmorris.net/posts/haskell-beginner-exercises-with-tests/index.html</id>
  <published>2010-04-25T09:53:01Z</published>
  <updated>2010-04-25T09:53:01Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Follow-on from <a href="http://blog.tmorris.net/haskell-exercises-for-beginners/">Haskell Exercises for Beginners</a></p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="co">-- TOTAL marks:    /66</span>

<span class="kw">module</span> <span class="dt">Exercises</span> <span class="kw">where</span>

<span class="kw">import</span> <span class="dt">Prelude</span> <span class="kw">hiding</span> (<span class="fu">sum</span>, <span class="fu">length</span>, <span class="fu">map</span>, <span class="fu">filter</span>, <span class="fu">maximum</span>, <span class="fu">reverse</span>, <span class="fu">succ</span>, <span class="fu">pred</span>)

<span class="co">-- BEGIN Helper functions and data types</span>

<span class="co">-- The custom list type</span>
<span class="kw">data</span> <span class="dt">List</span> t <span class="fu">=</span> <span class="dt">Nil</span> <span class="fu">|</span> <span class="dt">Cons</span> t (<span class="dt">List</span> t) <span class="kw">deriving</span> <span class="kw">Eq</span>

<span class="kw">instance</span> (<span class="kw">Show</span> t) <span class="ot">=&gt;</span> <span class="kw">Show</span> (<span class="dt">List</span> t) <span class="kw">where</span>
  <span class="fu">show</span> <span class="fu">=</span> <span class="fu">show</span> <span class="fu">.</span> toList
    <span class="kw">where</span>
    toList <span class="dt">Nil</span> <span class="fu">=</span> []
    toList (<span class="dt">Cons</span> h t) <span class="fu">=</span> h <span class="fu">:</span> toList t

<span class="co">-- the custom numeric type</span>
<span class="kw">data</span> <span class="dt">Natural</span> <span class="fu">=</span> <span class="dt">Zero</span> <span class="fu">|</span> <span class="dt">Succ</span> <span class="dt">Natural</span> <span class="kw">deriving</span> <span class="kw">Eq</span>
one <span class="fu">=</span> <span class="dt">Succ</span> <span class="dt">Zero</span>
two <span class="fu">=</span> <span class="dt">Succ</span> one
three <span class="fu">=</span> <span class="dt">Succ</span> two

<span class="kw">instance</span> <span class="kw">Show</span> <span class="dt">Natural</span> <span class="kw">where</span>
  <span class="fu">show</span> <span class="fu">=</span> <span class="fu">show</span> <span class="fu">.</span> <span class="fu">toInt</span>
    <span class="kw">where</span>
    <span class="fu">toInt</span> <span class="dt">Zero</span> <span class="fu">=</span> <span class="dv">0</span>
    <span class="fu">toInt</span> (<span class="dt">Succ</span> x) <span class="fu">=</span> <span class="dv">1</span> <span class="fu">+</span> <span class="fu">toInt</span> x

<span class="co">-- functions over Natural that you may consider using</span>
<span class="fu">succ</span><span class="ot"> ::</span> <span class="dt">Natural</span> <span class="ot">-&gt;</span> <span class="dt">Natural</span>
<span class="fu">succ</span> <span class="fu">=</span> <span class="dt">Succ</span>

<span class="fu">pred</span><span class="ot"> ::</span> <span class="dt">Natural</span> <span class="ot">-&gt;</span> <span class="dt">Natural</span>
<span class="fu">pred</span> <span class="dt">Zero</span> <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;bzzt. Zero has no predecessor in naturals&quot;</span>
<span class="fu">pred</span> (<span class="dt">Succ</span> x) <span class="fu">=</span> x

<span class="co">-- functions over List that you may consider using</span>
<span class="ot">foldRight ::</span> (a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> b
foldRight _ b <span class="dt">Nil</span> <span class="fu">=</span> b
foldRight f b (<span class="dt">Cons</span> h t) <span class="fu">=</span> f h (foldRight f b t)

<span class="ot">foldLeft ::</span> (b <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> b
foldLeft _ b <span class="dt">Nil</span> <span class="fu">=</span> b
foldLeft f b (<span class="dt">Cons</span> h t) <span class="fu">=</span> <span class="kw">let</span> b&#39; <span class="fu">=</span> f b h <span class="kw">in</span> b&#39; <span class="ot">`seq`</span> foldLeft f b&#39; t

<span class="ot">reduceRight ::</span> (a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> a) <span class="ot">-&gt;</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> a
reduceRight _ <span class="dt">Nil</span> <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;bzzt. reduceRight on empty list&quot;</span>
reduceRight f (<span class="dt">Cons</span> h t) <span class="fu">=</span> foldRight f h t

<span class="ot">reduceLeft ::</span> (a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> a) <span class="ot">-&gt;</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> a
reduceLeft _ <span class="dt">Nil</span> <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;bzzt. reduceLeft on empty list&quot;</span>
reduceLeft f (<span class="dt">Cons</span> h t) <span class="fu">=</span> foldLeft f h t

<span class="co">-- END Helper functions and data types</span>

<span class="co">-- BEGIN Exercises</span>

<span class="co">-- Exercise 1</span>
<span class="co">-- Relative Difficulty: 1</span>
<span class="co">-- Correctness: 2.0 marks</span>
<span class="co">-- Performance: 0.5 mark</span>
<span class="co">-- Elegance: 0.5 marks</span>
<span class="co">-- Total: 3</span>
<span class="ot">add ::</span> <span class="dt">Natural</span> <span class="ot">-&gt;</span> <span class="dt">Natural</span> <span class="ot">-&gt;</span> <span class="dt">Natural</span>
add <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 2</span>
<span class="co">-- Relative Difficulty: 2</span>
<span class="co">-- Correctness: 2.5 marks</span>
<span class="co">-- Performance: 1 mark</span>
<span class="co">-- Elegance: 0.5 marks</span>
<span class="co">-- Total: 4</span>
<span class="fu">sum</span><span class="ot"> ::</span> <span class="dt">List</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span>
<span class="fu">sum</span> <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 3</span>
<span class="co">-- Relative Difficulty: 2</span>
<span class="co">-- Correctness: 2.5 marks</span>
<span class="co">-- Performance: 1 mark</span>
<span class="co">-- Elegance: 0.5 marks</span>
<span class="co">-- Total: 4</span>
<span class="fu">length</span><span class="ot"> ::</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> <span class="dt">Int</span>
<span class="fu">length</span> <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 4</span>
<span class="co">-- Relative Difficulty: 5</span>
<span class="co">-- Correctness: 4.5 marks</span>
<span class="co">-- Performance: 1.0 mark</span>
<span class="co">-- Elegance: 1.5 marks</span>
<span class="co">-- Total: 7</span>
<span class="fu">map</span><span class="ot"> ::</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> <span class="dt">List</span> b
<span class="fu">map</span> <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 5</span>
<span class="co">-- Relative Difficulty: 5</span>
<span class="co">-- Correctness: 4.5 marks</span>
<span class="co">-- Performance: 1.5 marks</span>
<span class="co">-- Elegance: 1 mark</span>
<span class="co">-- Total: 7</span>
<span class="fu">filter</span><span class="ot"> ::</span> (a <span class="ot">-&gt;</span> <span class="dt">Bool</span>) <span class="ot">-&gt;</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> <span class="dt">List</span> a
<span class="fu">filter</span> <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 6</span>
<span class="co">-- Relative Difficulty: 5</span>
<span class="co">-- Correctness: 4.5 marks</span>
<span class="co">-- Performance: 1.5 marks</span>
<span class="co">-- Elegance: 1 mark</span>
<span class="co">-- Total: 7</span>
<span class="ot">append ::</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> <span class="dt">List</span> a
append <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 7</span>
<span class="co">-- Relative Difficulty: 5</span>
<span class="co">-- Correctness: 4.5 marks</span>
<span class="co">-- Performance: 1.5 marks</span>
<span class="co">-- Elegance: 1 mark</span>
<span class="co">-- Total: 7</span>
<span class="ot">flatten ::</span> <span class="dt">List</span> (<span class="dt">List</span> a) <span class="ot">-&gt;</span> <span class="dt">List</span> a
flatten <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 8</span>
<span class="co">-- Relative Difficulty: 7</span>
<span class="co">-- Correctness: 5.0 marks</span>
<span class="co">-- Performance: 1.5 marks</span>
<span class="co">-- Elegance: 1.5 mark</span>
<span class="co">-- Total: 8</span>
<span class="ot">flatMap ::</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> <span class="dt">List</span> b) <span class="ot">-&gt;</span> <span class="dt">List</span> b
flatMap <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 9</span>
<span class="co">-- Relative Difficulty: 8</span>
<span class="co">-- Correctness: 3.5 marks</span>
<span class="co">-- Performance: 3.0 marks</span>
<span class="co">-- Elegance: 2.5 marks</span>
<span class="co">-- Total: 9</span>
<span class="fu">maximum</span><span class="ot"> ::</span> <span class="dt">List</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span>
<span class="fu">maximum</span> <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 10</span>
<span class="co">-- Relative Difficulty: 10</span>
<span class="co">-- Correctness: 5.0 marks</span>
<span class="co">-- Performance: 2.5 marks</span>
<span class="co">-- Elegance: 2.5 marks</span>
<span class="co">-- Total: 10</span>
<span class="fu">reverse</span><span class="ot"> ::</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> <span class="dt">List</span> a
<span class="fu">reverse</span> <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- END Exercises</span>

<span class="co">-- BEGIN Tests for Exercises</span>

<span class="ot">main ::</span> <span class="dt">IO</span> ()
main <span class="fu">=</span>
  <span class="kw">let</span> showNil <span class="fu">=</span> <span class="fu">show</span> (<span class="dt">Nil</span><span class="ot"> ::</span> <span class="dt">List</span> <span class="dt">Int</span>)
      results <span class="fu">=</span>
        [
        <span class="co">-- add</span>
        (<span class="st">&quot;add&quot;</span>,
         <span class="fu">show</span> (add one two)
       , <span class="fu">show</span> three),

        (<span class="st">&quot;add&quot;</span>,
         <span class="fu">show</span> (add <span class="dt">Zero</span> two)
       , <span class="fu">show</span> two),

        <span class="co">-- sum</span>
        (<span class="st">&quot;sum&quot;</span>,
         <span class="fu">show</span> (<span class="fu">sum</span> (<span class="dt">Cons</span> <span class="dv">1</span> (<span class="dt">Cons</span> <span class="dv">2</span> (<span class="dt">Cons</span> <span class="dv">3</span> <span class="dt">Nil</span>))))
       , <span class="fu">show</span> <span class="dv">6</span>),

        (<span class="st">&quot;sum&quot;</span>,
         <span class="fu">show</span> (<span class="fu">sum</span> <span class="dt">Nil</span>)
       , <span class="fu">show</span> <span class="dv">0</span>),

        <span class="co">-- length</span>
        (<span class="st">&quot;length&quot;</span>,
         <span class="fu">show</span> (<span class="fu">length</span> (<span class="dt">Cons</span> <span class="ch">&#39;a&#39;</span> (<span class="dt">Cons</span> <span class="ch">&#39;b&#39;</span> (<span class="dt">Cons</span> <span class="ch">&#39;c&#39;</span> <span class="dt">Nil</span>))))
       , <span class="fu">show</span> <span class="dv">3</span>),

        (<span class="st">&quot;length&quot;</span>,
         <span class="fu">show</span> (<span class="fu">length</span> <span class="dt">Nil</span>)
       , <span class="fu">show</span> <span class="dv">0</span>),

        <span class="co">-- map</span>
        (<span class="st">&quot;map&quot;</span>,
         <span class="fu">show</span> (<span class="fu">map</span> (<span class="fu">+</span><span class="dv">1</span>) (<span class="dt">Cons</span> <span class="dv">1</span> (<span class="dt">Cons</span> <span class="dv">2</span> (<span class="dt">Cons</span> <span class="dv">3</span> <span class="dt">Nil</span>))))
       , <span class="fu">show</span> (<span class="dt">Cons</span> <span class="dv">2</span> (<span class="dt">Cons</span> <span class="dv">3</span> (<span class="dt">Cons</span> <span class="dv">4</span> <span class="dt">Nil</span>)))),

        (<span class="st">&quot;map&quot;</span>,
         <span class="fu">show</span> (<span class="fu">map</span> (<span class="fu">+</span><span class="dv">1</span>) <span class="dt">Nil</span>)
       , showNil),

        <span class="co">-- filter</span>
        (<span class="st">&quot;filter&quot;</span>,
         <span class="fu">show</span> (<span class="fu">filter</span> <span class="fu">even</span> (<span class="dt">Cons</span> <span class="dv">1</span> (<span class="dt">Cons</span> <span class="dv">2</span> (<span class="dt">Cons</span> <span class="dv">3</span> <span class="dt">Nil</span>))))
       , <span class="fu">show</span> (<span class="dt">Cons</span> <span class="dv">2</span> <span class="dt">Nil</span>)),

        (<span class="st">&quot;filter&quot;</span>,
         <span class="fu">show</span> (<span class="fu">filter</span> <span class="fu">even</span> <span class="dt">Nil</span>)
       , showNil),

        <span class="co">-- append</span>
        (<span class="st">&quot;append&quot;</span>,
         <span class="fu">show</span> (append (<span class="dt">Cons</span> <span class="dv">1</span> (<span class="dt">Cons</span> <span class="dv">2</span> (<span class="dt">Cons</span> <span class="dv">3</span> <span class="dt">Nil</span>))) (<span class="dt">Cons</span> <span class="dv">4</span> <span class="dt">Nil</span>))
       , <span class="fu">show</span> (<span class="dt">Cons</span> <span class="dv">1</span> (<span class="dt">Cons</span> <span class="dv">2</span> (<span class="dt">Cons</span> <span class="dv">3</span> (<span class="dt">Cons</span> <span class="dv">4</span> <span class="dt">Nil</span>))))),

        (<span class="st">&quot;append&quot;</span>,
         <span class="fu">show</span> (append (<span class="dt">Cons</span> <span class="dv">1</span> (<span class="dt">Cons</span> <span class="dv">2</span> (<span class="dt">Cons</span> <span class="dv">3</span> <span class="dt">Nil</span>))) <span class="dt">Nil</span>)
       , <span class="fu">show</span> (<span class="dt">Cons</span> <span class="dv">1</span> (<span class="dt">Cons</span> <span class="dv">2</span> (<span class="dt">Cons</span> <span class="dv">3</span> <span class="dt">Nil</span>)))),

        <span class="co">-- flatten</span>
        (<span class="st">&quot;flatten&quot;</span>,
         <span class="fu">show</span> (flatten (<span class="dt">Cons</span> (<span class="dt">Cons</span> <span class="dv">1</span> (<span class="dt">Cons</span> <span class="dv">2</span> <span class="dt">Nil</span>)) (<span class="dt">Cons</span> (<span class="dt">Cons</span> <span class="dv">3</span> (<span class="dt">Cons</span> <span class="dv">4</span> <span class="dt">Nil</span>)) <span class="dt">Nil</span>)))
       , <span class="fu">show</span> (<span class="dt">Cons</span> <span class="dv">1</span> (<span class="dt">Cons</span> <span class="dv">2</span> (<span class="dt">Cons</span> <span class="dv">3</span> (<span class="dt">Cons</span> <span class="dv">4</span> <span class="dt">Nil</span>))))),

        <span class="co">-- flatMap</span>
        (<span class="st">&quot;flatMap&quot;</span>,
         <span class="fu">show</span> (flatMap (<span class="dt">Cons</span> <span class="dv">1</span> (<span class="dt">Cons</span> <span class="dv">2</span> (<span class="dt">Cons</span> <span class="dv">3</span> <span class="dt">Nil</span>))) (\n <span class="ot">-&gt;</span> <span class="dt">Cons</span> (n<span class="dv">+1</span>) (<span class="dt">Cons</span> (n<span class="dv">+2</span>) <span class="dt">Nil</span>)))
       , <span class="fu">show</span> (<span class="dt">Cons</span> <span class="dv">2</span> (<span class="dt">Cons</span> <span class="dv">3</span> (<span class="dt">Cons</span> <span class="dv">3</span> (<span class="dt">Cons</span> <span class="dv">4</span> (<span class="dt">Cons</span> <span class="dv">4</span> (<span class="dt">Cons</span> <span class="dv">5</span> <span class="dt">Nil</span>))))))),

        <span class="co">-- maximum</span>
        (<span class="st">&quot;maximum&quot;</span>,
         <span class="fu">show</span> (<span class="fu">maximum</span> (<span class="dt">Cons</span> <span class="dv">3</span> (<span class="dt">Cons</span> <span class="dv">1</span> (<span class="dt">Cons</span> <span class="dv">2</span> <span class="dt">Nil</span>))))
       , <span class="fu">show</span> <span class="dv">3</span>),

        <span class="co">-- reverse</span>
        (<span class="st">&quot;reverse&quot;</span>,
         <span class="fu">show</span> (<span class="fu">reverse</span> (<span class="dt">Cons</span> <span class="dv">1</span> (<span class="dt">Cons</span> <span class="dv">2</span> (<span class="dt">Cons</span> <span class="dv">3</span> <span class="dt">Nil</span>))))
       , <span class="fu">show</span> (<span class="dt">Cons</span> <span class="dv">3</span> (<span class="dt">Cons</span> <span class="dv">2</span> (<span class="dt">Cons</span> <span class="dv">1</span> <span class="dt">Nil</span>))))
        ]
      check (n, a, b) <span class="fu">=</span> <span class="kw">do</span> <span class="fu">print</span> (<span class="st">&quot;=== &quot;</span> <span class="fu">++</span> n <span class="fu">++</span> <span class="st">&quot; ===&quot;</span>)
                           <span class="fu">print</span> (<span class="kw">if</span> a <span class="fu">==</span> b <span class="kw">then</span> <span class="st">&quot;PASS&quot;</span> <span class="kw">else</span> <span class="st">&quot;FAIL Expected: &quot;</span> <span class="fu">++</span> b <span class="fu">++</span> <span class="st">&quot; Actual: &quot;</span> <span class="fu">++</span> a)

  <span class="kw">in</span> <span class="fu">mapM_</span> check results

<span class="co">-- END Tests for Exercises</span></code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Monad Exercises in Scala and Haskell</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/monad-exercises-in-scala-and-haskell/index.html"/>
  <id>http://blog.tmorris.net/posts/monad-exercises-in-scala-and-haskell/index.html</id>
  <published>2010-04-05T16:32:14Z</published>
  <updated>2010-04-05T16:32:14Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Revised and including addendum.</p>
<p><strong>Scala</strong></p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// 1. Start here. Observe this trait</span>
<span class="kw">trait</span> Monad[M[_]] {
  <span class="kw">def</span> flatMap[A, B](a: M[A], f: A =&gt; M[B]): M[B]
  <span class="kw">def</span> unital[A](a: A): M[A]
}

<span class="co">// A simple data type, which turns out to satisfy the above trait</span>
<span class="kw">case</span> <span class="kw">class</span> Inter[A](f: Int =&gt; A)

<span class="co">// So does this.</span>
<span class="kw">case</span> <span class="kw">class</span> Identity[A](a: A)

<span class="co">// Monad implementations</span>
<span class="kw">object</span> Monad {
  <span class="co">// 2. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> ListMonad: Monad[List] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// 3. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> OptionMonad: Monad[Option] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// 4. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> InterMonad: Monad[Inter] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// 5. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> IdentityMonad: Monad[Identity] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)
}

<span class="kw">object</span> MonadicFunctions {
  <span class="co">// 6. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> sequence[M[_], A](as: List[M[A]], m: Monad[M]): M[List[A]] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// 7. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> fmap[M[_], A, B](a: M[A], f: A =&gt; B, m: Monad[M]): M[B] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// 8. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> flatten[M[_], A](a: M[M[A]], m: Monad[M]): M[A] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// 9. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> apply[M[_], A, B](f: M[A =&gt; B], a: M[A], m: Monad[M]): M[B] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// 10. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> filterM[M[_], A](f: A =&gt; M[Boolean], as: List[A]
    , m: Monad[M]): M[List[A]] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// 11. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> replicateM[M[_], A](n: Int, a: M[A], m: Monad[M]): M[List[A]] =
    <span class="fu">error</span>(<span class="st">&quot;todo: flatMap n times to produce a list&quot;</span>)

  <span class="co">// 12. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> lift2[M[_], A, B, C](f: (A, B) =&gt; C, a: M[A], b: M[B]
    , m: Monad[M]): M[C] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// lift3, lift4, etc. Interesting question: Can we have liftN?</span>
}

<span class="kw">object</span> Main {
  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]) {
    <span class="kw">import</span> Monad.<span class="fu">_</span>
    <span class="kw">import</span> MonadicFunctions.<span class="fu">_</span>

    <span class="kw">val</span> plusOne = <span class="fu">Inter</span>(<span class="dv">1</span>+)
    <span class="kw">val</span> multTwo = <span class="fu">Inter</span>(<span class="dv">2</span>*)
    <span class="kw">val</span> squared = <span class="fu">Inter</span>(n =&gt; n*n)
    <span class="kw">val</span> plus = (_: Int) + (_: Int)

    <span class="kw">val</span> values = List(
<span class="co">// sequence</span>
<span class="fu">sequence</span>(List(List(<span class="dv">1</span>, <span class="dv">2</span>), List(<span class="dv">3</span>, <span class="dv">4</span>)), ListMonad),
<span class="fu">sequence</span>(List(Some(<span class="dv">7</span>), Some(<span class="dv">8</span>), Some(<span class="dv">9</span>)), OptionMonad),
<span class="fu">sequence</span>(List(Some(<span class="dv">7</span>), None, Some(<span class="dv">9</span>)), OptionMonad),
<span class="fu">sequence</span>(List(plusOne, multTwo, squared), InterMonad) f <span class="dv">7</span>,
<span class="fu">sequence</span>(List(Identity(<span class="dv">7</span>), Identity(<span class="dv">4</span>)), IdentityMonad),
<span class="co">// fmap</span>
<span class="fu">fmap</span>(List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>), (x: Int) =&gt; x * <span class="dv">10</span>, ListMonad),
<span class="fu">fmap</span>(Some(<span class="dv">8</span>), (x: Int) =&gt; x * <span class="dv">10</span>, OptionMonad),
<span class="fu">fmap</span>(None: Option[Int], (x: Int) =&gt; x * <span class="dv">10</span>, OptionMonad),
<span class="fu">fmap</span>(plusOne, (x: Int) =&gt; x * <span class="dv">10</span>, InterMonad) f <span class="dv">7</span>,
<span class="fu">fmap</span>(Identity(<span class="dv">9</span>), (x: Int) =&gt; x * <span class="dv">10</span>, IdentityMonad),
<span class="co">// flatten</span>
<span class="fu">flatten</span>(List(List(<span class="dv">1</span>, <span class="dv">2</span>), List(<span class="dv">3</span>, <span class="dv">4</span>)), ListMonad),
<span class="fu">flatten</span>(Some(Some(<span class="dv">8</span>)), OptionMonad),
<span class="fu">flatten</span>(Some(None: Option[Int]), OptionMonad),
<span class="fu">flatten</span>(None: Option[Option[Int]], OptionMonad),
<span class="fu">flatten</span>(<span class="fu">Inter</span>(a =&gt; <span class="fu">Inter</span>(a *)), InterMonad) f <span class="dv">7</span>,
<span class="fu">flatten</span>(Identity(Identity(<span class="dv">8</span>)), IdentityMonad),
<span class="co">// apply</span>
<span class="fu">apply</span>(List((a: Int) =&gt; a + <span class="dv">1</span>,
           (a: Int) =&gt; a * <span class="dv">2</span>,
           (a: Int) =&gt; a % <span class="dv">2</span>), List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>), ListMonad),
<span class="fu">apply</span>(Some((a: Int) =&gt; a + <span class="dv">1</span>), Some(<span class="dv">8</span>), OptionMonad),
<span class="fu">apply</span>(None: Option[Int =&gt; Int], Some(<span class="dv">8</span>), OptionMonad),
<span class="fu">apply</span>(Some((a: Int) =&gt; a + <span class="dv">1</span>), None: Option[Int], OptionMonad),
<span class="fu">apply</span>(<span class="fu">Inter</span>(a =&gt; (b: Int) =&gt; a * b), <span class="fu">Inter</span>(<span class="dv">1</span>+), InterMonad) f <span class="dv">7</span>,
<span class="fu">apply</span>(Identity((a: Int) =&gt; a + <span class="dv">1</span>), Identity(<span class="dv">7</span>), IdentityMonad),
<span class="co">// filterM</span>
<span class="fu">filterM</span>((a: Int) =&gt; List(a &gt; <span class="dv">2</span>, a % <span class="dv">2</span> == <span class="dv">0</span>), List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>), ListMonad),
<span class="fu">filterM</span>((a: Int) =&gt; Some(a &gt; <span class="dv">1</span>), List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>), OptionMonad),
<span class="fu">filterM</span>((a: Int) =&gt; <span class="fu">Inter</span>(n =&gt; a * n % <span class="dv">2</span> == <span class="dv">0</span>),
  List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>), InterMonad) f <span class="dv">7</span>,
<span class="fu">filterM</span>((a: Int) =&gt; Identity(a &gt; <span class="dv">1</span>), List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>), IdentityMonad),
<span class="co">// replicateM</span>
<span class="fu">replicateM</span>(<span class="dv">2</span>, List(<span class="dv">7</span>, <span class="dv">8</span>), ListMonad),
<span class="fu">replicateM</span>(<span class="dv">2</span>, Some(<span class="dv">7</span>), OptionMonad),
<span class="fu">replicateM</span>(<span class="dv">2</span>, plusOne, InterMonad) f <span class="dv">7</span>,
<span class="fu">replicateM</span>(<span class="dv">2</span>, Identity(<span class="dv">6</span>), IdentityMonad),
<span class="co">// lift2</span>
<span class="fu">lift2</span>(plus, List(<span class="dv">1</span>, <span class="dv">2</span>), List(<span class="dv">3</span>, <span class="dv">4</span>), ListMonad),
<span class="fu">lift2</span>(plus, Some(<span class="dv">7</span>), Some(<span class="dv">8</span>), OptionMonad),
<span class="fu">lift2</span>(plus, Some(<span class="dv">7</span>), None: Option[Int], OptionMonad),
<span class="fu">lift2</span>(plus, None: Option[Int], Some(<span class="dv">8</span>), OptionMonad)
    )

    <span class="kw">val</span> verify = List(
<span class="co">// sequence</span>
List(List(<span class="dv">1</span>, <span class="dv">3</span>), List(<span class="dv">1</span>, <span class="dv">4</span>), List(<span class="dv">2</span>, <span class="dv">3</span>), List(<span class="dv">2</span>, <span class="dv">4</span>)),
Some(List(<span class="dv">7</span>, <span class="dv">8</span>, <span class="dv">9</span>)),
None,
List(<span class="dv">8</span>, <span class="dv">14</span>, <span class="dv">49</span>),
Identity(List(<span class="dv">7</span>, <span class="dv">4</span>)),
<span class="co">// fmap</span>
List(<span class="dv">10</span>, <span class="dv">20</span>, <span class="dv">30</span>),
Some(<span class="dv">80</span>),
None,
<span class="dv">80</span>,
Identity(<span class="dv">90</span>),
<span class="co">// flatten</span>
List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>),
Some(<span class="dv">8</span>),
None,
None,
<span class="dv">49</span>,
Identity(<span class="dv">8</span>),
<span class="co">// apply</span>
List(<span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">2</span>, <span class="dv">4</span>, <span class="dv">6</span>, <span class="dv">1</span>, <span class="dv">0</span>, <span class="dv">1</span>),
Some(<span class="dv">9</span>),
None,
None,
<span class="dv">56</span>,
Identity(<span class="dv">8</span>),
<span class="co">// filterM</span>
List(List(<span class="dv">3</span>), Nil, List(<span class="dv">2</span>, <span class="dv">3</span>), List(<span class="dv">2</span>), List(<span class="dv">3</span>),
  Nil, List(<span class="dv">2</span>, <span class="dv">3</span>), List(<span class="dv">2</span>)),
Some(List(<span class="dv">2</span>, <span class="dv">3</span>)),
List(<span class="dv">2</span>),
Identity(List(<span class="dv">2</span>, <span class="dv">3</span>)),
<span class="co">// replicateM</span>
List(List(<span class="dv">7</span>, <span class="dv">7</span>), List(<span class="dv">7</span>, <span class="dv">8</span>), List(<span class="dv">8</span>, <span class="dv">7</span>), List(<span class="dv">8</span>, <span class="dv">8</span>)),
Some(List(<span class="dv">7</span>, <span class="dv">7</span>)),
List(<span class="dv">8</span>, <span class="dv">8</span>),
Identity(List(<span class="dv">6</span>, <span class="dv">6</span>)),
<span class="co">// lift2</span>
List(<span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">5</span>, <span class="dv">6</span>),
Some(<span class="dv">15</span>),
None,
None
)

    <span class="kw">for</span>((a, b) &lt;- values zip verify)
      <span class="fu">println</span>(<span class="kw">if</span>(a == b) <span class="st">&quot;PASS&quot;</span>
              <span class="kw">else</span> <span class="st">&quot;FAIL. Expected: &quot;</span> + b + <span class="st">&quot; Actual: &quot;</span> + a)
  }
}</code></pre>
<p><strong>Haskell</strong></p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="ot">{-# LANGUAGE RankNTypes #-}</span>

<span class="co">-- 1. Start here. Observe this data type</span>
<span class="kw">data</span> <span class="dt">Monad&#39;</span> m <span class="fu">=</span> <span class="dt">Monad&#39;</span> {
<span class="ot">  unital ::</span> forall a<span class="fu">.</span> a <span class="ot">-&gt;</span> m a,
<span class="ot">  flatMap ::</span> forall a b<span class="fu">.</span> m a <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> m b) <span class="ot">-&gt;</span> m b
}

<span class="co">-- A simple data type, which turns out to satisfy the above trait</span>
<span class="kw">newtype</span> <span class="dt">Inter</span> a <span class="fu">=</span> <span class="dt">Inter</span> {<span class="ot"> f ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> a }

<span class="co">-- So does this.</span>
<span class="kw">newtype</span> <span class="dt">Identity</span> a <span class="fu">=</span> <span class="dt">Identity</span> {<span class="ot"> a ::</span> a }
  <span class="kw">deriving</span> <span class="kw">Show</span>

<span class="co">-- *** Monad implementations ***</span>

<span class="co">-- 2. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">listMonad ::</span> <span class="dt">Monad&#39;</span> []
listMonad <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- 3. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">maybeMonad ::</span> <span class="dt">Monad&#39;</span> <span class="dt">Maybe</span>
maybeMonad <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- 4. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">interMonad ::</span> <span class="dt">Monad&#39;</span> <span class="dt">Inter</span>
interMonad <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- 5. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">identityMonad ::</span> <span class="dt">Monad&#39;</span> <span class="dt">Identity</span>
identityMonad <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- *** Monadic functions ***</span>

<span class="co">-- 6. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">sequence&#39; ::</span> [m a] <span class="ot">-&gt;</span> <span class="dt">Monad&#39;</span> m <span class="ot">-&gt;</span> m [a]
sequence&#39; <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- 7. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">fmap&#39; ::</span> m a <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> <span class="dt">Monad&#39;</span> m <span class="ot">-&gt;</span> m b
fmap&#39; <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- 8. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">flatten ::</span> m (m a) <span class="ot">-&gt;</span> <span class="dt">Monad&#39;</span> m <span class="ot">-&gt;</span> m a
flatten <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- 9. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">apply ::</span> m (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> m a <span class="ot">-&gt;</span> <span class="dt">Monad&#39;</span> m <span class="ot">-&gt;</span> m b
apply <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- 10. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">filterM&#39; ::</span> (a <span class="ot">-&gt;</span> m <span class="dt">Bool</span>) <span class="ot">-&gt;</span> [a] <span class="ot">-&gt;</span> <span class="dt">Monad&#39;</span> m <span class="ot">-&gt;</span> m [a]
filterM&#39; <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- 11. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">replicateM&#39; ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> m a <span class="ot">-&gt;</span> <span class="dt">Monad&#39;</span> m <span class="ot">-&gt;</span> m [a]
replicateM&#39; <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo: flatMap n times to produce a list&quot;</span>

<span class="co">-- 12. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">lift2 ::</span> (a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> c) <span class="ot">-&gt;</span> m a <span class="ot">-&gt;</span> m b <span class="ot">-&gt;</span> <span class="dt">Monad&#39;</span> m <span class="ot">-&gt;</span> m c
lift2 <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- lift3, lift4, etc. Interesting question: Can we have liftN?</span>
<span class="ot">main ::</span> <span class="dt">IO</span> ()
main <span class="fu">=</span>
  <span class="kw">let</span> plusOne <span class="fu">=</span> <span class="dt">Inter</span> (<span class="dv">1</span><span class="fu">+</span>)
      multTwo <span class="fu">=</span> <span class="dt">Inter</span> (<span class="dv">2</span><span class="fu">*</span>)
      squared <span class="fu">=</span> <span class="dt">Inter</span> (\n <span class="ot">-&gt;</span> n<span class="fu">*</span>n)
      s x <span class="fu">=</span> <span class="fu">show</span> x
      (<span class="fu">%</span>) <span class="fu">=</span> f
      values <span class="fu">=</span>
        [
        <span class="co">-- sequence&#39;</span>
        s (sequence&#39; [[<span class="dv">1</span>, <span class="dv">2</span>], [<span class="dv">3</span>, <span class="dv">4</span>]] listMonad),
        s (sequence&#39; [<span class="kw">Just</span> <span class="dv">7</span>, <span class="kw">Just</span> <span class="dv">8</span>, <span class="kw">Just</span> <span class="dv">9</span>] maybeMonad),
        s (sequence&#39; [<span class="kw">Just</span> <span class="dv">7</span>, <span class="kw">Nothing</span>, <span class="kw">Nothing</span>] maybeMonad),
        s (sequence&#39; [plusOne, multTwo, squared] interMonad <span class="fu">%</span> <span class="dv">7</span>),
        s (sequence&#39; [<span class="dt">Identity</span> <span class="dv">7</span>, <span class="dt">Identity</span> <span class="dv">4</span>] identityMonad),
        <span class="co">-- fmap&#39;</span>
        s (fmap&#39; [<span class="dv">1</span><span class="fu">..</span><span class="dv">3</span>] (<span class="fu">*</span><span class="dv">10</span>) listMonad),
        s (fmap&#39; (<span class="kw">Just</span> <span class="dv">8</span>) (<span class="fu">*</span><span class="dv">10</span>) maybeMonad),
        s (fmap&#39; <span class="kw">Nothing</span> (<span class="fu">*</span><span class="dv">10</span>) maybeMonad),
        s (fmap&#39; plusOne (<span class="fu">*</span><span class="dv">10</span>) interMonad <span class="fu">%</span> <span class="dv">7</span>),
        s (fmap&#39; (<span class="dt">Identity</span> <span class="dv">9</span>) (<span class="fu">*</span><span class="dv">10</span>) identityMonad),
        <span class="co">-- flatten</span>
        s (flatten [[<span class="dv">1</span>, <span class="dv">2</span>], [<span class="dv">3</span>, <span class="dv">4</span>]] listMonad),
        s (flatten (<span class="kw">Just</span> (<span class="kw">Just</span> <span class="dv">8</span>)) maybeMonad),
        s (flatten (<span class="kw">Just</span> (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>)) maybeMonad),
        s (flatten (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> (<span class="dt">Maybe</span> <span class="dt">Int</span>)) maybeMonad),
        s (flatten (<span class="dt">Inter</span> (<span class="dt">Inter</span> <span class="fu">.</span> (<span class="fu">*</span>))) interMonad <span class="fu">%</span> <span class="dv">7</span>),
        s (flatten (<span class="dt">Identity</span> (<span class="dt">Identity</span> <span class="dv">8</span>)) identityMonad),
        <span class="co">-- apply</span>
        s (apply [(<span class="fu">+</span><span class="dv">1</span>), (<span class="fu">*</span><span class="dv">2</span>), (<span class="ot">`mod`</span> <span class="dv">2</span>)] [<span class="dv">1</span><span class="fu">..</span><span class="dv">3</span>] listMonad),
        s (apply (<span class="kw">Just</span> (<span class="fu">+</span><span class="dv">1</span>)) (<span class="kw">Just</span> <span class="dv">8</span>) maybeMonad),
        s (apply (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> (<span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span>)) (<span class="kw">Just</span> <span class="dv">8</span>) maybeMonad),
        s (apply (<span class="kw">Just</span> (<span class="fu">+</span><span class="dv">1</span>)) (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>) maybeMonad),
        s (apply (<span class="dt">Inter</span> (<span class="fu">*</span>)) (<span class="dt">Inter</span> (<span class="dv">1</span><span class="fu">+</span>)) interMonad <span class="fu">%</span> <span class="dv">7</span>),
        s (apply (<span class="dt">Identity</span> (<span class="fu">+</span><span class="dv">1</span>)) (<span class="dt">Identity</span> <span class="dv">7</span>) identityMonad),
        <span class="co">-- filterM&#39;</span>
        s (filterM&#39; (\a <span class="ot">-&gt;</span> [a <span class="fu">&gt;</span> <span class="dv">2</span>, a <span class="ot">`mod`</span> <span class="dv">2</span> <span class="fu">==</span> <span class="dv">0</span>]) [<span class="dv">1</span><span class="fu">..</span><span class="dv">3</span>] listMonad),
        s (filterM&#39; (\a <span class="ot">-&gt;</span> <span class="kw">Just</span> (a <span class="fu">&gt;</span> <span class="dv">1</span>)) [<span class="dv">1</span><span class="fu">..</span><span class="dv">3</span>] maybeMonad),
        s (filterM&#39; (\a <span class="ot">-&gt;</span> <span class="dt">Inter</span> (\n <span class="ot">-&gt;</span> a <span class="fu">*</span> n <span class="ot">`mod`</span> <span class="dv">2</span> <span class="fu">==</span> <span class="dv">0</span>)) [<span class="dv">1</span><span class="fu">..</span><span class="dv">3</span>]
          interMonad <span class="fu">%</span> <span class="dv">7</span>),
        s (filterM&#39; (<span class="dt">Identity</span> <span class="fu">.</span> (<span class="fu">&gt;</span><span class="dv">1</span>)) [<span class="dv">1</span><span class="fu">..</span><span class="dv">3</span>] identityMonad),
        <span class="co">-- replicateM&#39;</span>
        s (replicateM&#39; <span class="dv">2</span> [<span class="dv">7</span>, <span class="dv">8</span>] listMonad),
        s (replicateM&#39; <span class="dv">2</span> (<span class="kw">Just</span> <span class="dv">7</span>) maybeMonad),
        s (replicateM&#39; <span class="dv">2</span> plusOne interMonad <span class="fu">%</span> <span class="dv">7</span>),
        s (replicateM&#39; <span class="dv">2</span> (<span class="dt">Identity</span> <span class="dv">6</span>) identityMonad),
        <span class="co">-- lift2</span>
        s (lift2 (<span class="fu">+</span>) [<span class="dv">1</span>, <span class="dv">2</span>] [<span class="dv">3</span>, <span class="dv">4</span>] listMonad),
        s (lift2 (<span class="fu">+</span>) (<span class="kw">Just</span> <span class="dv">7</span>) (<span class="kw">Just</span> <span class="dv">8</span>) maybeMonad),
        s (lift2 (<span class="fu">+</span>) (<span class="kw">Just</span> <span class="dv">7</span>) (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>) maybeMonad),
        s (lift2 (<span class="fu">+</span>) (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>) (<span class="kw">Just</span> <span class="dv">8</span>) maybeMonad)
        ]
      verify <span class="fu">=</span>
        [
        <span class="co">-- sequence&#39;</span>
        s ([[<span class="dv">1</span>, <span class="dv">3</span>], [<span class="dv">1</span>, <span class="dv">4</span>], [<span class="dv">2</span>, <span class="dv">3</span>], [<span class="dv">2</span>, <span class="dv">4</span>]]),
        s (<span class="kw">Just</span> [<span class="dv">7</span><span class="fu">..</span><span class="dv">9</span>]),
        s (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>),
        s [<span class="dv">8</span>, <span class="dv">14</span>, <span class="dv">49</span>],
        s (<span class="dt">Identity</span> [<span class="dv">7</span>, <span class="dv">4</span>]),
        <span class="co">-- fmap&#39;</span>
        s [<span class="dv">10</span>, <span class="dv">20</span>, <span class="dv">30</span>],
        s (<span class="kw">Just</span> <span class="dv">80</span>),
        s (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>),
        s <span class="dv">80</span>,
        s (<span class="dt">Identity</span> <span class="dv">90</span>),
        <span class="co">-- flatten</span>
        s [<span class="dv">1</span><span class="fu">..</span><span class="dv">4</span>],
        s (<span class="kw">Just</span> <span class="dv">8</span>),
        s (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>),
        s (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>),
        s <span class="dv">49</span>,
        s (<span class="dt">Identity</span> <span class="dv">8</span>),
        <span class="co">-- apply</span>
        s [<span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">2</span>, <span class="dv">4</span>, <span class="dv">6</span>, <span class="dv">1</span>, <span class="dv">0</span>, <span class="dv">1</span>],
        s (<span class="kw">Just</span> <span class="dv">9</span>),
        s (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>),
        s (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>),
        s <span class="dv">56</span>,
        s (<span class="dt">Identity</span> <span class="dv">8</span>),
        <span class="co">-- filterM&#39;</span>
        s [[<span class="dv">3</span>], [], [<span class="dv">2</span>, <span class="dv">3</span>], [<span class="dv">2</span>], [<span class="dv">3</span>], [], [<span class="dv">2</span>, <span class="dv">3</span>], [<span class="dv">2</span>]],
        s (<span class="kw">Just</span> [<span class="dv">2</span>, <span class="dv">3</span>]),
        s [<span class="dv">2</span>],
        s (<span class="dt">Identity</span> [<span class="dv">2</span>, <span class="dv">3</span>]),
        <span class="co">-- replicateM</span>
        s [[<span class="dv">7</span>, <span class="dv">7</span>], [<span class="dv">7</span>, <span class="dv">8</span>], [<span class="dv">8</span>, <span class="dv">7</span>], [<span class="dv">8</span>, <span class="dv">8</span>]],
        s (<span class="kw">Just</span> [<span class="dv">7</span>, <span class="dv">7</span>]),
        s [<span class="dv">8</span>, <span class="dv">8</span>],
        s (<span class="dt">Identity</span> [<span class="dv">6</span>, <span class="dv">6</span>]),
        <span class="co">-- lift2</span>
        s [<span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">5</span>, <span class="dv">6</span>],
        s (<span class="kw">Just</span> <span class="dv">15</span>),
        s (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>),
        s (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>)
        ]
  <span class="kw">in</span> <span class="fu">mapM_</span>
      (\(a, b) <span class="ot">-&gt;</span>
        <span class="fu">print</span>(<span class="kw">if</span> a <span class="fu">==</span> b
                <span class="kw">then</span> <span class="st">&quot;PASS&quot;</span>
                <span class="kw">else</span> <span class="st">&quot;FAIL. Expected: &quot;</span> <span class="fu">++</span> b <span class="fu">++</span> <span class="st">&quot; Actual: &quot;</span> <span class="fu">++</span> a))
      (values <span class="ot">`zip`</span> verify)</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Monad Exercises in Scala (addendum)</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/monad-exercises-in-scala-addendum/index.html"/>
  <id>http://blog.tmorris.net/posts/monad-exercises-in-scala-addendum/index.html</id>
  <published>2010-04-03T15:45:00Z</published>
  <updated>2010-04-03T15:45:00Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Following is a test harness that should print a series of <code>PASS</code> when executed against a correct solution to the original <a href="http://blog.tmorris.net/monad-exercises-in-scala/">Monad Exercises in Scala</a>. These exercises include a Haskell version and a test harness for this is also found below.</p>
<p>I have also written a <a href="http://paste.pocoo.org/show/197013/">complete solution in Scala</a> and <a href="http://paste.pocoo.org/show/197014/">same again for Haskell</a> <em><strong>(clicking either link will give away the answer)</strong></em>.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> Main {
  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]) {
    <span class="kw">import</span> Monad.<span class="fu">_</span>
    <span class="kw">import</span> MonadicFunctions.<span class="fu">_</span>

    <span class="kw">val</span> plusOne = <span class="fu">Inter</span>(<span class="dv">1</span>+)
    <span class="kw">val</span> multTwo = <span class="fu">Inter</span>(<span class="dv">2</span>*)
    <span class="kw">val</span> squared = <span class="fu">Inter</span>(n =&gt; n*n)
    <span class="kw">val</span> plus = (_: Int) + (_: Int)

    <span class="kw">val</span> values = List(
<span class="co">// sequence</span>
<span class="fu">sequence</span>(List(List(<span class="dv">1</span>, <span class="dv">2</span>), List(<span class="dv">3</span>, <span class="dv">4</span>)), ListMonad),
<span class="fu">sequence</span>(List(Some(<span class="dv">7</span>), Some(<span class="dv">8</span>), Some(<span class="dv">9</span>)), OptionMonad),
<span class="fu">sequence</span>(List(Some(<span class="dv">7</span>), None, Some(<span class="dv">9</span>)), OptionMonad),
<span class="fu">sequence</span>(List(plusOne, multTwo, squared), InterMonad) f <span class="dv">7</span>,
<span class="fu">sequence</span>(List(Identity(<span class="dv">7</span>), Identity(<span class="dv">4</span>)), IdentityMonad),
<span class="co">// fmap</span>
<span class="fu">fmap</span>(List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>), (x: Int) =&gt; x * <span class="dv">10</span>, ListMonad),
<span class="fu">fmap</span>(Some(<span class="dv">8</span>), (x: Int) =&gt; x * <span class="dv">10</span>, OptionMonad),
<span class="fu">fmap</span>(None: Option[Int], (x: Int) =&gt; x * <span class="dv">10</span>, OptionMonad),
<span class="fu">fmap</span>(plusOne, (x: Int) =&gt; x * <span class="dv">10</span>, InterMonad) f <span class="dv">7</span>,
<span class="fu">fmap</span>(Identity(<span class="dv">9</span>), (x: Int) =&gt; x * <span class="dv">10</span>, IdentityMonad),
<span class="co">// flatten</span>
<span class="fu">flatten</span>(List(List(<span class="dv">1</span>, <span class="dv">2</span>), List(<span class="dv">3</span>, <span class="dv">4</span>)), ListMonad),
<span class="fu">flatten</span>(Some(Some(<span class="dv">8</span>)), OptionMonad),
<span class="fu">flatten</span>(Some(None: Option[Int]), OptionMonad),
<span class="fu">flatten</span>(None: Option[Option[Int]], OptionMonad),
<span class="fu">flatten</span>(<span class="fu">Inter</span>(a =&gt; <span class="fu">Inter</span>(a *)), InterMonad) f <span class="dv">7</span>,
<span class="fu">flatten</span>(Identity(Identity(<span class="dv">8</span>)), IdentityMonad),
<span class="co">// apply</span>
<span class="fu">apply</span>(List((a: Int) =&gt; a + <span class="dv">1</span>,
           (a: Int) =&gt; a * <span class="dv">2</span>,
           (a: Int) =&gt; a % <span class="dv">2</span>), List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>), ListMonad),
<span class="fu">apply</span>(Some((a: Int) =&gt; a + <span class="dv">1</span>), Some(<span class="dv">8</span>), OptionMonad),
<span class="fu">apply</span>(None: Option[Int =&gt; Int], Some(<span class="dv">8</span>), OptionMonad),
<span class="fu">apply</span>(Some((a: Int) =&gt; a + <span class="dv">1</span>), None: Option[Int], OptionMonad),
<span class="fu">apply</span>(<span class="fu">Inter</span>(a =&gt; (b: Int) =&gt; a * b), <span class="fu">Inter</span>(<span class="dv">1</span>+), InterMonad) f <span class="dv">7</span>,
<span class="fu">apply</span>(Identity((a: Int) =&gt; a + <span class="dv">1</span>), Identity(<span class="dv">7</span>), IdentityMonad),
<span class="co">// filterM</span>
<span class="fu">filterM</span>((a: Int) =&gt; List(a &gt; <span class="dv">2</span>, a % <span class="dv">2</span> == <span class="dv">0</span>), List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>), ListMonad),
<span class="fu">filterM</span>((a: Int) =&gt; Some(a &gt; <span class="dv">1</span>), List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>), OptionMonad),
<span class="fu">filterM</span>((a: Int) =&gt; <span class="fu">Inter</span>(n =&gt; a * n % <span class="dv">2</span> == <span class="dv">0</span>),
  List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>), InterMonad) f <span class="dv">7</span>,
<span class="fu">filterM</span>((a: Int) =&gt; Identity(a &gt; <span class="dv">1</span>), List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>), IdentityMonad),
<span class="co">// replicateM</span>
<span class="fu">replicateM</span>(<span class="dv">2</span>, List(<span class="dv">7</span>, <span class="dv">8</span>), ListMonad),
<span class="fu">replicateM</span>(<span class="dv">2</span>, Some(<span class="dv">7</span>), OptionMonad),
<span class="fu">replicateM</span>(<span class="dv">2</span>, plusOne, InterMonad) f <span class="dv">7</span>,
<span class="fu">replicateM</span>(<span class="dv">2</span>, Identity(<span class="dv">6</span>), IdentityMonad),
<span class="co">// lift2</span>
<span class="fu">lift2</span>(plus, List(<span class="dv">1</span>, <span class="dv">2</span>), List(<span class="dv">3</span>, <span class="dv">4</span>), ListMonad),
<span class="fu">lift2</span>(plus, Some(<span class="dv">7</span>), Some(<span class="dv">8</span>), OptionMonad),
<span class="fu">lift2</span>(plus, Some(<span class="dv">7</span>), None: Option[Int], OptionMonad),
<span class="fu">lift2</span>(plus, None: Option[Int], Some(<span class="dv">8</span>), OptionMonad)
    )

    <span class="kw">val</span> verify = List(
<span class="co">// sequence</span>
List(List(<span class="dv">1</span>, <span class="dv">3</span>), List(<span class="dv">1</span>, <span class="dv">4</span>), List(<span class="dv">2</span>, <span class="dv">3</span>), List(<span class="dv">2</span>, <span class="dv">4</span>)),
Some(List(<span class="dv">7</span>, <span class="dv">8</span>, <span class="dv">9</span>)),
None,
List(<span class="dv">8</span>, <span class="dv">14</span>, <span class="dv">49</span>),
Identity(List(<span class="dv">7</span>, <span class="dv">4</span>)),
<span class="co">// fmap</span>
List(<span class="dv">10</span>, <span class="dv">20</span>, <span class="dv">30</span>),
Some(<span class="dv">80</span>),
None,
<span class="dv">80</span>,
Identity(<span class="dv">90</span>),
<span class="co">// flatten</span>
List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>),
Some(<span class="dv">8</span>),
None,
None,
<span class="dv">49</span>,
Identity(<span class="dv">8</span>),
<span class="co">// apply</span>
List(<span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">2</span>, <span class="dv">4</span>, <span class="dv">6</span>, <span class="dv">1</span>, <span class="dv">0</span>, <span class="dv">1</span>),
Some(<span class="dv">9</span>),
None,
None,
<span class="dv">56</span>,
Identity(<span class="dv">8</span>),
<span class="co">// filterM</span>
List(List(<span class="dv">3</span>), Nil, List(<span class="dv">2</span>, <span class="dv">3</span>), List(<span class="dv">2</span>), List(<span class="dv">3</span>),
  Nil, List(<span class="dv">2</span>, <span class="dv">3</span>), List(<span class="dv">2</span>)),
Some(List(<span class="dv">2</span>, <span class="dv">3</span>)),
List(<span class="dv">2</span>),
Identity(List(<span class="dv">2</span>, <span class="dv">3</span>)),
<span class="co">// replicateM</span>
List(List(<span class="dv">7</span>, <span class="dv">7</span>), List(<span class="dv">7</span>, <span class="dv">8</span>), List(<span class="dv">8</span>, <span class="dv">7</span>), List(<span class="dv">8</span>, <span class="dv">8</span>)),
Some(List(<span class="dv">7</span>, <span class="dv">7</span>)),
List(<span class="dv">8</span>, <span class="dv">8</span>),
Identity(List(<span class="dv">6</span>, <span class="dv">6</span>)),
<span class="co">// lift2</span>
List(<span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">5</span>, <span class="dv">6</span>),
Some(<span class="dv">15</span>),
None,
None
)

    <span class="kw">for</span>((a, b) &lt;- values zip verify)
      <span class="fu">println</span>(<span class="kw">if</span>(a == b) <span class="st">&quot;PASS&quot;</span>
              <span class="kw">else</span> <span class="st">&quot;FAIL. Expected: &quot;</span> + b + <span class="st">&quot; Actual: &quot;</span> + a)
  }
}</code></pre>
<p>Haskell <code>main</code> function which should print a series of <code>PASS</code> when executed against the original <a href="http://blog.tmorris.net/monad-exercises-in-scala/">Monad Exercises in Scala</a>.</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="ot">main ::</span> <span class="dt">IO</span> ()
main <span class="fu">=</span>
  <span class="kw">let</span> plusOne <span class="fu">=</span> <span class="dt">Inter</span> (<span class="dv">1</span><span class="fu">+</span>)
      multTwo <span class="fu">=</span> <span class="dt">Inter</span> (<span class="dv">2</span><span class="fu">*</span>)
      squared <span class="fu">=</span> <span class="dt">Inter</span> (\n <span class="ot">-&gt;</span> n<span class="fu">*</span>n)
      s x <span class="fu">=</span> <span class="fu">show</span> x
      (<span class="fu">%</span>) <span class="fu">=</span> f
      values <span class="fu">=</span>
        [
        <span class="co">-- sequence&#39;</span>
        s (sequence&#39; [[<span class="dv">1</span>, <span class="dv">2</span>], [<span class="dv">3</span>, <span class="dv">4</span>]] listMonad),
        s (sequence&#39; [<span class="kw">Just</span> <span class="dv">7</span>, <span class="kw">Just</span> <span class="dv">8</span>, <span class="kw">Just</span> <span class="dv">9</span>] maybeMonad),
        s (sequence&#39; [<span class="kw">Just</span> <span class="dv">7</span>, <span class="kw">Nothing</span>, <span class="kw">Nothing</span>] maybeMonad),
        s (sequence&#39; [plusOne, multTwo, squared] interMonad <span class="fu">%</span> <span class="dv">7</span>),
        s (sequence&#39; [<span class="dt">Identity</span> <span class="dv">7</span>, <span class="dt">Identity</span> <span class="dv">4</span>] identityMonad),
        <span class="co">-- fmap&#39;</span>
        s (fmap&#39; [<span class="dv">1</span><span class="fu">..</span><span class="dv">3</span>] (<span class="fu">*</span><span class="dv">10</span>) listMonad),
        s (fmap&#39; (<span class="kw">Just</span> <span class="dv">8</span>) (<span class="fu">*</span><span class="dv">10</span>) maybeMonad),
        s (fmap&#39; <span class="kw">Nothing</span> (<span class="fu">*</span><span class="dv">10</span>) maybeMonad),
        s (fmap&#39; plusOne (<span class="fu">*</span><span class="dv">10</span>) interMonad <span class="fu">%</span> <span class="dv">7</span>),
        s (fmap&#39; (<span class="dt">Identity</span> <span class="dv">9</span>) (<span class="fu">*</span><span class="dv">10</span>) identityMonad),
        <span class="co">-- flatten</span>
        s (flatten [[<span class="dv">1</span>, <span class="dv">2</span>], [<span class="dv">3</span>, <span class="dv">4</span>]] listMonad),
        s (flatten (<span class="kw">Just</span> (<span class="kw">Just</span> <span class="dv">8</span>)) maybeMonad),
        s (flatten (<span class="kw">Just</span> (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>)) maybeMonad),
        s (flatten (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> (<span class="dt">Maybe</span> <span class="dt">Int</span>)) maybeMonad),
        s (flatten (<span class="dt">Inter</span> (<span class="dt">Inter</span> <span class="fu">.</span> (<span class="fu">*</span>))) interMonad <span class="fu">%</span> <span class="dv">7</span>),
        s (flatten (<span class="dt">Identity</span> (<span class="dt">Identity</span> <span class="dv">8</span>)) identityMonad),
        <span class="co">-- apply</span>
        s (apply [(<span class="fu">+</span><span class="dv">1</span>), (<span class="fu">*</span><span class="dv">2</span>), (<span class="ot">`mod`</span> <span class="dv">2</span>)] [<span class="dv">1</span><span class="fu">..</span><span class="dv">3</span>] listMonad),
        s (apply (<span class="kw">Just</span> (<span class="fu">+</span><span class="dv">1</span>)) (<span class="kw">Just</span> <span class="dv">8</span>) maybeMonad),
        s (apply (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> (<span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span>)) (<span class="kw">Just</span> <span class="dv">8</span>) maybeMonad),
        s (apply (<span class="kw">Just</span> (<span class="fu">+</span><span class="dv">1</span>)) (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>) maybeMonad),
        s (apply (<span class="dt">Inter</span> (<span class="fu">*</span>)) (<span class="dt">Inter</span> (<span class="dv">1</span><span class="fu">+</span>)) interMonad <span class="fu">%</span> <span class="dv">7</span>),
        s (apply (<span class="dt">Identity</span> (<span class="fu">+</span><span class="dv">1</span>)) (<span class="dt">Identity</span> <span class="dv">7</span>) identityMonad),
        <span class="co">-- filterM&#39;</span>
        s (filterM&#39; (\a <span class="ot">-&gt;</span> [a <span class="fu">&gt;</span> <span class="dv">2</span>, a <span class="ot">`mod`</span> <span class="dv">2</span> <span class="fu">==</span> <span class="dv">0</span>]) [<span class="dv">1</span><span class="fu">..</span><span class="dv">3</span>] listMonad),
        s (filterM&#39; (\a <span class="ot">-&gt;</span> <span class="kw">Just</span> (a <span class="fu">&gt;</span> <span class="dv">1</span>)) [<span class="dv">1</span><span class="fu">..</span><span class="dv">3</span>] maybeMonad),
        s (filterM&#39; (\a <span class="ot">-&gt;</span> <span class="dt">Inter</span> (\n <span class="ot">-&gt;</span> a <span class="fu">*</span> n <span class="ot">`mod`</span> <span class="dv">2</span> <span class="fu">==</span> <span class="dv">0</span>)) [<span class="dv">1</span><span class="fu">..</span><span class="dv">3</span>]
          interMonad <span class="fu">%</span> <span class="dv">7</span>),
        s (filterM&#39; (<span class="dt">Identity</span> <span class="fu">.</span> (<span class="fu">&gt;</span><span class="dv">1</span>)) [<span class="dv">1</span><span class="fu">..</span><span class="dv">3</span>] identityMonad),
        <span class="co">-- replicateM&#39;</span>
        s (replicateM&#39; <span class="dv">2</span> [<span class="dv">7</span>, <span class="dv">8</span>] listMonad),
        s (replicateM&#39; <span class="dv">2</span> (<span class="kw">Just</span> <span class="dv">7</span>) maybeMonad),
        s (replicateM&#39; <span class="dv">2</span> plusOne interMonad <span class="fu">%</span> <span class="dv">7</span>),
        s (replicateM&#39; <span class="dv">2</span> (<span class="dt">Identity</span> <span class="dv">6</span>) identityMonad),
        <span class="co">-- lift2</span>
        s (lift2 (<span class="fu">+</span>) [<span class="dv">1</span>, <span class="dv">2</span>] [<span class="dv">3</span>, <span class="dv">4</span>] listMonad),
        s (lift2 (<span class="fu">+</span>) (<span class="kw">Just</span> <span class="dv">7</span>) (<span class="kw">Just</span> <span class="dv">8</span>) maybeMonad),
        s (lift2 (<span class="fu">+</span>) (<span class="kw">Just</span> <span class="dv">7</span>) (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>) maybeMonad),
        s (lift2 (<span class="fu">+</span>) (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>) (<span class="kw">Just</span> <span class="dv">8</span>) maybeMonad)
        ]
      verify <span class="fu">=</span>
        [
        <span class="co">-- sequence&#39;</span>
        s ([[<span class="dv">1</span>, <span class="dv">3</span>], [<span class="dv">1</span>, <span class="dv">4</span>], [<span class="dv">2</span>, <span class="dv">3</span>], [<span class="dv">2</span>, <span class="dv">4</span>]]),
        s (<span class="kw">Just</span> [<span class="dv">7</span><span class="fu">..</span><span class="dv">9</span>]),
        s (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>),
        s [<span class="dv">8</span>, <span class="dv">14</span>, <span class="dv">49</span>],
        s (<span class="dt">Identity</span> [<span class="dv">7</span>, <span class="dv">4</span>]),
        <span class="co">-- fmap&#39;</span>
        s [<span class="dv">10</span>, <span class="dv">20</span>, <span class="dv">30</span>],
        s (<span class="kw">Just</span> <span class="dv">80</span>),
        s (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>),
        s <span class="dv">80</span>,
        s (<span class="dt">Identity</span> <span class="dv">90</span>),
        <span class="co">-- flatten</span>
        s [<span class="dv">1</span><span class="fu">..</span><span class="dv">4</span>],
        s (<span class="kw">Just</span> <span class="dv">8</span>),
        s (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>),
        s (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>),
        s <span class="dv">49</span>,
        s (<span class="dt">Identity</span> <span class="dv">8</span>),
        <span class="co">-- apply</span>
        s [<span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">2</span>, <span class="dv">4</span>, <span class="dv">6</span>, <span class="dv">1</span>, <span class="dv">0</span>, <span class="dv">1</span>],
        s (<span class="kw">Just</span> <span class="dv">9</span>),
        s (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>),
        s (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>),
        s <span class="dv">56</span>,
        s (<span class="dt">Identity</span> <span class="dv">8</span>),
        <span class="co">-- filterM&#39;</span>
        s [[<span class="dv">3</span>], [], [<span class="dv">2</span>, <span class="dv">3</span>], [<span class="dv">2</span>], [<span class="dv">3</span>], [], [<span class="dv">2</span>, <span class="dv">3</span>], [<span class="dv">2</span>]],
        s (<span class="kw">Just</span> [<span class="dv">2</span>, <span class="dv">3</span>]),
        s [<span class="dv">2</span>],
        s (<span class="dt">Identity</span> [<span class="dv">2</span>, <span class="dv">3</span>]),
        <span class="co">-- replicateM</span>
        s [[<span class="dv">7</span>, <span class="dv">7</span>], [<span class="dv">7</span>, <span class="dv">8</span>], [<span class="dv">8</span>, <span class="dv">7</span>], [<span class="dv">8</span>, <span class="dv">8</span>]],
        s (<span class="kw">Just</span> [<span class="dv">7</span>, <span class="dv">7</span>]),
        s [<span class="dv">8</span>, <span class="dv">8</span>],
        s (<span class="dt">Identity</span> [<span class="dv">6</span>, <span class="dv">6</span>]),
        <span class="co">-- lift2</span>
        s [<span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">5</span>, <span class="dv">6</span>],
        s (<span class="kw">Just</span> <span class="dv">15</span>),
        s (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>),
        s (<span class="kw">Nothing</span><span class="ot"> ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span>)
        ]
  <span class="kw">in</span> <span class="fu">mapM_</span>
      (\(a, b) <span class="ot">-&gt;</span>
        <span class="fu">print</span>(<span class="kw">if</span> a <span class="fu">==</span> b
                <span class="kw">then</span> <span class="st">&quot;PASS&quot;</span>
                <span class="kw">else</span> <span class="st">&quot;FAIL. Expected: &quot;</span> <span class="fu">++</span> b <span class="fu">++</span> <span class="st">&quot; Actual: &quot;</span> <span class="fu">++</span> a))
      (values <span class="ot">`zip`</span> verify)</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Type-classes are nothing like interfaces</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/type-classes-are-nothing-like-interfaces/index.html"/>
  <id>http://blog.tmorris.net/posts/type-classes-are-nothing-like-interfaces/index.html</id>
  <published>2010-04-02T08:16:13Z</published>
  <updated>2010-04-02T08:16:13Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>A beginner is confused about Haskell’s type-classes and so asks the question, “What is a type-class?” The response is often devastating, “You know, like Java or C# interfaces.” This wildly misleading statement can leave the beginner in a state of disrepair. I’ll tell you why but first I must emphasise.</p>
<blockquote>
<p>Type-classes are nothing like interfaces <em>(emphasis on nothing)</em>.</p>
</blockquote>
<p>Haskell has something like interfaces. They are called data types and are expressed using the <code>data</code> or <code>newtype</code> keywords. Languages like Java/C# have nothing like type-classes; there is not even a close analogy. Consider for example, Java’s <code>[Comparator](http://java.sun.com/javase/6/docs/api/java/util/Comparator.html)</code> interface. We would express this in Haskell like so:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">newtype</span> <span class="dt">Comparator</span> a <span class="fu">=</span> <span class="dt">C</span> {<span class="ot"> compare ::</span> a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Int</span> }</code></pre>
<p>Then if we wanted to sort a list, the type would be <code>sort :: Comparator a -&gt; [a] -&gt; [a]</code>. Notice the <em>explicit</em> passing of the <code>Comparator</code> that would be required at the call site. This is just like Java.</p>
<p>Now suppose we did something that Java cannot do. We used a type-class.</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">class</span> <span class="dt">Comparator</span> a <span class="kw">where</span>
<span class="ot">  compare ::</span> a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Int</span></code></pre>
<p>The type for sorting a list now becomes <code>sort :: Comparator a =&gt; [a] -&gt; [a]</code>. This is just like the previous signature except for the way the left-most arrow is written. This is an important distinction. When the caller uses this function, it <em>implicitly</em> passes the <code>Comparator</code>. Also, the type-class instance is decoupled from the data type. These are essential properties of type-classes. Indeed, it is its single-most defining property and since Java/C# have nothing like this, then it has nothing like type-classes.</p>
<p>Scala has implicit parameters which give you the ability to implement the essential property of type-classes (and more). Therefore, Scala does have something very much like type-classes. This is evident in a library such as <a href="http://code.google.com/p/scalaz">Scalaz</a>.</p>
<p>But let’s try to save the idea.</p>
<p>Java has implicit type-conversion by virtue of inheritance. For example, a method that accepts a <code>T</code> can be passed a <code>U</code> and its implicit conversion to a <code>T</code> is denoted by the way of <code>U extends T</code>. Notice that no side-effect can be performed during this conversion. This is unlike Scala’s implicit where it’s simply a bad idea, not enforced (Scala also has inheritance like Java).</p>
<p>So, if you are to say type-classes are like anything in these languages, it’s sort-of-like-yeah-ok-not-really inheritance. However, I’m sure you’ll agree, this will only cause confusion for the poor beginner, so it’s best not to draw the analogy at all.</p>
<p>Type-classes are a new concept to people coming from Java/C#. It is most appropriate to explain it as a new concept. I often use the contention between using <code>java.util.Comparable</code>, where the caller has the convenience of implicitly pass the implementation by way of inheritance but inconvenience of carrying the implementation with the data type versus using <code>java.util.Comparator</code> where the caller has the convenience of decoupling the implementation from the data type but requiring explicit passing at the call site. Type-classes (and Scala implicits) resolve this contention with a new concept.</p>
    </div>
  </content>
</entry>
<entry>
  <title>What Does Functional Programming Mean?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/what-does-functional-programming-mean/index.html"/>
  <id>http://blog.tmorris.net/posts/what-does-functional-programming-mean/index.html</id>
  <published>2010-03-31T10:00:29Z</published>
  <updated>2010-03-31T10:00:29Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://dl.dropbox.com/u/7810909/docs/what-does-fp-mean/what-does-fp-mean.html">Here are some slides to a short talk I gave a few weeks ago.</a></p>
<p>Hoping to get less ridiculous (i.e. more insightful) blog comments…</p>
    </div>
  </content>
</entry>
<entry>
  <title>Scalaz IRC</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/scalaz-irc/index.html"/>
  <id>http://blog.tmorris.net/posts/scalaz-irc/index.html</id>
  <published>2010-03-27T22:18:41Z</published>
  <updated>2010-03-27T22:18:41Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://code.google.com/p/scalaz">Scalaz</a> now has an IRC channel.</p>
<blockquote>
<p>irc://irc.freenode.net/#scalaz</p>
</blockquote>
    </div>
  </content>
</entry>
<entry>
  <title>Monad exercises in Scala</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/monad-exercises-in-scala/index.html"/>
  <id>http://blog.tmorris.net/posts/monad-exercises-in-scala/index.html</id>
  <published>2010-03-25T11:42:16Z</published>
  <updated>2010-03-25T11:42:16Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>A result of discussion in the #scala IRC channel.</p>
<p><em>A colleague has asked me to convert this to Haskell, which I have done below.</em></p>
<ul>
<li><p>The <code>trait Monad</code> answers the question “What does monad mean?”</p></li>
<li><p>The <code>object Monad</code> answers the question “What are some examples?”</p></li>
<li><p>The <code>object MonadicFunctions</code> answers the question “What are the practical implications?”</p></li>
</ul>
<p>If there are any questions or you get stuck, the <code>#scala</code> or <code>#scalaz</code> channel on Freenode could help out.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// 1. Start here. Observe this trait</span>
<span class="kw">trait</span> Monad[M[_]] {
  <span class="kw">def</span> flatMap[A, B](a: M[A], f: A =&gt; M[B]): M[B]
  <span class="kw">def</span> unital[A](a: A): M[A]
}

<span class="co">// A simple data type, which turns out to satisfy the above trait</span>
<span class="kw">case</span> <span class="kw">class</span> Inter[A](f: Int =&gt; A)

<span class="co">// So does this.</span>
<span class="kw">case</span> <span class="kw">class</span> Identity[A](a: A)

<span class="co">// Monad implementations</span>
<span class="kw">object</span> Monad {
  <span class="co">// 2. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> ListMonad: Monad[List] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// 3. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> OptionMonad: Monad[Option] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// 4. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> InterMonad: Monad[Inter] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// 5. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> IdentityMonad: Monad[Identity] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)
}

<span class="kw">object</span> MonadicFunctions {
  <span class="co">// 6. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> sequence[M[_], A](as: List[M[A]], m: Monad[M]): M[List[A]] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// 7. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> fmap[M[_], A, B](a: M[A], f: A =&gt; B, m: Monad[M]): M[B] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// 8. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> flatten[M[_], A](a: M[M[A]], m: Monad[M]): M[A] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// 9. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> apply[M[_], A, B](f: M[A =&gt; B], a: M[A], m: Monad[M]): M[B] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// 10. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> filterM[M[_], A](f: A =&gt; M[Boolean], as: List[A]
    , m: Monad[M]): M[List[A]] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// 11. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> replicateM[M[_], A](n: Int, a: M[A], m: Monad[M]): M[List[A]] =
    <span class="fu">error</span>(<span class="st">&quot;todo: flatMap n times to produce a list&quot;</span>)

  <span class="co">// 12. Replace error(&quot;todo&quot;) with an implementation</span>
  <span class="kw">def</span> lift2[M[_], A, B, C](f: (A, B) =&gt; C, a: M[A], b: M[B]
    , m: Monad[M]): M[C] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// lift3, lift4, etc. Interesting question: Can we have liftN?</span>
}</code></pre>
<p><strong>Haskell</strong></p>
<ul>
<li><p>The <code>data Monad'</code> answers the question “What does monad mean?”</p></li>
<li><p>The functions under <code>*** Monad implementations ***</code> answers the question “What are some examples?”</p></li>
<li><p>The functions under <code>*** Monadic Functions ***</code> answers the question “What are the practical implications?”</p></li>
</ul>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="ot">{-# LANGUAGE RankNTypes #-}</span>

<span class="co">-- 1. Start here. Observe this data type</span>
<span class="kw">data</span> <span class="dt">Monad&#39;</span> m <span class="fu">=</span> <span class="dt">Monad&#39;</span> {
<span class="ot">  unital ::</span> forall a<span class="fu">.</span> a <span class="ot">-&gt;</span> m a,
<span class="ot">  flatMap ::</span> forall a b<span class="fu">.</span> m a <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> m b) <span class="ot">-&gt;</span> m b
}

<span class="co">-- A simple data type, which turns out to satisfy the above trait</span>
<span class="kw">newtype</span> <span class="dt">Inter</span> a <span class="fu">=</span> <span class="dt">Inter</span> {<span class="ot"> f ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> a }

<span class="co">-- So does this.</span>
<span class="kw">newtype</span> <span class="dt">Identity</span> a <span class="fu">=</span> <span class="dt">Identity</span> {<span class="ot"> a ::</span> a }
  <span class="kw">deriving</span> <span class="kw">Show</span>

<span class="co">-- *** Monad implementations ***</span>

<span class="co">-- 2. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">listMonad ::</span> <span class="dt">Monad&#39;</span> []
listMonad <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- 3. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">maybeMonad ::</span> <span class="dt">Monad&#39;</span> <span class="dt">Maybe</span>
maybeMonad <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- 4. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">interMonad ::</span> <span class="dt">Monad&#39;</span> <span class="dt">Inter</span>
interMonad <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- 5. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">identityMonad ::</span> <span class="dt">Monad&#39;</span> <span class="dt">Identity</span>
identityMonad <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- *** Monadic functions ***</span>

<span class="co">-- 6. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">sequence&#39; ::</span> [m a] <span class="ot">-&gt;</span> <span class="dt">Monad&#39;</span> m <span class="ot">-&gt;</span> m [a]
sequence&#39; <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- 7. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">fmap&#39; ::</span> m a <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> <span class="dt">Monad&#39;</span> m <span class="ot">-&gt;</span> m b
fmap&#39; <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- 8. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">flatten ::</span> m (m a) <span class="ot">-&gt;</span> <span class="dt">Monad&#39;</span> m <span class="ot">-&gt;</span> m a
flatten <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- 9. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">apply ::</span> m (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> m a <span class="ot">-&gt;</span> <span class="dt">Monad&#39;</span> m <span class="ot">-&gt;</span> m b
apply <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- 10. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">filterM&#39; ::</span> (a <span class="ot">-&gt;</span> m <span class="dt">Bool</span>) <span class="ot">-&gt;</span> [a] <span class="ot">-&gt;</span> <span class="dt">Monad&#39;</span> m <span class="ot">-&gt;</span> m [a]
filterM&#39; <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- 11. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">replicateM&#39; ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> m a <span class="ot">-&gt;</span> <span class="dt">Monad&#39;</span> m <span class="ot">-&gt;</span> m [a]
replicateM&#39; <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo: flatMap n times to produce a list&quot;</span>

<span class="co">-- 12. Replace error &quot;todo&quot; with an implementation</span>
<span class="ot">lift2 ::</span> (a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> c) <span class="ot">-&gt;</span> m a <span class="ot">-&gt;</span> m b <span class="ot">-&gt;</span> <span class="dt">Monad&#39;</span> m <span class="ot">-&gt;</span> m c
lift2 <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- lift3, lift4, etc. Interesting question: Can we have liftN?</span></code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Why are there no big applications written using functional languages?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/why-are-there-no-big-applications-written-using-functional-languages/index.html"/>
  <id>http://blog.tmorris.net/posts/why-are-there-no-big-applications-written-using-functional-languages/index.html</id>
  <published>2010-03-24T21:56:48Z</published>
  <updated>2010-03-24T21:56:48Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Because there is no such thing as a big application. There is only bigger or smaller. This is a central tenet of functional programming. “Big application” is a euphemism for “My idea of programming does not scale beyond this point.” You don’t realise how much information you give away when you ask this question.</p>
<p>So can we can stop with the piffle and get on with the interesting and important stuff? Ta.</p>
    </div>
  </content>
</entry>
<entry>
  <title>A poke at the essence of functional programming</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/a-poke-at-the-essence-of-functional-programming/index.html"/>
  <id>http://blog.tmorris.net/posts/a-poke-at-the-essence-of-functional-programming/index.html</id>
  <published>2010-03-24T13:04:53Z</published>
  <updated>2010-03-24T13:04:53Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I used to work for IBM on the Java implementation. I learned the language inside-out. I did all those Sun certifications and other spanky things. I wanted to understand what a lot of people alleged was so special. I didn’t ever find it.</p>
<p>I have found that few people can tell me the answer to this question. If you don’t know the answer, don’t fret; it’s not the important part.</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="fu">method</span>(s1.<span class="fu">charAt</span>(i), s2.<span class="fu">charAt</span>(j));</code></pre>
<blockquote>
<p>Assuming <code>s1</code> and <code>s2</code> are both of the type <code>java.lang.String</code>, then which call to <code>charAt</code> will occur first?</p>
</blockquote>
<p>Many people would correctly guess at the left-most one. This is correct and is mandated by the specification.</p>
<p>However, on introspection, the reason nobody really knows <em>is because it doesn’t matter</em>. If the specification implementation had a bug and executed the right-most call first, then we, the programmer, would never even know. We gloss over this every day when we read Java code.</p>
<p>However, does this hold for all functions? What if it was something other than <code>charAt</code>? No, unfortunately, this only holds true for a specific set of functions. The <code>charAt</code> function is <em>referentially transparent</em>. For any given <code>String</code> and any given <code>int</code> then <code>charAt</code> will consistently return the same <code>char</code>. This is true for other referentially transparent functions too, but not any arbitrary function. Imagine if <code>charAt</code> did a database call or something like that!</p>
<p>Let us suppose now a new language feature that enforced the referential transparency of our functions. If it is referentially transparent, the compiler makes sure of it. Now imagine a new language where <strong>every</strong> function was referentially transparent.</p>
<p>All of a sudden, in the blink of an imagined hypothetical, the explicit order of invocation is no longer important. Just like that, poof, gone.</p>
<p>Welcome to the beginning of an understanding of the essence of functional programming.</p>
<p>Have fun! :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>I have found that...</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/i-have-found-that/index.html"/>
  <id>http://blog.tmorris.net/posts/i-have-found-that/index.html</id>
  <published>2010-03-23T09:12:36Z</published>
  <updated>2010-03-23T09:12:36Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <blockquote>
<p>I have found that many classes are created for the specific purpose of a <code>sequence</code> function in the <code>((-&gt;) t)</code> monad, particularly in Java, C# and Python. Create a class, with a constructor that takes an argument (t) so that one may call many of its methods, each of which has access to t.</p>
</blockquote>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="fu">sequence</span><span class="ot"> ::</span> [m a] <span class="ot">-&gt;</span> m [a]
<span class="fu">sequence*</span><span class="ot"> ::</span> [t <span class="ot">-&gt;</span> a] <span class="ot">-&gt;</span> t <span class="ot">-&gt;</span> [a]</code></pre>
<p>If we consider the type of <code>t</code> which we shall call <code>Swizzle</code> and the created class we shall call <code>SwizzleManager</code> then</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="co">// A constructor accepting a Swizzle</span>
SwizzleManager m = <span class="kw">new</span> <span class="fu">SwizzleManager</span>(t);
<span class="co">// One of the following usually follow:</span>
<span class="co">//   A list constructed by the results of executing several methods on &#39;m&#39;</span>
List&lt;r&gt; = { m.<span class="fu">a</span>(x), m.<span class="fu">b</span>(y), m.<span class="fu">c</span>(z) }
<span class="co">//   A loop over a list of the results of executing several methods on &#39;m&#39;</span>
<span class="kw">for</span>(R r : { m.<span class="fu">a</span>(x), m.<span class="fu">b</span>(y), m.<span class="fu">c</span>(z) }) {
  <span class="fu">use</span>(r);
}
<span class="co">//   A list of effects to execute using &#39;m&#39;</span>
m.<span class="fu">a</span>(x);
m.<span class="fu">b</span>(y);
m.<span class="fu">c</span>(z);</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Automated Validation with Applicatives and Semigroups (Part 2 - Java)</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/automated-validation-with-applicatives-and-semigroups-part-2-java/index.html"/>
  <id>http://blog.tmorris.net/posts/automated-validation-with-applicatives-and-semigroups-part-2-java/index.html</id>
  <published>2010-03-21T16:42:25Z</published>
  <updated>2010-03-21T16:42:25Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>In <a href="http://blog.tmorris.net/automated-validation-with-applicatives-and-semigroups-for-sanjiv/">a previous post</a>, I mentioned a small library for validating using an applicative functor pattern with a semigroup for accumulating errors using Haskell, Scala and Java programming languages. In this post, I will give a set up for an example usage, but not necessarily a complete example. This is left as an exercise and may be elaborated on in a future post.</p>
<p>I will start with Java. First we must decide <em>how we are going to accumulate errors</em>. I have decided to store them in a <code>LinkedList</code>. In more practical languages with a better collections library, we would probably use something else. We will use something else for Scala and Haskell (later!), or you could use the <a href="http://functionaljava.org/">Functional Java</a> extension. In the meantime, we will use <code>java.util.LinkedList</code>. We start by writing its <code>Semigroup</code> implementation:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">public</span> <span class="dt">static</span> &lt;a&gt; Semigroup&lt;LinkedList&lt;a&gt;&gt; <span class="fu">LinkedListSemigroup</span>() {
  <span class="kw">return</span> <span class="kw">new</span> Semigroup&lt;LinkedList&lt;a&gt;&gt;() {
    <span class="kw">public</span> LinkedList&lt;a&gt; <span class="fu">append</span>(<span class="dt">final</span> LinkedList&lt;a&gt; a1,
                                <span class="dt">final</span> LinkedList&lt;a&gt; a2) {
      <span class="dt">final</span> LinkedList&lt;a&gt; r = <span class="kw">new</span> LinkedList&lt;a&gt;(a1);
      r.<span class="fu">addAll</span>(a2);
      <span class="kw">return</span> r;
    }
  };
}</code></pre>
<p>This is very straight-forward. In the previous example, I mentioned a class <code>Person</code> that is made of an age and a name. The age is an integer between 0 and 130 while the name is any string that starts with an upper-case character. Let’s write these data types:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="co">// int wrapper between 0 and 130</span>
<span class="kw">class</span> Age {
  <span class="kw">private</span> <span class="dt">final</span> <span class="dt">int</span> i;
  <span class="kw">private</span> <span class="fu">Age</span>(<span class="dt">final</span> <span class="dt">int</span> i) { <span class="kw">this</span>.<span class="fu">i</span> = i; }
  <span class="kw">public</span> <span class="dt">int</span> <span class="fu">value</span>() { <span class="kw">return</span> i; }
  <span class="kw">public</span> <span class="dt">static</span> Age <span class="fu">age</span>(<span class="dt">final</span> <span class="dt">int</span> i) {
    <span class="kw">if</span>(i &lt;= <span class="dv">0</span> || i &gt;= <span class="dv">130</span>)
      <span class="kw">throw</span> <span class="kw">new</span> Error(<span class="st">&quot;out of range&quot;</span>);
    <span class="kw">else</span>
      <span class="kw">return</span> <span class="kw">new</span> <span class="fu">Age</span>(i);
  }
}</code></pre>
<p>And here is <code>Name</code>:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="co">// String wrapper starts with upper-case</span>
<span class="kw">class</span> Name {
  <span class="kw">private</span> <span class="dt">final</span> String s;
  <span class="kw">private</span> Name(<span class="dt">final</span> String s) { <span class="kw">this</span>.<span class="fu">s</span> = s; }
  <span class="kw">public</span> String <span class="fu">value</span>() { <span class="kw">return</span> s; }
  <span class="kw">public</span> <span class="dt">static</span> Name <span class="fu">name</span>(<span class="dt">final</span> String s) {
    <span class="kw">if</span>(s.<span class="fu">isEmpty</span>() || !Character.<span class="fu">isUpperCase</span>(s.<span class="fu">charAt</span>(<span class="dv">0</span>)))
      <span class="kw">throw</span> <span class="kw">new</span> java.<span class="fu">lang</span>.<span class="fu">Error</span>();
    <span class="kw">else</span>
      <span class="kw">return</span> <span class="kw">new</span> Name(s);
  }
}</code></pre>
<p>I won’t bother writing the <code>Person</code> data type, but it is sufficient to say it will have an <code>Age</code> field and a <code>Name</code> field.</p>
<p>Now for validation. Suppose we have two string values; one each for age and name. We would like to check these for validation and return either one or more error messages (<code>String</code>) or a <code>Person</code>. More succinctly, we want a function with the type:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Validation</span><span class="fu">&lt;</span><span class="dt">LinkedList</span><span class="fu">&lt;</span><span class="dt">String</span><span class="fu">&gt;</span>, <span class="dt">Person</span><span class="fu">&gt;&gt;</span></code></pre>
<p>How are we going to achieve this function? First we must say how to create an <code>Age</code> from a <code>String</code> or an error message if we cannot:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Validation</span><span class="fu">&lt;</span><span class="dt">LinkedList</span><span class="fu">&lt;</span><span class="dt">String</span><span class="fu">&gt;</span>, <span class="dt">Age</span><span class="fu">&gt;&gt;</span></code></pre>
<p>and same for <code>Name</code></p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Validation</span><span class="fu">&lt;</span><span class="dt">LinkedList</span><span class="fu">&lt;</span><span class="dt">String</span>, <span class="dt">Name</span><span class="fu">&gt;&gt;</span></code></pre>
<p>We also need a function to create a <code>Person</code> from an <code>Age</code> and a <code>Name</code></p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="dt">Age</span> <span class="ot">-&gt;</span> <span class="dt">Name</span> <span class="ot">-&gt;</span> <span class="dt">Person</span></code></pre>
<p>This is simple. It’s the <code>Person</code> constructor.</p>
<p>So to sum up, we need to write a function with this type:</p>
<p>Arguments:</p>
<p>*</p>
<pre class="sourceCode Java"><code class="sourceCode java">F&lt;String, Validation&lt;LinkedList&lt;string&gt;, Age&gt;&gt;&gt;</code></pre>
<p>*</p>
<pre class="sourceCode Java"><code class="sourceCode java">F&lt;String, Validation&lt;LinkedList&lt;string&gt;, Name&gt;&gt;&gt;</code></pre>
<p>*</p>
<pre class="sourceCode Java"><code class="sourceCode java">F&lt;Age, F&lt;Name, Person&gt;&gt;</code></pre>
<p>*</p>
<pre class="sourceCode Java"><code class="sourceCode java">Semigroup&lt;LinkedList&lt;string&gt;&gt;</code></pre>
<p>Return type:</p>
<pre class="sourceCode Java"><code class="sourceCode java">F&lt;String, F&lt;String, &lt;Validation&lt;LinkedList&lt;string&gt;, Person&gt;&gt;&gt;&gt;</code></pre>
<p>Of course such a function is likely to be polymorphic, rather than specifying concrete types. I recommend starting by writing a function with this type:</p>
<p>Arguments:</p>
<p>*</p>
<pre class="sourceCode Java"><code class="sourceCode java">F&lt;T, F&lt;U, V&gt;&gt;</code></pre>
<p>*</p>
<pre class="sourceCode Java"><code class="sourceCode java">F&lt;A, Validation&lt;E, T&gt;&gt;</code></pre>
<p>*</p>
<pre class="sourceCode Java"><code class="sourceCode java">F&lt;B, Validation&lt;E, U&gt;&gt;</code></pre>
<p>Return type:</p>
<pre class="sourceCode Java"><code class="sourceCode java">F&lt;A, F&lt;B, Validation&lt;E, V&gt;&gt;</code></pre>
<p>This function can be written by using the constructs mentioned in the previous post. I’m out of breath. Java is incredibly laborious.</p>
<p>Scala and Haskell for another time!</p>
    </div>
  </content>
</entry>
<entry>
  <title>Automated Validation with Applicatives and Semigroups (for Sanjiv)</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/automated-validation-with-applicatives-and-semigroups-for-sanjiv/index.html"/>
  <id>http://blog.tmorris.net/posts/automated-validation-with-applicatives-and-semigroups-for-sanjiv/index.html</id>
  <published>2010-03-21T10:33:36Z</published>
  <updated>2010-03-21T10:33:36Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Sanjiv is an ex-colleague of mine who recently gave an excellent presentation at <a href="http://www.meetup.com/Brisbane-Functional-Programming-Group-BFG/">Brisbane Functional Programming Group</a>. His presentation was on the use of the disjoint union algebraic data type for representing error handling or “validation”. This data type is often called <code>Either</code>. Sanjiv used <a href="http://www.scala-lang.org/docu/files/api/scala/Either.html">the Scala version</a> for his presentation.</p>
<p>Here I am going to write a data type that is just like (isomorphic to) <code>Either</code> called <code>Validation</code>. There will be two constructors for failure and success. I will be using Haskell, Scala and Java. I am going to present a function that is mentioned in an excellent paper called <a href="http://www.soi.city.ac.uk/~ross/papers/Applicative.html">Applicative Programming with Effects</a>.</p>
<p>There is a slight difference in my implementation to the function in this paper. The one mentioned in the paper uses a <code>Monoid</code> constraint, while I am using the more general <code>Semigroup</code>. This allows data types that are semigroups but not monoids (all monoids are semigroups). In particular, a non-empty list is a semigroup but not a monoid.</p>
<p>This constraint on the failing value allows the user to automatically accumulate errors as they chain through the <code>Validation</code> values, for example, by keeping them in a non-empty list. I am not going to give example usages of this code in this post because I think it is a great exercise for others and I do not want to spoil it. It is sufficient to say that any usage that type-checks is likely to be a useful example. I may give examples in the future if there is some confusion that needs clarification.</p>
<p>The function can accumulate <code>Validation</code> values using the applicative programming pattern. If all given are successful, you’ll be left with a function that takes all the successful values to a new value, which will be returned as a success. If at least one is not successful, the applicative pattern will begin accumulating with that error value and any future values.</p>
<p>I recommend starting with a simple example such as a <code>Person</code> type with an <code>age :: Int</code> and <code>name :: String</code> with imposed validation rules such as “age must be above 0 and less than 130” and “name must start with a capital letter”. The applied function at the end should be <code>ValidatedInt -&gt; ValidatedString -&gt; Person</code>.</p>
<p>Like I said, if there is any confusion, I’ll expand later. Put the questions in the comments. Enjoy! :)</p>
<p>Here is a Haskell implementation of this:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Validation</span> e a <span class="fu">=</span> <span class="dt">Fail</span> e <span class="fu">|</span> <span class="dt">Success</span> a <span class="kw">deriving</span> (<span class="kw">Eq</span>, <span class="kw">Show</span>)

<span class="co">-- Associative, binary operation (Monoid without identity)</span>
<span class="kw">class</span> <span class="dt">Semigroup</span> a <span class="kw">where</span>
<span class="ot">  append ::</span> a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> a

<span class="ot">(&lt;+&gt;) ::</span> <span class="dt">Validation</span> e a <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> <span class="dt">Validation</span> e b
<span class="dt">Fail</span> e <span class="fu">&lt;+&gt;</span> _ <span class="fu">=</span> <span class="dt">Fail</span> e
<span class="dt">Success</span> a <span class="fu">&lt;+&gt;</span> f <span class="fu">=</span> <span class="dt">Success</span> (f a)

<span class="ot">(&lt;*&gt;) ::</span> (<span class="dt">Semigroup</span> e) <span class="ot">=&gt;</span> <span class="dt">Validation</span> e a
    <span class="ot">-&gt;</span> <span class="dt">Validation</span> e (a <span class="ot">-&gt;</span> b)
    <span class="ot">-&gt;</span> <span class="dt">Validation</span> e b
<span class="dt">Fail</span> e1 <span class="fu">&lt;*&gt;</span> <span class="dt">Fail</span> e2 <span class="fu">=</span> <span class="dt">Fail</span> (e1 <span class="ot">`append`</span> e2)
<span class="dt">Fail</span> e1 <span class="fu">&lt;*&gt;</span> <span class="dt">Success</span> _ <span class="fu">=</span> <span class="dt">Fail</span> e1
<span class="dt">Success</span> _ <span class="fu">&lt;*&gt;</span> <span class="dt">Fail</span> e2 <span class="fu">=</span> <span class="dt">Fail</span> e2
<span class="dt">Success</span> a <span class="fu">&lt;*&gt;</span> <span class="dt">Success</span> f <span class="fu">=</span> <span class="dt">Success</span> (f a)</code></pre>
<p>And Scala:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">sealed</span> <span class="kw">trait</span> Validation[E, A] {
  <span class="kw">def</span> &lt;+&gt;[B](f: A =&gt; B): Validation[E, B] = <span class="kw">this</span> <span class="kw">match</span> {
    <span class="kw">case</span> <span class="fu">Fail</span>(e) =&gt; <span class="fu">Fail</span>(e)
    <span class="kw">case</span> <span class="fu">Success</span>(a) =&gt; <span class="fu">Success</span>(<span class="fu">f</span>(a))
  }

  <span class="kw">def</span> &lt;*&gt;[B](f: Validation[E, A =&gt; B])(<span class="kw">implicit</span> s: Semigroup[E])
    : Validation[E, B] = <span class="kw">this</span> <span class="kw">match</span> {
    <span class="kw">case</span> <span class="fu">Fail</span>(e1) =&gt; f <span class="kw">match</span> {
      <span class="kw">case</span> <span class="fu">Fail</span>(e2) =&gt; <span class="fu">Fail</span>(s <span class="fu">append</span> (e1, e2))
      <span class="kw">case</span> <span class="fu">Success</span>(_) =&gt; <span class="fu">Fail</span>(e1)
    }
    <span class="kw">case</span> <span class="fu">Success</span>(a) =&gt; f <span class="kw">match</span> {
      <span class="kw">case</span> <span class="fu">Fail</span>(e2) =&gt; <span class="fu">Fail</span>(e2)
      <span class="kw">case</span> <span class="fu">Success</span>(f) =&gt; <span class="fu">Success</span>(<span class="fu">f</span>(a))
    }
  }
}
<span class="kw">case</span> <span class="kw">class</span> Fail[E, A](e: E) <span class="kw">extends</span> Validation[E, A]
<span class="kw">case</span> <span class="kw">class</span> Success[E, A](a: A) <span class="kw">extends</span> Validation[E, A]

<span class="co">// Associative binary operation (Monoid without identity)</span>
<span class="kw">case</span> <span class="kw">class</span> Semigroup[A](append: (A, A) =&gt; A)</code></pre>
<p>And now, for the allegedly practical Java. Hold your breath:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="co">// Java pre-amble, sigh.</span>
<span class="kw">interface</span> F&lt;X, Y&gt; {
  Y <span class="fu">apply</span>(X x);
}

<span class="co">// Associative binary operation (Monoid without identity)</span>
<span class="kw">interface</span> Semigroup&lt;a&gt; {
  A <span class="fu">append</span>(A a1, A a2);
}

<span class="kw">abstract</span> <span class="kw">class</span> Validation&lt;E, A&gt; {
  <span class="co">// No algebraic data types in Java. Use a Church encoding (catamorphism).</span>
  <span class="kw">public</span> <span class="kw">abstract</span> &lt;x&gt; X <span class="fu">fold</span>(F&lt;E, X&gt; fail, F&lt;A, X&gt; success);

  <span class="co">// Construction for fail</span>
  <span class="kw">public</span> <span class="dt">static</span> &lt;E, A&gt; Validation&lt;E, A&gt; <span class="fu">fail</span>(<span class="dt">final</span> E e) {
    <span class="kw">return</span> <span class="kw">new</span> Validation&lt;E, A&gt;() {
      <span class="kw">public</span> &lt;x&gt; X <span class="fu">fold</span>(<span class="dt">final</span> F&lt;E, X&gt; fail, <span class="dt">final</span> F&lt;A, X&gt; success) {
        <span class="kw">return</span> fail.<span class="fu">apply</span>(e);
      }
    };
  }

  <span class="co">// Construction for success</span>
  <span class="kw">public</span> <span class="dt">static</span> &lt;E, A&gt; Validation&lt;E, A&gt; <span class="fu">success</span>(<span class="dt">final</span> A a) {
    <span class="kw">return</span> <span class="kw">new</span> Validation&lt;E, A&gt;() {
      <span class="kw">public</span> &lt;x&gt; X <span class="fu">fold</span>(<span class="dt">final</span> F&lt;E, X&gt; fail, <span class="dt">final</span> F&lt;A, X&gt; success) {
        <span class="kw">return</span> success.<span class="fu">apply</span>(a);
      }
    };
  }

  <span class="co">// &lt;+&gt;</span>
  <span class="kw">public</span> &lt;b&gt; Validation&lt;E, B&gt; <span class="fu">map</span>(<span class="dt">final</span> F&lt;A, B&gt; f) {
    <span class="kw">return</span> <span class="kw">new</span> Validation&lt;E, B&gt;() {
      <span class="kw">public</span> &lt;x&gt; X <span class="fu">fold</span>(<span class="dt">final</span> F&lt;E, X&gt; fail, <span class="dt">final</span> F&lt;B, X&gt; success) {
        <span class="kw">return</span> Validation.<span class="fu">this</span>.<span class="fu">fold</span>(fail, <span class="kw">new</span> F&lt;A, X&gt;() {
          <span class="kw">public</span> X <span class="fu">apply</span>(<span class="dt">final</span> A a) {
            <span class="kw">return</span> success.<span class="fu">apply</span>(f.<span class="fu">apply</span>(a));
          }
        });
      }
    };
  }

  <span class="co">// &lt;*&gt;</span>
  <span class="kw">public</span> &lt;b&gt; Validation&lt;E, B&gt; <span class="fu">applicativate</span>(
      <span class="dt">final</span> Validation&lt;E, F&lt;A, B&gt;&gt; f,
      <span class="dt">final</span> Semigroup&lt;e&gt; s <span class="co">/* no implicits or type-classes in Java */</span>) {
    <span class="kw">return</span> Validation.<span class="fu">this</span>.<span class="fu">fold</span>(<span class="kw">new</span> F&lt;E, Validation&lt;E, B&gt;&gt;() {
      <span class="kw">public</span> Validation&lt;E, B&gt; <span class="fu">apply</span>(<span class="dt">final</span> E e1) {
        <span class="kw">return</span> f.<span class="fu">fold</span>(<span class="kw">new</span> F&lt;E, Validation&lt;E, B&gt;&gt;() {
          <span class="kw">public</span> Validation&lt;E, B&gt; <span class="fu">apply</span>(<span class="dt">final</span> E e2) {
            <span class="co">// case (Fail(e1), Fail(e2))</span>
            <span class="kw">return</span> Validation.<span class="fu">fail</span>(s.<span class="fu">append</span>(e1, e2));
          }
        }, <span class="kw">new</span> F&lt;F&lt;A, B&gt;, Validation&lt;E, B&gt;&gt;() {
          <span class="kw">public</span> Validation&lt;E, B&gt; <span class="fu">apply</span>(<span class="dt">final</span> F&lt;A, B&gt; f) {
            <span class="co">// case (Fail(e1), Success(f))</span>
            <span class="kw">return</span> Validation.<span class="fu">fail</span>(e1);
          }
        });
      }
    }, <span class="kw">new</span> F&lt;A, Validation&lt;E, B&gt;&gt;() {
      <span class="kw">public</span> Validation&lt;E, B&gt; <span class="fu">apply</span>(<span class="dt">final</span> A a) {
        <span class="kw">return</span> f.<span class="fu">fold</span>(<span class="kw">new</span> F&lt;E, Validation&lt;E, B&gt;&gt;() {
          <span class="kw">public</span> Validation&lt;E, B&gt; <span class="fu">apply</span>(<span class="dt">final</span> E e2) {
            <span class="co">// case (Success(a), Fail(e2))</span>
            <span class="kw">return</span> Validation.<span class="fu">fail</span>(e2);
          }
        }, <span class="kw">new</span> F&lt;F&lt;A, B&gt;, Validation&lt;E, B&gt;&gt;() {
          <span class="kw">public</span> Validation&lt;E, B&gt; <span class="fu">apply</span>(<span class="dt">final</span> F&lt;A, B&gt; f) {
            <span class="co">// case (Success(a), Success(f))</span>
            <span class="kw">return</span> Validation.<span class="fu">success</span>(f.<span class="fu">apply</span>(a));
          }
        });
      }
    });
  }
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Linq has nothing to do with SQL or enumerable lists</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/linq-has-nothing-to-do-with-sql-or-enumerable-lists/index.html"/>
  <id>http://blog.tmorris.net/posts/linq-has-nothing-to-do-with-sql-or-enumerable-lists/index.html</id>
  <published>2010-02-19T10:43:43Z</published>
  <updated>2010-02-19T10:43:43Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>There seems to be quite a lot of misunderstanding of Linq. I am not sure how widespread this misunderstanding is, but if I can be persuaded that my selection sample extrapolates accurately, I might consider expanding on this fact:</p>
<blockquote>
<p>Linq has nothing to do with SQL or enumerable lists. Nothing and also, not a single thing.</p>
</blockquote>
<p>If this is contentious, please let me know and I will endeavour to do something about it (I already have, so I’ll just refer on to begin with).</p>
    </div>
  </content>
</entry>
<entry>
  <title>SKI combinator calculus in Java</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/ski-combinator-calculus-in-java/index.html"/>
  <id>http://blog.tmorris.net/posts/ski-combinator-calculus-in-java/index.html</id>
  <published>2010-02-08T17:17:57Z</published>
  <updated>2010-02-08T17:17:57Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> Lam&lt;X, Y&gt; {
  Y <span class="fu">apply</span>(X x);
}

<span class="co">// http://en.wikipedia.org/wiki/SKI_combinator_calculus</span>
<span class="kw">class</span> SKI {
  <span class="kw">public</span> <span class="dt">static</span> &lt;A, B, C&gt; Lam&lt;Lam&lt;A, Lam&lt;B, C&gt;&gt;, Lam&lt;Lam&lt;A, B&gt;, Lam&lt;A, C&gt;&gt;&gt; <span class="fu">s</span>() {
    <span class="kw">return</span> <span class="kw">new</span> Lam&lt;Lam&lt;A, Lam&lt;B, C&gt;&gt;, Lam&lt;Lam&lt;A, B&gt;, Lam&lt;A, C&gt;&gt;&gt;() {
      <span class="kw">public</span> Lam&lt;Lam&lt;A, B&gt;, Lam&lt;A, C&gt;&gt; <span class="fu">apply</span>(<span class="dt">final</span> Lam&lt;A, Lam&lt;B, C&gt;&gt; f) {
        <span class="kw">return</span> <span class="kw">new</span> Lam&lt;Lam&lt;A, B&gt;, Lam&lt;A, C&gt;&gt;() {
          <span class="kw">public</span> Lam&lt;A, C&gt; <span class="fu">apply</span>(<span class="dt">final</span> Lam&lt;A, B&gt; g) {
            <span class="kw">return</span> <span class="kw">new</span> Lam&lt;A, C&gt;() {
              <span class="kw">public</span> C <span class="fu">apply</span>(<span class="dt">final</span> A a) {
                <span class="kw">return</span> f.<span class="fu">apply</span>(a).<span class="fu">apply</span>(g.<span class="fu">apply</span>(a));
              }
            };
          }
        };
      }
    };
  }

  <span class="kw">public</span> <span class="dt">static</span> &lt;A, B&gt; Lam&lt;A, Lam&lt;B, A&gt;&gt; <span class="fu">k</span>() {
    <span class="kw">return</span> <span class="kw">new</span> Lam&lt;A, Lam&lt;B, A&gt;&gt;() {
      <span class="kw">public</span> Lam&lt;B, A&gt; <span class="fu">apply</span>(<span class="dt">final</span> A a) {
        <span class="kw">return</span> <span class="kw">new</span> Lam&lt;B, A&gt;() {
          <span class="kw">public</span> A <span class="fu">apply</span>(<span class="dt">final</span> B b) {
            <span class="kw">return</span> a;
          }
        };
      }
    };
  }

  <span class="kw">public</span> <span class="dt">static</span> &lt;a&gt; Lam&lt;A, A&gt; <span class="fu">i</span>() {
    <span class="kw">return</span> SKI.&lt;A, Lam&lt;A, A&gt;, A&gt;<span class="fu">s</span>().<span class="fu">apply</span>(SKI.&lt;A, Lam&lt;A, A&gt;&gt;<span class="fu">k</span>()).<span class="fu">apply</span>(SKI.&lt;A, A&gt;<span class="fu">k</span>());
  }
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Scala exercise</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/scala-exercise/index.html"/>
  <id>http://blog.tmorris.net/posts/scala-exercise/index.html</id>
  <published>2010-02-06T09:37:10Z</published>
  <updated>2010-02-06T09:37:10Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>A result of a discussion in the <a href="irc://freenode.net/#scala">#scala IRC channel</a>.</p>
<p><strong>Write a minimum function that works on <code>Array[String]</code> and <code>List[Int]</code>.</strong> <em>(see <code>error(&quot;todo&quot;)</code>)</em></p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> Foldable[-F[_]] {
  <span class="kw">def</span> foldl[A, B](f: (A, B) =&gt; A, a: A, as: F[B]): A

  <span class="kw">def</span> reducel[A](f: (A, A) =&gt; A, as: F[A]): Option[A] = foldl[Option[A], A]((a1, a2) =&gt;
    Some(a1 <span class="kw">match</span> {
      <span class="kw">case</span> None =&gt; a2
      <span class="kw">case</span> Some(x) =&gt; <span class="fu">f</span>(a2, x)
    }), None, as)
}

<span class="kw">object</span> Foldable {
  <span class="kw">val</span> ListFoldable = <span class="kw">new</span> Foldable[List] {
    <span class="kw">def</span> foldl[A, B](f: (A, B) =&gt; A, a: A, as: List[B]) =
      as.<span class="fu">foldLeft</span>(a)(f)
  }

  <span class="kw">val</span> ArrayFoldable = <span class="kw">new</span> Foldable[Array] {
    <span class="kw">def</span> foldl[A, B](f: (A, B) =&gt; A, a: A, as: Array[B]) =
      as.<span class="fu">foldLeft</span>(a)(f)
  }
}

<span class="kw">sealed</span> <span class="kw">trait</span> Ordering
<span class="kw">case</span> <span class="kw">object</span> LT <span class="kw">extends</span> Ordering
<span class="kw">case</span> <span class="kw">object</span> EQ <span class="kw">extends</span> Ordering
<span class="kw">case</span> <span class="kw">object</span> GT <span class="kw">extends</span> Ordering

<span class="co">// contra</span>
<span class="kw">trait</span> Order[A] {
  <span class="kw">def</span> <span class="fu">compare</span>(a1: A, a2: A): Ordering

  <span class="kw">def</span> <span class="fu">min</span>(a1: A, a2: A) =
    <span class="kw">if</span>(<span class="fu">compare</span>(a1, a2) == LT) a1 <span class="kw">else</span> a2
}

<span class="kw">object</span> Order {
  <span class="kw">def</span> order[A](f: (A, A) =&gt; Ordering): Order[A] = <span class="kw">new</span> Order[A] {
    <span class="kw">def</span> <span class="fu">compare</span>(a1: A, a2: A) = <span class="fu">f</span>(a1, a2)
  }

  <span class="kw">val</span> IntOrder = order[Int]((a1, a2) =&gt;
    <span class="kw">if</span>(a1 &gt; a2) GT
    <span class="kw">else</span> <span class="kw">if</span>(a1 &lt; a2) LT
    <span class="kw">else</span> EQ)

  <span class="kw">val</span> StringOrder = order[String]((a1, a2) =&gt;
    <span class="kw">if</span>(a1 &gt; a2) GT
    <span class="kw">else</span> <span class="kw">if</span>(a1 &lt; a2) LT
    <span class="kw">else</span> EQ)
}

<span class="kw">object</span> Main {
  <span class="kw">import</span> Foldable.<span class="fu">_</span>
  <span class="kw">import</span> Order.<span class="fu">_</span>

  <span class="kw">def</span> minimum[F[_], A](as: F[A], order: Order[A], fold: Foldable[F]) =
    <span class="co">// Zm9sZC5yZWR1Y2VsW0FdKChhLCBiKSA9PiBvcmRlci5taW4oYSwgYiksIGFzKQ==</span>
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]) {
    <span class="kw">val</span> i = <span class="fu">minimum</span>(args, StringOrder, ArrayFoldable)
    <span class="fu">println</span>(i)

    <span class="kw">val</span> j = <span class="fu">minimum</span>(List(<span class="dv">5</span>, <span class="dv">8</span>, <span class="dv">2</span>, <span class="dv">9</span>), IntOrder, ListFoldable)
    <span class="fu">println</span>(j)
  }
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Functional Java 2.21</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/functional-java-221/index.html"/>
  <id>http://blog.tmorris.net/posts/functional-java-221/index.html</id>
  <published>2010-02-05T20:49:15Z</published>
  <updated>2010-02-05T20:49:15Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Includes a number of bug fixes and an immutable 2-3 finger tree for sequences supporting access to the ends in amortized O(1) time.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Higher-order Polymorphism for pseudo-Java</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/higher-order-polymorphism-for-pseudo-java/index.html"/>
  <id>http://blog.tmorris.net/posts/higher-order-polymorphism-for-pseudo-java/index.html</id>
  <published>2010-01-28T16:48:14Z</published>
  <updated>2010-01-28T16:48:14Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <pre class="sourceCode Java"><code class="sourceCode java"><span class="co">// Simulate Higher-Order Functions.</span>
<span class="co">// A lambda function is any implementation of this interface.</span>
<span class="kw">interface</span> Lambda&lt;X, Y&gt; {
  Y <span class="fu">apply</span>(X x);
}

<span class="co">// What is a covariant functor?</span>
<span class="co">// It is any implementation of this interface.</span>
<span class="co">// All implementations must also satisfy:</span>
<span class="co">//   * The law of identity</span>
<span class="co">//   * The law of composition</span>
<span class="co">// (but let&#39;s brush that to the side)</span>
<span class="kw">interface</span> Functor&lt;f&gt; {
  &lt;A, B&gt; F&lt;b&gt; <span class="fu">fmap</span>(F&lt;a&gt; a, Lambda&lt;A, B&gt; f);
}

<span class="kw">import java.util.LinkedList;</span>

<span class="co">// Here is the functor for Java&#39;s LinkedList.</span>
<span class="co">// It maps a function across each element of the list and returns a new one.</span>
<span class="co">// (trust me, it satisfies the two laws).</span>
<span class="kw">class</span> LinkedListFunctor <span class="kw">implements</span> Functor&lt;linkedlist&gt; {
  <span class="kw">public</span> &lt;A, B&gt; LinkedList&lt;b&gt; <span class="fu">fmap</span>(<span class="dt">final</span> LinkedList&lt;a&gt; a, <span class="dt">final</span> Lambda&lt;A, B&gt; f) {
    <span class="dt">final</span> LinkedList&lt;b&gt; r = <span class="kw">new</span> LinkedList&lt;b&gt;();
    <span class="kw">for</span>(<span class="dt">final</span> A x : a)
      r.<span class="fu">append</span>(f.<span class="fu">apply</span>(x));
    <span class="kw">return</span> r;
  }
}

<span class="co">// Here is a trivial Java data type.</span>
<span class="co">// It happens to be a covariant functor.</span>
<span class="co">// Let&#39;s witness its instance...</span>
<span class="kw">interface</span> IntConverter&lt;a&gt; {
  A <span class="fu">convert</span>(<span class="dt">int</span> i);
}

<span class="co">// The Functor instance for the IntConverter.</span>
<span class="kw">class</span> IntConverterFunctor <span class="kw">implements</span> Functor&lt;intconverter&gt; {
  <span class="kw">public</span> &lt;A, B&gt; IntConverter&lt;b&gt; <span class="fu">fmap</span>(<span class="dt">final</span> IntConverter&lt;a&gt; a, <span class="dt">final</span> Lambda&lt;A, B&gt; f) {
    <span class="kw">return</span> <span class="kw">new</span> IntConverter&lt;b&gt;() {
      <span class="kw">public</span> B <span class="fu">convert</span>(<span class="dt">final</span> <span class="dt">int</span> i) {
        <span class="kw">return</span> f.<span class="fu">apply</span>(a.<span class="fu">convert</span>(i));
      }
    };
  }
}

<span class="co">// So why do we care?</span>
<span class="co">// Because it prevents an enormous (*enormous*, *ENORMOUS!*)</span>
<span class="co">// amount of otherwise needless repetition.</span>

<span class="kw">class</span> FunctorX {
  <span class="co">// Gives rise to:</span>
  <span class="co">// LinkedList&lt;Lambda&lt;A, B&gt;&gt; =&gt; A =&gt; LinkedList&lt;b&gt;</span>
  <span class="co">// IntConverter&lt;Lambda&lt;A, B&gt;&gt; =&gt; A =&gt; IntConverter&lt;b&gt;</span>
  <span class="co">// ...</span>
  <span class="co">// F&lt;Lambda&lt;A, B&gt;&gt; =&gt; A =&gt; F&lt;b&gt; (for many values of F)</span>
  <span class="kw">public</span> <span class="dt">static</span> &lt;A, B, F&gt; F&lt;b&gt; <span class="fu">fapply</span>(<span class="dt">final</span> Functor&lt;f&gt; f, <span class="dt">final</span> F&lt;Lambda&lt;A, B&gt;&gt; lam, <span class="dt">final</span> A a) {
    <span class="kw">return</span> f.<span class="fu">fmap</span>(lam, <span class="kw">new</span> Lambda&lt;Lambda&lt;A, B&gt;, B&gt;() {
      <span class="kw">public</span> B <span class="fu">apply</span>(<span class="dt">final</span> Lambda&lt;A, B&gt; z) {
        <span class="kw">return</span> z.<span class="fu">apply</span>(a);
      }
    });
  }

  <span class="co">// ... etcetra.</span>
}

<span class="co">// It turns a linear amount of code into a constant amount of code.</span>
<span class="co">// Similarly a sort function that runs on lists of</span>
<span class="co">// any type (provided a comparator) alleviates the need for linear</span>
<span class="co">// amounts of code (a sort function for each possible list element type).</span></code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>MSN/Yahoo! web spiders blocked</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/msnyahoo-web-spiders-blocked/index.html"/>
  <id>http://blog.tmorris.net/posts/msnyahoo-web-spiders-blocked/index.html</id>
  <published>2010-01-24T23:03:20Z</published>
  <updated>2010-01-24T23:03:20Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I have blocked the msnbot and yahoo! web spiders from indexing this site (and all others at this IP address). They choke up the network with distributed multiple connections. Pretty silly/primitive technique of indexing a web site.</p>
    </div>
  </content>
</entry>
<entry>
  <title>What is Haskell's primary feature?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/what-is-haskells-primary-feature/index.html"/>
  <id>http://blog.tmorris.net/posts/what-is-haskells-primary-feature/index.html</id>
  <published>2010-01-22T19:30:37Z</published>
  <updated>2010-01-22T19:30:37Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Today I was asked what Haskell’s main feature is. The answer is its non-strict evaluation.</p>
<p>Java is a strictly evaluated language. Consider this Java program:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">class</span> C {
  <span class="dt">static</span> String <span class="fu">i</span>() {
    <span class="kw">throw</span> <span class="kw">new</span> Error(<span class="st">&quot;boo!&quot;</span>);
  }

  <span class="dt">static</span> &lt;a&gt; <span class="dt">int</span> <span class="fu">f</span>(A a) {
    <span class="kw">return</span> <span class="dv">3</span>;
  }

  <span class="kw">public</span> <span class="dt">static</span> <span class="dt">void</span> <span class="fu">main</span>(String[] args) {
    <span class="dt">int</span> k = <span class="fu">f</span>(<span class="fu">i</span>());
    System.<span class="fu">out</span>.<span class="fu">println</span>(k);
  }
}</code></pre>
<p>The program fails with a runtime error.</p>
<p>Consider this (otherwise equivalent) Haskell program:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">i <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;boo!&quot;</span>

f a <span class="fu">=</span> <span class="dv">3</span>

main <span class="fu">=</span> <span class="kw">let</span> k <span class="fu">=</span> f i
       <span class="kw">in</span> <span class="fu">print</span> k</code></pre>
<p>The program prints 3 and does not fail like the Java program. This is a key property of Haskell with very far reaching implications. One of those implications is that Haskell is a pure language. There are many more implications, particularly with respect to the compositional properties of programs.</p>
<p>Haskell’s evaluation model and its implications is perhaps its most widely misunderstood feature. While the benefits are (enormously) enormous, they are far too deep to consider writing a short article about.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Dear Java guy, State is a monad</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/dear-java-guy-state-is-a-monad/index.html"/>
  <id>http://blog.tmorris.net/posts/dear-java-guy-state-is-a-monad/index.html</id>
  <published>2010-01-19T16:21:12Z</published>
  <updated>2010-01-19T16:21:12Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> Pair&lt;A, B&gt; {
  A <span class="fu">first</span>();
  B <span class="fu">second</span>();
}

<span class="kw">class</span> Pairs {
  <span class="kw">public</span> <span class="dt">static</span> &lt;A, B&gt; Pair&lt;A, B&gt; <span class="fu">pair</span>(<span class="dt">final</span> A a, <span class="dt">final</span> B b) {
    <span class="kw">return</span> <span class="kw">new</span> Pair&lt;A, B&gt;() {
      <span class="kw">public</span> A <span class="fu">first</span>() { <span class="kw">return</span> a; }
      <span class="kw">public</span> B <span class="fu">second</span>() { <span class="kw">return</span> b; }
    };
  }
}

<span class="kw">interface</span> State&lt;S, A&gt; {
  Pair&lt;S, A&gt; <span class="fu">run</span>(S s);
}

<span class="kw">interface</span> Function&lt;X, Y&gt; {
  Y <span class="fu">apply</span>(X x);
}

<span class="kw">class</span> States {
  <span class="co">// State&lt;S, _&gt; is a covariant functor</span>
  <span class="kw">public</span> <span class="dt">static</span> &lt;S, A, B&gt; State&lt;S, B&gt; <span class="fu">map</span>(<span class="dt">final</span> State&lt;S, A&gt; s, <span class="dt">final</span> Function&lt;A, B&gt; f) {
    <span class="kw">return</span> <span class="kw">new</span> State&lt;S, B&gt;() {
      <span class="kw">public</span> Pair&lt;S, B&gt; <span class="fu">run</span>(<span class="dt">final</span> S k) {
        <span class="dt">final</span> Pair&lt;S, A&gt; p = s.<span class="fu">run</span>(k);
        <span class="kw">return</span> Pairs.<span class="fu">pair</span>(p.<span class="fu">first</span>(), f.<span class="fu">apply</span>(p.<span class="fu">second</span>()));
      }
    };
  }

  <span class="co">// // State&lt;S, _&gt; is a monad</span>
  <span class="kw">public</span> <span class="dt">static</span> &lt;S, A, B&gt; State&lt;S, B&gt; <span class="fu">bind</span>(<span class="dt">final</span> State&lt;S, A&gt; s, <span class="dt">final</span> Function&lt;A, State&lt;S, B&gt;&gt; f) {
    <span class="kw">return</span> <span class="kw">new</span> State&lt;S, B&gt;() {
      <span class="kw">public</span> Pair&lt;S, B&gt; <span class="fu">run</span>(<span class="dt">final</span> S k) {
        <span class="dt">final</span> Pair&lt;S, A&gt; p = s.<span class="fu">run</span>(k);
        <span class="kw">return</span> f.<span class="fu">apply</span>(p.<span class="fu">second</span>()).<span class="fu">run</span>(p.<span class="fu">first</span>());
      }
    };
  }
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>What Does Monad Mean?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/what-does-monad-mean/index.html"/>
  <id>http://blog.tmorris.net/posts/what-does-monad-mean/index.html</id>
  <published>2010-01-14T13:22:49Z</published>
  <updated>2010-01-14T13:22:49Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><strong>Slides</strong> <a href="http://docs.tmorris.net/what-does-monad-mean/what-does-monad-mean.html">http://docs.tmorris.net/what-does-monad-mean/what-does-monad-mean.html</a></p>
<p><strong>Video</strong> <a href="http://vimeo.com/8729673">http://vimeo.com/8729673</a></p>
    </div>
  </content>
</entry>
<entry>
  <title>Parsing map data using a lazy language</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/parsing-map-data-using-a-lazy-language/index.html"/>
  <id>http://blog.tmorris.net/posts/parsing-map-data-using-a-lazy-language/index.html</id>
  <published>2010-01-10T10:25:25Z</published>
  <updated>2010-01-10T10:25:25Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Haskell is a pure lazy programming language. The laziness of Haskell allows certain performance improvements without sacrificing compositional program properties. I have recently written parsers for XML map data formats that allow a user to “read a data file into a collection of immutable objects.” If I told you I used the parser library to “read in” a 140GB map data file and you’re not familiar with a lazy language, you might have asked how I did this within the constraints of memory requirements. Easy of course; I used a lazy language. The implications of a lazy (and therefore, pure) language are widely misunderstood, so I say “easy” wishing it really was easy for all people, but I know it isn’t (keep practicing!).</p>
<p><a href="http://www.haskell.org/haskellwiki/HXT">HXT</a> is a parsing library for XML that is based on <a href="http://www.cs.chalmers.se/~rjmh/afp-arrows.pdf">Hughes’ arrows</a> and allows a user to piece together their own specific XML parser. I used it to parse the <a href="http://www.topografix.com/GPX/1/1/">GPS Exchange (GPX)</a> and <a href="http://wiki.openstreetmap.org/wiki/API_v0.6/DTD">OpenStreetMap (OSM)</a> data formats.</p>
<p><a href="http://code.google.com/p/geo-gpx/">Here</a> are some example uses of parsing GPX files and <a href="http://code.google.com/p/geo-osm/">here</a> are examples parsing OSM files. My favourite is a very simple example (there are more complex ones) that removes waypoints from a GPX file. <a href="http://lists.openstreetmap.org/pipermail/newbies/2009-May/003131.html">This question (how to remove waypoints from gpx?)</a> was asked on the OSM mailing list quite a while ago; questions like these partially inspired me to write these libraries.</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">import</span> <span class="dt">Data.Geo.GPX</span>

<span class="ot">removeWpts ::</span> <span class="fu">FilePath</span> <span class="ot">-&gt;</span> <span class="fu">FilePath</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> ()
removeWpts <span class="fu">=</span> <span class="fu">flip</span> interactGpx (usingWpts (<span class="fu">const</span> []))</code></pre>
<p>The implementation is very simple. The <code>interactGpx</code> function takes two file names and a function that transforms a <code>Gpx</code> data structure to a new <code>Gpx</code>. The <code>interactGpx</code> function reads in the first given file name to a <code>Gpx</code>, executes the given function to produce a new <code>Gpx</code>, then writes the result to the other given file name.</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="ot">interactGpx ::</span> <span class="fu">FilePath</span> <span class="ot">-&gt;</span> (<span class="dt">Gpx</span> <span class="ot">-&gt;</span> <span class="dt">Gpx</span>) <span class="ot">-&gt;</span> <span class="fu">FilePath</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> ()</code></pre>
<p>The <code>usingWpts</code> function takes a function that transforms a list of waypoints to a new list of waypoints and a <code>Gpx</code> value and returns a new <code>Gpx</code> value with the waypoints transformed.</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="ot">usingWpts ::</span> ([<span class="dt">WptType</span>] <span class="ot">-&gt;</span> [<span class="dt">WptType</span>]) <span class="ot">-&gt;</span> <span class="dt">Gpx</span> <span class="ot">-&gt;</span> <span class="dt">Gpx</span></code></pre>
<p>Of course, since we want to remove all waypoints, we ignore the given list of waypoints and return an empty list (<code>const []</code>). Pretty neat I reckon!</p>
<p>You can get either of these libraries from <a href="http://hackage.haskell.org/">hackage</a>:</p>
<ul>
<li><p><a href="http://hackage.haskell.org/package/GPX">GPX</a></p></li>
<li><p><a href="http://hackage.haskell.org/package/OSM">OSM</a></p></li>
</ul>
<p>Here is each of their home page:</p>
<ul>
<li><p><a href="http://code.google.com/p/geo-gpx/">GPX</a></p></li>
<li><p><a href="http://code.google.com/p/geo-osm/">OSM</a></p></li>
</ul>
    </div>
  </content>
</entry>
<entry>
  <title>Debut with a Catamorphism</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/debut-with-a-catamorphism/index.html"/>
  <id>http://blog.tmorris.net/posts/debut-with-a-catamorphism/index.html</id>
  <published>2009-12-02T20:36:27Z</published>
  <updated>2009-12-02T20:36:27Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Hello everyone,</p>
<p>Many of you know I have been battling health problems for the last 2 years subsequent to a sporting injury. After a total of six surgical procedures, my most recent about 3 weeks ago, I am glad to be almost completely cured. Today I lodged a formal complaint to the Medical Health Board of Queensland against six doctors (coincidentally, the same number of operations – there were a total of 19 doctors mentioned).</p>
<p>As a result of the aforementioned, I haven’t written in a while, so I plan to return to my usual from now on.</p>
<p>I thought I’d write a little about a pervasive problem on the Scala mailing lists. Specifically, the misunderstanding of the purpose of static typing. Of course, there will always be lots of myths and proponents willing to ensure their survival, however, I am a strong believer that education is the only means by which we can advance the software development industry, despite the task often appearing insurmountable (ala Scala mailing list).</p>
<p>Some discussions recently on the Scala mailing list include the relationship between <code>scala.Option</code> data type and <code>null</code> and another discussion about documentation and types that are once-inhabited such as <code>forall a b c. (a -&gt; b) -&gt; (b -&gt; c) -&gt; a -&gt; c</code></p>
<p>I thought I’d propose a small piece of code and leave any potential insights unstated so as not to destroy anything for the observer. There is a Haskell version toward the end.</p>
<p>I propose the following data type:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> MyOption[+A] {
  <span class="co">// single abstract method</span>
  <span class="kw">def</span> cata[X](some: A =&gt; X, none: =&gt; X): X
}</code></pre>
<p>Astute observers will notice that the <code>cata</code> method is similar to a combination of the <code>map</code> and <code>getOrElse</code> methods on <code>scala.Option</code>. This topic has also arisen on the Scala mailing list in the past. In other words, I could have written this:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> MyOption[+A] {
  <span class="co">// two abstract methods</span>
  <span class="kw">def</span> map[X](f: A =&gt; X): MyOption[X]
  <span class="kw">def</span> getOrElse[AA &gt;: A](a: =&gt; AA): AA
}</code></pre>
<p>…and I’d have a data structure that is exactly the same as the previous one. What may not be obvious is that <code>MyOption</code> is also exactly the same as <code>scala.Option</code>. The correct term for “exactly the same” is <em>isomorphic</em>. Yes, this is despite not using case classes or subclasses – coincidentally, another area where much mythology is prevalent.</p>
<p>I could also write construction functions that are akin to <code>scala.None</code> and <code>scala.Some</code>:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> MyOption {
  <span class="kw">def</span> none[A] = <span class="kw">new</span> MyOption[A] {
    <span class="kw">def</span> cata[X](s: A =&gt; X, n: =&gt; X) = n
  }

  <span class="kw">def</span> some[A](a: A) = <span class="kw">new</span> MyOption[A] {
    <span class="kw">def</span> cata[X](s: A =&gt; X, n: =&gt; X) = <span class="fu">s</span>(a)
  }
}</code></pre>
<p>As an exercise, I propose filling out the <code>Option</code> API, however, using the single abstract method <code>cata</code> and the <code>none</code>/<code>some</code> constructor functions for additional convenience. I promise you it can be done and that anything <code>scala.Option</code> can do, <code>MyOption</code> can do also (and vice versa), since they are isomorphic.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> MyOption[+A] {
  <span class="co">// single abstract method</span>
  <span class="kw">def</span> cata[X](some: A =&gt; X, none: =&gt; X): X

  <span class="kw">def</span> map[B](f: A =&gt; B): MyOption[B] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="kw">def</span> flatMap[B](f: A =&gt; MyOption[B]): MyOption[B] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="kw">def</span> getOrElse[AA &gt;: A](e: =&gt; AA): AA = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="kw">def</span> <span class="fu">filter</span>(p: A =&gt; Boolean): MyOption[A] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="kw">def</span> <span class="fu">foreach</span>(f: A =&gt; Unit): Unit = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="kw">def</span> isDefined: Boolean = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="kw">def</span> isEmpty: Boolean = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// WARNING: not defined for None</span>
  <span class="kw">def</span> get: A = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="kw">def</span> orElse[AA &gt;: A](o: MyOption[AA]): MyOption[AA] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="kw">def</span> toLeft[X](right: =&gt; X): Either[A, X] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="kw">def</span> toRight[X](left: =&gt; X): Either[X, A] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="kw">def</span> toList: List[A] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="kw">def</span> iterator: Iterator[A] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)
}

<span class="kw">object</span> MyOption {
  <span class="kw">def</span> none[A] = <span class="kw">new</span> MyOption[A] {
    <span class="kw">def</span> cata[X](s: A =&gt; X, n: =&gt; X) = n
  }

  <span class="kw">def</span> some[A](a: A) = <span class="kw">new</span> MyOption[A] {
    <span class="kw">def</span> cata[X](s: A =&gt; X, n: =&gt; X) = <span class="fu">s</span>(a)
  }
}</code></pre>
<p>If you get stuck, the answer is base-64 encoded below, however, I encourage you to follow the types and to the extent that there may be ambiguity, follow the existing Scala API specification for <code>scala.Option</code>. If need be, please ask questions. Best of luck!</p>
<pre><code>dHJhaXQgTXlPcHRpb25bK0FdIHsKICAvLyBzaW5nbGUgYWJzdHJhY3QgbWV0aG9kCiAgZGVmIGNh
dGFbWF0oc29tZTogQSA9PiBYLCBub25lOiA9PiBYKTogWAoKICBpbXBvcnQgTXlPcHRpb24uXwoK
ICBkZWYgbWFwW0JdKGY6IEEgPT4gQik6IE15T3B0aW9uW0JdID0gY2F0YShmIGFuZFRoZW4gc29t
ZSwgbm9uZSkKCiAgLy8gQWxzbwogIC8vIGRlZiBtYXBbQl0oZjogQSA9PiBCKTogTXlPcHRpb25b
Ql0gPSBmbGF0TWFwKGYgYW5kVGhlbiBzb21lKQoKICBkZWYgZmxhdE1hcFtCXShmOiBBID0+IE15
T3B0aW9uW0JdKTogTXlPcHRpb25bQl0gPSBjYXRhKGYsIG5vbmUpCgogIGRlZiBnZXRPckVsc2Vb
QUEgPjogQV0oZTogPT4gQUEpOiBBQSA9IGNhdGEocyA9PiBzLCBlKQoKICBkZWYgZmlsdGVyKHA6
IEEgPT4gQm9vbGVhbik6IE15T3B0aW9uW0FdID0gY2F0YShhID0+IGlmKHAoYSkpIHNvbWUoYSkg
ZWxzZSBub25lLCBub25lKQoKICBkZWYgZm9yZWFjaChmOiBBID0+IFVuaXQpOiBVbml0ID0gY2F0
YShmLCAoKSkKCiAgZGVmIGlzRGVmaW5lZDogQm9vbGVhbiA9IGNhdGEoXyA9PiB0cnVlLCBmYWxz
ZSkKCiAgZGVmIGlzRW1wdHk6IEJvb2xlYW4gPSBjYXRhKF8gPT4gZmFsc2UsIHRydWUpCgogIC8v
IFdBUk5JTkc6IG5vdCBkZWZpbmVkIGZvciBOb25lCiAgZGVmIGdldDogQSA9IGNhdGEoYSA9PiBh
LCBlcnJvcigiTm9uZS5nZXQiKSkKCiAgZGVmIG9yRWxzZVtBQSA+OiBBXShvOiBNeU9wdGlvbltB
QV0pOiBNeU9wdGlvbltBQV0gPSBjYXRhKF8gPT4gdGhpcywgbykKCiAgZGVmIHRvTGVmdFtYXShy
aWdodDogPT4gWCk6IEVpdGhlcltBLCBYXSA9IGNhdGEoTGVmdChfKSwgUmlnaHQocmlnaHQpKQoK
ICBkZWYgdG9SaWdodFtYXShsZWZ0OiA9PiBYKTogRWl0aGVyW1gsIEFdID0gY2F0YShSaWdodChf
KSwgTGVmdChsZWZ0KSkKCiAgZGVmIHRvTGlzdDogTGlzdFtBXSA9IGNhdGEoTGlzdChfKSwgTmls
KQoKICBkZWYgaXRlcmF0b3I6IEl0ZXJhdG9yW0FdID0gY2F0YShJdGVyYXRvci5zaW5nbGUoXyks
IEl0ZXJhdG9yLmVtcHR5KQp9CgpvYmplY3QgTXlPcHRpb24gewogIGRlZiBub25lW0FdID0gbmV3
IE15T3B0aW9uW0FdIHsKICAgIGRlZiBjYXRhW1hdKHM6IEEgPT4gWCwgbjogPT4gWCkgPSBuCiAg
fQoKICBkZWYgc29tZVtBXShhOiBBKSA9IG5ldyBNeU9wdGlvbltBXSB7CiAgICBkZWYgY2F0YVtY
XShzOiBBID0+IFgsIG46ID0+IFgpID0gcyhhKQogIH0KfQoK</code></pre>
<p>For Haskell users:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="ot">{-# LANGUAGE RankNTypes #-}</span>

<span class="co">-- Data.Maybe</span>
<span class="kw">newtype</span> <span class="dt">Option</span> a <span class="fu">=</span> <span class="dt">Option</span> {<span class="ot"> cata ::</span> forall x<span class="fu">.</span> (a <span class="ot">-&gt;</span> x) <span class="ot">-&gt;</span> x <span class="ot">-&gt;</span> x }

<span class="co">-- Just</span>
<span class="ot">some ::</span> a <span class="ot">-&gt;</span> <span class="dt">Option</span> a
some a <span class="fu">=</span> <span class="dt">Option</span> (\s _ <span class="ot">-&gt;</span> s a)

<span class="co">-- Nothing</span>
<span class="ot">none ::</span> <span class="dt">Option</span> a
none <span class="fu">=</span> <span class="dt">Option</span> (<span class="fu">const</span> <span class="fu">id</span>)

<span class="co">-- fmap</span>
<span class="ot">map&#39; ::</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> <span class="dt">Option</span> a <span class="ot">-&gt;</span> <span class="dt">Option</span> b
map&#39; f m <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- (&gt;&gt;=)</span>
<span class="ot">flatMap ::</span> (a <span class="ot">-&gt;</span> <span class="dt">Option</span> b) <span class="ot">-&gt;</span> <span class="dt">Option</span> a <span class="ot">-&gt;</span> <span class="dt">Option</span> b
flatMap f m <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- fromMaybe</span>
<span class="ot">getOrElse ::</span> <span class="dt">Option</span> a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> a
getOrElse <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="fu">filter</span><span class="ot"> ::</span> <span class="dt">Option</span> a <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> <span class="dt">Bool</span>) <span class="ot">-&gt;</span> <span class="dt">Option</span> a
<span class="fu">filter</span> m p <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- mapM_</span>
<span class="ot">foreach ::</span> <span class="dt">Option</span> a <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> <span class="dt">IO</span> ()) <span class="ot">-&gt;</span> <span class="dt">IO</span> ()
foreach m f <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- isJust</span>
<span class="ot">isDefined ::</span> <span class="dt">Option</span> a <span class="ot">-&gt;</span> <span class="dt">Bool</span>
isDefined m <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- isNothing</span>
<span class="ot">isEmpty ::</span> <span class="dt">Option</span> a <span class="ot">-&gt;</span> <span class="dt">Bool</span>
isEmpty m <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- WARNING: not defined for None</span>
<span class="co">-- fromJust</span>
<span class="ot">get ::</span> <span class="dt">Option</span> a <span class="ot">-&gt;</span> a
get m <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- mplus</span>
<span class="ot">orElse ::</span> <span class="dt">Option</span> a <span class="ot">-&gt;</span> <span class="dt">Option</span> a <span class="ot">-&gt;</span> <span class="dt">Option</span> a
orElse m n <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="ot">toLeft ::</span> <span class="dt">Option</span> a <span class="ot">-&gt;</span> x <span class="ot">-&gt;</span> <span class="dt">Either</span> a x
toLeft m x <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="ot">toRight ::</span> <span class="dt">Option</span> a <span class="ot">-&gt;</span> x <span class="ot">-&gt;</span> <span class="dt">Either</span> x a
toRight m x <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- maybeToList</span>
<span class="ot">toList ::</span> <span class="dt">Option</span> a <span class="ot">-&gt;</span> [a]
toList m <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

iterator <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;bzzt. This is Haskell silly.&quot;</span></code></pre>
<pre><code>ey0jIExBTkdVQUdFIFJhbmtOVHlwZXMgIy19CgotLSBEYXRhLk1heWJlCm5ld3R5cGUgT3B0aW9u
IGEgPSBPcHRpb24geyBjYXRhIDo6IGZvcmFsbCB4LiAoYSAtPiB4KSAtPiB4IC0+IHggfQoKLS0g
SnVzdApzb21lIDo6IGEgLT4gT3B0aW9uIGEKc29tZSBhID0gT3B0aW9uIChccyBfIC0+IHMgYSkK
Ci0tIE5vdGhpbmcKbm9uZSA6OiBPcHRpb24gYQpub25lID0gT3B0aW9uIChjb25zdCBpZCkKCi0t
IGZtYXAKbWFwJyA6OiAoYSAtPiBiKSAtPiBPcHRpb24gYSAtPiBPcHRpb24gYgptYXAnIGYgbSA9
IGNhdGEgbSAoc29tZSAuIGYpIG5vbmUKCi0tICg+Pj0pCmZsYXRNYXAgOjogKGEgLT4gT3B0aW9u
IGIpIC0+IE9wdGlvbiBhIC0+IE9wdGlvbiBiCmZsYXRNYXAgZiBtID0gY2F0YSBtIGYgbm9uZQoK
LS0gZnJvbU1heWJlCmdldE9yRWxzZSA6OiBPcHRpb24gYSAtPiBhIC0+IGEKZ2V0T3JFbHNlID0g
ZmxpcCBjYXRhIGlkCgpmaWx0ZXIgOjogT3B0aW9uIGEgLT4gKGEgLT4gQm9vbCkgLT4gT3B0aW9u
IGEKZmlsdGVyIG0gcCA9IGNhdGEgbSAoXGEgLT4gaWYgcChhKSB0aGVuIHNvbWUgYSBlbHNlIG5v
bmUpIG5vbmUKCi0tIG1hcE1fCmZvcmVhY2ggOjogT3B0aW9uIGEgLT4gKGEgLT4gSU8gKCkpIC0+
IElPICgpCmZvcmVhY2ggbSBmID0gY2F0YSBtIGYgKHJldHVybiAoKSkKCi0tIGlzSnVzdAppc0Rl
ZmluZWQgOjogT3B0aW9uIGEgLT4gQm9vbAppc0RlZmluZWQgbSA9IGNhdGEgbSAoY29uc3QgVHJ1
ZSkgRmFsc2UKCi0tIGlzTm90aGluZwppc0VtcHR5IDo6IE9wdGlvbiBhIC0+IEJvb2wKaXNFbXB0
eSBtID0gY2F0YSBtIChjb25zdCBGYWxzZSkgVHJ1ZQoKLS0gV0FSTklORzogbm90IGRlZmluZWQg
Zm9yIE5vbmUKLS0gZnJvbUp1c3QKZ2V0IDo6IE9wdGlvbiBhIC0+IGEKZ2V0IG0gPSBjYXRhIG0g
aWQgKGVycm9yICJOb25lLmdldCIpCgotLSBtcGx1cwpvckVsc2UgOjogT3B0aW9uIGEgLT4gT3B0
aW9uIGEgLT4gT3B0aW9uIGEKb3JFbHNlIG0gbiA9IGNhdGEgbSAoY29uc3QgbSkgbgoKdG9MZWZ0
IDo6IE9wdGlvbiBhIC0+IHggLT4gRWl0aGVyIGEgeAp0b0xlZnQgbSB4ID0gY2F0YSBtIExlZnQg
KFJpZ2h0IHgpCgp0b1JpZ2h0IDo6IE9wdGlvbiBhIC0+IHggLT4gRWl0aGVyIHggYQp0b1JpZ2h0
IG0geCA9IGNhdGEgbSBSaWdodCAoTGVmdCB4KQoKLS0gbWF5YmVUb0xpc3QKdG9MaXN0IDo6IE9w
dGlvbiBhIC0+IFthXQp0b0xpc3QgbSA9IGNhdGEgbSAoOltdKSBbXQoKaXRlcmF0b3IgPSBlcnJv
ciAiYnp6dC4gVGhpcyBpcyBIYXNrZWxsIHNpbGx5LiIK</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>22 of 99</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/22-of-99/index.html"/>
  <id>http://blog.tmorris.net/posts/22-of-99/index.html</id>
  <published>2009-03-31T19:14:27Z</published>
  <updated>2009-03-31T19:14:27Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>From <a href="http://aperiodic.net/phil/scala/s-99/">http://aperiodic.net/phil/scala/s-99/</a>.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> NinetyNine {
  <span class="co">// P01</span>
  <span class="kw">def</span> last[A](as: List[A]): A = as <span class="kw">match</span> {
    <span class="kw">case</span> Nil =&gt; <span class="fu">error</span>(<span class="st">&quot;last on empty list&quot;</span>)
    <span class="kw">case</span> List(x) =&gt; x
    <span class="kw">case</span> _ :: xs =&gt; <span class="fu">last</span>(xs)
  }

  <span class="co">// P02</span>
  <span class="kw">def</span> penultimate[A](as: List[A]): A = as <span class="kw">match</span> {
    <span class="kw">case</span> x :: _ :: Nil =&gt; x
    <span class="kw">case</span> _ =&gt; <span class="fu">penultimate</span>(as.<span class="fu">tail</span>)
  }

  <span class="co">// P03</span>
  <span class="kw">def</span> nth[A](n: Int, as: List[A]): A = as <span class="kw">match</span> {
    <span class="kw">case</span> x :: _ <span class="kw">if</span> n == <span class="dv">0</span> =&gt; x
    <span class="kw">case</span> _ =&gt; <span class="fu">nth</span>(n - <span class="dv">1</span>, as.<span class="fu">tail</span>)
  }

  <span class="co">// P04</span>
  <span class="kw">def</span> length[A](as: List[A]) = (<span class="dv">0</span> /: as)((a, _) =&gt; a + <span class="dv">1</span>)

  <span class="co">// P05</span>
  <span class="kw">def</span> reverse[A](as: List[A]) = (List[A]() /: as)((a, b) =&gt; b :: a)

  <span class="co">// P06</span>
  <span class="kw">def</span> isPalindrome[A](as: List[A]) = as == <span class="fu">reverse</span>(as)

  <span class="co">// P07</span>
  <span class="kw">def</span> <span class="fu">flatten</span>(as: Any*): List[Any] = as flatMap {
    <span class="kw">case</span> (ns: List[Any]) =&gt; <span class="fu">flatten</span>(ns: _*)
    <span class="kw">case</span> (n: Any) =&gt; List(n)
  } toList

  <span class="co">// List is missing a group method</span>
  <span class="kw">implicit</span> <span class="kw">def</span> Group[A](as: List[A]): { <span class="kw">def</span> group: List[List[A]] } = <span class="kw">new</span> {
    <span class="kw">def</span> group = as <span class="kw">match</span> {
      <span class="kw">case</span> Nil =&gt; Nil
      <span class="kw">case</span> x :: xs =&gt; {
        <span class="kw">val</span> (a, b) = xs.<span class="fu">span</span>(_ == x)
        (x :: a) :: Group(b).<span class="fu">group</span>
      }
    }
  }

  <span class="co">// P08</span>
  <span class="kw">def</span> compress[A](as: List[A]) = as.<span class="fu">group</span> <span class="fu">map</span> (_.<span class="fu">head</span>)

  <span class="kw">def</span> compress2[A](as: List[A]): List[A] = as <span class="kw">match</span> {
    <span class="kw">case</span> Nil =&gt; Nil
    <span class="kw">case</span> x :: xs =&gt; x :: <span class="fu">compress</span>(xs.<span class="fu">dropWhile</span>(_ == x))
  }

  <span class="co">// P09</span>
  <span class="kw">def</span> pack[A] = (_: List[A]).<span class="fu">group</span>

  <span class="co">// P10</span>
  <span class="kw">def</span> encode[A](as: List[A]) = <span class="fu">pack</span>(as) <span class="fu">map</span> (k =&gt; (k.<span class="fu">length</span>, k.<span class="fu">head</span>))

  <span class="co">// P11</span>
  <span class="co">// ick</span>
  <span class="kw">def</span> encodeModified[A](as: List[A]) = <span class="fu">pack</span>(as) <span class="fu">map</span> (k =&gt; {
    <span class="kw">val</span> l = k.<span class="fu">length</span>
    <span class="kw">val</span> h = k.<span class="fu">head</span>
    <span class="kw">if</span>(l == <span class="dv">1</span>) h <span class="kw">else</span> (l, h)
  })

  <span class="co">// P12</span>
  <span class="co">// ick</span>
  <span class="kw">def</span> <span class="fu">decodeModified</span>(as: List[_]) = as flatMap {
    <span class="kw">case</span> (n: Int, s) =&gt; Stream.<span class="fu">make</span>(n, s)
    <span class="kw">case</span> s =&gt; List(s)
  }

  <span class="co">// P13</span>
  <span class="co">// WTF?</span>
  <span class="kw">def</span> encode_direct[A] = (_: List[A]).<span class="fu">group</span> <span class="fu">map</span> (k =&gt; (k.<span class="fu">length</span>, k.<span class="fu">head</span>))

  <span class="co">// P14</span>
  <span class="kw">def</span> duplicate[A] = (_: List[A]) <span class="fu">flatMap</span> (k =&gt; List(k, k))

  <span class="co">// P15</span>
  <span class="kw">def</span> duplicateN[A](n: Int, as: List[A]) = as <span class="fu">flatMap</span> (k =&gt; Stream.<span class="fu">make</span>(n, k))

  <span class="co">// P16</span>
  <span class="kw">def</span> drop[A](n: Int, as: List[A]) = as.<span class="fu">zipWithIndex</span> filter { <span class="kw">case</span> (_, x) =&gt; x % n != <span class="dv">2</span> } <span class="fu">map</span> (_.<span class="fu">_1</span>)

  <span class="co">// P17</span>
  <span class="kw">def</span> split[A](n: Int, as: List[A]) = (as take n, as drop n)

  <span class="co">// P18</span>
  <span class="kw">def</span> slice[A](x: Int, y: Int, as: List[A]) = as drop x <span class="fu">take</span> (y - x)

  <span class="co">// P19</span>
  <span class="kw">def</span> rotate[A](n: Int, as: List[A]): List[A] =
    <span class="kw">if</span>(n &lt; <span class="dv">0</span>) <span class="fu">rotate</span>(as.<span class="fu">length</span> + n, as)
    <span class="kw">else</span> (as drop n) ::: (as take n)

  <span class="co">// P20</span>
  <span class="kw">def</span> remove_at[A](n: Int, as: List[A]) = {
    <span class="kw">val</span> (k, Some(z)) = as.<span class="fu">zipWithIndex</span>.<span class="fu">foldRight</span>[(List[A], Option[A])]((Nil, None)) { <span class="kw">case</span> ((a, x), (t, s)) =&gt; <span class="kw">if</span>(n == x) (t, Some(a)) <span class="kw">else</span> (a :: t, s) }
    (k, z)
  }

  <span class="co">// P21</span>
  <span class="kw">def</span> insert_at[A](a: A, n: Int, as: List[A]) = {
    <span class="kw">val</span> (x, y) = as splitAt n
    x ::: a :: y
  }

  <span class="co">// another missing library function</span>
  <span class="kw">implicit</span> <span class="kw">def</span> Unfold[A](a: A): { <span class="kw">def</span> unfold[B](f: A =&gt; Option[(B, A)]): List[B] } = <span class="kw">new</span> {
    <span class="kw">def</span> unfold[B](f: A =&gt; Option[(B, A)]) = <span class="fu">f</span>(a) <span class="kw">match</span> {
      <span class="kw">case</span> None =&gt; Nil
      <span class="kw">case</span> Some((b, z)) =&gt; b :: (<span class="fu">Unfold</span>(z) unfold f)
    }
  }

  <span class="co">// P22</span>
  <span class="kw">def</span> range[A](x: Int, y: Int) = x <span class="fu">unfold</span> (a =&gt; <span class="kw">if</span>(a &gt; y) None <span class="kw">else</span> Some(a, a + <span class="dv">1</span>))

  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]) {
    <span class="kw">val</span> ps = List(
      <span class="fu">last</span>(List(<span class="dv">1</span>, <span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">5</span>, <span class="dv">8</span>)), <span class="co">// P01</span>
      <span class="fu">penultimate</span>(List(<span class="dv">1</span>, <span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">5</span>, <span class="dv">8</span>)), <span class="co">// P02</span>
      <span class="fu">nth</span>(<span class="dv">2</span>, List(<span class="dv">1</span>, <span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">5</span>, <span class="dv">8</span>)), <span class="co">// P03</span>
      <span class="fu">length</span>(List(<span class="dv">1</span>, <span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">5</span>, <span class="dv">8</span>)), <span class="co">// P04</span>
      <span class="fu">reverse</span>(List(<span class="dv">1</span>, <span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">5</span>, <span class="dv">8</span>)), <span class="co">// P05</span>
      <span class="fu">isPalindrome</span>(List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">2</span>, <span class="dv">1</span>)), <span class="co">// P06</span>
      <span class="fu">flatten</span>(List(<span class="dv">1</span>, <span class="dv">1</span>), <span class="dv">2</span>, List(<span class="dv">3</span>, List(<span class="dv">5</span>, <span class="dv">8</span>))), <span class="co">// P07</span>
      <span class="fu">compress</span>(List(&#39;a, &#39;a, &#39;a, &#39;a, &#39;b, &#39;c, &#39;c, &#39;a, &#39;a, &#39;d, &#39;e, &#39;e, &#39;e, &#39;e)), <span class="co">// P08</span>
      <span class="fu">pack</span>(List(&#39;a, &#39;a, &#39;a, &#39;a, &#39;b, &#39;c, &#39;c, &#39;a, &#39;a, &#39;d, &#39;e, &#39;e, &#39;e, &#39;e)), <span class="co">// P09</span>
      <span class="fu">encode</span>(List(&#39;a, &#39;a, &#39;a, &#39;a, &#39;b, &#39;c, &#39;c, &#39;a, &#39;a, &#39;d, &#39;e, &#39;e, &#39;e, &#39;e)), <span class="co">// P10</span>
      <span class="fu">encodeModified</span>(List(&#39;a, &#39;a, &#39;a, &#39;a, &#39;b, &#39;c, &#39;c, &#39;a, &#39;a, &#39;d, &#39;e, &#39;e, &#39;e, &#39;e)), <span class="co">// P11</span>
      <span class="fu">decodeModified</span>(List((<span class="dv">4</span>, &#39;a), &#39;b, (<span class="dv">2</span>, &#39;c), (<span class="dv">2</span>, &#39;a), &#39;d, (<span class="dv">4</span>, &#39;e))), <span class="co">// P12</span>
      <span class="fu">encode_direct</span>(List(&#39;a, &#39;a, &#39;a, &#39;a, &#39;b, &#39;c, &#39;c, &#39;a, &#39;a, &#39;d, &#39;e, &#39;e, &#39;e, &#39;e)), <span class="co">// P13</span>
      <span class="fu">duplicate</span>(List(&#39;a, &#39;b, &#39;c, &#39;c, &#39;d)), <span class="co">// P14</span>
      <span class="fu">duplicateN</span>(<span class="dv">3</span>, List(&#39;a, &#39;b, &#39;c, &#39;c, &#39;d)), <span class="co">// P15</span>
      <span class="fu">drop</span>(<span class="dv">3</span>, List(&#39;a, &#39;b, &#39;c, &#39;d, &#39;e, &#39;f, &#39;g, &#39;h, &#39;i, &#39;j, &#39;k)), <span class="co">// P16</span>
      <span class="fu">split</span>(<span class="dv">3</span>, List(&#39;a, &#39;b, &#39;c, &#39;d, &#39;e, &#39;f, &#39;g, &#39;h, &#39;i, &#39;j, &#39;k)), <span class="co">// P17</span>
      <span class="fu">slice</span>(<span class="dv">3</span>, <span class="dv">7</span>, List(&#39;a, &#39;b, &#39;c, &#39;d, &#39;e, &#39;f, &#39;g, &#39;h, &#39;i, &#39;j, &#39;k)), <span class="co">// P18</span>
      (<span class="fu">rotate</span>(<span class="dv">3</span>, List(&#39;a, &#39;b, &#39;c, &#39;d, &#39;e, &#39;f, &#39;g, &#39;h, &#39;i, &#39;j, &#39;k)), <span class="fu">rotate</span>(-<span class="dv">2</span>, List(&#39;a, &#39;b, &#39;c, &#39;d, &#39;e, &#39;f, &#39;g, &#39;h, &#39;i, &#39;j, &#39;k))), <span class="co">// P19</span>
      <span class="fu">remove_at</span>(<span class="dv">1</span>, List(&#39;a, &#39;b, &#39;c, &#39;d)), <span class="co">// P20</span>
      <span class="fu">insert_at</span>(&#39;new, <span class="dv">1</span>, List(&#39;a, &#39;b, &#39;c, &#39;d)), <span class="co">// P21</span>
      <span class="fu">range</span>(<span class="dv">4</span>, <span class="dv">9</span>), <span class="co">// P22</span>
    )

    ps.<span class="fu">zipWithIndex</span> foreach { <span class="kw">case</span> (p, n) =&gt; <span class="fu">println</span>(<span class="st">&quot;P&quot;</span> + (n + <span class="dv">1</span>) + <span class="st">&quot;: &quot;</span> + p) }
  }
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Assessing and being held responsible for the cost of bad decisions</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/assessing-and-being-held-responsible-for-the-cost-of-bad-decisions/index.html"/>
  <id>http://blog.tmorris.net/posts/assessing-and-being-held-responsible-for-the-cost-of-bad-decisions/index.html</id>
  <published>2009-03-30T12:04:41Z</published>
  <updated>2009-03-30T12:04:41Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I was recently working on a software project where the client would consult one organisation then that organisation would consult through to my organisation and eventually to me. Unfortunately, the organisation with direct contact to the client does not have very much skill in understanding computer programming problems, <a href="http://blog.tmorris.net/why-functional-programming-matters-in-short-prose/">the notion of software reusability and decomposition</a> and generally advising the client in such a way to ensure that their interests and expectations are met. This is unfortunate, but also incredibly common (dare I say it, so-called “enterprise” programmers).</p>
<p>A consequence of this debacle is that the software project is highly unlikely to meet the client’s expectation at all or in a timely fashion. Furthermore, I am likely to be asked to accept responsibility for this failure. This is despite my insistence that “using Scala and functional programming is not a panacea, especially when foolish demands are made of me” and various other protests of varying nature.</p>
<p>I used to have to deal with this kind of ineptitude when I was at IBM and I had some very rigorous methods for eschewing the responsibility for poor decisions by those who (I grit my teeth, but it must be said) are incompetent-but-unaware-of-it, while still achieving what was required of me. Such opaqueness does not exist in this case and I’d prefer to produce a useful and timely solution for the client with skilled consulting and the advanced programming techniques that are available.</p>
<p>But I can’t and I’ll be paying the price in the end.</p>
<p>How do others manage this scenario?</p>
    </div>
  </content>
</entry>
<entry>
  <title>SBS English Failure</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/sbs-english-failure/index.html"/>
  <id>http://blog.tmorris.net/posts/sbs-english-failure/index.html</id>
  <published>2009-03-29T21:02:41Z</published>
  <updated>2009-03-29T21:02:41Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I sometimes watch the <a href="http://www.sbs.com.au/">SBS television station</a> – the content is generally of a higher standard than commercial stations with a greater display of intellectual rigour.</p>
<p>However, there is a Ticketek advertisement on this station with a caption, “What do you think your doing?”.</p>
<p><em>Ugh.</em></p>
    </div>
  </content>
</entry>
<entry>
  <title>Mount Mee State Forest</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/mount-mee-state-forest/index.html"/>
  <id>http://blog.tmorris.net/posts/mount-mee-state-forest/index.html</id>
  <published>2009-03-24T20:19:52Z</published>
  <updated>2009-03-24T20:19:52Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I <a href="http://blog.tmorris.net/category/mapping/">once wrote about</a> the mapping of tracks, campgrounds and points of interest in <a href="http://www.epa.qld.gov.au/projects/park/index.cgi?parkid=63">Mount Mee State Forest</a>. Since I have been trapped in my house for many months due to injury, I have entered all my mapping data into <a href="http://openstreetmap.org/">OpenStreetMap</a> including Mount Mee State Forest.</p>
<p><a href="http://openstreetmap.org/export?lat=-27.0981&amp;lon=152.6837&amp;zoom=13&amp;layers=B000FTF">Here is a link to the PotLatch map of Mount Mee</a>, however, I much prefer <a href="http://josm.openstreetmap.de/">JOSM</a> for entering map data – a surprisingly usable and relatively bug-free Java application (no really!).</p>
<p>If you have track logs – particularly in GPX format – and you’re willing to donate them, I’d be happy to enter them in or use them to tighten up some of the tracks already entered.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Functional Java 2.19</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/functional-java-219/index.html"/>
  <id>http://blog.tmorris.net/posts/functional-java-219/index.html</id>
  <published>2009-03-23T17:58:30Z</published>
  <updated>2009-03-23T17:58:30Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>New for <a href="http://functionaljava.org/">Functional Java</a> 2.19:</p>
<ul>
<li><p>Comonadic operations on <code>Stream</code>, <code>Tree</code> and other data types</p></li>
<li><p>Database monad (<code>java.sql.Connection</code> as a functor)</p></li>
<li><p>Natural Number data type</p></li>
<li><p>The Constant Arrow ($)</p></li>
<li><p>Immutable Tree Map</p></li>
<li><p>A parallel quick-sort using Functional Java actors</p></li>
<li><p><em>much more</em></p></li>
</ul>
    </div>
  </content>
</entry>
<entry>
  <title>Dear Agile/Lean/Scrum/XP Person</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/dear-agileleanscrumxp-person/index.html"/>
  <id>http://blog.tmorris.net/posts/dear-agileleanscrumxp-person/index.html</id>
  <published>2009-02-19T13:50:50Z</published>
  <updated>2009-02-19T13:50:50Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I want you to imagine a scenario for me.</p>
<p>Did you know that carrying a Tiger’s Eye crystal provides protection and clearer thought? Yeah OK I agree, all that crystal healing stuff is just silly nonsense that essentially exists to provide a placebo effect. This doesn’t stop some people from genuinely believing in the healing properties of crystals of course – and they are certainly being exposed to a bias of confirmation. This is because a critical failure of rational faculties has occurred somehow – you and I see straight through it; it’s obviously nonsense! But they seek peer reinforcement for their mistake and have a hard time understanding what it is like to not believe in the healing properties of crystals.</p>
<p>If it is so blatantly false, then why do some apparently intellectually-equipped people swear by it?</p>
<p>Now suppose you were invited to be healed by a crystal healer and you decline because you have other relevant tasks to achieve. What would you say when asked why the declination? You wouldn’t want to insult the questioner – that they believe such a ridiculous proposition doesn’t compel you to simply insult their person, however, if you were to answer the question honestly, they would take offence. You’re caught in a pickle now, so what then? Dishonesty? Appeasing their fantasy?</p>
<p>Would you answer with a question, “I don’t believe crystal healing is effective, because there is no empirical data to suggest it is so. Can you show me otherwise?” to which they respond, “Sure! We use a process of high energy physics photography to derive our scientific conclusions.” So what now? They just provide more bunk – again, you and I see straight through it. You can make no progress. The only reasonable conversation you can have is one about how to deduce true facts in general.</p>
<p>But it gets worse, now imagine that the invitation to the crystal healing session requires that you drink frog poison upon entry, because the ancient Egyptians did it to appease the Gods with a small personal sacrifice. In this scenario, 150 people die each year from ingestion of frog poison, but the crystal healers put this down to anger from the Gods that must only be appeased further, otherwise it will be 300!</p>
<p>At this point, you now object to attendance on the grounds that it is detrimental to your health. Furthermore, you may even feel a moral obligation toward anybody else who has been coaxed into this form of abuse. You’re in a really big pickle now aren’t you?</p>
<p>This is exactly the pickle I am in when you try to peddle your pseudoscience onto me. I don’t want to insult you, but I don’t want to suffer the adverse effects of your crack-pottery. Furthermore, I don’t want other people, who have been tricked (as you have been), to suffer – I feel compelled to warn them against it. Again, not to offend you (though it might), but because I have a deep sense of empathy for all people, including you.</p>
<p>On the other hand, I could do what a lot of us non-crystal-healers do and be proactive in completely ignoring your existence wherever possible but that doesn’t take away from my sense of empathy.</p>
    </div>
  </content>
</entry>
<entry>
  <title>IntelliJ IDEA leaps ahead for Scala development</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/intellij-idea-leaps-ahead-for-scala-development/index.html"/>
  <id>http://blog.tmorris.net/posts/intellij-idea-leaps-ahead-for-scala-development/index.html</id>
  <published>2009-02-17T07:01:37Z</published>
  <updated>2009-02-17T07:01:37Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Much of my work is in Scala or Haskell. Lately, it is mostly in Scala. Sometimes I have the unfortunate imposition to use Java by a false authority. This is where <a href="http://functionaljava.org/">Functional Java</a> is handy – in an attempt to make Java somewhat practical, even if only to a small degree.</p>
<p>JetBrains has granted Functional Java an open source licence to use their IntelliJ IDEA. I recently downloaded the 8.1 version and started working on some of the Scala components of Functional Java.</p>
<p>It is pleasing to have a usable IDE that is easy to install on my 64-bit Linux machine. It is more pleasing that the Scala plugin has all the required fundamental features and few bugs. I also use a 32-bit machine running Linux and it was just as much a breeze to install and use there. Of course, I do not use Compiz on these machines, since it screws up swing applications. I do, however, use <a href="http://xmonad.org/">xmonad</a> window manager, which boosts productivity quite a lot.</p>
<p>The Scala plugin has the much desired “Go to declaration”, is able to report many compile-time errors – though not all and I expect I push Scala a bit harder than many others in terms of finding quirks in the language. It has many other features – some of which need a bit of work, but many of which are significantly ahead of other IDEs, particularly when it comes to stability.</p>
<p>Thanks JetBrains for making it viable to use advanced programming concepts in a capable programming language.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Third World Medicine</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/third-world-medicine/index.html"/>
  <id>http://blog.tmorris.net/posts/third-world-medicine/index.html</id>
  <published>2009-02-14T10:11:32Z</published>
  <updated>2009-02-14T10:11:32Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I’ve had two operations on my right ankle and both have failed to correctly diagnose and address the underlying symptomatic complaints that have existed for over 18 months. I am now aware of what the correct diagnosis is, verifiable with historical and radiographic evidence and repeatable symptomatic observations.</p>
<p>The surgeons are cautious given that I’ve already used up two of my available surgery cookie quota and hesitant to go again. This is despite having an exact pinpoint of where the problem is and published literature of what procedure is required. I simply have no rational explanation for this and, if it weren’t for my discomfort, it would leave me in awe.</p>
<p>The diagnosis is anteromedial osseous impingement of the right ankle visible on CT, verified by a radiologist and repeatable on dorsiflexion. This has come about from repeated trauma and in particular, a grade 3 inversion sprain in July 2007. I require a resection of this excess ossification.</p>
<p>I am asking (begging) my international audience for recommendations of a surgeon who is willing to perform this procedure as soon as possible in any part of the world. I suspect, only because I have no other explanation, that there is some bureaucratic restriction preventing me from making progress with surgeons here.</p>
<p>Suggestions please?</p>
    </div>
  </content>
</entry>
<entry>
  <title>Funky Scala Bifunctor</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/funky-scala-bifunctor/index.html"/>
  <id>http://blog.tmorris.net/posts/funky-scala-bifunctor/index.html</id>
  <published>2009-02-14T17:16:26Z</published>
  <updated>2009-02-14T17:16:26Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>A co-variant binary functor (aka bifunctor) is any type constructor with a kind * -&gt; * -&gt; * that can satisfy identity and composition when mapping on either type variable. A couple of examples of bifunctors in the Scala library are</p>
<ul>
<li><p><code>Tuple2</code></p></li>
<li><p><code>Either</code></p></li>
</ul>
<p>Note that <code>Function1</code> is not a bifunctor, evident by the fact that it is contra-variant in its first type variable. It is notable that <code>Tuple2</code> represents <em>conjunction</em> while <code>Either</code> represents the <em>disjunction</em> of two theorems under the <a href="http://en.wikipedia.org/wiki/Curry-Howard_correspondence">Curry-Howard Isomorphism</a> (<code>Function1</code> represents <em>implication</em>`).</p>
<p>A bifunctor often combines the two possible mappings into a function called <code>bimap</code> with the signature (Scala-ish syntax):</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">F[A, B] =&gt; (A =&gt; C) =&gt; (B =&gt; D) =&gt; F[C, D]</code></pre>
<p>Recall that identity and composition laws must satisfy in the implementation.</p>
<p>Consider now an implementation of <code>bimap</code> for both <code>Tuple2</code> and <code>Either</code>:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> Bifunctor[F[+_, +_]] {
  <span class="kw">def</span> bimap[A, B, C, D](fa: F[A, B], f: A =&gt; C, g: B =&gt; D): F[C, D]
}

<span class="kw">object</span> Bifunctor {
  <span class="kw">implicit</span> <span class="kw">def</span> Tuple2Bifunctor = <span class="kw">new</span> Bifunctor[Tuple2] {
    <span class="kw">def</span> bimap[A, B, C, D](fa: (A, B), f: A =&gt; C, g: B =&gt; D) =
      (<span class="fu">f</span>(fa.<span class="fu">_1</span>), <span class="fu">g</span>(fa.<span class="fu">_2</span>))
  }

  <span class="kw">implicit</span> <span class="kw">def</span> EitherBifunctor = <span class="kw">new</span> Bifunctor[Either] {
    <span class="kw">def</span> bimap[A, B, C, D](fa: Either[A, B], f: A =&gt; C, g: B =&gt; D) =
      fa <span class="kw">match</span> {
        <span class="kw">case</span> <span class="fu">Left</span>(a) =&gt; <span class="fu">Left</span>(<span class="fu">f</span>(a))
        <span class="kw">case</span> <span class="fu">Right</span>(b) =&gt; <span class="fu">Right</span>(<span class="fu">g</span>(b))
      }
  }
}</code></pre>
<p>These implementations are quite easy to understand, but they are not so pretty to use. This is an unfortunate consequence of a number of factors about Scala, including:</p>
<ul>
<li><p>Higher-kinds are never inferred</p></li>
<li><p>Functions cannot be used in infix position</p></li>
</ul>
<p>In Scala, methods that end with a colon (:) can have their arguments swapped when not using dot notation. For example, the following two lines are equivalent:</p>
<pre><code>obj.::(arg) 
arg :: obj</code></pre>
<p>This is evident when using <code>scala.List</code> and the cons (<code>::</code>) method.</p>
<p>We might wrap up our <code>Bifunctor</code> implementation similarly and create some nice syntax for mapping on the bifunctor. For example, let us define three methods on any <code>Bifunctor</code> value:</p>
<ul>
<li><p><code>&lt;-:</code> for mapping on one side</p></li>
<li><p><code>:-&gt;</code> for mapping on the other side</p></li>
<li><p><code>&lt;-:-&gt;</code> for mapping on both sides</p></li>
</ul>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> BifunctorW[F[+_, +_], A, B] {
  <span class="kw">val</span> value: F[A, B]
  <span class="kw">val</span> bifunctor: Bifunctor[F]

  <span class="kw">def</span> &lt;-:-&gt;[C, D](f: A =&gt; C, g: B =&gt; D) = bifunctor.<span class="fu">bimap</span>(value, f, g)

  <span class="kw">def</span> &lt;-:[C](f: A =&gt; C) = bifunctor.<span class="fu">bimap</span>(value, f, identity[B])

  <span class="kw">def</span> :-&gt;[D](g: B =&gt; D) = bifunctor.<span class="fu">bimap</span>(value, identity[A], g)
}

<span class="kw">object</span> BifunctorW {
  <span class="co">// a somewhat verbose but handy trick</span>
  <span class="co">// for partially applying type variables.</span>
  <span class="kw">def</span> bifunctor[F[+_, +_]] = <span class="kw">new</span> BifunctorApply[F] {
    <span class="kw">def</span> apply[A, B](v: F[A, B])(<span class="kw">implicit</span> b: Bifunctor[F]) =
        <span class="kw">new</span> BifunctorW[F, A, B] {
      <span class="kw">val</span> value = v
      <span class="kw">val</span> bifunctor = b
    }
  }

  <span class="kw">trait</span> BifunctorApply[F[+_, +_]] {
    <span class="kw">def</span> apply[A, B](v: F[A, B])(<span class="kw">implicit</span> b: Bifunctor[F]): BifunctorW[F, A, B]
  }

  <span class="kw">implicit</span> <span class="kw">def</span> Tuple2Bifunctor[A, B](v: (A, B)) =
    bifunctor[Tuple2](v)

  <span class="kw">implicit</span> <span class="kw">def</span> Either2Bifunctor[A, B](v: Either[A, B]) =
    bifunctor[Either](v)
}</code></pre>
<p>So we’ve wrapped a value and its <code>Bifunctor</code> implementation. So how does it look when we use it? Like this!</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> Main {
  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]) {
    <span class="kw">import</span> BifunctorW.<span class="fu">_</span>

    <span class="kw">val</span> x: Either[Int, String] = <span class="fu">Left</span>(<span class="dv">7</span>)
    <span class="kw">val</span> y = (<span class="st">&quot;hello&quot;</span>, <span class="dv">42</span>)

    <span class="kw">val</span> f = (n: Int) =&gt; n + <span class="dv">1</span>
    <span class="kw">val</span> g = (s: String) =&gt; s.<span class="fu">reverse</span>
    <span class="kw">val</span> h = (s: String) =&gt; s.<span class="fu">toUpperCase</span>
    <span class="kw">val</span> i = (n: Int) =&gt; n * <span class="dv">2</span>

   <span class="co">// Pretty neat eh?</span>
    <span class="kw">val</span> p = f &lt;-: x :-&gt; g
    <span class="kw">val</span> q = h &lt;-: y :-&gt; i

    <span class="co">// $ scala Main</span>
    <span class="co">// Left(8)</span>
    <span class="co">// (HELLO,84)</span>
    <span class="fu">println</span>(p)
    <span class="fu">println</span>(q)
  }
}</code></pre>
<p>And I think that’s an elegant use of a sometimes baroque (when trying for advanced concepts) language :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>No True Australian</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/no-true-australian/index.html"/>
  <id>http://blog.tmorris.net/posts/no-true-australian/index.html</id>
  <published>2009-01-27T17:04:29Z</published>
  <updated>2009-01-27T17:04:29Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://www.ntnews.com.au/article/2009/01/27/29541_ntnews.html">It’s not racist – though it’s a gross display of the ineptitude with the basic faculties of reason of a few poorly educated people who have my deepest sympathy.</a> <a href="http://en.wikipedia.org/wiki/No_true_Scotsman">Here is some light reading material that might interest them.</a></p>
    </div>
  </content>
</entry>
<entry>
  <title>Playing with Scala and Arrows</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/playing-with-scala-and-arrows/index.html"/>
  <id>http://blog.tmorris.net/posts/playing-with-scala-and-arrows/index.html</id>
  <published>2009-01-25T12:34:12Z</published>
  <updated>2009-01-25T12:34:12Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I decided to play around with <a href="http://www.cs.chalmers.se/~rjmh/pubs.htm">arrows</a> and Scala to see how far I could get. I remember vividly the effort required to get a Monad abstraction for <a href="http://code.google.com/p/scalaz/">Scalaz</a> to work and be useful all at once with so many competing tensions (e.g. type inferencer, composability, repetition).</p>
<p>I didn’t go so far as to test the usefulness, but I was able to express the Kleisli arrow without too much effort. I wonder if it is a viable addition for Scalaz.</p>
<p>Here it is.</p>
<p>The typical Functor/Monad abstraction. These are required for the Kleisli arrow.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> Functor[F[+_]] {
  <span class="kw">def</span> fmap[A, B](fa: F[A], f: A =&gt; B): F[B]
}

<span class="kw">trait</span> Monad[M[+_]] <span class="kw">extends</span> Functor[M] {
  <span class="kw">def</span> pure[A](a: A): M[A]
  <span class="kw">def</span> bind[A, B](ma: M[A], f: A =&gt; M[B]): M[B]

  <span class="kw">final</span> <span class="kw">def</span> fmap[A, B](fa: M[A], f: A =&gt; B) =
    <span class="fu">bind</span>(fa, (a: A) =&gt; <span class="fu">pure</span>(<span class="fu">f</span>(a)))
}</code></pre>
<p>The Kleisli data type and a convenient constructor.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> Kleisli[M[+_], -A, +B] {
  <span class="kw">def</span> <span class="fu">apply</span>(a: A): M[B]
}

<span class="kw">object</span> Kleisli {
  <span class="kw">def</span> kleisli[M[+_], A, B](f: A =&gt; M[B]) = <span class="kw">new</span> Kleisli[M, A, B] {
    <span class="kw">def</span> <span class="fu">apply</span>(a: A) = <span class="fu">f</span>(a)
  }
}</code></pre>
<p>The arrow abstraction.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> Arrow[A[-_, +_]] {
  <span class="kw">def</span> arrow[B, C](f: B =&gt; C): A[B, C]

  <span class="kw">def</span> compose[B, C, D](a1: A[B, C], a2: A[C, D]): A[B, D]

  <span class="kw">def</span> first[B, C, D](a: A[B, C]): A[(B, D), (C, D)]

  <span class="kw">def</span> second[B, C, D](a: A[B, C]): A[(D, B), (D, C)]
}</code></pre>
<p>and the clincher…</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> Arrow {
  <span class="kw">val</span> Function1Arrow = <span class="kw">new</span> Arrow[Function1] {
    <span class="kw">def</span> arrow[B, C](f: B =&gt; C) = f

    <span class="kw">def</span> compose[B, C, D](a1: B =&gt; C, a2: C =&gt; D) =
      a2 compose a1

    <span class="kw">def</span> first[B, C, D](a: B =&gt; C) =
      (bd: (B, D)) =&gt; (<span class="fu">a</span>(bd.<span class="fu">_1</span>), bd.<span class="fu">_2</span>)

    <span class="kw">def</span> second[B, C, D](a: B =&gt; C) =
      (db: (D, B)) =&gt; (db.<span class="fu">_1</span>, <span class="fu">a</span>(db.<span class="fu">_2</span>))
  }

  <span class="kw">def</span> KleisliArrow[M[+_]](<span class="kw">implicit</span> m: Monad[M]) =
        <span class="kw">new</span> Arrow[PartialType[Kleisli, M]#Apply] {
    <span class="kw">import</span> Kleisli.<span class="fu">kleisli</span>

    <span class="kw">def</span> arrow[B, C](f: B =&gt; C) =
      kleisli[M, B, C](b =&gt; m.<span class="fu">pure</span>(<span class="fu">f</span>(b)))

    <span class="kw">def</span> compose[B, C, D](a1: Kleisli[M, B, C], a2: Kleisli[M, C, D]) =
      kleisli[M, B, D](b =&gt; m.<span class="fu">bind</span>(<span class="fu">a1</span>(b), (c: C) =&gt; <span class="fu">a2</span>(c)))

    <span class="kw">def</span> first[B, C, D](a: Kleisli[M, B, C]) =
      kleisli[M, (B, D), (C, D)] { <span class="kw">case</span> (b, d) =&gt; m.<span class="fu">fmap</span>(<span class="fu">a</span>(b), (c: C) =&gt; (c, d)) }

    <span class="kw">def</span> second[B, C, D](a: Kleisli[M, B, C]) =
      kleisli[M, (D, B), (D, C)]{ <span class="kw">case</span> (d, b) =&gt; m.<span class="fu">fmap</span>(<span class="fu">a</span>(b), (c: C) =&gt; (d, c)) }
  }
}</code></pre>
<p>TODO</p>
<ol style="list-style-type: decimal">
<li><p>Write functions across arrows.</p></li>
<li><p>Can arrows be made useful within the constraints of Scala?</p></li>
</ol>
    </div>
  </content>
</entry>
<entry>
  <title>Continuation monad in Scala</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/continuation-monad-in-scala/index.html"/>
  <id>http://blog.tmorris.net/posts/continuation-monad-in-scala/index.html</id>
  <published>2008-12-28T13:25:41Z</published>
  <updated>2008-12-28T13:25:41Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Here is how a continuation data type might look in Scala:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">sealed</span> <span class="kw">trait</span> Continuation[R, +A] {
  <span class="kw">def</span> <span class="fu">apply</span>(f: A =&gt; R): R

  <span class="kw">import</span> Continuation.<span class="fu">continuation</span>

  <span class="kw">def</span> map[B](k: A =&gt; B) =
    continuation[R, B](z =&gt; <span class="fu">apply</span>(z compose k))

  <span class="kw">def</span> flatMap[B](k: A =&gt; Continuation[R, B]) =
    continuation[R, B](z =&gt; <span class="fu">apply</span>(<span class="fu">k</span>(_)(z)))
}</code></pre>
<p>Note that there are <code>map</code> and <code>flatMap</code> functions that satisfy the functor and monad laws. <code>Continuation[R, _]</code> is a monad.</p>
<p>Now let’s add some construction functions:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> Continuation {
  <span class="kw">def</span> continuation[R, A](g: (A =&gt; R) =&gt; R) = <span class="kw">new</span> Continuation[R, A] {
    <span class="kw">def</span> <span class="fu">apply</span>(f: A =&gt; R) = <span class="fu">g</span>(f)
  }

  <span class="kw">def</span> <span class="dt">unit</span>[R] = <span class="kw">new</span> {
    <span class="kw">def</span> apply[A](a: A) = continuation[R, A](f =&gt; <span class="fu">f</span>(a))
  }

  <span class="kw">def</span> callcc[R, A, B](f: (A =&gt; Continuation[R, B]) =&gt; Continuation[R, A]) =
    continuation[R, A](k =&gt; <span class="fu">f</span>(a =&gt; <span class="fu">continuation</span>(x =&gt; <span class="fu">k</span>(a)))(k))
}</code></pre>
<p>The <code>continuation</code> function is a straight-forward construction. The <code>unit</code> function constructs a continuation is such a way as to satisfy the monad laws against the <code>flatMap</code> method. The <code>callcc</code> function (call with current continuation) is to allow “escaping” from the current continuation.</p>
<p>Here is some example client code that squares a number using a continuation (see <code>squarec</code>):</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> Square {
  <span class="kw">import</span> Continuation.<span class="fu">_</span>

  <span class="kw">def</span> <span class="fu">square</span>(n: Int) = n * n

  <span class="co">// Continuation for square</span>
  <span class="kw">def</span> squarec[R](n: Int) = <span class="dt">unit</span>[R](<span class="fu">square</span>(n))

  <span class="co">// Continuation for effect (Unit) on square.</span>
  <span class="co">// This is simply to help the type inferencer by applying a type argument.</span>
  <span class="kw">def</span> <span class="fu">squareE</span>(n: Int) = squarec[Unit](n)

  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]) {
    <span class="kw">val</span> k = <span class="fu">squareE</span>(<span class="fu">args</span>(<span class="dv">0</span>).<span class="fu">toInt</span>)
    <span class="fu">k</span>(println)
  }
}</code></pre>
<p>A slightly more complicated example for modelling exceptions. Let’s divide where the denominator must be 0 or an “exception” is thrown:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> Divide {
  <span class="kw">import</span> Continuation.<span class="fu">_</span>

  <span class="co">// Division</span>
  <span class="kw">def</span> div[R](c: String =&gt; Continuation[R, Int])
            (n: Int, <span class="co">// numerator</span>
             d: Int) <span class="co">// denominator</span>
                    : Continuation[R, Int] =
    callcc[R, Int, String](ok =&gt;
      callcc[R, String, String](err =&gt;
        <span class="kw">if</span>(d == <span class="dv">0</span>) <span class="fu">err</span>(<span class="st">&quot;Denominator 0&quot;</span>)
        <span class="kw">else</span> <span class="fu">ok</span>(n / d)
      ) flatMap c)

  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]) {
    <span class="kw">def</span> divError[R] = div[R](<span class="fu">error</span>(_)) _
    <span class="fu">println</span>(<span class="fu">divError</span>(<span class="dv">7</span>, <span class="dv">3</span>)(x =&gt; x))
    <span class="fu">println</span>(<span class="fu">divError</span>(<span class="dv">7</span>, <span class="dv">0</span>)(x =&gt; x)) <span class="co">// throws error</span>
  }
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Controlling effects with flatMap/>>=</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/controlling-effects-with-flatmap/index.html"/>
  <id>http://blog.tmorris.net/posts/controlling-effects-with-flatmap/index.html</id>
  <published>2008-12-26T14:40:56Z</published>
  <updated>2008-12-26T14:40:56Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I used to lecture at university. These days I teach for fun. Sometimes I am asked about controlling effects in a pure programming language such as Haskell by people who are very familiar with Scala’s <code>flatMap</code> method on List type, Option and so on (sadly, it is missing from the most fundamental of all – <code>Function1</code>). I often do this on a white-board and it has been reasonably successful at producing “aha! moments” so maybe it will help you.</p>
<p>Scala includes special syntax for using this method in the form of for-comprehensions. Specifically code like the following…</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">for(k <span class="ot">&lt;-</span> e1;
    l <span class="ot">&lt;-</span> e2(k);
    m <span class="ot">&lt;-</span> e3;
    n <span class="ot">&lt;-</span> e4(k, m))
  yield f(k, l, m, n)</code></pre>
<p>…is translated into…</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">e1 <span class="fu">flatMap</span> (k =&gt;
<span class="fu">e2</span>(k) <span class="fu">flatMap</span> (l =&gt;
e3 <span class="fu">flatMap</span> (m =&gt;
<span class="fu">e4</span>(k, m) <span class="fu">map</span> (n =&gt;
<span class="fu">f</span>(k, l, m, n)))))</code></pre>
<p>Notice the final call to <code>map</code> which is a <em>specialisation</em> of a call to <code>flatMap</code> by taking the <em>unital</em> for the type constructor under consideration. Gobbledy-gook? It’s simple really. Consider Lists:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">x map f
<span class="co">// can also be written</span>
x <span class="fu">flatMap</span> (z =&gt; List(<span class="fu">f</span>(z)))</code></pre>
<p>That is because <code>x =&gt; List(x)</code> is the unit for <code>List</code>. For <code>Option</code> this function is the unit operation: <code>x =&gt; Some(x)</code>. Try it next time you call <code>map</code> – use <code>flatMap</code> instead plus the unit operation for whatever type constructor you’re using (<code>List</code>, <code>Option</code>, whatever) – you’ll always get the same result. For <code>Function1</code> the unit operation is <code>x =&gt; y =&gt; x</code>. I digress.</p>
<p>When I am asked about controlling side-effects I point to this <code>flatMap</code> business first so that I can assume familiarity (simple right?), then I switch to a completely different discussion about say, the following Java program snippet:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">T t = <span class="fu">e1</span>();
<span class="fu">e2</span>(t);
U u = <span class="fu">e3</span>(t);
V v = <span class="fu">e4</span>(t, u);
<span class="kw">return</span> <span class="fu">e5</span>(u, v);</code></pre>
<p>What I do with this snippet is invent a new programming that has very similar, but still different syntax to Java and I rewrite the program above. I do two things first</p>
<ol style="list-style-type: decimal">
<li><p>The syntax for assignment occurs in reverse</p></li>
<li><p>I remove type annotations (like T, U and V)</p></li>
</ol>
<p>Here is how the program looks now:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="fu">e1</span>() = t;
<span class="fu">e2</span>(t);
<span class="fu">e3</span>(t) = u;
<span class="fu">e4</span>(t, u) = v;
<span class="kw">return</span> <span class="fu">e5</span>(u, v);</code></pre>
<p>Next I replace semi-colons (except the last one) with <code>=&gt;</code> and I rename <code>return</code> to <code>unit</code>:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="fu">e1</span>() = t =&gt;
<span class="fu">e2</span>(t) =&gt;
<span class="fu">e3</span>(t) = u =&gt;
<span class="fu">e4</span>(t, u) = v =&gt;
<span class="dt">unit</span> <span class="fu">e5</span>(u, v)</code></pre>
<p>Finally, I replace the equals sign with <code>flatMap</code> and I add a special case for the call to <code>e2</code> which has no return value by calling <code>flatMap</code> but ignoring the parameter to the given function (denoted with an underscore):</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="fu">e1</span>() flatMap t =&gt;
<span class="fu">e2</span>(t) flatMap _ =&gt;
<span class="fu">e3</span>(t) flatMap u =&gt;
<span class="fu">e4</span>(t, u) flatMap v =&gt;
<span class="dt">unit</span> <span class="fu">e5</span>(u, v)</code></pre>
<p>Since we know that the call to <code>flatMap</code> with <code>unit</code> can be replaced with a call to <code>map</code> let’s do that:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="fu">e1</span>() flatMap t =&gt;
<span class="fu">e2</span>(t) flatMap _ =&gt;
<span class="fu">e3</span>(t) flatMap u =&gt;
<span class="fu">e4</span>(t, u) map v =&gt;
<span class="fu">e5</span>(u, v)</code></pre>
<p>Voila! Have we just turned an imperative program into a pure one just by altering syntax!? Not really – rather, the distinction between imperative and pure is entirely dependent on the colour of your glasses. There is no hard-and-fast divide between one and the other (let that not detract from the huge implications of using one or the other). Importantly, we have seen that we can control side-effects with <code>flatMap</code>.</p>
<p>The <code>flatMap</code> method is at the very essence of a computational model called monads. Note that while we can control side-effects with monads, monads are not always about controlling side-effects! Indeed, when we call <code>flatMap</code> on <code>Option</code> or <code>List</code> we are using monads that have nothing to do with side-effects.</p>
<p>Haskell calls <code>flatMap</code> by a different name <code>&gt;&gt;=</code> and instead of for-comprehensions, Haskell has do-notation.</p>
<p>Pretty simple really isn’t it? :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>Scalaz moved to Google Code</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/scalaz-moved-to-google-code/index.html"/>
  <id>http://blog.tmorris.net/posts/scalaz-moved-to-google-code/index.html</id>
  <published>2008-12-25T07:54:22Z</published>
  <updated>2008-12-25T07:54:22Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Scalaz is no longer on the workingmouse website but is hosted on Google Code at <a href="http://code.google.com/p/scalaz/">http://code.google.com/p/scalaz/</a>.</p>
    </div>
  </content>
</entry>
<entry>
  <title>= ≠ ⇒</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/e289a0-e28792/index.html"/>
  <id>http://blog.tmorris.net/posts/e289a0-e28792/index.html</id>
  <published>2008-12-13T19:30:00Z</published>
  <updated>2008-12-13T19:30:00Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>If you say “Microsoft Windows = bad” you are almost certainly making a false claim within your own beliefs. Not because Windows is not bad necessarily and not because I might think it is good, but because Windows = bad is likely to give rise to an absurdity within your own beliefs should I interrogate you on the matter. There is a difference. Consider also “Hitler = bad”. If you think that “Windows = bad” and “Hitler = bad” then you also think “Windows = Hitler”. I will expect you don’t believe “Windows = Hitler”.</p>
<p>What you likely intend instead is “Windows ⇒ bad”. You could read this as “Windows implies bad”. Now you are free to believe the following three statements without giving rise to an inconsistency in your belief:</p>
<ol style="list-style-type: decimal">
<li><p>Windows ⇒ bad</p></li>
<li><p>Hitler ⇒ bad</p></li>
<li><p>Windows ≠ Hitler</p></li>
</ol>
<p>Here is the truth table for implication:</p>
<blockquote>
<p>P Q P⇒Q 0 0 1 0 1 1 1 0 0 1 1 1</p>
</blockquote>
<p>Notice how ⇒ does not commute? Specifically, if you swap the propositions around you might get a different result. Bad ⇒ Windows is not the same as Windows ⇒ Bad – of course. This cannot be said for =. Bad = Windows is the same as Windows = bad.</p>
<p>You might wonder why I care so much. After all, if you said “Windows = bad” I’d know what you meant. But did you know what you meant and is this understanding universal each time you relax your discourse like this?</p>
<p>I have often observed a confusion between equivalence (also often called bi-implication) and implication in general discussion. Indeed, I hypothesise that this tendency to subvert a proposition in this manner is responsible for many failings in humanity’s general faculty of reason. I think we as a species would be better for it if we repair this failure of intellectual discipline (for what gain anyway?).</p>
<p>Therefore, I think that not only is this trivial correction important, but very much so. Thanks for listening.</p>
    </div>
  </content>
</entry>
<entry>
  <title>A fine motto</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/a-fine-motto/index.html"/>
  <id>http://blog.tmorris.net/posts/a-fine-motto/index.html</id>
  <published>2008-12-09T09:28:19Z</published>
  <updated>2008-12-09T09:28:19Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Inspired by <a href="http://groups.google.com/group/capistrano/msg/f5213577eaeadc47?pli=1">a very important point made by Jamis Buck</a>.</p>
<blockquote>
<p>If you use Windows then you have my sympathy but nothing more. However, if you are stupid enough to elect to use Windows then you don’t even have my sympathy.</p>
</blockquote>
<p>This attitude – although somewhat stolen – is incredibly vital to maintaining my sanity. If I may replace Windows with other values maintaining the same sentiment:</p>
<ul>
<li><p>Java</p></li>
<li><p>Maven (I’m looking at you my <a href="http://functionaljava.org/">Functional Java</a> users)</p></li>
<li><p>Ruby</p></li>
<li><p>Ruby on Rails</p></li>
<li><p>Eclipse</p></li>
</ul>
    </div>
  </content>
</entry>
<entry>
  <title>scala.Function1 lacking</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/scalafunction1-lacking/index.html"/>
  <id>http://blog.tmorris.net/posts/scalafunction1-lacking/index.html</id>
  <published>2008-12-03T17:36:51Z</published>
  <updated>2008-12-03T17:36:51Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>The Scala API leaves a lot to be desired. I’m going to pick on a few methods that should appear, but do not, on <code>[scala.Function1](http://www.scala-lang.org/docu/files/api/scala/Function1.html)</code>.</p>
<p>They are:</p>
<ul>
<li><p><code>map</code></p></li>
<li><p><code>flatMap</code></p></li>
<li><p><code>&lt;*&gt;</code> <a href="http://en.wikipedia.org/wiki/SKI_combinator_calculus">(the S combinator)</a></p></li>
<li><p><code>on</code></p></li>
</ul>
<p>Using some magic with the <code>implicit</code> keyword I can make it appear as if these methods did in fact exist:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">sealed</span> <span class="kw">trait</span> RichFunction1[-T, +R] {
  <span class="kw">def</span> <span class="fu">apply</span>(t: T): R

  <span class="kw">import</span> RichFunction1.<span class="fu">rich</span>

  <span class="kw">def</span> map[X](g: R =&gt; X) = rich[T, X](g <span class="fu">compose</span> (<span class="fu">apply</span>(_)))

  <span class="kw">def</span> flatMap[TT &lt;: T, X](g: R =&gt; RichFunction1[TT, X]) =
    rich[TT, X](t =&gt; <span class="fu">g</span>(<span class="fu">apply</span>(t))(t))

  <span class="co">// The S combinator (SKI)</span>
  <span class="kw">def</span> &lt;*&gt;[TT &lt;: T, X](f: RichFunction1[TT, R =&gt; X]) = (t: TT) =&gt; <span class="fu">f</span>(t)(<span class="fu">apply</span>(t))

  <span class="co">// S again, swapped arguments</span>
  <span class="kw">def</span> &lt;*&gt;:[TT &lt;: T, X](f: RichFunction1[TT, R =&gt; X]) = &lt;*&gt;(f)

  <span class="co">// map with swapped arguments</span>
  <span class="kw">def</span> &lt;-:[X](g: R =&gt; X) = <span class="fu">map</span>(g)

  <span class="kw">def</span> on[K](f: (R, R) =&gt; K, t1: T, t2: T): K = <span class="fu">f</span>(<span class="fu">apply</span>(t1), <span class="fu">apply</span>(t2))
}

<span class="kw">object</span> RichFunction1 {
  <span class="kw">implicit</span> <span class="kw">def</span> rich[T, R](f: T =&gt; R) = <span class="kw">new</span> RichFunction1[T, R] {
    <span class="kw">def</span> <span class="fu">apply</span>(t: T) = <span class="fu">f</span>(t)
  }
}</code></pre>
<p>By having <code>flatMap</code> (and therefore <code>map</code>) this allows you to remove a lot of duplication. This may come at the expense of syntactical noise per Scala, but not always. Suppose you were given a String and you wanted to check if it was equal to one of a few Strings (ignoring case). You could use some trickery with existing methods on <code>List</code>, but I want to keep this example simple, so let us ignore that possibility for now (and accept that I could come up with a sufficient example that such trickery is insufficient).</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// For example, suppose this predicate function</span>
<span class="kw">def</span> <span class="fu">predicate</span>(s1: String) = s1 <span class="fu">equalsIgnoreCase</span> (_: String)</code></pre>
<p>Here is the repetition</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// predicate(s, _) repeats</span>
<span class="kw">def</span> <span class="fu">f</span>(s: String) = <span class="fu">predicate</span>(<span class="st">&quot;x&quot;</span>)(s) || <span class="fu">predicate</span>(<span class="st">&quot;y&quot;</span>)(s) || <span class="fu">predicate</span>(<span class="st">&quot;z&quot;</span>)(s)</code></pre>
<p>But if we have <code>flatMap</code> and <code>map</code> we can use a for-comprehension:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// Taking advantage of flatMap/map</span>
<span class="kw">val</span> g = <span class="kw">for</span>(a &lt;- <span class="fu">predicate</span>(<span class="st">&quot;x&quot;</span>);
            b &lt;- <span class="fu">predicate</span>(<span class="st">&quot;y&quot;</span>);
            c &lt;- <span class="fu">predicate</span>(<span class="st">&quot;z&quot;</span>))
        <span class="kw">yield</span> a || b || c</code></pre>
<p>Here is how that same code looks when expanded:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// Expansion of g</span>
<span class="kw">val</span> h = <span class="fu">predicate</span>(<span class="st">&quot;x&quot;</span>) <span class="fu">flatMap</span> (a =&gt;
        <span class="fu">predicate</span>(<span class="st">&quot;y&quot;</span>) <span class="fu">flatMap</span> (b =&gt;
        <span class="fu">predicate</span>(<span class="st">&quot;z&quot;</span>) <span class="fu">map</span> ((c =&gt;
          a || b || c))))</code></pre>
<p>How about some fancy stuff with the S combinator (<code>&lt;*&gt;</code>):</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">val</span> or = Function.<span class="fu">curried</span>((_: Boolean) || (_: Boolean) || (_: Boolean))

<span class="co">// Using the S combinator</span>
<span class="kw">val</span> i = <span class="fu">predicate</span>(<span class="st">&quot;z&quot;</span>) &lt;*&gt;
        (<span class="fu">predicate</span>(<span class="st">&quot;y&quot;</span>) &lt;*&gt;
        (<span class="fu">predicate</span>(<span class="st">&quot;x&quot;</span>) map
        or))</code></pre>
<p>Or with the arguments swapped around:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// Using S with swapped arguments</span>
<span class="kw">val</span> j = ((or &lt;-: <span class="fu">predicate</span>(<span class="st">&quot;x&quot;</span>)) &lt;*&gt;: <span class="fu">predicate</span>(<span class="st">&quot;y&quot;</span>)) &lt;*&gt;: <span class="fu">predicate</span>(<span class="st">&quot;z&quot;</span>)</code></pre>
<p>Pretty neat eh?</p>
<p>Suppose you wanted to check if the length of one List was less than the length of another. You might be tempted to write <code>x.length &lt; y.length</code>. Notice how <code>_.length</code> repeats? Again I want to keep this example simple so while the solution below is more noisy, there are cases where it is not.</p>
<p>Scala is let down a little by first-class function semantics. We’ll begin with assuming this first-class function value:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">val</span> length = (_: List[Int]).<span class="fu">length</span></code></pre>
<p>Then comparing using length:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">val</span> k = length <span class="fu">on</span> (_ &lt; _, List(<span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>, <span class="dv">7</span>), List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>))</code></pre>
<p>A bit noisier but the repetition is gone. It’s a shame that abstraction comes at a syntactic cost and in some cases it may even be worth that cost. I wish I had the choice.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Do Air Conditioning geeks exist?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/do-air-conditioning-geeks-exist/index.html"/>
  <id>http://blog.tmorris.net/posts/do-air-conditioning-geeks-exist/index.html</id>
  <published>2008-12-01T18:27:29Z</published>
  <updated>2008-12-01T18:27:29Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I work from home now. It rocks :) I also live in a rental property in <a href="http://www.bom.gov.au/climate/averages/tables/cw_040223.shtml">the warm climate of Brisbane, Australia</a>.</p>
<p>I wish to convert one of the rooms – westward-facing, 3 metres by 3 metres – into my office. I currently work in the main living area under a split system A/C and this has some problems that I want to alleviate.</p>
<p>Below is an image of the only window in this room. It has a single slider 570mm by 1450mm (the pink line) which is fitted with a security screen by pop-rivets. This window faces west and there is drainage outside.</p>
<div class="figure">
<img src="http://public.tmorris.net/image/misc/bedroomwindow.jpg" alt="Bedroom Window" /><p class="caption">Bedroom Window</p>
</div>
<p>What is an appropriate set up for cooling such a room, given that it is a rental property? I have looked at evaporative coolers and portable air conditioners but have been advised against both given our climate. It also appears somewhat difficult to use a portable A/C given the fixed security screen and the need for an external vent – can it me reversibly modified somehow? I find no other appropriate option and am a bit of a deadlock. Advice?</p>
    </div>
  </content>
</entry>
<entry>
  <title>Why Functional Programming Matters in short prose</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/why-functional-programming-matters-in-short-prose/index.html"/>
  <id>http://blog.tmorris.net/posts/why-functional-programming-matters-in-short-prose/index.html</id>
  <published>2008-11-30T11:35:51Z</published>
  <updated>2008-11-30T11:35:51Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://www.md.chalmers.se/~rjmh/Papers/whyfp.html">Why Functional Programming Matters</a> paraphrased – a result of a discussion in an IRC channel. Others may find value.</p>
<p>A program may be represented as a function that accepts some input and produces some outputλ This function may be composed of parts; other functions and values.</p>
<p>Suppose any function that exists. I will suppose one that is made of parts A, B, C and D. I might denote this A ∘ B ∘ C ∘ D. Now suppose you desire a function that is made of parts A, B, C and E. Then the effort required for your function should be proportional to the effort required for E alone.</p>
<p>The closer you are to achieving this objective for any function, the closer you are to the essence of (pure) functional programming. This exists independently of the programming language, though programming languages will vary significantly in the degree to which they accommodate this objective.</p>
<p>Imperative programming – specifically the scope of a destructive update – is the anti-thesis of this objective.</p>
    </div>
  </content>
</entry>
<entry>
  <title>ObserveFunctorMonad</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/observefunctormonad/index.html"/>
  <id>http://blog.tmorris.net/posts/observefunctormonad/index.html</id>
  <published>2008-11-30T18:58:51Z</published>
  <updated>2008-11-30T18:58:51Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>An exercise arising from an IRC discussion in #scala:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">    <span class="kw">trait</span> Functor[F[_]] {
      <span class="kw">def</span> fmap[A, B](fa: F[A], f: A =&gt; B): F[B]
    }
    
    <span class="kw">trait</span> Monad[M[_]] {
      <span class="kw">def</span> bind[A, B](ma: M[A], f: A =&gt; M[B]): M[B]
      <span class="kw">def</span> pure[A](a: A): M[A]
    }
    
    <span class="kw">object</span> ObserveFunctorMonad {
      <span class="kw">def</span> observe[K[_]](m: Monad[K]): Functor[K] = <span class="fu">error</span>(<span class="st">&quot;your homework&quot;</span>)
    }</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Mount Mee State Forest Campgrounds</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/mount-mee-state-forest-campgrounds/index.html"/>
  <id>http://blog.tmorris.net/posts/mount-mee-state-forest-campgrounds/index.html</id>
  <published>2008-11-29T20:52:51Z</published>
  <updated>2008-11-29T20:52:51Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I am an avid GPS user and I visit <a href="http://www.epa.qld.gov.au/projects/park/index.cgi?parkid=63">Mount Mee State Forest</a> regularly on my dirt bike (Husqvarna TE450). I encounter queries on forums for the locations of <a href="http://www.epa.qld.gov.au/parks_and_forests/find_a_park_or_forest/mount_mee_state_forest_and_forest_reserve__camping_information/">the campgrounds in this forest</a>, so here they are:</p>
<p>Neurum Creek Campground -27.061853° 152.696228° <em>-27°03’42.67&quot; 152°41’46.42&quot;</em></p>
<p>Archer Campground -27.016317° 152.697767° <em>-27°00’58.74&quot; 152°41’51.96&quot;</em></p>
<p>You can get to Neurum Creek Campground by taking <a href="http://maps.google.com/maps?f=q&amp;hl=en&amp;geocode=&amp;q=sellin+road+dayboro+queensland&amp;sll=35.338111,-81.860311&amp;sspn=0.013181,0.027874&amp;ie=UTF8&amp;ll=-27.182835,152.815747&amp;spn=0.007187,0.013937&amp;z=17">Sellin Road</a> then turning onto Neurum Creek Road and following it north. Archer Campground can be found by taking Sellin Road then Lovedays Road, however, it is easier to approach from the north side of the forest and head south. Both of these campgrounds require a permit through the Environmental Protection Agency (EPA) or you can <a href="https://www.epa.qld.gov.au/parks/iaparks/gds/IAGDS050.jsp?quickParkId=3">book online</a>.</p>
<p>There is another campground called <a href="http://www.ncbr.com.au/">Neurum Creek Bush Retreat</a> but this is a <strong>different</strong> campground to those two mentioned. It is privately owned and I have personally stayed a weekend there and recommend it, especially if you have children or want a weekend of dirt bike riding (though the operators are understandably strict about noise control) since you can head south into Mount Mee State Forest or head over to <a href="http://www.epa.qld.gov.au/projects/park/index.cgi?parkid=7">Beerburrum State Forest</a>. This campground is even further north of the state forest than the other two (which are situated in the forest boundaries), but is a short ride on gravel to the forest entrance.</p>
<p><a href="http://projects.tmorris.net/public/maps/gpx/Mount%20Mee%20State%20Forest.gpx">Here</a> is a reasonably comprehensive GPX file of Mount Mee State Forest including the two campgrounds and many dirt trails. I’d upload it to OpenStreetMap but I have yet to figure that out.</p>
<p>I use a <a href="https://buy.garmin.com/shop/shop.do?pID=309#gpsmap60cx">Garmin 60Cx</a> unit.</p>
<p>I hope this helps ;)</p>
<p><em>Update: I have uploaded all tracks to OSM <a href="http://blog.tmorris.net/mount-mee-state-forest/">See here</a></em></p>
    </div>
  </content>
</entry>
<entry>
  <title>Clean-up resource with Scala</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/clean-up-resource-with-scala/index.html"/>
  <id>http://blog.tmorris.net/posts/clean-up-resource-with-scala/index.html</id>
  <published>2008-11-17T16:14:55Z</published>
  <updated>2008-11-17T16:14:55Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <blockquote>
<p><code>Nov 17 15:48:39 &lt;jinok&gt;</code> i hate wasting vertical space declaring vals that i need to initialize outside of a try block so i can clean them up in a finally block <code>Nov 17 15:48:53 &lt;jinok&gt;</code> so i’ve started doing the initialization using lazy vals.</p>
</blockquote>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">sealed</span> <span class="kw">trait</span> Resource[+T] {
  <span class="kw">val</span> value: T
  <span class="kw">def</span> close: Unit

  <span class="kw">def</span> use[X](f: T =&gt; X) = <span class="kw">try</span> { <span class="fu">f</span>(value) } <span class="kw">finally</span> { close }
}

<span class="kw">import</span> java.<span class="fu">io</span>.<span class="fu">InputStream</span>

<span class="kw">object</span> Resource {
  <span class="kw">def</span> resource[T](t: T, c: =&gt; Unit) = <span class="kw">new</span> Resource[T] {
    <span class="kw">val</span> value = t
    <span class="kw">def</span> close = c
  }

  <span class="kw">implicit</span> <span class="kw">def</span> <span class="fu">InputStreamResource</span>(t: InputStream) = <span class="fu">resource</span>(t, t.<span class="fu">close</span>)
}

<span class="kw">object</span> Example {
  <span class="kw">import</span> Resource.<span class="fu">_</span>

  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]) {
    <span class="kw">val</span> in = <span class="kw">new</span> java.<span class="fu">io</span>.<span class="fu">FileInputStream</span>(<span class="st">&quot;/etc/passwd&quot;</span>)
    <span class="co">// print the first character of /etc/passwd</span>
    <span class="fu">println</span>(in <span class="fu">use</span> (_.<span class="fu">read</span>.<span class="fu">toChar</span>))
  }
}</code></pre>
<p>Reader’s exercise: <code>Resource</code> is a functor and monad. Implement the <code>map</code> and <code>flatMap</code> methods. Observe trickiness and ask why?</p>
    </div>
  </content>
</entry>
<entry>
  <title>Agile is falling, like religions do</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/agile-is-falling-like-religions-do/index.html"/>
  <id>http://blog.tmorris.net/posts/agile-is-falling-like-religions-do/index.html</id>
  <published>2008-11-16T07:32:02Z</published>
  <updated>2008-11-16T07:32:02Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Re: Comments on <a href="http://jamesshore.com/Blog/The-Decline-and-Fall-of-Agile.html">http://jamesshore.com/Blog/The-Decline-and-Fall-of-Agile.html</a></p>
<p>For example</p>
<blockquote>
<p>Well, okay, but Agile is starting to sound a lot more like religious rhetoric than an engineering practice.</p>
</blockquote>
<p>and</p>
<blockquote>
<p><em>Insert compelling argument here.</em> It is a religion.</p>
</blockquote>
<p>Agile is not a religion, however, both Agile and religions are non-ideas. Also referred to as the third value of the propositional truth trichotomy, “not even false”, non-terminating computation, the bottom value, unfalsifiable, or if you prefer, outright nonsense. All religions and Agile (and Scrum and REST and SOA and… need I go on?) fall into this broader category. It might be healthy to call this category “religion”, but many observers - at least in my dealings - won’t understand why you have shifted to this consistent definition.</p>
<p>Hitherto Agile and religions exhibit common traits; ill-definition (you know the <strong>real</strong> Agile or are you a real Muslim?), sub-cultures in conflict (religion implies war), extreme absurdity in contrast to a mild absurdity (an invisible sky daddy watching everything we do, whose son died for sins…), cult leaders able to alter the course of the flock and cognitive dissonance - holding two otherwise immediately apparent logically contradicting positions at once.</p>
<p>I’m happy to hear this pseudo-science is falling - its absence is an improvement for the industry and the quality of software development. However, the concern is that it will be replaced by another non-concept for the scientific-illiterates to sustain their well-intentioned misguidance.</p>
<p>History tells us that its downfall is not an improvement. After all, what was immediately before the current Abrahamic false ideas? The creation of the universe and therefore, the first religions? No, I don’t think so either - I don’t think anybody does :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>IntelliJ IDEA 8.0 + Scala turns the tide</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/intellij-idea-80-scala-turns-the-tide/index.html"/>
  <id>http://blog.tmorris.net/posts/intellij-idea-80-scala-turns-the-tide/index.html</id>
  <published>2008-11-07T09:42:55Z</published>
  <updated>2008-11-07T09:42:55Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I have a couple of whining rants on here about the ineptitude of the IntelliJ IDEA Early Access Program releases and the Scala plugin. It was, at that time, quite unusable, which is fine on its own, but I was concerned by the fact that the number and magnitude of the workarounds was increasing over time.</p>
<p>I am pleased to report that my preliminary use of the recently released IntelliJ IDEA 8.0 and the Scala plugin appears to require significantly less workarounds to the degree that it is now usable. In fact, it is more usable than it has been in a long time.</p>
<p>Myself and at least one other person were initially tricked into believing that there was no Scala plugin available because it was not listed in the Available plugins. There was however, a “Scala Application runner” plugin available. Installing this also installs the Scala plugin.</p>
<p>Unless I am making a judgment too early, I consider IntelliJ IDEA to have redeemed itself from my earlier complaints and I am thankful to the JetBrains team for making it so (with little/no effort on my part).</p>
<p>Interestingly, I note that JetBrains are considering adding automated specification testing and make a reference to ScalaCheck in <a href="http://plugins.intellij.net/plugin/?id=1347">this discussion</a>. I wonder if they are aware of <a href="http://functionaljava.org/">this alternative (Functional Java)</a> that does the same with a more comprehensive library and also able to be used from standard Java.</p>
<p>Thanks for listening to my whining earlier and thanks to JetBrains for making smooth development with Scala possible :)</p>
<p>Edit: Except this same old bug is still there (it has been there for months) when expanding some source trees (I know I’m not the only one to experience this):</p>
<pre><code>Error during dispatching of java.awt.event.MouseEvent[MOUSE_PRESSED,(118,350),absolute(114,375),button=1,modifiers=Button1,extModifiers=Button1,clickCount=1] on frame0
java.lang.StackOverflowError
	at com.intellij.psi.impl.CachedValueImpl.a(CachedValueImpl.java:1)
	at com.intellij.psi.impl.CachedValueImpl.a(CachedValueImpl.java:70)
	at com.intellij.psi.impl.CachedValueImpl.a(CachedValueImpl.java:3)
	at com.intellij.psi.impl.CachedValueImpl.a(CachedValueImpl.java:104)
	at com.intellij.psi.impl.CachedValueImpl.getValue(CachedValueImpl.java:41)</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>The State Monad for Scala users</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/the-state-monad-for-scala-users/index.html"/>
  <id>http://blog.tmorris.net/posts/the-state-monad-for-scala-users/index.html</id>
  <published>2008-11-03T12:55:14Z</published>
  <updated>2008-11-03T12:55:14Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://wiki.workingmouse.com/index.php/Scalaz">Scalaz 3.2</a> includes support for a State data type for the <a href="http://scala-lang.org/">Scala Programming Language</a>. This data type is a monad and thus supports <code>flatMap</code> and can be used in a for-comprehension.</p>
<p>Below I will give a practical demonstration of why you might choose to use the State data type as a monad.</p>
<p>Consider a binary leaf tree data type:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">sealed</span> <span class="kw">abstract</span> <span class="kw">class</span> Tree[+A]
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">class</span> Leaf[A](a: A) <span class="kw">extends</span> Tree[A]
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">class</span> Branch[A](left: Tree[A], right: Tree[A]) <span class="kw">extends</span> Tree[A]</code></pre>
<p>This is pretty simple so far. Now suppose we wanted to map a function across a <code>Tree</code> from left to right <strong>where the result depended on the previous result</strong>. For this example, consider that we wanted to number each leaf by adding 1 as we traverse left to right (at a given starting value). That is, the result depends on the previous result because we must add 1 to that previous result.</p>
<p>We might implement this by passing in the integer value and returning the pair of the <code>Tree</code> as it is constructed and the integer value as it increments. Such an implementation might look like this:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">sealed</span> <span class="kw">abstract</span> <span class="kw">class</span> Tree[+A] {
  <span class="kw">def</span> <span class="fu">number</span>(seed: Int): (Tree[(A, Int)], Int) = <span class="kw">this</span> <span class="kw">match</span> {
    <span class="kw">case</span> <span class="fu">Leaf</span>(x) =&gt; (<span class="fu">Leaf</span>(x, seed), seed + <span class="dv">1</span>)
    <span class="kw">case</span> <span class="fu">Branch</span>(left, right) =&gt; left number seed <span class="kw">match</span> {
      <span class="kw">case</span> (l, ls) =&gt; {
        right number ls <span class="kw">match</span> {
          <span class="kw">case</span> (r, rs) =&gt; (<span class="fu">Branch</span>(l, r), rs)
        }
      }
    }
  }
}</code></pre>
<p>This code is pretty messy and it would become even messier with a less trivial example to apply across the <code>Tree</code>.</p>
<p>The <code>State</code> data type is effectively a <code>Function[S, (S, A)]</code> and the monad instance runs across the <code>Function[_, (_, A)]</code> part. That is to say, the <code>flatMap</code> signature looks roughly like this:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> State[S, A] {
  <span class="kw">val</span> s: Function[S, (S, A)] <span class="co">// abstract</span>
  <span class="kw">def</span> flatMap[B](f: A =&gt; Function[S, (S, B)]): Function[S, (S, B)]
}</code></pre>
<p>You might consider filling out this method signature for fun :)</p>
<p>The <code>flatMap</code> function allows the user to make the state change implicit rather than explicit (and messy!). The <code>State</code> data type includes a few useful methods and functions. I will only use two of those functions below; <code>init</code>, which constructs a <code>State</code> object that has computed the state itself. For example, going with the analogy to <code>Function[S, (S, A)]</code>, the <code>init</code> function looks like this: <code>s =&gt; (s, s)</code> and so returns a <code>State[S, S]</code>. The second function is <code>modify</code>, which applies a transform the state and it is intended to ignore the computed value (<code>Unit</code>).</p>
<p>Here is our new implementation:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">import</span> scalaz.<span class="fu">State</span>
<span class="kw">import</span> scalaz.<span class="fu">State</span>.<span class="fu">_</span>

<span class="kw">def</span> numbers: State[Int, Tree[(A, Int)]] = <span class="kw">this</span> <span class="kw">match</span> {
  <span class="kw">case</span> <span class="fu">Leaf</span>(x) =&gt; <span class="kw">for</span>(s &lt;- init[Int];
                      n &lt;- <span class="fu">modify</span>((_: Int) + <span class="dv">1</span>))
                  <span class="kw">yield</span> <span class="fu">Leaf</span>((x, s + <span class="dv">1</span>))
  <span class="kw">case</span> <span class="fu">Branch</span>(left, right) =&gt; <span class="kw">for</span>(l &lt;- left.<span class="fu">numbers</span>;
                                  r &lt;- right.<span class="fu">numbers</span>)
                              <span class="kw">yield</span> <span class="fu">Branch</span>(l, r)
}</code></pre>
<p>This is much neater and hides the otherwise explicit recursive application of adding 1 to an integer. Following is a complete source file that can be compiled successfully against Scalaz 3.2 using the latest version of Scala.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">sealed</span> <span class="kw">abstract</span> <span class="kw">class</span> Tree[+A] {
  <span class="kw">def</span> <span class="fu">number</span>(seed: Int): (Tree[(A, Int)], Int) = <span class="kw">this</span> <span class="kw">match</span> {
    <span class="kw">case</span> <span class="fu">Leaf</span>(x) =&gt; (<span class="fu">Leaf</span>(x, seed), seed + <span class="dv">1</span>)
    <span class="kw">case</span> <span class="fu">Branch</span>(left, right) =&gt; left number seed <span class="kw">match</span> {
      <span class="kw">case</span> (l, ls) =&gt; {
        right number ls <span class="kw">match</span> {
          <span class="kw">case</span> (r, rs) =&gt; (<span class="fu">Branch</span>(l, r), rs)
        }
      }
    }
  }

  <span class="kw">import</span> scalaz.<span class="fu">State</span>
  <span class="kw">import</span> scalaz.<span class="fu">State</span>.<span class="fu">_</span>

  <span class="kw">def</span> numbers: State[Int, Tree[(A, Int)]] = <span class="kw">this</span> <span class="kw">match</span> {
    <span class="kw">case</span> <span class="fu">Leaf</span>(x) =&gt; <span class="kw">for</span>(s &lt;- init[Int];
                        n &lt;- <span class="fu">modify</span>((_: Int) + <span class="dv">1</span>))
                    <span class="kw">yield</span> <span class="fu">Leaf</span>((x, s + <span class="dv">1</span>))
    <span class="kw">case</span> <span class="fu">Branch</span>(left, right) =&gt; <span class="kw">for</span>(l &lt;- left.<span class="fu">numbers</span>;
                                    r &lt;- right.<span class="fu">numbers</span>)
                                <span class="kw">yield</span> <span class="fu">Branch</span>(l, r)
  }
}
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">class</span> Leaf[A](a: A) <span class="kw">extends</span> Tree[A]
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">class</span> Branch[A](left: Tree[A], right: Tree[A]) <span class="kw">extends</span> Tree[A]</code></pre>
<p>And if you find Haskell easier to read, this might help too. It is a roughly equivalent program using GHC’s built-in <code>State</code> data type.</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">import</span> <span class="dt">Control.Monad.State.Lazy</span>

<span class="kw">data</span> <span class="dt">Tree</span> a <span class="fu">=</span> <span class="dt">Leaf</span> a <span class="fu">|</span> <span class="dt">Branch</span> (<span class="dt">Tree</span> a) (<span class="dt">Tree</span> a)

<span class="ot">number ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Tree</span> a <span class="ot">-&gt;</span> (<span class="dt">Tree</span> (a, <span class="dt">Int</span>),<span class="dt">Int</span>)
number seed (<span class="dt">Leaf</span> a) <span class="fu">=</span> (<span class="dt">Leaf</span> (a, seed), seed <span class="fu">+</span> <span class="dv">1</span>)
number seed (<span class="dt">Branch</span> left right)
 <span class="fu">=</span> <span class="kw">let</span> (l, ls) <span class="fu">=</span> number seed left
       (r, rs) <span class="fu">=</span> number ls right
   <span class="kw">in</span>
       (<span class="dt">Branch</span> l r, rs)

<span class="ot">numbers ::</span> <span class="dt">Tree</span> a <span class="ot">-&gt;</span> <span class="dt">State</span> <span class="dt">Int</span> (<span class="dt">Tree</span> (a, <span class="dt">Int</span>))
numbers (<span class="dt">Leaf</span> a) <span class="fu">=</span> <span class="kw">do</span> n <span class="ot">&lt;-</span> get
                      modify (<span class="fu">+</span><span class="dv">1</span>)
                      <span class="fu">return</span> (<span class="dt">Leaf</span> (a, n))

numbers (<span class="dt">Branch</span> l r) <span class="fu">=</span> <span class="kw">do</span> left <span class="ot">&lt;-</span> numbers l
                          right <span class="ot">&lt;-</span> numbers r
                          <span class="fu">return</span> (<span class="dt">Branch</span> left right)

<span class="ot">initState ::</span> <span class="dt">State</span> s s
initState <span class="fu">=</span> <span class="dt">State</span> (\s <span class="ot">-&gt;</span> (s, s))</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>One of your best Pat</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/one-of-your-best-pat/index.html"/>
  <id>http://blog.tmorris.net/posts/one-of-your-best-pat/index.html</id>
  <published>2008-11-01T07:41:12Z</published>
  <updated>2008-11-01T07:41:12Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Well done. Keep it up.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Intellij + Scala; it is with great regret...</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/intellij-scala-it-is-with-great-regret/index.html"/>
  <id>http://blog.tmorris.net/posts/intellij-scala-it-is-with-great-regret/index.html</id>
  <published>2008-10-30T14:18:58Z</published>
  <updated>2008-10-30T14:18:58Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Sadly, despite <a href="http://blog.tmorris.net/intellij-idea-scala-utterly-unusable/">my expressed hopes</a>, in appears the state of Intellij IDEA with Scala is not improving but worsening. This is sad. Each time you start up IDEA you still get a lovely internal error and exception stack trace. But worse, ever since the 8890 EAP build, the application hangs with any reasonably sized Scala project. This is even more sad. A colleague has confirmed this on his Mac, however, we are unable to revert to a usable version since you cannot download older EAP releases.</p>
<p>The suspected trend toward becoming more unusable for Intellij IDEA and Scala is regrettably confirmed. I wish it were not so ):</p>
<p>The Windows Vista upgrade to XP effect perhaps?</p>
    </div>
  </content>
</entry>
<entry>
  <title>Java/Ruby does not generalise to static/dynamic</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/javaruby-does-not-generalise-to-staticdynamic/index.html"/>
  <id>http://blog.tmorris.net/posts/javaruby-does-not-generalise-to-staticdynamic/index.html</id>
  <published>2008-10-16T06:44:54Z</published>
  <updated>2008-10-16T06:44:54Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>So you were once a Java fanboy and now you’ve apostatised to the Ruby cult. Now you believe you hold veritable opinions about “statically typed languages” and “dynamically typed languages”. How wrong you are.</p>
<p>Java is not representative of static type systems, not even a bit. It lacks some of the most basic features of a static type system. It might even be said that its static type system imposes some of the most impractical insanity that could possibly be conceived. Why do I think this? <a href="http://functionaljava.org/">Because I have pushed Java’s static type system to its limits</a> and relative to its peers, it fails miserably. I’ve seen the language inside-out. I used to work on the JDK implementation for a certain corporation (of questionable ethical standards). I even have the spanky Sun Java Programmer/Developer certifications. Yes I have been drowned in Java Jolly Junkie bullshit and revived.</p>
<p>So you use Ruby eh? It allows you to express things that Java was too rigid to allow, right? That doesn’t mean a thing about static type systems, right? RIGHT?</p>
<p>When you use Java and Ruby as the example for static and dynamic type systems, I am reminded of my children who compare the flight of their scrunched up pieces of paper… er highly aerodynamic, radar-resistant aircraft (sorry boys). Hopefully some day they will learn what a wind tunnel is and what it takes to engineer a fighter-aircraft. Will you?</p>
<p>This kind of enthusiasm is to be encouraged – if you are 6 years old – but you are not, so you just look like you are in an adult’s body. No really, you do. This might be fine with you (who am I to judge?), but if it is not, it might help to know <a href="http://www.pphsg.org/cdsmith/types.html">What to Know Before Debating Type Systems</a>. Just a thought – there is plenty of other information available should you desire to seek it, just drop me a line.</p>
<p>Here are some tips to get started; static typing and explicit type annotating are two very different things. Don’t use the two notions interchangeably – not even loosely. Dynamically-typed languages do not produce shorter code, this is a myth. In fact, what constitutes shorter code is often misunderstood – certainly by Ruby (and Python, Groovy for that matter) advocates that I have encountered. I’m tempted to dispense with this myth with a challenge, but I’m not sure if I can be bothered (I have a life outside of whinging on my blog you know). It would also fail to do the topic justice. An entire discussion on what constitutes shorter code is in order.</p>
<p>For the love of GADTs, in the meantime, please stop talking nonsense about static and dynamic type systems. It only serves to hurt other potential learners by perpetuating misinformation. Myths spread by repetition – be honest and break the cycle.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Does Scala have Java's ternary operator?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/does-scala-have-javas-ternary-operator/index.html"/>
  <id>http://blog.tmorris.net/posts/does-scala-have-javas-ternary-operator/index.html</id>
  <published>2008-10-13T18:29:41Z</published>
  <updated>2008-10-13T18:29:41Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I hear this question a lot. Yes it does. Instead of <code>c ? p : q</code>, it is written <code>if(c) p else q</code>.</p>
<p>This may not be preferable. Perhaps you’d like to write it using the same syntax as Java. Sadly, you can’t. This is because <code>:</code> is not a valid identifier. Fear not, <code>|</code> is! Would you settle for this?</p>
<pre class="sourceCode Java"><code class="sourceCode java">c ? p | q</code></pre>
<p>Then you’ll need the following code. Notice the call-by-name (<code>=&gt;</code>) annotations on the arguments. This evaluation strategy is required to correctly rewrite Java’s ternary operator. This cannot be done in Java itself.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">case</span> <span class="kw">class</span> <span class="fu">Bool</span>(b: Boolean) {
  <span class="kw">def</span> ?[X](t: =&gt; X) = <span class="kw">new</span> {
    <span class="kw">def</span> |(f: =&gt; X) = <span class="kw">if</span>(b) t <span class="kw">else</span> f
  }
}

<span class="kw">object</span> Bool {
  <span class="kw">implicit</span> <span class="kw">def</span> <span class="fu">BooleanBool</span>(b: Boolean) = <span class="fu">Bool</span>(b)
}</code></pre>
<p>Here is an example using the new operator that we just defined:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> T {
  <span class="kw">val</span> condition = <span class="kw">true</span>

  <span class="kw">import</span> Bool.<span class="fu">_</span>

  <span class="co">// yay!</span>
  <span class="kw">val</span> x = condition ? <span class="st">&quot;yes&quot;</span> | <span class="st">&quot;no&quot;</span>
}</code></pre>
<p>Have fun ;)</p>
    </div>
  </content>
</entry>
<entry>
  <title>Project Euler Problem 2 Functional Java</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/project-euler-problem-2-functional-java/index.html"/>
  <id>http://blog.tmorris.net/posts/project-euler-problem-2-functional-java/index.html</id>
  <published>2008-10-03T14:04:43Z</published>
  <updated>2008-10-03T14:04:43Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://projecteuler.net/index.php?section=problems&amp;id=2">Project Euler Problem 2</a> using <a href="http://functionaljava.org/">Functional Java</a>:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">import fj.data.Stream;</span>
<span class="kw">import fj.P1;</span>
<span class="kw">import fj.F2;</span>
<span class="kw">import static fj.function.Integers.even;</span>
<span class="kw">import static fj.pre.Ord.intOrd;</span>
<span class="kw">import static fj.pre.Monoid.intAdditionMonoid;</span>
<span class="kw">import static fj.data.Stream.cons;</span>
<span class="kw">import static fj.Function.curry;</span>

...

Stream&lt;integer&gt; fibs = <span class="kw">new</span> F2&lt;Integer, Integer, Stream&lt;integer&gt;&gt;() {
  <span class="kw">public</span> Stream&lt;integer&gt; <span class="fu">f</span>(<span class="dt">final</span> Integer a, <span class="dt">final</span> Integer b) {
    <span class="kw">return</span> <span class="fu">cons</span>(a, P1.<span class="fu">curry</span>(<span class="fu">curry</span>(<span class="kw">this</span>).<span class="fu">f</span>(b)).<span class="fu">f</span>(a + b));
  }
}.<span class="fu">f</span>(<span class="dv">1</span>, <span class="dv">2</span>);

<span class="dt">final</span> <span class="dt">int</span> problem2 = intAdditionMonoid.<span class="fu">sumLeft</span>(fibs.<span class="fu">takeWhile</span>(intOrd.<span class="fu">isLessThan</span>(<span class="dv">1000001</span>)).<span class="fu">filter</span>(even).<span class="fu">toList</span>());</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Project Euler Problem 1 Functional Java</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/project-euler-problem-1-functional-java/index.html"/>
  <id>http://blog.tmorris.net/posts/project-euler-problem-1-functional-java/index.html</id>
  <published>2008-10-03T13:59:39Z</published>
  <updated>2008-10-03T13:59:39Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://projecteuler.net/index.php?section=problems&amp;id=1">Project Euler Problem 1</a> using <a href="http://functionaljava.org/">Functional Java</a>:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">import static fj.pre.Monoid.intAdditionMonoid;</span>
<span class="kw">import static fj.data.List.range;</span>
<span class="kw">import fj.F;</span>

...

<span class="dt">final</span> <span class="dt">int</span> problem1 = intAdditionMonoid.<span class="fu">sumLeft</span>(<span class="fu">range</span>(<span class="dv">0</span>, <span class="dv">1000</span>).<span class="fu">filter</span>(<span class="kw">new</span> F&lt;Integer, Boolean&gt;() {
  <span class="kw">public</span> Boolean <span class="fu">f</span>(<span class="dt">final</span> Integer a) {
    <span class="kw">return</span> a % <span class="dv">3</span> == <span class="dv">0</span> || a % <span class="dv">5</span> == <span class="dv">0</span>;
  }
}));</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>'Scala: Gotchya!'</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/scala-gotchya/index.html"/>
  <id>http://blog.tmorris.net/posts/scala-gotchya/index.html</id>
  <published>2008-10-01T09:08:01Z</published>
  <updated>2008-10-01T09:08:01Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I have been caught out by type-checking code that fails at runtime. It should have failed at compile-time due to a language limitation in structural types – not a logical absurdity in the code itself. Thankfully I have a workaround, but it does provoke persistent hesitance – giving that disgusting feeling as if I were using something as degenerate as, for example, Ruby or even worse (can it get worse?), Groovy. I’ll have to counsel myself on that one.</p>
<p>Nevertheless, I give warning. Here is the <a href="http://lampsvn.epfl.ch/trac/scala/ticket/1388">bug report</a>. Here is the fun. Observe:</p>
<pre><code>scala&gt; def left[B] = new { def apply[A](a: A): Either[A, B] = Left(a) }
left: [B]java.lang.Object{def apply[A](A): Either[A,B]}

scala&gt; left[String](7)
res6: Either[Int,String] = Left(7)

scala&gt; def left[B] = new { def apply[A](a: A, b: B): Either[A, B] = Left(a) }
left: [B]java.lang.Object{def apply[A](A,B): Either[A,B]}

scala&gt; left(7, &quot;&quot;)
res8: Either[Int,java.lang.String] = Left(7)

scala&gt; left[String](7, &quot;&quot;)
java.lang.NoSuchMethodException: $anon$1.apply(java.lang.Object, java.lang.String)
        at java.lang.Class.getMethod(Class.java:1605)
        at .reflMethod$Method1(&lt;console&gt;:6)
        at .&lt;init&gt;(&lt;console&gt;:6)
        at .&lt;clinit&gt;(&lt;console&gt;)
        at RequestResult$.&lt;init&gt;(&lt;console&gt;:3)
        at RequestResult$.&lt;clinit&gt;(&lt;console&gt;)
        at RequestResult$result(&lt;console&gt;)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native ...</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>IntelliJ IDEA whinge</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/intellij-idea-whinge/index.html"/>
  <id>http://blog.tmorris.net/posts/intellij-idea-whinge/index.html</id>
  <published>2008-09-26T08:52:59Z</published>
  <updated>2008-09-26T08:52:59Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>An update on <a href="http://blog.tmorris.net/intellij-idea-scala-utterly-unusable/">IntelliJ IDEA + Scala utterly unusable</a></p>
<ol style="list-style-type: decimal">
<li><p>Delete ~/.IntelliJIdea80 (oh well, I’m so used to specifying my settings over and over anyway).</p></li>
<li><p>Start IntelliJ IDEA. <strong>Do not open a project</strong></p></li>
<li><p>Install the Scala plugin</p></li>
<li><p>Open your project</p></li>
<li><p>Observe not-useless usability</p>
<ol style="list-style-type: decimal">
<li><p>There are still issues of not being able to open certain source folders (try it and see for yourself <code>scalaz.control</code> in Scalaz trunk)</p></li>
<li><p>Other minor annoyances that needn’t be mentioned</p></li>
</ol></li>
</ol>
<p>I have repeated this twice on different machines (8823). Swapping steps 3 and 4 result in a rapid degeneration of usefulness to the point of absolute uselessness.</p>
<p>Thanks again for listening. I hope the usability trend reverses.</p>
    </div>
  </content>
</entry>
<entry>
  <title>IntelliJ IDEA + Scala utterly unusable</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/intellij-idea-scala-utterly-unusable/index.html"/>
  <id>http://blog.tmorris.net/posts/intellij-idea-scala-utterly-unusable/index.html</id>
  <published>2008-09-24T09:34:48Z</published>
  <updated>2008-09-24T09:34:48Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>It seems that IntelliJ IDEA 8.0 EAP and its Scala plugin have reached the point of being completely unusable. This is such a shame given that there are no existing viable alternatives (don’t say Eclipse and expect me to keep a straight face). I guess it will be emacs or Kate in the future.</p>
<p>The last few EAP releases crash the IDE when you expand some source trees resulting in a perpetual wait icon. I receive a dialog about submitting the bug and I have done, three times. The last two EAP releases (8823 and 8810) don’t allow me to install the Scala plugin at all. Upon restart, the IDE is unaware that the Scala plugin has even been installed. As a result, I have to use 8664, which my trial is due to expire any time soon.</p>
<p>The IDE constantly gives me false errors (surely it is not difficult to download the Scalaz source and observe the IDE complaining about errors that do not exist?). The IDE causes a segmentation fault if I use the Sun JDK 1.6.0_07 and I receive an UnspportedClassVersionError if I use version 1.5, so I am forced to use 1.6.0_10. The IDE is barely responsive on a 3.2GHz machine with 1.5GB memory and it doesn’t even align scaladoc comments properly as you write them. I am constantly manually fixing up indentation in the source code.</p>
<p>With so many elementary failures, I think any reasonable person would concede that IntelliJ IDEA is as unusable as Eclipse. That ends my whinge; thanks for listening.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Did you to have be so blunt?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/did-you-to-have-be-so-blunt/index.html"/>
  <id>http://blog.tmorris.net/posts/did-you-to-have-be-so-blunt/index.html</id>
  <published>2008-09-23T20:18:28Z</published>
  <updated>2008-09-23T20:18:28Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://realtimecollisiondetection.net/blog/?p=81">http://realtimecollisiondetection.net/blog/?p=81</a></p>
<p>My favourites:</p>
<blockquote>
<p>In contrast, design patterns are purported “master programmer advice” strongly suggesting to young or otherwise impressionable programmers that the design patterns convey important concepts, practices, or principles that have been “prethought.” However, design patterns are not “master programmer advice!”</p>
</blockquote>
<blockquote>
<p>Far from “master programmers,” design patterns are the work of people who do conferences, talks, and books for a living, to further their own cause</p>
</blockquote>
<p>And the clincher:</p>
<blockquote>
<p>Design patterns are spoonfeed material for brainless programmers incapable of independent thought, who will be resolved to producing code as mediocre as the design patterns they use to create it.</p>
</blockquote>
<p>I’m sure you knew you’d be standing on toes, despite the the overwhelmingly defensible truth value of your statements. Don’t adjust your sight Christer, it’s dead on target ;)</p>
    </div>
  </content>
</entry>
<entry>
  <title>Partially Applying Scala type variables</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/partially-applying-scala-type-variables/index.html"/>
  <id>http://blog.tmorris.net/posts/partially-applying-scala-type-variables/index.html</id>
  <published>2008-09-22T12:57:36Z</published>
  <updated>2008-09-22T12:57:36Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Below is a neat trick that others may find useful when designing APIs using the Scala programming language.</p>
<p>Scala’s type inferencer is not as clever as some. As a result, we often find ourselves explicitly annotating type variables in certain contexts. This can become a little annoying, but what is worse, is if you have a type variable list and only one of those requires explicit specification, the others must also be explicitly specified even though they would have otherwise been inferred.</p>
<p>Let me demonstrate. I will use Scala’s higher-kinds, which are never inferred (this is quite acceptable given the problems associated with inferring higher-kinds – consider Java and C# where they do not even exist, thus leading to an enormous repetitive chore) though other examples may be applicable. However, it can be annoying if you were to write say, the Monad join function:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">def</span> join[M[_], A](m: M[M[A]]): M[A] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)</code></pre>
<p>A caller invocation might look like:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">val</span> x = join[List, Int](List(List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>), List(<span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>)))</code></pre>
<p>Notice the explicit annotation with the <code>List</code> type constructor, however, the second type variable (<code>Int</code>) must also be explicitly specified, even though it could have otherwise been inferred. This is a bit annoying.</p>
<p>We can do away with it like so:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">def</span> join[M[_]] = <span class="kw">new</span> {
  <span class="kw">def</span> apply[A](m: M[M[A]]): M[A] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)
}</code></pre>
<p>And now the caller code no longer has that clumsy type annotation:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">val</span> x = join[List](List(List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>), List(<span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>)))</code></pre>
<p>Yay! Have a nice day :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>20 Intermediate Haskell Exercises</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/20-intermediate-haskell-exercises/index.html"/>
  <id>http://blog.tmorris.net/posts/20-intermediate-haskell-exercises/index.html</id>
  <published>2008-09-18T07:06:07Z</published>
  <updated>2008-09-18T07:06:07Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">class</span> <span class="dt">Fluffy</span> f <span class="kw">where</span>
<span class="ot">  furry ::</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> f a <span class="ot">-&gt;</span> f b

<span class="co">-- Exercise 1</span>
<span class="co">-- Relative Difficulty: 1</span>
<span class="kw">instance</span> <span class="dt">Fluffy</span> [] <span class="kw">where</span>
  furry <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 2</span>
<span class="co">-- Relative Difficulty: 1</span>
<span class="kw">instance</span> <span class="dt">Fluffy</span> <span class="dt">Maybe</span> <span class="kw">where</span>
  furry <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 3</span>
<span class="co">-- Relative Difficulty: 5</span>
<span class="kw">instance</span> <span class="dt">Fluffy</span> ((<span class="ot">-&gt;</span>) t) <span class="kw">where</span>
  furry <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="kw">newtype</span> <span class="dt">EitherLeft</span> b a <span class="fu">=</span> <span class="dt">EitherLeft</span> (<span class="dt">Either</span> a b)
<span class="kw">newtype</span> <span class="dt">EitherRight</span> a b <span class="fu">=</span> <span class="dt">EitherRight</span> (<span class="dt">Either</span> a b)

<span class="co">-- Exercise 4</span>
<span class="co">-- Relative Difficulty: 5</span>
<span class="kw">instance</span> <span class="dt">Fluffy</span> (<span class="dt">EitherLeft</span> t) <span class="kw">where</span>
  furry <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 5</span>
<span class="co">-- Relative Difficulty: 5</span>
<span class="kw">instance</span> <span class="dt">Fluffy</span> (<span class="dt">EitherRight</span> t) <span class="kw">where</span>
  furry <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="kw">class</span> <span class="dt">Misty</span> m <span class="kw">where</span>
<span class="ot">  banana ::</span> (a <span class="ot">-&gt;</span> m b) <span class="ot">-&gt;</span> m a <span class="ot">-&gt;</span> m b
<span class="ot">  unicorn ::</span> a <span class="ot">-&gt;</span> m a
  <span class="co">-- Exercise 6</span>
  <span class="co">-- Relative Difficulty: 3</span>
  <span class="co">-- (use banana and/or unicorn)</span>
<span class="ot">  furry&#39; ::</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> m a <span class="ot">-&gt;</span> m b
  furry&#39; <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 7</span>
<span class="co">-- Relative Difficulty: 2</span>
<span class="kw">instance</span> <span class="dt">Misty</span> [] <span class="kw">where</span>
  banana <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>
  unicorn <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 8</span>
<span class="co">-- Relative Difficulty: 2</span>
<span class="kw">instance</span> <span class="dt">Misty</span> <span class="dt">Maybe</span> <span class="kw">where</span>
  banana <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>
  unicorn <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 9</span>
<span class="co">-- Relative Difficulty: 6</span>
<span class="kw">instance</span> <span class="dt">Misty</span> ((<span class="ot">-&gt;</span>) t) <span class="kw">where</span>
  banana <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>
  unicorn <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 10</span>
<span class="co">-- Relative Difficulty: 6</span>
<span class="kw">instance</span> <span class="dt">Misty</span> (<span class="dt">EitherLeft</span> t) <span class="kw">where</span>
  banana <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>
  unicorn <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 11</span>
<span class="co">-- Relative Difficulty: 6</span>
<span class="kw">instance</span> <span class="dt">Misty</span> (<span class="dt">EitherRight</span> t) <span class="kw">where</span>
  banana <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>
  unicorn <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 12</span>
<span class="co">-- Relative Difficulty: 3</span>
<span class="ot">jellybean ::</span> (<span class="dt">Misty</span> m) <span class="ot">=&gt;</span> m (m a) <span class="ot">-&gt;</span> m a
jellybean <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 13</span>
<span class="co">-- Relative Difficulty: 6</span>
<span class="ot">apple ::</span> (<span class="dt">Misty</span> m) <span class="ot">=&gt;</span> m a <span class="ot">-&gt;</span> m (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> m b
apple <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 14</span>
<span class="co">-- Relative Difficulty: 6</span>
<span class="ot">moppy ::</span> (<span class="dt">Misty</span> m) <span class="ot">=&gt;</span> [a] <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> m b) <span class="ot">-&gt;</span> m [b]
moppy <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 15</span>
<span class="co">-- Relative Difficulty: 6</span>
<span class="co">-- (bonus: use moppy)</span>
<span class="ot">sausage ::</span> (<span class="dt">Misty</span> m) <span class="ot">=&gt;</span> [m a] <span class="ot">-&gt;</span> m [a]
sausage <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 16</span>
<span class="co">-- Relative Difficulty: 6</span>
<span class="co">-- (bonus: use apple + furry&#39;)</span>
<span class="ot">banana2 ::</span> (<span class="dt">Misty</span> m) <span class="ot">=&gt;</span> (a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> c) <span class="ot">-&gt;</span> m a <span class="ot">-&gt;</span> m b <span class="ot">-&gt;</span> m c
banana2 <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 17</span>
<span class="co">-- Relative Difficulty: 6</span>
<span class="co">-- (bonus: use apple + banana2)</span>
<span class="ot">banana3 ::</span> (<span class="dt">Misty</span> m) <span class="ot">=&gt;</span> (a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> c <span class="ot">-&gt;</span> d) <span class="ot">-&gt;</span> m a <span class="ot">-&gt;</span> m b <span class="ot">-&gt;</span> m c <span class="ot">-&gt;</span> m d
banana3 <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 18</span>
<span class="co">-- Relative Difficulty: 6</span>
<span class="co">-- (bonus: use apple + banana3)</span>
<span class="ot">banana4 ::</span> (<span class="dt">Misty</span> m) <span class="ot">=&gt;</span> (a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> c <span class="ot">-&gt;</span> d <span class="ot">-&gt;</span> e) <span class="ot">-&gt;</span> m a <span class="ot">-&gt;</span> m b <span class="ot">-&gt;</span> m c <span class="ot">-&gt;</span> m d <span class="ot">-&gt;</span> m e
banana4 <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="kw">newtype</span> <span class="dt">State</span> s a <span class="fu">=</span> <span class="dt">State</span> {
<span class="ot">  state ::</span> (s <span class="ot">-&gt;</span> (s, a))
}

<span class="co">-- Exercise 19</span>
<span class="co">-- Relative Difficulty: 9</span>
<span class="kw">instance</span> <span class="dt">Fluffy</span> (<span class="dt">State</span> s) <span class="kw">where</span>
  furry <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 20</span>
<span class="co">-- Relative Difficulty: 10</span>
<span class="kw">instance</span> <span class="dt">Misty</span> (<span class="dt">State</span> s) <span class="kw">where</span>
  banana <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>
  unicorn <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span></code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Amuse yourself</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/amuse-yourself/index.html"/>
  <id>http://blog.tmorris.net/posts/amuse-yourself/index.html</id>
  <published>2008-09-11T06:44:08Z</published>
  <updated>2008-09-11T06:44:08Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>From <a href="http://westernfrontamerica.com/2008/09/08/doom-earth-man-god/">“Never again will I doom the earth because of man…” By: God By J.D. Longstreet</a>.</p>
<p>The argument goes something like this. Man cannot destroy the world, since <a href="http://www.biblegateway.com/passage/?search=genesis%208:21&amp;version=9;">Genesis 8:21</a> says so. Therefore, Global Warming is a conspiracy by scientific illiterates. Yes I cringed in embarrassment too.</p>
<p>Ignoring the scary implications of the prevalence of this kind of superstitious crackpottery, consider the somewhat amusing (I thought so anyway) excerpt below:</p>
<blockquote>
<p>Then they [the Global Warming conspirators] use the guilt trip they have imposed on fellow human beings to shame us into completely altering the way we live. It is the oldest con game in the book. And the peoples of the planet are falling for it.</p>
</blockquote>
<p>I wonder which book that might be :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>20 Intermediate Scala Exercises</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/20-intermediate-scala-exercises/index.html"/>
  <id>http://blog.tmorris.net/posts/20-intermediate-scala-exercises/index.html</id>
  <published>2008-09-10T13:36:45Z</published>
  <updated>2008-09-10T13:36:45Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I will be publishing answers to these exercises as well as the <a href="http://blog.tmorris.net/revised-scala-exercises/">Revised Scala Exercises</a> in the near future. In the meantime, see if you can tackle the exercises below. In almost all cases, the type signature is enough to derive what the implementation should be. In all other cases, the solution is as difficult to derive anyway, so consider it an equivalent achievement.</p>
<p>The source file below compiles, but is missing certain function implementations (where you see <code>error(&quot;todo&quot;)</code>). Enjoy and if you have questions, please feel free to post them :)</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> PartialType[T[_, _], A] {
  <span class="kw">type</span> Apply[B] = T[A, B]
  <span class="kw">type</span> Flip[B] = T[B, A]
}

<span class="kw">trait</span> Fluffy[F[_]] {
  <span class="kw">def</span> furry[A, B](f: A =&gt; B, fa: F[A]): F[B]
}

<span class="kw">object</span> Fluffy {
  <span class="co">// Exercise 1</span>
  <span class="co">// Relative Difficulty: 1</span>
  <span class="kw">def</span> ListFluffy: Fluffy[List] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 2</span>
  <span class="co">// Relative Difficulty: 1</span>
  <span class="kw">def</span> OptionFluffy: Fluffy[Option] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 3</span>
  <span class="co">// Relative Difficulty: 1</span>
  <span class="kw">def</span> StreamFluffy: Fluffy[Stream] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 4</span>
  <span class="co">// Relative Difficulty: 1</span>
  <span class="kw">def</span> ArrayFluffy: Fluffy[Array] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 5</span>
  <span class="co">// Relative Difficulty: 5</span>
  <span class="kw">def</span> Function1Fluffy[X]: Fluffy[PartialType[Function1, X]#Apply] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 6</span>
  <span class="co">// Relative Difficulty: 6</span>
  <span class="kw">def</span> EitherLeftFluffy[X]: Fluffy[PartialType[Either.<span class="fu">LeftProjection</span>, X]#Flip] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 7</span>
  <span class="co">// Relative Difficulty: 4</span>
  <span class="kw">def</span> EitherRightFluffy[X]: Fluffy[PartialType[Either.<span class="fu">RightProjection</span>, X]#Apply] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)
}

<span class="kw">trait</span> Misty[M[_]] <span class="kw">extends</span> Fluffy[M] {
  <span class="kw">def</span> banana[A, B](f: A =&gt; M[B], ma: M[A]): M[B]

  <span class="kw">def</span> unicorn[A](a: A): M[A]

  <span class="co">// Exercise 8</span>
  <span class="co">// Relative Difficulty: 3</span>
  <span class="co">// (use banana and/or unicorn)</span>
  <span class="kw">def</span> furry[A, B](f: A =&gt; B, ma: M[A]): M[B] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)
}

<span class="kw">object</span> Misty {
  <span class="co">// Exercise 9</span>
  <span class="co">// Relative Difficulty: 2</span>
  <span class="kw">def</span> ListMisty: Misty[List] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 10</span>
  <span class="co">// Relative Difficulty: 2</span>
  <span class="kw">def</span> OptionMisty: Misty[Option] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 11</span>
  <span class="co">// Relative Difficulty: 2</span>
  <span class="kw">def</span> StreamMisty: Misty[Stream] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 12</span>
  <span class="co">// Relative Difficulty: 2</span>
  <span class="kw">def</span> ArrayMisty: Misty[Array] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 13</span>
  <span class="co">// Relative Difficulty: 6</span>
  <span class="kw">def</span> Function1Misty[X]: Misty[PartialType[Function1, X]#Apply] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 14</span>
  <span class="co">// Relative Difficulty: 7</span>
  <span class="kw">def</span> EitherLeftMisty[X]: Misty[PartialType[Either.<span class="fu">LeftProjection</span>, X]#Flip] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 15</span>
  <span class="co">// Relative Difficulty: 5</span>
  <span class="kw">def</span> EitherRightMisty[X]: Misty[PartialType[Either.<span class="fu">RightProjection</span>, X]#Apply] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 16</span>
  <span class="co">// Relative Difficulty: 3</span>
  <span class="kw">def</span> jellybean[M[_], A](ma: M[M[A]], m: Misty[M]): M[A] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 17</span>
  <span class="co">// Relative Difficulty: 6</span>
  <span class="kw">def</span> apple[M[_], A, B](ma: M[A], mf: M[A =&gt; B], m: Misty[M]): M[B] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 18</span>
  <span class="co">// Relative Difficulty: 6</span>
  <span class="kw">def</span> moppy[M[_], A, B](as: List[A], f: A =&gt; M[B], m: Misty[M]): M[List[B]] =
    <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)
}

<span class="kw">object</span> AdvancedFun {
  <span class="kw">case</span> <span class="kw">class</span> State[S, A](f: S =&gt; (S, A))

  <span class="co">// Exercise 19</span>
  <span class="co">// Relative Difficulty: 9</span>
  <span class="kw">def</span> StateFluffy[S]: Fluffy[PartialType[State, S]#Apply] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 20</span>
  <span class="co">// Relative Difficulty: 10</span>
  <span class="kw">def</span> StateMisty[S]: Misty[PartialType[State, S]#Apply] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Proving the existence of curry</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/proving-the-existence-of-curry/index.html"/>
  <id>http://blog.tmorris.net/posts/proving-the-existence-of-curry/index.html</id>
  <published>2008-09-05T10:57:44Z</published>
  <updated>2008-09-05T10:57:44Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Prove <code>∀A. ∀B. ∀C. ((A∧B)→C)→A→B→C</code> with a truth table.</p>
<p>WTF does that mean? It means that for any three propositions (A, B, C), then the conjunction (logical AND) of A and B implies C implies A implies B implies C. Note that → is right-associative, so X→Y→Z is the same as X→(Y→Z). If you are unfamiliar with denotational semantics (these crazy symbols), then perhaps this more relaxed notation makes sense <code>forall A B C. ((A, B) -&gt; C) -&gt; A -&gt; B -&gt; C</code>. Remember this notation, because we will use it later.</p>
<p>Here are some truth tables for conjunction and implication to get started:</p>
<pre><code>Conjunction
P  Q  P∧Q
0  0  0
0  1  0
1  0  0
1  1  1

Implication
P  Q  P→Q
0  0  1
0  1  1
1  0  0
1  1  1</code></pre>
<p>We can prove the truth of the above statement by observing a tautology (all true values) in a truth table.</p>
<pre><code>1  2  3  4    5        6    7      8

A  B  C  A∧B  (A∧B)→C  B→C  A→B→C  ((A∧B)→C)→A→B→C
0  0  0  0    1        1    1      1
0  0  1  0    1        1    1      1
0  1  0  0    1        0    1      1
0  1  1  0    1        1    1      1
1  0  0  0    1        1    1      1
1  0  1  0    1        1    1      1
1  1  0  1    0        0    0      1
1  1  1  1    1        1    1      1</code></pre>
<p>Observe that column 8 is true. Therefore <code>∀A. ∀B. ∀C. ((A∧B)→C)→A→B→C</code> is a true statement.</p>
<p>Remember this statement earlier <code>forall A B C. ((A, B) -&gt; C) -&gt; A -&gt; B -&gt; C</code>? If you have <a href="http://haskell.org/ghc">GHCi</a>installed, go to the prompt and type <code>:set -fglasgow-exts</code>. Then ask for the type of the <code>curry</code> function <code>:type curry</code>. You will see this:</p>
<pre><code>Prelude&gt; :type curry
curry :: forall a b c. ((a, b) -&gt; c) -&gt; a -&gt; b -&gt; c</code></pre>
<p>Same same! :)</p>
<p>OK, so Haskell is for crazy people who use (oh dear!) logic which has nothing to do with that <em>real world</em> and they should all be writing enterprise Java applications like real programmers, right? Yeah right. Yep uh huh.</p>
<p>So let’s write this in Java, just for kicks and just to be noisy. Start with the conjunction and implication primitives:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> Implication&lt;P, Q&gt; {
  Q <span class="fu">implies</span>(P p);
}

<span class="kw">interface</span> Conjunction&lt;P, Q&gt; {
  P <span class="fu">p</span>();
  Q <span class="fu">q</span>();
}</code></pre>
<p>Next write the method for representing the aforementioned statement:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">class</span> S {
  <span class="dt">static</span> &lt;A, B, C&gt; Implication&lt;Implication&lt;Conjunction&lt;A, B&gt;, C&gt;, Implication&lt;A, Implication&lt;B, C&gt;&gt;&gt; <span class="fu">s</span>() {
    <span class="kw">return</span> <span class="kw">null</span>; <span class="co">// todo</span>
  }
}</code></pre>
<p>I shall leave it as a reader exercise to implement the <code>s</code> method. I assure you of only one possible implementation if you do not use <code>null</code>, exceptions or side-effects.</p>
<p>Function currying, like all programming concepts, is a logical statement under the Curry-Howard Isomorphism. Have a nice day :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>Flippin' Scala</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/flippin-scala/index.html"/>
  <id>http://blog.tmorris.net/posts/flippin-scala/index.html</id>
  <published>2008-08-22T11:00:52Z</published>
  <updated>2008-08-22T11:00:52Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Once upon a time, I tried to write some Scala 2.7.1 for <a href="http://functionaljava.org/">Functional Java</a> and <a href="http://reductiotest.org/">Reductio</a>, but the compiler broke. So I filed <a href="https://lampsvn.epfl.ch/trac/scala/ticket/765">the bug</a> and waited for a fix. Thanks to Odersky et. al., the fix came promptly, so I started using one of the Scala 2.7.1-&gt;2.7.2 nightly builds and then I could compile my Scala code, yay! But that didn’t stop <a href="https://issues.workingmouse.com/view.php?id=49">users complaining about crashes</a> when using Scala 2.7.1 due its bad class file parser. Some users even <a href="http://groups.google.com/group/reductio/browse_thread/thread/289340b14deecdaf">stopped using Reductio because they don’t trust non-release builds</a>. Oh well.</p>
<p>So I try out this new code snippet, nothing complicated:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">class</span> Foo[F[_]]

<span class="kw">object</span> Foo {
  <span class="kw">def</span> <span class="fu">foo</span>(n: Int)(<span class="kw">implicit</span> f: Foo[IN] <span class="kw">forSome</span> { <span class="kw">type</span> IN[_] }) = <span class="st">&quot;foo&quot;</span>

  <span class="kw">implicit</span> <span class="kw">val</span> z: Foo[List] = <span class="kw">new</span> Foo[List]

  <span class="kw">val</span> t = <span class="fu">foo</span>(<span class="dv">7</span>)
}</code></pre>
<p>But Scala 2.7.1 falls over. So does the 2.7.1-&gt;2.7.2 nightly build that I was using. Ugh! So I try out Scala 2.7.2-RC1, yay it compiles my legitimate source file. But does it compile all my other source?</p>
<p>Er no, <a href="http://lampsvn.epfl.ch/trac/scala/ticket/1270">Scala 2.7.2-RC1 produces bad class files</a> when compiling code that is otherwise fine with previous Scala versions. In an attempt to obtain one bug fix I have also had to adopt another – one that makes its use non-viable. I am stuck with dealing with the former bug, which is also somewhat non-viable but only slightly more so than the latter. Give me a friggin’ break!</p>
<p>Ugh, this is not the first occurrence of this silliness. Flippin’ Scala, does this shit ever stop?</p>
    </div>
  </content>
</entry>
<entry>
  <title>Introductory C-H and Static Typing</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/introductory-c-h-and-static-typing/index.html"/>
  <id>http://blog.tmorris.net/posts/introductory-c-h-and-static-typing/index.html</id>
  <published>2008-08-15T09:21:40Z</published>
  <updated>2008-08-15T09:21:40Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>We use logic every day. No, I don’t mean just us programmers; I mean all of us. Here is an observation about propositional logic:</p>
<blockquote>
<p>I have three propositions P, Q and R.</p>
</blockquote>
<p>It doesn’t matter what these three propositions actually are, it will always hold that, “if P then Q implies that if Q then R implies that if P then R”.</p>
<p>I’ve subverted that a little to try to make it read a little better, but perhaps look it at it a bit more formally:</p>
<pre><code>forall P Q R. (P → Q) → (Q → R) → (P → R)</code></pre>
<p>You might like to try it out on paper using some example propositions, such as:</p>
<ul>
<li><p>P = Today is Tuesday</p></li>
<li><p>Q = I am going swimming</p></li>
<li><p>R = I have hairy armpits</p></li>
</ul>
<p>I won’t bastardise it with English again ;) However, I will give you a hint. Here is the truth table for → (logical implication):</p>
<pre><code>A | B | A → B
0 | 0 | 1
0 | 1 | 1
1 | 0 | 0
1 | 1 | 1</code></pre>
<p>Here is where it gets a little interesting. This same logical statement <code>forall P Q R. (P → Q) → (Q → R) → (P → R)</code> can also be expressed in most programming languages. Here it is in Java as the <code>z</code> method:</p>
<pre><code>interface F&lt;A, B&gt; { B f(A a); }
static &lt;P, Q, R&gt; F&lt;P, R&gt; z(F&lt;P, Q&gt; f, F&lt;Q, R&gt; g) { ...</code></pre>
<p>It gets more interesting; there is only <em>one implementation</em> of this function if we assume a terminating subset of the language (for Java, no <code>null</code> or throwing an exception). If you add in a side-effect such as writing to a file or the network, then you have perverted the function signature. Java allows us to do that, so we also have to assume a subset of the language that disallows this unfortunate anomaly. This notion of a type signature having only one implementation is called <em>once inhabited</em>.</p>
<p>Let’s write out the truth table for this. Notice the consistent <code>1</code> values in the final column. The statement is a tautology.</p>
<pre><code>P | Q | R | P → R | Q → R | P → R | (Q → R) → P → R | (P → Q) → (Q → R) → P → R
0 | 0 | 0 | 1     | 1     | 1     | 1               | 1
0 | 0 | 1 | 1     | 1     | 1     | 1               | 1
0 | 1 | 0 | 1     | 0     | 1     | 1               | 1
0 | 1 | 1 | 1     | 1     | 1     | 1               | 1
1 | 0 | 0 | 0     | 1     | 0     | 0               | 1
1 | 0 | 1 | 0     | 1     | 1     | 1               | 1
1 | 1 | 0 | 1     | 0     | 0     | 1               | 1
1 | 1 | 1 | 1     | 1     | 1     | 1               | 1</code></pre>
<p>Under the Curry-Howard Isomorphism, logical implication is represented by a function or in the example above using Java, by the <code>F</code> interface. The <code>z</code> function is called <em>function composition</em>. It takes the two give functions/propositions and composes them.</p>
<p>In Haskell, function composition is not called <code>z</code> as we called it with Java, but instead <code>(.)</code>. That’s a full-stop character in parentheses. We can ask for the type of <code>(.)</code> in the GHC interpreter:</p>
<pre><code>Prelude&gt; :type (.)
(.) :: (b -&gt; c) -&gt; (a -&gt; b) -&gt; a -&gt; c</code></pre>
<p>We might even call it by passing in function instances (similar to instances of the Java <code>F</code> interface):</p>
<pre><code>Prelude&gt; ((+1) . (*7)) 20
141

Prelude&gt; (reverse . map Char.toUpper) &quot;hello there&quot;
&quot;EREHT OLLEH&quot;</code></pre>
<p>You could do the same using Java, but it’s a little more verbose, so I’ll omit that ;)</p>
<p>Here is a simple quiz. If we suppose the same <code>F</code> interface earlier, how many implementations of this function are there:</p>
<pre><code>static &lt;a&gt; F&lt;A, A&gt; t() { ...</code></pre>
<p>What about this one?</p>
<pre><code>static &lt;A, B&gt; F&lt;A, B&gt; u() { ...</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Java interop errata</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/java-interop-errata/index.html"/>
  <id>http://blog.tmorris.net/posts/java-interop-errata/index.html</id>
  <published>2008-08-13T09:34:04Z</published>
  <updated>2008-08-13T09:34:04Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>There are a few possibilities for improvement on this <a href="http://blog.thinkrelevance.com/2008/8/12/java-next-2-java-interop">Scala Swing Example</a>.</p>
<ul>
<li><p>Removed unnecessary semi-colons</p></li>
<li><p>Inlined import</p></li>
<li><p>Removed <code>=</code> in main declaration (strongly advised on functions returning <code>Unit</code> and especially more for <code>main</code>)</p></li>
<li><p>Removed a few unnecessary parentheses</p></li>
</ul>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">import</span> javax.<span class="fu">swing</span>.<span class="fu">_</span>
<span class="kw">import</span> java.<span class="fu">awt</span>.<span class="fu">event</span>.{ActionEvent, ActionListener}

<span class="kw">object</span> HelloWorld <span class="kw">extends</span> JFrame(<span class="st">&quot;Hello Swing&quot;</span>) {
  <span class="kw">def</span> <span class="fu">showButtonMessage</span>(msg: String)  =
    JOptionPane.<span class="fu">showMessageDialog</span>(<span class="kw">null</span>, String<span class="fu">.format</span>(<span class="st">&quot;&quot;&quot;&lt;html&gt;Hello from &lt;b&gt;Scala&lt;/b&gt;. Button </span><span class="ch">%s</span><span class="st"> pressed&quot;&quot;&quot;</span>, Array(msg)));

  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]) {
    <span class="fu">setDefaultCloseOperation</span>(JFrame.<span class="fu">EXIT_ON_CLOSE</span>)
    <span class="kw">val</span> button = <span class="kw">new</span> JButton(<span class="st">&quot;Click Me&quot;</span>)
    button.<span class="fu">addActionListener</span>((e:ActionEvent) =&gt; <span class="fu">showButtonMessage</span>(e.<span class="fu">getActionCommand</span>.<span class="fu">toString</span>))
    getContentPane add button
    pack
    <span class="fu">setVisible</span>(<span class="kw">true</span>)
  }

  <span class="kw">implicit</span> <span class="kw">def</span> <span class="fu">actionPerformedWrapper</span>(func: (ActionEvent) =&gt; Unit) = <span class="kw">new</span> ActionListener {
    <span class="kw">def</span> <span class="fu">actionPerformed</span>(e:ActionEvent) = <span class="fu">func</span>(e)
  }
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Functional Java 2.9</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/functional-java-29/index.html"/>
  <id>http://blog.tmorris.net/posts/functional-java-29/index.html</id>
  <published>2008-08-05T11:33:43Z</published>
  <updated>2008-08-05T11:33:43Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><strong>Patient</strong>: I have 6 potentially failing methods (a, b, c, d, e, f) and if one of those fails, I want to cease execution and return that failure, otherwise continue execution.</p>
<p><strong>Doctor</strong>: What do they return if they succeed?</p>
<p><strong>Patient</strong>: Nothing, they side-effect</p>
<p><strong>Doctor</strong>: eek! OK, let’s see what we can do? What happens after you’ve completed this computation?</p>
<p><strong>Patient</strong>: Well, it gets a bit hairier you see. Then I have 3 more potentially failing computations (g, h, i) and if any of those fail (or the original failed), then I also want to fail, however, I want to <em>keep</em> the errors in these last three computations.</p>
<p><strong>Doctor</strong>: So let’s get this right, you perform all of the latter three computations regardless of their outcome and you only succeed if all nine computations succeed and you fail otherwise?</p>
<p><strong>Patient</strong>: Yes, that’s right and…</p>
<p><strong>Doctor</strong>: And for whatever silly reason, you’re using Java.</p>
<p><strong>Patient</strong>: <em>cowers</em>; er yeah.</p>
<p><strong>Doctor</strong>: Well, I’ve told you about that, haven’t I?</p>
<p><strong>Patient</strong>: <em>cowers more</em>; yes you have but…</p>
<p><strong>Doctor</strong>: So, if any of the first six computations fail, then you check the latter three for failures as well. These latter three are side-effecting, void return type, as well aren’t they?</p>
<p><strong>Patient</strong>: Yes…</p>
<p><strong>Doctor</strong>: If the first six succeed, you perform the latter three computations anyway, accumulating potential failures.</p>
<p><strong>Patient</strong>: Right, exactly</p>
<p><strong>Doctor</strong>: And just as an interesting observation, you will have at most, four errors and possibly none in the event of all nine succeeding.</p>
<p><strong>Patient</strong>: Umm yeah, I hadn’t thought of it that way.</p>
<p><strong>Doctor</strong>: <em>smiles</em></p>
<pre class="sourceCode Java"><code class="sourceCode java">Validation&lt;Throwable, Unit&gt; a;
Validation&lt;Throwable, Unit&gt; b;
Validation&lt;Throwable, Unit&gt; c;
Validation&lt;Throwable, Unit&gt; d;
Validation&lt;Throwable, Unit&gt; e;
Validation&lt;Throwable, Unit&gt; f;
<span class="co">////</span>
Validation&lt;Throwable, Unit&gt; g;
Validation&lt;Throwable, Unit&gt; h;
Validation&lt;Throwable, Unit&gt; i;

Validation&lt;Throwable, Unit&gt; <span class="fu">first</span>() {
  <span class="kw">return</span> a.<span class="fu">sequence</span>(b).
          <span class="fu">sequence</span>(c).
          <span class="fu">sequence</span>(d).
          <span class="fu">sequence</span>(e).
          <span class="fu">sequence</span>(f);
}

Option&lt;NonEmptyList&lt;throwable&gt;&gt; <span class="fu">second</span>() {
  <span class="kw">return</span> <span class="fu">first</span>().<span class="fu">nel</span>().<span class="fu">accumulate</span>(Semigroup.&lt;throwable&gt;<span class="fu">nonEmptyListSemigroup</span>(),
          g.<span class="fu">nel</span>(),
          h.<span class="fu">nel</span>(),
          i.<span class="fu">nel</span>());
}</code></pre>
<p><strong>Doctor</strong>: Now, this is the best that Java can do at solving this very popular request of yours, but come and see me when you’re ready to upgrade your tools…</p>
<p><strong>Patient</strong>: Thanks Doc! I will!</p>
<p><strong>Doctor</strong>: <em>outward smile, inward scepticism</em>; In the meantime, I will prescribe you with <a href="http://functionaljava.org/">Functional Java 2.9</a> which is only going to work if you exercise <em>at least some</em> amount of intellectual discipline. You will need it for the solution above.</p>
<p><strong>Doctor</strong>: On your way then.</p>
<p><em>Update: Functional Java 2.10 includes <code>Validation.sequence</code>.</em></p>
    </div>
  </content>
</entry>
<entry>
  <title>Posterior Tibial Tendon Impingement</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/posterior-tibial-tendon-impingement/index.html"/>
  <id>http://blog.tmorris.net/posts/posterior-tibial-tendon-impingement/index.html</id>
  <published>2008-08-03T08:55:24Z</published>
  <updated>2008-08-03T08:55:24Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <h4 id="july-2007">July 2007</h4>
<ul>
<li><p>Right ankle sprain</p></li>
<li><p>Fifth life-time occurrence</p></li>
<li><p>X-Ray reveals no fracture (Royal Brisbane Hospital)</p></li>
<li><p>Zero weight bearing for 6 days</p></li>
</ul>
<h4 id="january-2008">January 2008</h4>
<ul>
<li><p>Certain movements cause swelling and discomfort</p></li>
<li><p>Movement is restricted in bending the knee with the foot flat on the ground (name?) – can get the knee vertical with the tip of the foot, but no further</p></li>
<li><p>MRI ordered by local GP <em>(see below)</em></p></li>
<li><p>Radiography report is unremarkable and states no anterolateral abnormality (even though the pain is posteromedial?)</p></li>
</ul>
<h4 id="february-2008">February 2008</h4>
<ul>
<li><p>Local GP administers cortico-steroid injection. Due to the swelling, the exact site of the pain cannot be accurately located. Since swelling has stopped (I have ceased rigorous activity), I estimate that the injection missed by about 2cm.</p></li>
<li><p>Improvement over the following 3 weeks and flexibility increases, just a little (I can get my knee 3cm passed the tip of my foot vertically)</p></li>
</ul>
<h4 id="may-2008">May 2008</h4>
<ul>
<li><p>Ceased all sporting activity, in particular squash (3 times per week, including A1 grade competition)</p></li>
<li><p>This was due to this injury and one other; scapholunate ligament tear resulting in instability</p></li>
</ul>
<h4 id="june-2008">June 2008</h4>
<ul>
<li><p>Subcutaneous atrophy from steroid injection begins to subside</p></li>
<li><p>Further injections are advised against by local GP</p></li>
<li><p>Arthroscopy of the wrist for scapholunate ligament repair (Dr. Peter Rowan, BOSMC)</p></li>
</ul>
<h4 id="july-2008">July 2008</h4>
<ul>
<li><p>Wrist Arthroscopy has failed (reconstruction pending?)</p></li>
<li><p><strong>HELP!</strong></p></li>
</ul>
<h4 id="august-2008-update">04 August 2008 <em>(update)</em></h4>
<ul>
<li><p>Appointment with <a href="http://www.gregsterling.com.au/">Greg Sterling</a> on 30 September</p></li>
<li><p>YAY! 57 sleeps to go</p></li>
</ul>
<h4 id="photos">Photos</h4>
<ul>
<li><p>Taken 2 August 2008</p></li>
<li><p>Red mark denotes site of impingement</p></li>
<li><p>Note atrophy below the mark</p></li>
</ul>
<p><a href="http://www.xdweb.net/~dibblego/right-ankle/PHOTO/00001.jpg"><img src="http://www.xdweb.net/~dibblego/right-ankle/PHOTO/00001-small.jpg" alt="Ankle 1" /></a></p>
<p><a href="http://www.xdweb.net/~dibblego/right-ankle/PHOTO/00002.jpg"><img src="http://www.xdweb.net/~dibblego/right-ankle/PHOTO/00002-small.jpg" alt="Ankle 2" /></a></p>
<p><a href="http://www.xdweb.net/~dibblego/right-ankle/PHOTO/00003.jpg"><img src="http://www.xdweb.net/~dibblego/right-ankle/PHOTO/00003-small.jpg" alt="Ankle 3" /></a></p>
<p><a href="http://www.xdweb.net/~dibblego/right-ankle/PHOTO/00004.jpg"><img src="http://www.xdweb.net/~dibblego/right-ankle/PHOTO/00004-small.jpg" alt="Ankle 4" /></a></p>
<h4 id="mri">MRI</h4>
<p><a href="http://xdweb.net/~dibblego/right-ankle/report">Radiographer Report <em>(Transcribed)</em></a></p>
<h5 id="images-dicom">Images (DICOM)</h5>
<p><a href="http://xdweb.net/~dibblego/right-ankle/DICOM.tar.gz">All DICOM images</a> (tar.gz) 71MB</p>
<p><a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000000">MR000000</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000000">MR000000</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000000">MR000000</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000000">MR000000</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000000">MR000000</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000001">MR000001</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000001">MR000001</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000001">MR000001</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000001">MR000001</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000001">MR000001</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000002">MR000002</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000002">MR000002</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000002">MR000002</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000002">MR000002</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000002">MR000002</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000003">MR000003</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000003">MR000003</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000003">MR000003</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000003">MR000003</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000003">MR000003</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000004">MR000004</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000004">MR000004</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000004">MR000004</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000004">MR000004</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000004">MR000004</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000005">MR000005</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000005">MR000005</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000005">MR000005</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000005">MR000005</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000005">MR000005</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000006">MR000006</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000006">MR000006</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000006">MR000006</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000006">MR000006</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000006">MR000006</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000007">MR000007</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000007">MR000007</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000007">MR000007</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000007">MR000007</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000007">MR000007</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000008">MR000008</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000008">MR000008</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000008">MR000008</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000008">MR000008</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000008">MR000008</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000009">MR000009</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000009">MR000009</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000009">MR000009</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000009">MR000009</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000009">MR000009</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000010">MR000010</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000010">MR000010</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000010">MR000010</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000010">MR000010</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000010">MR000010</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000011">MR000011</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000011">MR000011</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000011">MR000011</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000011">MR000011</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000011">MR000011</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000012">MR000012</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000012">MR000012</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000012">MR000012</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000012">MR000012</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000012">MR000012</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000013">MR000013</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000013">MR000013</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000013">MR000013</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000013">MR000013</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000013">MR000013</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000014">MR000014</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000014">MR000014</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000014">MR000014</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000014">MR000014</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000014">MR000014</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000015">MR000015</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000015">MR000015</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000015">MR000015</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000015">MR000015</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000015">MR000015</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000016">MR000016</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000016">MR000016</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000016">MR000016</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000016">MR000016</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000016">MR000016</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000017">MR000017</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000017">MR000017</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000017">MR000017</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000017">MR000017</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000017">MR000017</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000018">MR000018</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000018">MR000018</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000018">MR000018</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000018">MR000018</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000018">MR000018</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000019">MR000019</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000001/MR000019">MR000019</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000019">MR000019</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000019">MR000019</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000004/MR000019">MR000019</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000020">MR000020</a> MR000020 <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000020">MR000020</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000020">MR000020</a> MR000020 <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000021">MR000021</a> MR000021 <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000021">MR000021</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000021">MR000021</a> MR000021 <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000022">MR000022</a> MR000022 <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000022">MR000022</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000022">MR000022</a> MR000022 <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000000/MR000023">MR000023</a> MR000023 <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000002/MR000023">MR000023</a> <a href="http://xdweb.net/~dibblego/right-ankle/DICOM/ST000000/SE000003/MR000023">MR000023</a> MR000023</p>
<h5 id="images-png">Images (PNG)</h5>
<p><a href="http://xdweb.net/~dibblego/right-ankle/PNG.tar.gz">All PNG images</a> (tar.gz) 23MB</p>
<p><a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000000.png">MR000000</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000000.png">MR000000</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000000.png">MR000000</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000000.png">MR000000</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000000.png">MR000000</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000001.png">MR000001</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000001.png">MR000001</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000001.png">MR000001</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000001.png">MR000001</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000001.png">MR000001</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000002.png">MR000002</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000002.png">MR000002</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000002.png">MR000002</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000002.png">MR000002</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000002.png">MR000002</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000003.png">MR000003</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000003.png">MR000003</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000003.png">MR000003</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000003.png">MR000003</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000003.png">MR000003</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000004.png">MR000004</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000004.png">MR000004</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000004.png">MR000004</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000004.png">MR000004</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000004.png">MR000004</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000005.png">MR000005</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000005.png">MR000005</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000005.png">MR000005</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000005.png">MR000005</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000005.png">MR000005</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000006.png">MR000006</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000006.png">MR000006</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000006.png">MR000006</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000006.png">MR000006</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000006.png">MR000006</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000007.png">MR000007</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000007.png">MR000007</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000007.png">MR000007</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000007.png">MR000007</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000007.png">MR000007</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000008.png">MR000008</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000008.png">MR000008</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000008.png">MR000008</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000008.png">MR000008</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000008.png">MR000008</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000009.png">MR000009</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000009.png">MR000009</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000009.png">MR000009</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000009.png">MR000009</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000009.png">MR000009</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000010.png">MR000010</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000010.png">MR000010</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000010.png">MR000010</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000010.png">MR000010</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000010.png">MR000010</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000011.png">MR000011</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000011.png">MR000011</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000011.png">MR000011</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000011.png">MR000011</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000011.png">MR000011</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000012.png">MR000012</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000012.png">MR000012</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000012.png">MR000012</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000012.png">MR000012</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000012.png">MR000012</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000013.png">MR000013</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000013.png">MR000013</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000013.png">MR000013</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000013.png">MR000013</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000013.png">MR000013</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000014.png">MR000014</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000014.png">MR000014</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000014.png">MR000014</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000014.png">MR000014</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000014.png">MR000014</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000015.png">MR000015</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000015.png">MR000015</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000015.png">MR000015</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000015.png">MR000015</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000015.png">MR000015</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000016.png">MR000016</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000016.png">MR000016</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000016.png">MR000016</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000016.png">MR000016</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000016.png">MR000016</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000017.png">MR000017</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000017.png">MR000017</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000017.png">MR000017</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000017.png">MR000017</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000017.png">MR000017</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000018.png">MR000018</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000018.png">MR000018</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000018.png">MR000018</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000018.png">MR000018</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000018.png">MR000018</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000019.png">MR000019</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000001/MR000019.png">MR000019</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000019.png">MR000019</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000019.png">MR000019</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000004/MR000019.png">MR000019</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000020.png">MR000020</a> MR000020 <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000020.png">MR000020</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000020.png">MR000020</a> MR000020 <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000021.png">MR000021</a> MR000021 <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000021.png">MR000021</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000021.png">MR000021</a> MR000021 <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000022.png">MR000022</a> MR000022 <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000022.png">MR000022</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000022.png">MR000022</a> MR000022 <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000000/MR000023.png">MR000023</a> MR000023 <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000002/MR000023.png">MR000023</a> <a href="http://xdweb.net/~dibblego/right-ankle/PNG/ST000000/SE000003/MR000023.png">MR000023</a> MR000023</p>
    </div>
  </content>
</entry>
<entry>
  <title>Tony’s Wager</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/tonys-wager/index.html"/>
  <id>http://blog.tmorris.net/posts/tonys-wager/index.html</id>
  <published>2008-07-29T08:41:22Z</published>
  <updated>2008-07-29T08:41:22Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <blockquote>
<p>It is better not to believe in God, since if he does not exist, you lose nothing, but if he does exist, you are going to hell, where it is nice and warm. Winter sucks.</p>
</blockquote>
    </div>
  </content>
</entry>
<entry>
  <title>Revised Scala Exercises</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/revised-scala-exercises/index.html"/>
  <id>http://blog.tmorris.net/posts/revised-scala-exercises/index.html</id>
  <published>2008-07-29T10:08:00Z</published>
  <updated>2008-07-29T10:08:00Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Without the rules as per last time, I have rewritten the Scala exercises to be closer to the Haskell revision. Enjoy :)</p>
<p>(And yes, I will get around to giving you all feedback (you should also see my email inbox) – just hang in there!).</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">sealed</span> <span class="kw">trait</span> List[+A] {
  <span class="kw">override</span> <span class="kw">def</span> toString = {
    <span class="kw">def</span> <span class="fu">toScalaList</span>(t: List[A]): scala.<span class="fu">List</span>[A] = t <span class="kw">match</span> {
      <span class="kw">case</span> Empty =&gt; Nil
      <span class="kw">case</span> <span class="fu">Cons</span>(h, t) =&gt; h :: <span class="fu">toScalaList</span>(t)
    }
    <span class="fu">toScalaList</span>(<span class="kw">this</span>).<span class="fu">toString</span>
  }
}
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> Empty <span class="kw">extends</span> List[Nothing]
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">class</span> Cons[A](h: A, t: List[A]) <span class="kw">extends</span> List[A]

<span class="kw">object</span> List {
  <span class="kw">def</span> foldRight[A, B](as: List[A], b: B, f: (A, B) =&gt; B): B = as <span class="kw">match</span> {
    <span class="kw">case</span> Empty =&gt; b
    <span class="kw">case</span> <span class="fu">Cons</span>(h, t) =&gt; <span class="fu">f</span>(h, <span class="fu">foldRight</span>(t, b, f))
  }

  <span class="kw">def</span> foldLeft[A, B](as: List[A], b: B, f: (B, A) =&gt; B): B = as <span class="kw">match</span> {
    <span class="kw">case</span> Empty =&gt; b
    <span class="kw">case</span> <span class="fu">Cons</span>(h, t) =&gt; <span class="fu">foldLeft</span>(t, <span class="fu">f</span>(b, h), f)
  }

  <span class="kw">def</span> reduceRight[A](as: List[A], f: (A, A) =&gt; A): A = as <span class="kw">match</span> {
    <span class="kw">case</span> Empty =&gt; <span class="fu">error</span>(<span class="st">&quot;bzzt. reduceRight on empty list&quot;</span>)
    <span class="kw">case</span> <span class="fu">Cons</span>(h, t) =&gt; <span class="fu">foldRight</span>(t, h, f)
  }

  <span class="kw">def</span> reduceLeft[A](as: List[A], f: (A, A) =&gt; A): A = as <span class="kw">match</span> {
    <span class="kw">case</span> Empty =&gt; <span class="fu">error</span>(<span class="st">&quot;bzzt. reduceLeft on empty list&quot;</span>)
    <span class="kw">case</span> <span class="fu">Cons</span>(h, t) =&gt; <span class="fu">foldLeft</span>(t, h, f)
  }

  <span class="kw">def</span> unfold[A, B](b: B, f: B =&gt; Option[(A, B)]): List[A] = <span class="fu">f</span>(b) <span class="kw">match</span> {
    <span class="kw">case</span> Some((a, b)) =&gt; <span class="fu">Cons</span>(a, <span class="fu">unfold</span>(b, f))
    <span class="kw">case</span> scala.<span class="fu">None</span> =&gt; Empty
  }
}

<span class="kw">sealed</span> <span class="kw">trait</span> Natural {
  <span class="kw">override</span> <span class="kw">def</span> toString = {
    <span class="kw">def</span> <span class="fu">toInt</span>(n: Natural): Int = n <span class="kw">match</span> {
      <span class="kw">case</span> Zero =&gt; <span class="dv">0</span>
      <span class="kw">case</span> <span class="fu">Succ</span>(x) =&gt; <span class="dv">1</span> + <span class="fu">toInt</span>(x)
    }
    <span class="fu">toInt</span>(<span class="kw">this</span>).<span class="fu">toString</span>
  }
}
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> Zero <span class="kw">extends</span> Natural
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">class</span> <span class="fu">Succ</span>(c: Natural) <span class="kw">extends</span> Natural

<span class="kw">object</span> Exercises {

<span class="co">// Exercise 1</span>
<span class="co">// Relative Difficulty: 1</span>
<span class="co">// Correctness: 2.0 marks</span>
<span class="co">// Performance: 0.5 mark</span>
<span class="co">// Elegance: 0.5 marks</span>
<span class="co">// Total: 3</span>
<span class="kw">def</span> <span class="fu">add</span>(x: Natural, y: Natural): Natural = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

<span class="co">// Exercise 2</span>
<span class="co">// Relative Difficulty: 2</span>
<span class="co">// Correctness: 2.5 marks</span>
<span class="co">// Performance: 1 mark</span>
<span class="co">// Elegance: 0.5 marks</span>
<span class="co">// Total: 4</span>
<span class="kw">def</span> <span class="fu">sum</span>(is: List[Int]): Int = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

<span class="co">// Exercise 3</span>
<span class="co">// Relative Difficulty: 2</span>
<span class="co">// Correctness: 2.5 marks</span>
<span class="co">// Performance: 1 mark</span>
<span class="co">// Elegance: 0.5 marks</span>
<span class="co">// Total: 4</span>
<span class="kw">def</span> length[A](as: List[A]): Int = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

<span class="co">// Exercise 4</span>
<span class="co">// Relative Difficulty: 5</span>
<span class="co">// Correctness: 4.5 marks</span>
<span class="co">// Performance: 1.0 mark</span>
<span class="co">// Elegance: 1.5 marks</span>
<span class="co">// Total: 7</span>
<span class="kw">def</span> map[A, B](as: List[A], f: A =&gt; B): List[B] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

<span class="co">// Exercise 5</span>
<span class="co">// Relative Difficulty: 5</span>
<span class="co">// Correctness: 4.5 marks</span>
<span class="co">// Performance: 1.5 marks</span>
<span class="co">// Elegance: 1 mark</span>
<span class="co">// Total: 7</span>
<span class="kw">def</span> filter[A](as: List[A], f: A =&gt; Boolean): List[A] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

<span class="co">// Exercise 6</span>
<span class="co">// Relative Difficulty: 5</span>
<span class="co">// Correctness: 4.5 marks</span>
<span class="co">// Performance: 1.5 marks</span>
<span class="co">// Elegance: 1 mark</span>
<span class="co">// Total: 7</span>
<span class="kw">def</span> append[A](x: List[A], y: List[A]): List[A] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

<span class="co">// Exercise 7</span>
<span class="co">// Relative Difficulty: 5</span>
<span class="co">// Correctness: 4.5 marks</span>
<span class="co">// Performance: 1.5 marks</span>
<span class="co">// Elegance: 1 mark</span>
<span class="co">// Total: 7</span>
<span class="kw">def</span> flatten[A](as: List[List[A]]): List[A] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

<span class="co">// Exercise 8</span>
<span class="co">// Relative Difficulty: 7</span>
<span class="co">// Correctness: 5.0 marks</span>
<span class="co">// Performance: 1.5 marks</span>
<span class="co">// Elegance: 1.5 mark</span>
<span class="co">// Total: 8</span>
<span class="kw">def</span> flatMap[A, B](as: List[A], f: A =&gt; List[B]): List[B] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

<span class="co">// Exercise 9</span>
<span class="co">// Relative Difficulty: 8</span>
<span class="co">// Correctness: 3.5 marks</span>
<span class="co">// Performance: 3.0 marks</span>
<span class="co">// Elegance: 2.5 marks</span>
<span class="co">// Total: 9</span>
<span class="kw">def</span> <span class="fu">maximum</span>(is: List[Int]): Int = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

<span class="co">// Exercise 10</span>
<span class="co">// Relative Difficulty: 10</span>
<span class="co">// Correctness: 5.0 marks</span>
<span class="co">// Performance: 2.5 marks</span>
<span class="co">// Elegance: 2.5 marks</span>
<span class="co">// Total: 10</span>
<span class="kw">def</span> reverse[A](as: List[A]): List[A] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Actor concurrency for Java</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/actor-concurrency-for-java/index.html"/>
  <id>http://blog.tmorris.net/posts/actor-concurrency-for-java/index.html</id>
  <published>2008-07-25T15:26:27Z</published>
  <updated>2008-07-25T15:26:27Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://functionaljava.org/">Functional Java</a> 2.8 contains a concurrency API that implements Actors as seen in Erlang and Scala. This allows a user to take advantage of multiple core machines in their Java code.</p>
<p><a href="http://apocalisp.wordpress.com/">Runar</a> has written articles explain how to use the API – it’s pretty darn easy for a client – just don’t look under the hood ;)</p>
<ul>
<li><p><a href="http://apocalisp.wordpress.com/2008/06/18/parallel-strategies-and-the-callable-monad">Higher-Order Java Parallelism, Part 1: Parallel Strategies and the Callable Monad</a></p></li>
<li><p><a href="http://apocalisp.wordpress.com/2008/06/30/parallel-list-transformations/">Higher-Order Java Parallelism, Part 2: Parallel List Transformations</a></p></li>
</ul>
<p>Here is an <a href="http://projects.workingmouse.com/public/functionaljava/artifacts/2.8/demo/bgga/concurrent/Fibs.java">example</a> of a parallel fibonacci that uses a few hundred virtual threads (unlike <a href="http://projects.workingmouse.com/public/functionaljava/artifacts/2.8/demo/bgga/concurrent/PingPong.java">the ping/pong example</a> that uses… wait for it… <strong>millions</strong> of virtual threads!). On my quad-core machine, the fibonacci computation speeds up by about 6 times (45 seconds serially to about 7 seconds when using actors).</p>
<p><a href="http://projects.workingmouse.com/public/functionaljava/artifacts/2.8/demo/bgga/concurrent/Fibs.java">The example</a> uses Java 7 BGGA syntax (imports omitted) and after compilation, runs fine on any 1.5 JVM. This example is <a href="http://projects.workingmouse.com/public/functionaljava/artifacts/2.8/demo/1.5/concurrent/Fibs.java">also available with Java 1.5 source code</a> in the Functional Java release.</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="co">/**</span>
<span class="co"> * Parallel Fibonacci numbers.</span>
<span class="co"> * Based on a Haskell example by Don Stewart.</span>
<span class="co"> * Author: Runar</span>
<span class="co"> */</span>
<span class="kw">public</span> <span class="kw">class</span> Fibs {

  <span class="kw">private</span> <span class="dt">static</span> <span class="dt">final</span> <span class="dt">int</span> CUTOFF = <span class="dv">35</span>;

  <span class="kw">public</span> <span class="dt">static</span> <span class="dt">void</span> <span class="fu">main</span>(<span class="dt">final</span> String[] args) <span class="kw">throws</span> Exception {
    <span class="kw">if</span> (args.<span class="fu">length</span> &lt; <span class="dv">1</span>)
      <span class="kw">throw</span> <span class="fu">error</span>(<span class="st">&quot;This program takes an argument: number_of_threads&quot;</span>);

    <span class="dt">final</span> <span class="dt">int</span> threads = Integer.<span class="fu">parseInt</span>(args[<span class="dv">0</span>]);
    <span class="dt">final</span> ExecutorService pool = Executors.<span class="fu">newFixedThreadPool</span>(threads);
    <span class="dt">final</span> Strategy&lt;unit&gt; su = Strategy.<span class="fu">executorStrategy</span>(pool);
    <span class="dt">final</span> Strategy&lt;Promise&lt;integer&gt;&gt; spi = Strategy.<span class="fu">executorStrategy</span>(pool);

    <span class="dt">final</span> Actor&lt;List&lt;integer&gt;&gt; out = <span class="fu">actor</span>(su, { List&lt;integer&gt; fs =&gt; {
      <span class="dt">int</span> i = <span class="dv">0</span>;
      <span class="kw">for</span> (List&lt;integer&gt; ns = fs; ns.<span class="fu">isNotEmpty</span>(); ns = ns.<span class="fu">tail</span>()) {
        System.<span class="fu">out</span>.<span class="fu">println</span>(MessageFormat<span class="fu">.format</span>(<span class="st">&quot;n={0}=&gt;{1}&quot;</span>, i, ns.<span class="fu">head</span>()));
        i++;
      }
      pool.<span class="fu">shutdown</span>();
    }});

    System.<span class="fu">out</span>.<span class="fu">println</span>(<span class="st">&quot;Calculating Fibonacci sequence in parallel...&quot;</span>);

    <span class="dt">final</span> F&lt;Integer, Promise&lt;integer&gt;&gt; fib = { Integer n =&gt; (n &lt; CUTOFF) ?
        <span class="fu">promise</span>(su, P.<span class="fu">p</span>(<span class="fu">serialFib</span>(n))) :
        fib.<span class="fu">f</span>(n - <span class="dv">1</span>).<span class="fu">bind</span>(<span class="fu">join</span>(su, P1.<span class="fu">curry</span>(fib).<span class="fu">f</span>(n - <span class="dv">2</span>)), { <span class="dt">int</span> a =&gt; { <span class="dt">int</span> b =&gt; a + b }} ) };

    <span class="fu">join</span>(su, <span class="fu">fmap</span>(Promise.&lt;integer&gt;<span class="fu">sequence</span>(su)).<span class="fu">f</span>(spi.<span class="fu">parMap</span>(fib).<span class="fu">f</span>(<span class="fu">range</span>(<span class="dv">0</span>, <span class="dv">46</span>)))).<span class="fu">to</span>(out);
  }

  <span class="kw">public</span> <span class="dt">static</span> <span class="dt">int</span> <span class="fu">serialFib</span>(<span class="dt">final</span> <span class="dt">int</span> n) {
    <span class="kw">if</span> (n &lt; <span class="dv">2</span>)
      <span class="kw">return</span> n;
    <span class="kw">else</span> <span class="kw">return</span> <span class="fu">serialFib</span>(n - <span class="dv">1</span>) + <span class="fu">serialFib</span>(n - <span class="dv">2</span>);
  }
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Haskell exercises for beginners</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/haskell-exercises-for-beginners/index.html"/>
  <id>http://blog.tmorris.net/posts/haskell-exercises-for-beginners/index.html</id>
  <published>2008-07-17T11:33:07Z</published>
  <updated>2008-07-17T11:33:07Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>The exercises below are similar to my previous ‘Scala exercises for beginners’, except the rules a little clearer. For those of who have emailed me or submitted responses here on the blog, I will get around to providing you feedback, however, I’d prefer to do so on the revised version of the Exercises since then I can maintain a bit of clarity in explaining the solutions; specifically, why one may be preferred over another. I hope you don’t mind.</p>
<p>If you have not used Haskell before, download and install <a href="http://haskell.org/ghc">GHC</a>, start up the interpreter (ghci) and load the source file. e.g. <code>:load Exercises.hs</code> If you are on Debian, you can install GHC and start the interpreter with: <code>apt-get install ghc6 &amp;&amp; ghci</code>.</p>
<p>The source file below can be found <a href="https://bitbucket.org/dibblego/haskell-course/src/default/L02/List.hs">here</a>.</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="co">-- + Complete the 10 exercises below by filling out the function bodies.</span>
<span class="co">--   The code currently compiles, but none of the tests pass (the test function).</span>
<span class="co">--   Replace the function bodies (error &quot;todo&quot;) with an appropriate solution.</span>
<span class="co">-- + These exercises may be done in any order, however:</span>
<span class="co">--   Exercises are generally increasing in difficulty, though some people may find later exercise easier.</span>
<span class="co">--   The tests are written to execute in the order 1 to 10, so you need to have Exercise n passing before Exercise (n+1) passes.</span>
<span class="co">-- + Note the existence of the library function max :: Int -&gt; Int -&gt; Int which will help you with Exercise 9.</span>
<span class="co">-- + Bonus for using the provided functions or for using one exercise solution to help solve another.</span>
<span class="co">-- + Approach with your best available intuition; just dive in and do what you can!</span>

<span class="co">-- TOTAL marks:    /66</span>

<span class="kw">module</span> <span class="dt">L02.List</span> <span class="kw">where</span>

<span class="kw">import</span> <span class="dt">Prelude</span> <span class="kw">hiding</span> (<span class="fu">sum</span>, <span class="fu">length</span>, <span class="fu">map</span>, <span class="fu">filter</span>, <span class="fu">maximum</span>, <span class="fu">reverse</span>)

<span class="co">-- BEGIN Helper functions and data types</span>

<span class="co">-- The custom list type</span>
<span class="kw">data</span> <span class="dt">List</span> t <span class="fu">=</span> <span class="dt">Nil</span> <span class="fu">|</span> t <span class="fu">:|</span> <span class="dt">List</span> t <span class="kw">deriving</span> <span class="kw">Eq</span>

<span class="co">-- Right-associative</span>
<span class="kw">infixr</span> <span class="dv">5</span> <span class="fu">:|</span>

<span class="kw">instance</span> (<span class="kw">Show</span> t) <span class="ot">=&gt;</span> <span class="kw">Show</span> (<span class="dt">List</span> t) <span class="kw">where</span>
  <span class="fu">show</span> <span class="fu">=</span> <span class="fu">show</span> <span class="fu">.</span> foldRight (<span class="fu">:</span>) []

<span class="co">-- functions over List that you may consider using</span>
<span class="ot">foldRight ::</span> (a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> b
foldRight _ b <span class="dt">Nil</span>      <span class="fu">=</span> b
foldRight f b (h <span class="fu">:|</span> t) <span class="fu">=</span> f h (foldRight f b t)

<span class="ot">foldLeft ::</span> (b <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> b
foldLeft _ b <span class="dt">Nil</span>      <span class="fu">=</span> b
foldLeft f b (h <span class="fu">:|</span> t) <span class="fu">=</span> <span class="kw">let</span> b&#39; <span class="fu">=</span> f b h <span class="kw">in</span> b&#39; <span class="ot">`seq`</span> foldLeft f b&#39; t

<span class="ot">reduceRight ::</span> (a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> a) <span class="ot">-&gt;</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> a
reduceRight _ <span class="dt">Nil</span>      <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;bzzt. reduceRight on empty list&quot;</span>
reduceRight f (h <span class="fu">:|</span> t) <span class="fu">=</span> foldRight f h t

<span class="ot">reduceLeft ::</span> (a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> a) <span class="ot">-&gt;</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> a
reduceLeft _ <span class="dt">Nil</span>      <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;bzzt. reduceLeft on empty list&quot;</span>
reduceLeft f (h <span class="fu">:|</span> t) <span class="fu">=</span> foldLeft f h t

<span class="co">-- END Helper functions and data types</span>

<span class="co">-- BEGIN Exercises</span>

<span class="co">-- Exercise 1</span>
<span class="co">-- Relative Difficulty: 1</span>
<span class="co">-- Correctness: 2.0 marks</span>
<span class="co">-- Performance: 0.5 mark</span>
<span class="co">-- Elegance: 0.5 marks</span>
<span class="co">-- Total: 3</span>
<span class="ot">headOr ::</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> a
headOr <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 2</span>
<span class="co">-- Relative Difficulty: 2</span>
<span class="co">-- Correctness:   2.5 marks</span>
<span class="co">-- Performance: 1 mark</span>
<span class="co">-- Elegance: 0.5 marks</span>
<span class="co">-- Total: 4</span>
<span class="fu">sum</span><span class="ot"> ::</span> <span class="dt">List</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span>
<span class="fu">sum</span> <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 3</span>
<span class="co">-- Relative Difficulty: 2</span>
<span class="co">-- Correctness: 2.5 marks</span>
<span class="co">-- Performance: 1 mark</span>
<span class="co">-- Elegance: 0.5 marks</span>
<span class="co">-- Total: 4</span>
<span class="fu">length</span><span class="ot"> ::</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> <span class="dt">Int</span>
<span class="fu">length</span> <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 4</span>
<span class="co">-- Relative Difficulty: 5</span>
<span class="co">-- Correctness: 4.5 marks</span>
<span class="co">-- Performance: 1.0 mark</span>
<span class="co">-- Elegance: 1.5 marks</span>
<span class="co">-- Total: 7</span>
<span class="fu">map</span><span class="ot"> ::</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> <span class="dt">List</span> b
<span class="fu">map</span> <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 5</span>
<span class="co">-- Relative Difficulty: 5</span>
<span class="co">-- Correctness: 4.5 marks</span>
<span class="co">-- Performance: 1.5 marks</span>
<span class="co">-- Elegance: 1 mark</span>
<span class="co">-- Total: 7</span>
<span class="fu">filter</span><span class="ot"> ::</span> (a <span class="ot">-&gt;</span> <span class="dt">Bool</span>) <span class="ot">-&gt;</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> <span class="dt">List</span> a
<span class="fu">filter</span> <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 6</span>
<span class="co">-- Relative Difficulty: 5</span>
<span class="co">-- Correctness: 4.5 marks</span>
<span class="co">-- Performance: 1.5 marks</span>
<span class="co">-- Elegance: 1 mark</span>
<span class="co">-- Total: 7</span>
<span class="ot">append ::</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> <span class="dt">List</span> a
append <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 7</span>
<span class="co">-- Relative Difficulty: 5</span>
<span class="co">-- Correctness: 4.5 marks</span>
<span class="co">-- Performance: 1.5 marks</span>
<span class="co">-- Elegance: 1 mark</span>
<span class="co">-- Total: 7</span>
<span class="ot">flatten ::</span> <span class="dt">List</span> (<span class="dt">List</span> a) <span class="ot">-&gt;</span> <span class="dt">List</span> a
flatten <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 8</span>
<span class="co">-- Relative Difficulty: 7</span>
<span class="co">-- Correctness: 5.0 marks</span>
<span class="co">-- Performance: 1.5 marks</span>
<span class="co">-- Elegance: 1.5 mark</span>
<span class="co">-- Total: 8</span>
<span class="ot">flatMap ::</span> (a <span class="ot">-&gt;</span> <span class="dt">List</span> b) <span class="ot">-&gt;</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> <span class="dt">List</span> b
flatMap <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 9</span>
<span class="co">-- Relative Difficulty: 8</span>
<span class="co">-- Correctness: 3.5 marks</span>
<span class="co">-- Performance: 3.0 marks</span>
<span class="co">-- Elegance: 2.5 marks</span>
<span class="co">-- Total: 9</span>
<span class="fu">maximum</span><span class="ot"> ::</span> <span class="dt">List</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span>
<span class="fu">maximum</span> <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- Exercise 10</span>
<span class="co">-- Relative Difficulty: 10</span>
<span class="co">-- Correctness: 5.0 marks</span>
<span class="co">-- Performance: 2.5 marks</span>
<span class="co">-- Elegance: 2.5 marks</span>
<span class="co">-- Total: 10</span>
<span class="fu">reverse</span><span class="ot"> ::</span> <span class="dt">List</span> a <span class="ot">-&gt;</span> <span class="dt">List</span> a
<span class="fu">reverse</span> <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;todo&quot;</span>

<span class="co">-- END Exercises</span>

<span class="co">-- BEGIN Tests for Exercises</span>

<span class="ot">test ::</span> <span class="dt">IO</span> ()
test <span class="fu">=</span>
  <span class="kw">let</span> showNil <span class="fu">=</span> <span class="fu">show</span> (<span class="dt">Nil</span><span class="ot"> ::</span> <span class="dt">List</span> <span class="dt">Int</span>)
      results <span class="fu">=</span>
        [
        <span class="co">-- headOr</span>
        (<span class="st">&quot;headOr&quot;</span>,
         <span class="fu">show</span> (headOr (<span class="dv">1</span> <span class="fu">:|</span> <span class="dv">2</span> <span class="fu">:|</span> <span class="dv">3</span> <span class="fu">:|</span> <span class="dt">Nil</span>) <span class="dv">7</span>)
       , <span class="fu">show</span> <span class="dv">1</span>),

        (<span class="st">&quot;headOr&quot;</span>,
         <span class="fu">show</span> (headOr <span class="dt">Nil</span> <span class="dv">8</span>)
       , <span class="fu">show</span> <span class="dv">8</span>),

        <span class="co">-- sum</span>
        (<span class="st">&quot;sum&quot;</span>,
         <span class="fu">show</span> (<span class="fu">sum</span> (<span class="dv">1</span> <span class="fu">:|</span> <span class="dv">2</span> <span class="fu">:|</span> <span class="dv">3</span> <span class="fu">:|</span> <span class="dt">Nil</span>))
       , <span class="fu">show</span> <span class="dv">6</span>),

        (<span class="st">&quot;sum&quot;</span>,
         <span class="fu">show</span> (<span class="fu">sum</span> <span class="dt">Nil</span>)
       , <span class="fu">show</span> <span class="dv">0</span>),

        <span class="co">-- length</span>
        (<span class="st">&quot;length&quot;</span>,
         <span class="fu">show</span> (<span class="fu">length</span> (<span class="ch">&#39;a&#39;</span> <span class="fu">:|</span> <span class="ch">&#39;b&#39;</span> <span class="fu">:|</span> <span class="ch">&#39;c&#39;</span> <span class="fu">:|</span> <span class="dt">Nil</span>))
       , <span class="fu">show</span> <span class="dv">3</span>),

        (<span class="st">&quot;length&quot;</span>,
         <span class="fu">show</span> (<span class="fu">length</span> <span class="dt">Nil</span>)
       , <span class="fu">show</span> <span class="dv">0</span>),

        <span class="co">-- map</span>
        (<span class="st">&quot;map&quot;</span>,
         <span class="fu">show</span> (<span class="fu">map</span> (<span class="fu">+</span><span class="dv">1</span>) (<span class="dv">1</span> <span class="fu">:|</span> <span class="dv">2</span> <span class="fu">:|</span> <span class="dv">3</span> <span class="fu">:|</span> <span class="dt">Nil</span>))
       , <span class="fu">show</span> (<span class="dv">2</span> <span class="fu">:|</span> <span class="dv">3</span> <span class="fu">:|</span> <span class="dv">4</span> <span class="fu">:|</span> <span class="dt">Nil</span>)),

        (<span class="st">&quot;map&quot;</span>,
         <span class="fu">show</span> (<span class="fu">map</span> (<span class="fu">+</span><span class="dv">1</span>) <span class="dt">Nil</span>)
       , showNil),

        <span class="co">-- filter</span>
        (<span class="st">&quot;filter&quot;</span>,
         <span class="fu">show</span> (<span class="fu">filter</span> <span class="fu">even</span> (<span class="dv">1</span> <span class="fu">:|</span> <span class="dv">2</span> <span class="fu">:|</span> <span class="dv">3</span> <span class="fu">:|</span> <span class="dt">Nil</span>))
       , <span class="fu">show</span> (<span class="dv">2</span> <span class="fu">:|</span> <span class="dt">Nil</span>)),

        (<span class="st">&quot;filter&quot;</span>,
         <span class="fu">show</span> (<span class="fu">filter</span> <span class="fu">even</span> <span class="dt">Nil</span>)
       , showNil),

        <span class="co">-- append</span>
        (<span class="st">&quot;append&quot;</span>,
         <span class="fu">show</span> (append (<span class="dv">1</span> <span class="fu">:|</span> <span class="dv">2</span> <span class="fu">:|</span> <span class="dv">3</span> <span class="fu">:|</span> <span class="dt">Nil</span>) (<span class="dv">4</span> <span class="fu">:|</span> <span class="dt">Nil</span>))
       , <span class="fu">show</span> (<span class="dv">1</span> <span class="fu">:|</span> <span class="dv">2</span> <span class="fu">:|</span> <span class="dv">3</span> <span class="fu">:|</span> <span class="dv">4</span> <span class="fu">:|</span> <span class="dt">Nil</span>)),

        (<span class="st">&quot;append&quot;</span>,
         <span class="fu">show</span> (append (<span class="dv">1</span> <span class="fu">:|</span> <span class="dv">2</span> <span class="fu">:|</span> <span class="dv">3</span> <span class="fu">:|</span> <span class="dt">Nil</span>) <span class="dt">Nil</span>)
       , <span class="fu">show</span> (<span class="dv">1</span> <span class="fu">:|</span> <span class="dv">2</span> <span class="fu">:|</span> <span class="dv">3</span> <span class="fu">:|</span> <span class="dt">Nil</span>)),

        <span class="co">-- flatten</span>
        (<span class="st">&quot;flatten&quot;</span>,
         <span class="fu">show</span> (flatten ((<span class="dv">1</span> <span class="fu">:|</span> <span class="dv">2</span> <span class="fu">:|</span> <span class="dt">Nil</span>) <span class="fu">:|</span> ((<span class="dv">3</span> <span class="fu">:|</span> <span class="dv">4</span> <span class="fu">:|</span> <span class="dt">Nil</span>) <span class="fu">:|</span> <span class="dt">Nil</span>)))
       , <span class="fu">show</span> (<span class="dv">1</span> <span class="fu">:|</span> <span class="dv">2</span> <span class="fu">:|</span> <span class="dv">3</span> <span class="fu">:|</span> <span class="dv">4</span> <span class="fu">:|</span> <span class="dt">Nil</span>)),

        <span class="co">-- flatMap</span>
        (<span class="st">&quot;flatMap&quot;</span>,
         <span class="fu">show</span> (flatMap (\n <span class="ot">-&gt;</span> (n<span class="dv">+1</span>) <span class="fu">:|</span> (n<span class="dv">+2</span>) <span class="fu">:|</span> <span class="dt">Nil</span>) (<span class="dv">1</span> <span class="fu">:|</span> <span class="dv">2</span> <span class="fu">:|</span> <span class="dv">3</span> <span class="fu">:|</span> <span class="dt">Nil</span>))
       , <span class="fu">show</span> (<span class="dv">2</span> <span class="fu">:|</span> <span class="dv">3</span> <span class="fu">:|</span> <span class="dv">3</span> <span class="fu">:|</span> <span class="dv">4</span> <span class="fu">:|</span> <span class="dv">4</span> <span class="fu">:|</span> <span class="dv">5</span> <span class="fu">:|</span> <span class="dt">Nil</span>)),

        <span class="co">-- maximum</span>
        (<span class="st">&quot;maximum&quot;</span>,
         <span class="fu">show</span> (<span class="fu">maximum</span> (<span class="dv">3</span> <span class="fu">:|</span> <span class="dv">1</span> <span class="fu">:|</span> <span class="dv">2</span> <span class="fu">:|</span> <span class="dt">Nil</span>))
       , <span class="fu">show</span> <span class="dv">3</span>),

        <span class="co">-- reverse</span>
        (<span class="st">&quot;reverse&quot;</span>,
         <span class="fu">show</span> (<span class="fu">reverse</span> (<span class="dv">1</span> <span class="fu">:|</span> <span class="dv">2</span> <span class="fu">:|</span> <span class="dv">3</span> <span class="fu">:|</span> <span class="dt">Nil</span>))
       , <span class="fu">show</span> (<span class="dv">3</span> <span class="fu">:|</span> <span class="dv">2</span> <span class="fu">:|</span> <span class="dv">1</span> <span class="fu">:|</span> <span class="dt">Nil</span>))
        ]
      check (n, a, b) <span class="fu">=</span> <span class="kw">do</span> <span class="fu">print</span> (<span class="st">&quot;=== &quot;</span> <span class="fu">++</span> n <span class="fu">++</span> <span class="st">&quot; ===&quot;</span>)
                           <span class="fu">print</span> (<span class="kw">if</span> a <span class="fu">==</span> b <span class="kw">then</span> <span class="st">&quot;PASS&quot;</span> <span class="kw">else</span> <span class="st">&quot;FAIL Expected: &quot;</span> <span class="fu">++</span> b <span class="fu">++</span> <span class="st">&quot; Actual: &quot;</span> <span class="fu">++</span> a)

  <span class="kw">in</span> <span class="fu">mapM_</span> check results

<span class="co">-- END Tests for Exercises</span>

<span class="co">-- Utility</span>

<span class="fu">all</span> <span class="ot">::</span>
  (a <span class="ot">-&gt;</span> <span class="dt">Bool</span>)
  <span class="ot">-&gt;</span> <span class="dt">List</span> a
  <span class="ot">-&gt;</span> <span class="dt">Bool</span>
<span class="fu">all</span> p <span class="fu">=</span>
  foldRight (<span class="fu">&amp;&amp;</span>) <span class="kw">True</span> <span class="fu">.</span> <span class="fu">map</span> p

isEmpty <span class="ot">::</span>
  <span class="dt">List</span> a
  <span class="ot">-&gt;</span> <span class="dt">Bool</span>
isEmpty <span class="dt">Nil</span>    <span class="fu">=</span> <span class="kw">True</span>
isEmpty (_<span class="fu">:|</span>_) <span class="fu">=</span> <span class="kw">False</span>

contains <span class="ot">::</span>
  <span class="kw">Eq</span> a <span class="ot">=&gt;</span>
  <span class="dt">List</span> a
  <span class="ot">-&gt;</span> a
  <span class="ot">-&gt;</span> <span class="dt">Bool</span>
contains <span class="dt">Nil</span>    _ <span class="fu">=</span> <span class="kw">False</span>
contains (h<span class="fu">:|</span>t) e <span class="fu">=</span> h <span class="fu">==</span> e <span class="fu">||</span> contains t e</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Scala exercises for beginners</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/scala-exercises-for-beginners/index.html"/>
  <id>http://blog.tmorris.net/posts/scala-exercises-for-beginners/index.html</id>
  <published>2008-07-15T11:12:51Z</published>
  <updated>2008-07-15T11:12:51Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>The following exercises have come from of a course that I give on Functional Programming. I have assigned them difficulty ratings to make it a bit more exciting. Download the compilable source code from <a href="https://bitbucket.org/dibblego/haskell-course/raw/0.0.2/ports/Exercises.scala">here</a> or find it below. Enjoy :)</p>
<p>These exercises can be translated into <strong>any language powerful enough to possess algebraic data types and case matching</strong> <em>(yes, I am talking to <a href="http://beust.com/weblog/archives/000490.html">you</a>)</em>. Haskell is another such language and I will convert these exercises to Haskell if prompted.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// You are not permitted to use these List methods:</span>
<span class="co">// * length</span>
<span class="co">// * map</span>
<span class="co">// * filter</span>
<span class="co">// * ::: (and variations such as ++)</span>
<span class="co">// * flatten</span>
<span class="co">// * flatMap</span>
<span class="co">// * reverse (and variations i.e. reverseMap, reverse_:::)</span>
<span class="co">// This also means you are not permitted to use for-comprehensions on Lists.</span>
<span class="co">// You are permitted to use the functions you write yourself. For example, Exercise 2 may use Exercise 1 or Exercise 3.</span>
<span class="co">// Using permitted existing methods where appropriate will attract marks for elegance.</span>

<span class="co">// TOTAL marks:    /66</span>

<span class="kw">object</span> Exercises {
  <span class="kw">def</span> <span class="fu">succ</span>(n: Int) = n + <span class="dv">1</span>
  <span class="kw">def</span> <span class="fu">pred</span>(n: Int) = n - <span class="dv">1</span>

  <span class="co">// Exercise 1</span>
  <span class="co">// Relative Difficulty: 1</span>
  <span class="co">// Correctness: 2.0 marks</span>
  <span class="co">// Performance: 0.5 mark</span>
  <span class="co">// Elegance: 0.5 marks</span>
  <span class="co">// Total: 3</span>
  <span class="kw">def</span> <span class="fu">add</span>(x: Int, y: Int): Int = <span class="fu">error</span>(<span class="st">&quot;todo: Assume x and y are 0 or positive. Do not use + or - on Int. Only permitted to use succ/pred (above).&quot;</span>)

  <span class="co">// Exercise 2</span>
  <span class="co">// Relative Difficulty: 2</span>
  <span class="co">// Correctness: 2.5 marks</span>
  <span class="co">// Performance: 1 mark</span>
  <span class="co">// Elegance: 0.5 marks</span>
  <span class="co">// Total: 4</span>
  <span class="kw">def</span> <span class="fu">sum</span>(x: List[Int]): Int = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 3</span>
  <span class="co">// Relative Difficulty: 2</span>
  <span class="co">// Correctness: 2.5 marks</span>
  <span class="co">// Performance: 1 mark</span>
  <span class="co">// Elegance: 0.5 marks</span>
  <span class="co">// Total: 4</span>
  <span class="kw">def</span> length[A](x: List[A]): Int = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 4</span>
  <span class="co">// Relative Difficulty: 5</span>
  <span class="co">// Correctness: 4.5 marks</span>
  <span class="co">// Performance: 1.0 mark</span>
  <span class="co">// Elegance: 1.5 marks</span>
  <span class="co">// Total: 7</span>
  <span class="kw">def</span> map[A, B](x: List[A], f: A =&gt; B): List[B] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 5</span>
  <span class="co">// Relative Difficulty: 5</span>
  <span class="co">// Correctness: 4.5 marks</span>
  <span class="co">// Performance: 1.5 marks</span>
  <span class="co">// Elegance: 1 mark</span>
  <span class="co">// Total: 7</span>
  <span class="kw">def</span> filter[A](x: List[A], f: A =&gt; Boolean): List[A] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 6</span>
  <span class="co">// Relative Difficulty: 5</span>
  <span class="co">// Correctness: 4.5 marks</span>
  <span class="co">// Performance: 1.5 marks</span>
  <span class="co">// Elegance: 1 mark</span>
  <span class="co">// Total: 7</span>
  <span class="kw">def</span> append[A](x: List[A], y: List[A]): List[A] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 7</span>
  <span class="co">// Relative Difficulty: 5</span>
  <span class="co">// Correctness: 4.5 marks</span>
  <span class="co">// Performance: 1.5 marks</span>
  <span class="co">// Elegance: 1 mark</span>
  <span class="co">// Total: 7</span>
  <span class="kw">def</span> concat[A](x: List[List[A]]): List[A] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 8</span>
  <span class="co">// Relative Difficulty: 7</span>
  <span class="co">// Correctness: 5.0 marks</span>
  <span class="co">// Performance: 1.5 marks</span>
  <span class="co">// Elegance: 1.5 mark</span>
  <span class="co">// Total: 8</span>
  <span class="kw">def</span> concatMap[A, B](x: List[A], f: A =&gt; List[B]): List[B] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 9</span>
  <span class="co">// Relative Difficulty: 8</span>
  <span class="co">// Correctness: 3.5 marks</span>
  <span class="co">// Performance: 3.0 marks</span>
  <span class="co">// Elegance: 2.5 marks</span>
  <span class="co">// Total: 9</span>
  <span class="kw">def</span> <span class="fu">maximum</span>(x: List[Int]): Int = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)

  <span class="co">// Exercise 10</span>
  <span class="co">// Relative Difficulty: 10</span>
  <span class="co">// Correctness: 5.0 marks</span>
  <span class="co">// Performance: 2.5 marks</span>
  <span class="co">// Elegance: 2.5 marks</span>
  <span class="co">// Total: 10</span>
  <span class="kw">def</span> reverse[A](x: List[A]): List[A] = <span class="fu">error</span>(<span class="st">&quot;todo&quot;</span>)
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Just an observation</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/just-an-observation/index.html"/>
  <id>http://blog.tmorris.net/posts/just-an-observation/index.html</id>
  <published>2008-07-07T16:51:07Z</published>
  <updated>2008-07-07T16:51:07Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>When some programmers pick up a functional programming language like Microsoft Excel, they stop caring about identifier names.</p>
<pre><code>A1 = blah
B1 = function(A1, C2)
...</code></pre>
<p>Can this observation be explained while maintaining consistency? I think it can.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Implicits for the Fearless</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/implicits-for-the-fearless/index.html"/>
  <id>http://blog.tmorris.net/posts/implicits-for-the-fearless/index.html</id>
  <published>2008-07-05T09:48:06Z</published>
  <updated>2008-07-05T09:48:06Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Some programmers are married to the imperative, side-effecting mindset. This makes them fearful of Scala’s <code>implicit</code> keyword (among many other high-level programming constructs and abstractions). You can read all sorts of amateurish criticism of this language construct on various websites, but I plan to show why they are a necessity to the language being useful (in the intellectually true and meaningful sense – not in a “Java” “pragmatist” sense (I know I’m treading on thin ice here, but the point is worthwhile)).</p>
<p>I also do not plan to address the amateurish claims specifically, since if you are like me, you simply acknowledge their existence, feel a bit sad, then get over it and move on. I mention these cases so that they can be contrasted to my plan to address a discussion I had with someone (who shall remain nameless for now and leave it up to them if they wish to reveal themselves) who put forward an <em>intellectually constructed</em> argument about why they can/should be eliminated. These kind of discussions are very purposeful. While my opponent’s argument was well thought-out (in contrast to the aforementioned), I still think it is wrong. Here is why.</p>
<p>You can do away with <code>implicit</code> definitions in favour of named functions with partial application. This is true, but is it <em>useful</em>? Furthermore, Scala is not exactly friendly to partially applying function arguments, requiring varying levels of awkwardness in certain contexts. I will assume, since I am a nice guy, that this is not the case. I will now alter the argument to what I consider to be equivalent, “Haskell can do away with type-classes”. I altered the argument simply for the sake of brevity in discussion – I will tie it back to Scala code examples at the end.</p>
<p>Let us assume we get rid of just one Haskell type-class, <code>Monad</code>. A monad is a <em>useful</em> abstraction, so we would certainly have to represent it (if you don’t believe this, then it is almost certain that <a href="http://sigfpe.blogspot.com/2006/08/you-could-have-invented-monads-and.html">you have reinvented monads inadvertently</a>). We might do this as follows:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="ot">{-# LANGUAGE RankNTypes #-}</span>

<span class="kw">data</span> <span class="dt">Monad&#39;</span> m <span class="fu">=</span> <span class="dt">Monad&#39;</span> {
<span class="ot">  unit ::</span> (forall a<span class="fu">.</span> a <span class="ot">-&gt;</span> m a),
<span class="ot">  bind ::</span> (forall a b<span class="fu">.</span> m a <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> m b) <span class="ot">-&gt;</span> m b)
}</code></pre>
<p>Then, when it comes to instances, we would write:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">listMonad <span class="fu">=</span> <span class="dt">Monad&#39;</span> (<span class="fu">return</span><span class="ot"> ::</span> a <span class="ot">-&gt;</span> [a]) (<span class="fu">&gt;&gt;=</span>)
maybeMonad <span class="fu">=</span> <span class="dt">Monad&#39;</span> (<span class="fu">return</span><span class="ot"> ::</span> a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a) (<span class="fu">&gt;&gt;=</span>)</code></pre>
<p>Now when we wish to write the all-important functions over monads, we have to do the following:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">sequence&#39; monad [] <span class="fu">=</span> unit monad []
sequence&#39; monad (x<span class="fu">:</span>xs) <span class="fu">=</span> <span class="kw">let</span> (<span class="fu">&gt;&gt;&gt;=</span>) <span class="fu">=</span> bind monad <span class="kw">in</span> x <span class="fu">&gt;&gt;&gt;=</span> \y <span class="ot">-&gt;</span> sequence&#39; monad xs <span class="fu">&gt;&gt;&gt;=</span> \ys <span class="ot">-&gt;</span> unit monad (y<span class="fu">:</span>ys)

mapM&#39; monad f <span class="kw">as</span> <span class="fu">=</span> <span class="fu">...</span> etc<span class="fu">.</span> etc<span class="fu">.</span></code></pre>
<p>The proposal by my opponent in the discussion is that we now write a version of each monad function for each instance by partially applying the monad instance. This is very cumbersome and importantly, <em>less useful</em>.</p>
<p><sub>~</sub>{.Haskell} listSequence = sequence’ listMonad maybeSequence = sequence’ maybeMonad</p>
<p>listMapM = mapM’ listMonad <sub>~</sub> … and so on.</p>
<p>This creates what would otherwise be code in the order of O(1) to turn into O(n) code! This is not good. Do we get any benefit? No, there is no benefit, other than, in the case of Scala, appeasement of ‘the irrational squad’ i.e. those fervently offended by the suggestion to divorce imperative programming. Let us just address this irrationality, even if just briefly, so we can move on.</p>
<p>Unlike Scala, Haskell’s side-effects are controlled, so the mind-shift is <em>forced</em> by the compiler (a successful form of counselling?). A Scala implicit function <em>can</em> perform side-effects. This would be very bad; if they were controlled, would these irrational objections be raised? The answer is no and it is quite easy to expose.</p>
<p>A claim to the contrary is often a case of <a href="http://en.wikipedia.org/wiki/Doublethink">doublethink</a>. Java is a programming language that deliberately encourages side-effects and by implication (also, by its poor type system), makes abstraction and composition extremely difficult to the point of impossibility very early on (see <a href="http://functionaljava.org/">Functional Java</a> for evidence). Yet even in this language – perhaps the most contrived available – we find implicit conversions that attract no objections whatsoever!</p>
<p>Imagine this Java signature <code>int toInt(char c)</code>. Such a user-defined function could indeed perform side-effects and any language feature permitting implicit use of this function is likely to attract criticism. Yet, this is one example of such a function built right-in to the Java language, which is <em>guaranteed by the language specification</em> to perform no side-effects. It is the fact that it is internalised by the user to perform no side-effects that makes it acceptable.</p>
<p>This is valid Java:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="dt">int</span> i = c; <span class="co">// where c is of type char</span></code></pre>
<p>I don’t wish to labour this point, other than to make it clear how easy it is to crush these irrationalities (it continues on in a usual uninteresting fashion).</p>
<p>Requiring code to blow out to O(n) from O(1) is itself not bad, but to further observe that there is no gain from it is conclusive. Interestingly, this is similar to a complaint by David MacIver (and myself – I am just less vocal about it) that Scala lacks default function argument lists in preference for overloading. This also creates unnecessary code-bloat (O(1) -&gt; O(n)) for no benefit. (I hope I am not misrepresenting David here – I have lost the reference to his complaint).</p>
<p>Here is the equivalent Scala code to the above, however, Scala’s type system lacks the ability to pass the <code>unit</code> and <code>bind</code> functions – instead requiring the use of traits.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> Unit[U[_]] {
  <span class="kw">def</span> <span class="dt">unit</span>[A](a: A): U[A]
}

<span class="kw">trait</span> Bind[M[_]] {
  <span class="kw">def</span> bind[A, B](ma: M[A], f: A =&gt; M[B]): M[B]
}

<span class="kw">case</span> <span class="kw">class</span> Monad[M[_]](u: Unit[M], b: Bind[M])

<span class="kw">object</span> Monad {
  <span class="kw">val</span> listMonad = Monad[List](<span class="kw">new</span> Unit[List] {
    <span class="kw">def</span> <span class="dt">unit</span>[A](a: A) = List(a) }, <span class="kw">new</span> Bind[List] {
    <span class="kw">def</span> bind[A, B](ma: List[A], f: A =&gt; List[B]) = ma flatMap f
  })

  <span class="kw">def</span> sequence[M[_], A](m: Monad[M], as: List[M[A]]): M[List[A]] = as <span class="kw">match</span> {
    <span class="kw">case</span> Nil =&gt; m.<span class="fu">u</span>.<span class="fu">unit</span>(Nil)
    <span class="kw">case</span> x :: xs =&gt; m.<span class="fu">b</span>.<span class="fu">bind</span>(x, (y: A) =&gt; m.<span class="fu">b</span>.<span class="fu">bind</span>(sequence[M, A](m, xs), (ys: List[A]) =&gt; m.<span class="fu">u</span>.<span class="fu">unit</span>(y::ys)))
  }

  <span class="kw">def</span> listSequence[A](as: List[List[A]]) = sequence[List, A](listMonad, as)
  <span class="kw">def</span> optionSequence[A](as: List[List[A]]) = sequence[Option, A](optionMonad, as)
  <span class="co">// etc. etc. O(n)!</span>
}</code></pre>
<p>As you can see, I was being <em>very</em> nice when I converted the argument to Haskell. The argument against such a proposal becomes even stronger in the context of Scala.</p>
<p>To my opponent, thanks for the discussion; it was fun and the intellectual maturity is admirable :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>Applicative Functor laws using Reductio (Scala)</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/applicative-functor-laws-using-reductio-scala/index.html"/>
  <id>http://blog.tmorris.net/posts/applicative-functor-laws-using-reductio-scala/index.html</id>
  <published>2008-07-03T16:42:55Z</published>
  <updated>2008-07-03T16:42:55Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Here is the <code>Applicative</code> functor type-class (<em>see <a href="http://www.soi.city.ac.uk/~ross/papers/Applicative.html">Applicative Programming with Effects</a>, Conor McBride, Ross Paterson</em>):</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">class</span> <span class="kw">Applicative</span> f <span class="kw">where</span>
<span class="ot">  pure ::</span> a <span class="ot">-&gt;</span> f a
<span class="ot">  (&lt;*&gt;) ::</span> f (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> f a <span class="ot">-&gt;</span> f b</code></pre>
<p>Here are the laws for the Applicative functor type-class:</p>
<ul>
<li><p>identity<br /><code>pure id &lt;*&gt; u == u</code></p></li>
<li><p>composition<br /><code>pure (.) &lt;*&gt; u &lt;*&gt; v &lt;*&gt; w == u &lt;*&gt; (v &lt;*&gt; w)</code></p></li>
<li><p>homomorphism<br /><code>pure f &lt;*&gt; pure x == pure (f x)</code></p></li>
<li><p>interchange<br /><code>u &lt;*&gt; pure x == pure (\f -&gt; f x) &lt;*&gt; u</code></p></li>
</ul>
<p>Here are those laws stated using <a href="http://reductiotest.org/">Reductio</a>. I have changed <code>pure</code> to <code>unit</code> and the language is Scala:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> ApplicativeLaws {
  <span class="kw">def</span> identity[A[_], X](<span class="kw">implicit</span> a: Applicative[A],
                                 aax: Arbitrary[A[X]],
                                 e: Equal[A[X]]) =
    <span class="fu">prop</span>((apx: A[X]) =&gt; apx === <span class="fu">a</span>(a.<span class="fu">unit</span>((x: X) =&gt; x), apx))

  <span class="kw">def</span> composition[A[_], X, Y, Z](<span class="kw">implicit</span> a: Applicative[A],
                                aayz: Arbitrary[A[Y =&gt; Z]],
                                aaxy: Arbitrary[A[X =&gt; Y]],
                                aax: Arbitrary[A[X]],
                                e: Equal[A[Z]]) =
    <span class="fu">prop</span>((apyz: A[Y =&gt; Z], apxy: A[X =&gt; Y], apx: A[X]) =&gt;
            <span class="fu">a</span>(apyz, <span class="fu">a</span>(apxy, apx)) ===
            <span class="fu">a</span>(<span class="fu">a</span>(<span class="fu">a</span>(a.<span class="fu">unit</span>((f: Y =&gt; Z) =&gt; (g: X =&gt; Y) =&gt; f compose g), apyz), apxy), apx))

  <span class="kw">def</span> homomorphism[A[_], X, Y](<span class="kw">implicit</span> a: Applicative[A],
                                        ax: Arbitrary[X],
                                        axy: Arbitrary[X =&gt; Y],
                                        e: Equal[A[Y]]) =
    <span class="fu">prop</span>((f: X =&gt; Y, x: X) =&gt; <span class="fu">a</span>(a.<span class="fu">unit</span>(f), a.<span class="fu">unit</span>(x)) === a.<span class="fu">unit</span>(<span class="fu">f</span>(x)))

  <span class="kw">def</span> interchange[A[_], X, Y](<span class="kw">implicit</span> a: Applicative[A],
                                       ax: Arbitrary[X],
                                       apxy: Arbitrary[A[X =&gt; Y]],
                                       e: Equal[A[Y]]) =
    <span class="fu">prop</span>((f: A[X =&gt; Y], x: X) =&gt;
      <span class="fu">a</span>(f, a.<span class="fu">unit</span>(x)) === <span class="fu">a</span>(a.<span class="fu">unit</span>((f: X =&gt; Y) =&gt; <span class="fu">f</span>(x)), f))
}</code></pre>
<p>Pretty neat eh? :) Let’s test the <code>Applicative</code> instance for <code>List</code>:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">List(identity[List, Int],
     composition[List, Int, Long, String],
     homomorphism[List, Int, String],
     interchange[List, Int, String]).
  <span class="fu">foreach</span>(p =&gt; summary println p)</code></pre>
<p>This runs 100 unit tests per property, so 400 unit tests altogether. Here is the output:</p>
<pre><code>OK, passed 100 tests.
OK, passed 100 tests.
OK, passed 100 tests.
OK, passed 100 tests.</code></pre>
<p>Woot woot!</p>
    </div>
  </content>
</entry>
<entry>
  <title>Just what the funk is a Functor anyway?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/just-what-the-funk-is-a-functor-anyway/index.html"/>
  <id>http://blog.tmorris.net/posts/just-what-the-funk-is-a-functor-anyway/index.html</id>
  <published>2008-06-28T18:28:15Z</published>
  <updated>2008-06-28T18:28:15Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://apocalisp.wordpress.com/">Runar</a> recently made mention of these so-called Functors and Monads in <a href="http://apocalisp.wordpress.com/2008/06/18/parallel-strategies-and-the-callable-monad/">his excellent post about concurrency/actors in Java</a>. There are all sorts of tutorials out there for understanding what a Monad is, however, I am of the opinion that one must first understand what a Functor is. This is because it is less complex and more general (all monads are functors plus more).</p>
<p>The Java Posse also made a couple of false claims about Runar’s article, but one in particular needs addressing. This is the notion that a functor is applicable to “Functional Programming”. This is false. A functor is applicable to <em>programming</em>. You really, really need to understand what a functor is, if you’re ever going to be skilled in <em>any type of</em> programming; even if it’s just Java web applications for the rest of your life. This concept does not exist ‘on the other side of the fence’ in the imaginary ‘functional programming world’. These suggestions are understandable of course and I don’t intend to labour the point – only make this point clear, since these apparent divides seem to pop up often. On with the story…</p>
<p>In Java, we have an interface called <code>[CharSequence](http://java.sun.com/javase/6/docs/api/java/lang/CharSequence.html)</code>. A few things can be said about <code>CharSequence</code>. How about:</p>
<blockquote>
<p>All implementations guarantee that for some integer <code>n</code>, then if <code>n &gt;= 0 &amp;&amp; n &lt; length()</code>, then <code>charAt(n)</code> will not throw an exception.</p>
</blockquote>
<p>We might call this a <em>law</em> about <code>CharSequence</code> that all implementations must satisfy. We could even find other laws that must satisfy about implementations of the <code>CharSequence</code> interface.</p>
<p>A Functor is an interface and it has two laws. Sadly though, this interface cannot be expressed using Java’s type system – it is simply not clever enough. We must use a hypothetical Java to express it. First though, we have to make up for Java’s missing first-class functions by using an interface. This is easy:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> Function&lt;A, B&gt; {
  B <span class="fu">f</span>(A a);
}</code></pre>
<p>OK, so this a just an interface like any others. It needn’t satisfy any laws; it just takes an argument (A) and returns (B). We could write bazillions of implementations of this interface in Java. We’re going to need this interface to write the <code>Functor</code> interface.</p>
<p>Now, the missing part of Java is called <em>higher-kinds</em> – a term you needn’t concern yourself with too much. I hope this hypothetical syntax is enough to make the point clear:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> Functor&lt;E&lt;_&gt;&gt; {
  &lt;A, B&gt; E&lt;b&gt; <span class="fu">fmap</span>(Function&lt;A, B&gt; f, E&lt;a&gt; fa);
}</code></pre>
<p>So the foreign part here is <code>E&lt;_&gt;</code>. Consider E to stand for ‘Environment’. It is a type parameter that takes yet another type parameter (which is why it is denoted E&lt;_&gt;). This means I could use <code>List</code> or <code>Set</code>, but not <code>Integer</code> as the type parameter value for E, since <code>List</code> and <code>Set</code> take another type parameter while <code>Integer</code> does not. You might think of the <code>Functor</code> interface as ‘applying the given function within the environment’.</p>
<p>We might write an implementation like this:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">class</span> ListFunctor <span class="kw">implements</span> Functor&lt;list&gt; {
  <span class="kw">public</span> &lt;A, B&gt; List&lt;b&gt; <span class="fu">fmap</span>(Function&lt;A, B&gt; f, List&lt;a&gt; list) {
    <span class="co">// todo: apply the given function on all elements in &#39;list&#39; and return the result</span>
  }
}</code></pre>
<p>In general discussion, we would call this <em>the list functor</em>, simply because the value for the environment has been applied. In Runar’s article, he was talking about the <code>Callable</code> functor; yet another environment. There are many possibilities for the environment here; <code>List</code> and <code>Callable</code> are but two.</p>
<h4 id="the-laws">The Laws</h4>
<p>Let us not forget the laws :) Just like all implementations of <code>CharSequence</code> have laws to obey, so do all functors. They are called <em>identity</em> and <em>composition</em>.</p>
<h5 id="identity">Identity</h5>
<p>Remember the <code>Function</code> interface? Here is an implementation:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">class</span> Identity&lt;a&gt; <span class="kw">implements</span> Function&lt;A, A&gt; {
  <span class="kw">public</span> A <span class="fu">f</span>(A a) { <span class="kw">return</span> a; }
}</code></pre>
<p>If we are given an implementation of <code>Functor</code> – which I will call <code>f</code> – then it must satisfy <code>f.fmap(new Identity(), x)</code> is equivalent to <code>x</code> <em>(for any value of x)</em>. So that’s the identity law out of the way. Mapping <em>the identity function</em> across a functor yields the same value.</p>
<h5 id="composition">Composition</h5>
<p>The law of composition is a little less friendly when it comes to expressing it in Java so I will refrain :) While it is an important part of making up the concept of a functor, it may be best to defer this final piece of the puzzle for now.</p>
<p>For completeness, I will state the law using a shorter syntax, but if this is foreign or worrying, then please ignore it: <code>f.fmap(a compose b, x)</code> is equivalent to <code>f.fmap(a, f.fmap(b, x))</code> <em>(for any value of a, b and x – a and b are <code>Function</code> objects)</em>.</p>
<p>That’s all there is to a Functor. If you use the <code>map</code> function on lists or perhaps the <code>map</code> method on <code>scala.Option</code>, then you are using one specific instance of a functor, since these functions/methods satisfy the conditions for a functor. Even throwing an exception is using a specific functor! Perhaps that can be explained another time :)</p>
<p>I should also add that when referring to a functor (unqualified), we are referring to a <em>covariant</em> functor. Other types of functors include contra-variant and invariant functors. We can talk about those another day :)</p>
<p>Next: Just What the Flip is a Monad?</p>
<p>Questions?</p>
    </div>
  </content>
</entry>
<entry>
  <title>Monad Laws using Reductio (Scala)</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/monad-laws-using-reductio-scala/index.html"/>
  <id>http://blog.tmorris.net/posts/monad-laws-using-reductio-scala/index.html</id>
  <published>2008-06-26T10:57:10Z</published>
  <updated>2008-06-26T10:57:10Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>In the spirit of yesterday’s post that denoted the Functor Laws using Reductio, I will also give the Monad Laws. Before I do however, here is an example use of the <code>FunctorLaws</code> object that runs 600 unit tests when testing a <code>Functor</code> implementation for <code>scala.Option[A]</code>, <code>scala.List</code> and finally, for the <code>scala.Either[A, _]</code> functor just to make it a bit quirky and probably confuse a few of you (in that case, ignore it for now!) :)</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">val</span> prop_OptionIdentity = identity[Option, Int]
<span class="kw">val</span> prop_OptionComposition = composition[Option, Int, String, Long]

<span class="kw">val</span> prop_ListIdentity = identity[List, Int]
<span class="kw">val</span> prop_ListComposition = composition[List, Int, String, Long]

<span class="kw">val</span> prop_EitherIdentity = identity[Apply1Of2[Either, String]#Apply, Int]
<span class="kw">val</span> prop_EitherComposition = composition[Apply1Of2[Either, String]#Apply, Int, String, Long]

<span class="co">// OK passed 100 tests. (appears 6 times -- once per property)</span></code></pre>
<p>…and the obligatory Monad Laws follow (import statements omitted this time, but they are the same as previous)…</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> MonadLaws {
  <span class="kw">def</span> leftIdentity[M[_], A, B](<span class="kw">implicit</span> m: Monad[M],
                                     am: Arbitrary[M[B]],
                                     aa: Arbitrary[A],
                                     ca: Coarbitrary[A]) =
    <span class="fu">prop</span>((a: A, f: A =&gt; M[B]) =&gt;
      m.<span class="fu">bind</span>(f, m.<span class="fu">unit</span>(a)) === <span class="fu">f</span>(a))

  <span class="kw">def</span> rightIdentity[M[_], A](<span class="kw">implicit</span> m: Monad[M],
                                      am: Arbitrary[M[A]]) =
    <span class="fu">prop</span>((ma: M[A]) =&gt; m.<span class="fu">bind</span>((a: A) =&gt;
      m.<span class="fu">unit</span>(a), ma) === ma)

  <span class="kw">def</span> associativity[M[_], A, B, C](<span class="kw">implicit</span> m: Monad[M],
                                           am: Arbitrary[M[A]],
                                           ca: Coarbitrary[A],
                                           cb: Coarbitrary[B],
                                           amb: Arbitrary[M[B]],
                                           amc: Arbitrary[M[C]]) =
    <span class="fu">prop</span>((ma: M[A], f: A =&gt; M[B], g: B =&gt; M[C]) =&gt;
      m.<span class="fu">bind</span>(g, m.<span class="fu">bind</span>(f, ma)) === m.<span class="fu">bind</span>((a: A) =&gt; m.<span class="fu">bind</span>(g, <span class="fu">f</span>(a)), ma))
}</code></pre>
<p>Woot! Woot!</p>
    </div>
  </content>
</entry>
<entry>
  <title>You’d naturally write flatMap yourself if asked the question</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/youd-naturally-write-flatmap-yourself-if-asked-the-question/index.html"/>
  <id>http://blog.tmorris.net/posts/youd-naturally-write-flatmap-yourself-if-asked-the-question/index.html</id>
  <published>2008-06-25T10:04:45Z</published>
  <updated>2008-06-25T10:04:45Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Many people struggle to understand those fluffy things called <em>Monads</em> and why they are important. I’m not going to attempt to alleviate this to a large degree, but I have had a recent success with a friend in having them attempt to write a familiar Scala function as a method. That is, the <code>[List.flatten](http://www.scala-lang.org/docu/files/api/scala/List$object.html#flatten(List[List[A]]))</code> function, which simply takes a <code>List</code> of <code>List</code> of some type <code>A</code> and returns a <code>List[A]</code>. It does this by concatenating all the lists together. I think most people are familiar with this function and have a good mental model of how it works. If this is the case and you are less confident about <code>List.flatMap</code>, then I hope to bring a point to your attention that might help you bring it home.</p>
<p>If you take a look at <code>List.sort</code>, you see it takes a function <code>(A, A) =&gt; Boolean</code>. This is because the type parameter to <code>List</code> is ‘just any A’. It would be nice if it was ‘any A, so long as it has defined order’. That way, you can just call <code>list.sort</code> and be done with it. This would require the creation of a new class with a more restricted type parameter; for example, you might pass the function at list creation time, like you do with a <code>TreeMap</code>.</p>
<p>Imagine writing <code>List.flatten</code> on the <code>List[A]</code> class as a <em>method</em> using the same technique. You wouldn’t be able to, since the method belongs on a <code>List[List[A]]</code>. You’d need to write the method such that it takes an argument: <code>A =&gt; List[A]</code> before you could then call <code>flatten</code>. When you have a <code>List[List[A]]</code>, you’d just call this method with the identity function <code>x =&gt; x</code> to obtain your resulting <code>List[A]</code>. Here is how the method would look:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">def</span> <span class="fu">flatten</span>(f: A =&gt; List[A]): List[A] = ...</code></pre>
<p>Guess what?! This method is <code>flatMap</code>! Let’s ignore the fact that the Scala API is significantly broken, including the <code>List.flatMap</code> method using <code>Iterable</code> in place of <code>List</code> here. Notice though, that <code>flatMap</code> is actually generalised by taking another type parameter, so we have just invented an unnecessarily specialised version of <code>flatMap</code>. Let’s fix it:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">def</span> flatten[B](f: A =&gt; List[B]): List[B] = ...</code></pre>
<p>Woot woot! In other words, <code>flatten(list)</code> is equivalent to <code>list flatMap (x =&gt; x)</code>. Furthermore, this should hold for more than just list, but for other type constructors too (sadly, <code>Option</code> is missing a flatten function: <code>Option[Option[A]] =&gt; Option[A]</code>). This is a special relationship that all monads have (join is a synonym for flatten and bind is a synonym for flatMap):</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">join <span class="fu">=</span> bind <span class="fu">id</span></code></pre>
<p>We can express this using <a href="http://reductiotest.org/">Reductio</a> (the Scala API of course!):</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">val</span> prop_flat = <span class="fu">prop</span>((t: List[List[Int]]) =&gt; List.<span class="fu">flatten</span>(t) == t.<span class="fu">flatMap</span>(x =&gt; x))
<span class="co">// OK passed 100 tests.</span></code></pre>
<p>I hope this helps. If it doesn’t, ask a question or ignore my ranting :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>Functor Laws using Reductio (Scala)</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/functor-laws-using-reductio-scala/index.html"/>
  <id>http://blog.tmorris.net/posts/functor-laws-using-reductio-scala/index.html</id>
  <published>2008-06-25T16:07:08Z</published>
  <updated>2008-06-25T16:07:08Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>A somewhat intricate and extremely useful code snippet using <a href="http://reductiotest.org/">Reductio</a> for testing the laws of any Functor instance (note that the <code>Functor</code> type is part of <a href="http://wiki.workingmouse.com/index.php/Scalaz">Scalaz</a>):</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">import</span> reductios.<span class="fu">Property</span>.<span class="fu">_</span>
<span class="kw">import</span> reductios.<span class="fu">Arbitrary</span>
<span class="kw">import</span> reductio.<span class="fu">Coarbitrary</span>
<span class="kw">import</span> reductios.<span class="fu">Arbitrary</span>.<span class="fu">_</span>

<span class="kw">object</span> FunctorLaws {
  <span class="kw">def</span> identity[F[_], A](<span class="kw">implicit</span> f: Functor[F], af: Arbitrary[F[A]]) =
    <span class="fu">prop</span>((fa: F[A]) =&gt; f.<span class="fu">fmap</span>((a: A) =&gt; a, fa) === fa)

  <span class="kw">def</span> composition[F[_], A, B, C](<span class="kw">implicit</span> f: Functor[F],
                                          af: Arbitrary[F[A]],
                                          ac: Arbitrary[C],
                                          cb: Coarbitrary[B],
                                          ab: Arbitrary[B],
                                          ca: Coarbitrary[A]) =
    <span class="fu">prop</span>((fa: F[A], h: B =&gt; C, i: A =&gt; B) =&gt;
            f.<span class="fu">fmap</span>(h compose i, fa) === f.<span class="fu">fmap</span>(h, f.<span class="fu">fmap</span>(i, fa)))
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>ABC Learning Centres required for adults</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/abc-learning-centres-required-for-adults/index.html"/>
  <id>http://blog.tmorris.net/posts/abc-learning-centres-required-for-adults/index.html</id>
  <published>2008-06-23T15:05:32Z</published>
  <updated>2008-06-23T15:05:32Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>From <a href="http://www.news.com.au/comments/0,23600,23907216-462,00.html">http://www.news.com.au/comments/0,23600,23907216-462,00.html</a> on the recent price rise by ABC Learning Centres (i.e. child care):</p>
<blockquote>
<p>ABC Learing centres have now increased there fees three times since early 2007. There justification for these raises in no way benefit the children in they’re care or they’re staff!.</p>
</blockquote>
    </div>
  </content>
</entry>
<entry>
  <title>Applicative Functors in Scala</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/applicative-functors-in-scala/index.html"/>
  <id>http://blog.tmorris.net/posts/applicative-functors-in-scala/index.html</id>
  <published>2008-06-20T09:39:02Z</published>
  <updated>2008-06-20T09:39:02Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>The <a href="http://www.soi.city.ac.uk/~ross/papers/Applicative.html">Applicative Functor</a> pattern is an incredibly powerful abstraction. I recently added it to a branch of <a href="http://wiki.workingmouse.com/index.php/Scalaz">Scalaz</a>. However, it would be nice if I could alter the fixity of functions so that the parentheses below are not required to make the expression right-associative.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">val</span> add = (a: Int) =&gt; (b: Int) =&gt; (c: Int) =&gt; a + b + c
<span class="kw">val</span> none: Option[Int] = None <span class="co">// Grrr Scala</span>

<span class="co">// Some(24)</span>
<span class="fu">println</span>(Some(<span class="dv">7</span>) &lt;*&gt; (Some(<span class="dv">8</span>) &lt;*&gt; (Some(<span class="dv">9</span>) &gt; add)))

<span class="co">// None</span>
<span class="fu">println</span>(Some(<span class="dv">7</span>) &lt;*&gt; (none &lt;*&gt; (Some(<span class="dv">9</span>) &gt; add)))

<span class="co">// List(87, 88, 89, 91, 92, 93)</span>
<span class="fu">println</span>(List(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>) &lt;*&gt; (List(<span class="dv">77</span>) &lt;*&gt; (List(<span class="dv">9</span>, <span class="dv">13</span>) &gt; add)))</code></pre>
<p>Having to write that silly <code>none</code> value is annoying too. At the very least a none function would suffice:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">def</span> none[A]: Option[A] = None</code></pre>
<p>That way. I could use <code>none[Int]</code> and be done with it.</p>
<p>Still, this pattern is a nice tool to use and I will surely be using it in the future.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Tests as Documentation</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/tests-as-documentation/index.html"/>
  <id>http://blog.tmorris.net/posts/tests-as-documentation/index.html</id>
  <published>2008-06-17T15:39:04Z</published>
  <updated>2008-06-17T15:39:04Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://wiki.workingmouse.com/index.php/Tests_As_Documentation"><em>(Copied from)</em></a></p>
<h4 id="wouldnt-it-be-nice-if">Wouldn’t it be nice if?</h4>
<p>When disciplined programmers write unit tests, they often make reference to the fact that their tests provide a means of documentation the software that it is testing. This documentation is more appropriate than what would otherwise be informal and potentially ambiguous comments using English. Take the simple example of adding two numbers. We might document using informal language:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="co">/**</span>
<span class="co"> * Adds the two arguments.</span>
<span class="co"> *</span>
<span class="co"> * </span><span class="kw">@param a </span><span class="co">Add this argument to the other one.</span>
<span class="co"> * </span><span class="kw">@param b </span><span class="co">Add this argument to the other one.</span>
<span class="co"> * </span><span class="kw">@return </span><span class="co">The sum of the two arguments.</span>
<span class="co"> */</span></code></pre>
<p>With unit tests, we might instead write something more formal and unambiguous:</p>
<p><sub><del>{.Java} assertEqual(add(2, 2), 4) assertEqual(add(4, 3), 7)</del></sub> … so on</p>
<p>It might be argued that both these forms of documentation complement each other. After all, while the unit tests have less room for misinterpretation, they are incomplete; for example, what about <code>add(88, 37)</code>? The English description makes up for this shortcoming.</p>
<p>We could reword our English to be a little more succinct:</p>
<p><sub>~</sub>{.Java} /** * Passing 0 as one argument returns the other argument, * otherwise, the result is the same as subtracting 1 from one argument and * adding 1 to the other argument then passing those values instead. * e.g. add(2, 8 ) is the same as add(1, 9) and so on until one of the arguments reaches 0. */</p>
<p>Wouldn’t it be nice if we could express this formally in unit tests? You can, read on.</p>
<p>While this example is trivial, it scales in proportion to the amount of discipline that the programmer is willing to exercise by <em>controlling side-effects</em> in their program. If we write our programs such that most of our methods retain the property of <em>referential transparency</em>, we can use this advanced method of tests as documentation. When we refactor our code to make tests easier to write, it is often the case that we are doing exactly this anyway. Win win!</p>
<h4 id="lets-scale-up-a-little">Let’s scale up a little</h4>
<p>We’ll give a slightly less trivial example next, but not so trivial that it takes away from the important points. In fact, let’s unit test a specific part of the Java Collections library – the <code>java.util.Collections.reverse</code> method. There are various ways of testing this method and we will choose one here that serves to illustrate the point of unit tests as documentation.</p>
<p>The <code>reverse</code> method can be described as follows:</p>
<ol style="list-style-type: decimal">
<li><p>For the empty list, then reversing this list is always the same list</p></li>
<li><p>For the list with one element, then reversing this list is always the same list</p></li>
<li><p>For any other two lists (let’s call them ‘a’ and ‘b’), then appending b to a then reversing will yield the same list as reversing a, then appending the result to the reverse of b. Since this statement is a little convoluted, let’s write it with some pseudo-Java syntax notation: <code>(a.append(b)).reverse() == b.reverse().append(a.reverse())</code></p></li>
</ol>
<p>It is an interesting observation here that we have <em>completely specified</em> the <code>reverse</code> method. That is, under some reasonable assumptions, it is not possible to write a method that is not equivalent to <code>reverse</code> that also satisfies our statements above. This is the ultimate form of code documentation!</p>
<p>We will ignore the first statement for the sake of interest and verbosity and focus on expressing the other two. This is because statements 2 and 3 have <em>free variables</em>, while statement 1 is merely an assertion that does not illustrate any interesting points. Let us start with the second statement and articulate it using <a href="http://reductiotest.org/">Reductio</a>:</p>
<pre class="sourceCode Java"><code class="sourceCode java">    Property p2 = <span class="fu">property</span>(arbInteger, <span class="kw">new</span> F&lt;Integer, Property&gt;() {
      <span class="kw">public</span> Property <span class="fu">f</span>(Integer i) {
        <span class="kw">return</span> <span class="fu">prop</span>(<span class="fu">single</span>(i).<span class="fu">equals</span>(<span class="fu">reverse</span>(<span class="fu">single</span>(i))));
      }
    });</code></pre>
<p>That pretty much sums up statement 2 doesn’t it? What about statement 3:</p>
<pre class="sourceCode Java"><code class="sourceCode java">Property p3 = <span class="fu">property</span>(<span class="fu">arbLinkedList</span>(arbInteger), <span class="fu">arbLinkedList</span>(arbInteger), <span class="kw">new</span> F2&lt;LinkedList&lt;integer&gt;, LinkedList&lt;integer&gt;, Property&gt;() {
  <span class="kw">public</span> Property <span class="fu">f</span>(LinkedList&lt;integer&gt; a, LinkedList&lt;integer&gt; b) {
    <span class="dt">final</span> LinkedList&lt;integer&gt; x = <span class="fu">reverse</span>(<span class="fu">append</span>(a, b));
    <span class="dt">final</span> LinkedList&lt;integer&gt; y = <span class="fu">append</span>(<span class="fu">reverse</span>(b), <span class="fu">reverse</span>(a));
    <span class="kw">return</span> <span class="fu">prop</span>(x.<span class="fu">equals</span>(y));
  }
});</code></pre>
<h4 id="is-that-it">Is that it?</h4>
<p>Yep. Notwithstanding the absence of statement 1, we have completely specified the behaviour for the Java <code>Collections.reverse</code> method. We have exhaustive and formal documentation instead of one or the other as we traditionally do. What an improvement!</p>
<h4 id="yeah-but-i-want-to-unit-test-it-too">Yeah but I want to unit test it too</h4>
<p>That’s not hard either. How many unit tests do you want to run? By default, Reductio will run 100 unit tests per <code>Property</code> declaration. You can adjust this and various other factors about how your unit tests are executed. If you want to take the default, then a few more lines of code are enough to do just that:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="fu">list</span>(p2, p3).<span class="fu">foreach</span>(<span class="kw">new</span> Effect&lt;property&gt;() {
  <span class="kw">public</span> <span class="dt">void</span> <span class="fu">e</span>(Property p) {
    summary.<span class="fu">println</span>(p.<span class="fu">check</span>());
  }
});</code></pre>
<p>If you run this line of code, you will see the result of your 200 unit tests on the standard output:</p>
<pre><code>OK, passed 100 tests.
OK, passed 100 tests.</code></pre>
<p>Is that too magical for you? Don’t believe me? Want to see it fail? OK, let’s fail it. In the expression of statement 3, change the line <code>b.addAll(a)</code> to <code>a.addAll(b)</code> and run again. What did you see? Here is what I saw:</p>
<pre><code>OK, passed 100 tests.
Falsified after 4 passed tests with arguments: [[3, 2, -3, 4, -3],[2, -3, 4, -3]]</code></pre>
<p>Yep, it failed alright :) When those two list values are used as our free variables, the property is false and the unit test fails.</p>
<h4 id="other-resources">Other Resources</h4>
<ul>
<li><p><a href="http://wiki.workingmouse.com/index.php/A_Case_for_Automated_Testing">A Case for Automated Testing</a></p></li>
<li><p><a href="http://wiki.workingmouse.com/index.php/Reductio_EqualsHashCode">Reductio EqualsHashCode</a></p></li>
<li><p><a href="http://reductiotest.org/">Reductio Website</a></p></li>
<li><p><a href="http://reductiotest.org/examples">More Reductio examples</a></p></li>
<li><p><a href="http://reductiotest.org/manual">Reductio Manual</a></p></li>
</ul>
<h4 id="complete-runnable-source-code">Complete Runnable Source Code</h4>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">import fj.Effect;</span>
<span class="kw">import fj.F;</span>
<span class="kw">import fj.F2;</span>
<span class="kw">import static fj.data.List.list;</span>
<span class="kw">import static reductio.Arbitrary.arbInteger;</span>
<span class="kw">import static reductio.Arbitrary.arbLinkedList;</span>
<span class="kw">import static reductio.CheckResult.summary;</span>
<span class="kw">import reductio.Property;</span>
<span class="kw">import static reductio.Property.prop;</span>
<span class="kw">import static reductio.Property.property;</span>

<span class="kw">import java.util.Collections;</span>
<span class="kw">import static java.util.Collections.singletonList;</span>
<span class="kw">import java.util.LinkedList;</span>

<span class="kw">public</span> <span class="kw">class</span> ListReverse {
  <span class="kw">public</span> <span class="dt">static</span> <span class="dt">void</span> <span class="fu">main</span>(String[] args) {
    Property p2 = <span class="fu">property</span>(arbInteger, <span class="kw">new</span> F&lt;Integer, Property&gt;() {
      <span class="kw">public</span> Property <span class="fu">f</span>(Integer i) {
        <span class="kw">return</span> <span class="fu">prop</span>(<span class="fu">single</span>(i).<span class="fu">equals</span>(<span class="fu">reverse</span>(<span class="fu">single</span>(i))));
      }
    });

    Property p3 = <span class="fu">property</span>(<span class="fu">arbLinkedList</span>(arbInteger), <span class="fu">arbLinkedList</span>(arbInteger), <span class="kw">new</span> F2&lt;LinkedList&lt;integer&gt;, LinkedList&lt;integer&gt;, Property&gt;() {
      <span class="kw">public</span> Property <span class="fu">f</span>(LinkedList&lt;integer&gt; a, LinkedList&lt;integer&gt; b) {
        <span class="dt">final</span> LinkedList&lt;integer&gt; x = <span class="fu">reverse</span>(<span class="fu">append</span>(a, b));
        <span class="dt">final</span> LinkedList&lt;integer&gt; y = <span class="fu">append</span>(<span class="fu">reverse</span>(b), <span class="fu">reverse</span>(a));
        <span class="kw">return</span> <span class="fu">prop</span>(x.<span class="fu">equals</span>(y));
      }
    });

    <span class="fu">list</span>(p2, p3).<span class="fu">foreach</span>(<span class="kw">new</span> Effect&lt;property&gt;() {
      <span class="kw">public</span> <span class="dt">void</span> <span class="fu">e</span>(Property p) {
        summary.<span class="fu">println</span>(p.<span class="fu">check</span>());
      }
    });
  }

  <span class="dt">static</span> &lt;a&gt; LinkedList&lt;a&gt; <span class="fu">single</span>(A a) {
    <span class="kw">return</span> <span class="kw">new</span> LinkedList&lt;a&gt;(<span class="fu">singletonList</span>(a));
  }

  <span class="dt">static</span> &lt;a&gt; LinkedList&lt;a&gt; <span class="fu">reverse</span>(LinkedList&lt;a&gt; as) {
    LinkedList&lt;a&gt; aas = <span class="kw">new</span> LinkedList&lt;a&gt;(as);
    Collections.<span class="fu">reverse</span>(aas);
    <span class="kw">return</span> aas;
  }

  <span class="dt">static</span> &lt;a&gt; LinkedList&lt;a&gt; <span class="fu">append</span>(LinkedList&lt;a&gt; as1, LinkedList&lt;a&gt; as2) {
    LinkedList&lt;a&gt; aas = <span class="kw">new</span> LinkedList&lt;a&gt;(as1);
    aas.<span class="fu">addAll</span>(as2);
    <span class="kw">return</span> aas;
  }
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>A Case for Automated Testing</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/a-case-for-automated-testing/index.html"/>
  <id>http://blog.tmorris.net/posts/a-case-for-automated-testing/index.html</id>
  <published>2008-06-06T15:58:53Z</published>
  <updated>2008-06-06T15:58:53Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://wiki.workingmouse.com/index.php/A_Case_for_Automated_Testing"><em>(Copied from)</em></a></p>
<h4 id="discipline-and-testing">Discipline and Testing</h4>
<p>Disciplined programmers write tests while developing code. Some even refactor their tests when certain situations arise. Imagine this one. You have just written a method that takes two integer arguments, adds them and subtracts seven before returning the result.</p>
<p>Your code might look like this:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="dt">int</span> <span class="fu">addThenSubtract7</span>(<span class="dt">int</span> x, <span class="dt">int</span> y) {
  <span class="kw">return</span> x + y - <span class="dv">7</span>;
}</code></pre>
<p>When you test this code – either before, during or after you write the method above – you will likely write tests that exhibit some property about the method under test. For example, when one argument is the negation of the other, you will always get back <code>-7</code>.</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="fu">assertEquals</span>(-<span class="dv">7</span>, <span class="fu">addThenSubtract7</span>(<span class="dv">0</span>, <span class="dv">0</span>));
<span class="fu">assertEquals</span>(-<span class="dv">7</span>, <span class="fu">addThenSubtract7</span>(<span class="dv">1</span>, -<span class="dv">1</span>));
<span class="fu">assertEquals</span>(-<span class="dv">7</span>, <span class="fu">addThenSubtract7</span>(<span class="dv">2</span>, -<span class="dv">2</span>));
<span class="fu">assertEquals</span>(-<span class="dv">7</span>, <span class="fu">addThenSubtract7</span>(<span class="dv">3</span>, -<span class="dv">3</span>));
<span class="fu">assertEquals</span>(-<span class="dv">7</span>, <span class="fu">addThenSubtract7</span>(<span class="dv">4</span>, -<span class="dv">4</span>));
<span class="fu">assertEquals</span>(-<span class="dv">7</span>, <span class="fu">addThenSubtract7</span>(<span class="dv">5</span>, -<span class="dv">5</span>));</code></pre>
<p>You might refactor in this scenario:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="fu">assertTrue</span>(<span class="fu">negationBecomesNegative7</span>(<span class="dv">0</span>));
<span class="fu">assertTrue</span>(<span class="fu">negationBecomesNegative7</span>(<span class="dv">1</span>));
<span class="fu">assertTrue</span>(<span class="fu">negationBecomesNegative7</span>(<span class="dv">2</span>));
...

<span class="kw">public</span> <span class="dt">boolean</span> <span class="fu">negationBecomesNegative7</span>(<span class="dt">int</span> a) {
  <span class="kw">return</span> <span class="fu">addThenSubtract</span>(a, -a) == -<span class="dv">7</span>;
}</code></pre>
<p>Indeed, you might use a loop for your input values:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">for</span>(<span class="dt">int</span> i = <span class="dv">0</span>; i &lt; <span class="dv">100</span>; i++) {
  <span class="fu">assertTrue</span>(<span class="fu">negationBecomesNegative7</span>(i));
}
...</code></pre>
<h4 id="specifying-properties">Specifying Properties</h4>
<p>There are other properties about the method <code>addThenSubtract7</code>. For example, if you switch the arguments, the result is unaffected. In fact, this property comes up a fair bit so it even has a name; <em>commutativity</em>. You could come up with a similar scenario as that described above through a process of repeating assertions with different values, refactoring a bit and generally trying to test as rigorously as possible with minimal effort and permitting future maintainability of both your code and your tests.</p>
<p>Eventually, you will have written properties about your method such that there is no reason to write any more properties, since they would be implied by your existing properties. For example:</p>
<ul>
<li><p>You could write a test for <code>addThenSubtract7(0, anyValue)</code> results in <code>anyValue - 7</code>.</p></li>
<li><p>Then you could write a test for commutativity; <code>addThenSubtract7(someX, someY)</code> results in the same value as <code>addThenSubtract7(someY, someX)</code>.</p></li>
</ul>
<p>Now, is there any point writing a test for <code>addThenSubtract7(anyValue, 0)</code> results in <code>anyValue - 7</code>? Isn’t this implied by the test for commutativity? Right, this test would be redundant.</p>
<p>Ultimately, you could aim for an <em>unambiguous specification</em> of your method under test. However is there a nicer way to write all these tests?</p>
<h4 id="lets-automate-it">Let’s Automate it!</h4>
<p>Going back to the first property <code>negationBecomesNegative7</code>, don’t you really just want to say this and then let the rest be taken care of by clever automation?</p>
<pre><code>for all int values named a. then addThenSubtract7(a, -a) == -7</code></pre>
<p>This is the job of <em>Automated Specification-based Testing</em> such as that which is implemented by <a href="http://reductiotest.org/">Reductio for Java</a>. Reductio allows you to write the above expression using standard Java syntax:</p>
<pre class="sourceCode Java"><code class="sourceCode java">Property p = <span class="fu">property</span>(arbInteger, <span class="kw">new</span> F&lt;integer, Property&gt;() {
  <span class="kw">public</span> Property <span class="fu">f</span>(<span class="dt">final</span> Integer a) {
    <span class="kw">return</span> <span class="fu">prop</span>(<span class="fu">addThenSubtract7</span>(a, -a) == -<span class="dv">7</span>);
  }
});</code></pre>
<p>What is going on here? We are passing in our generator of arbitrary integer values (<code>arbInteger</code>), then an anonymous inner class that asserts our property for our <em>free variable</em> (the one called ‘a’).</p>
<p>OK, it can’t be this easy can it? No, sorry, it can’t. There is an enormous of work to do next. Ready, here it is:</p>
<pre><code>p.check();</code></pre>
<p>With all that heavy lifting taken off you by the test automation, you should now have plenty of time and energy to get on with delivering your software to your client or maybe reading news blogs if that is what you prefer :)</p>
<h4 id="shrinking">Shrinking</h4>
<p>When you run the test automation, you receive a result of success after running 100 (by default – adjustable of course) tests or you receive a failed result with a counter-example. That is, you receive a value for your free variable (a) for which the property was not true.</p>
<p>Does it stop here? I mean, this is great and everything, but surely there’s not more help that can be provided by clever test automation software? There are a couple more clever things that can be done.</p>
<p>First is the <em>shrinking of a counter-example</em>. Imagine there was a bug in the <code>addThenSubtract7</code> method and you received a counter-example of <code>1789234</code>. What’s so special about this number? Well, that depends on the bug, however, maybe this is just the first counter-example that was found. Imagine, however, that the bug also exhibited itself (i.e. the property fails) with a counter-example of <code>2</code>. Isn’t this a more useful counter-example? Wouldn’t you prefer that this one was reported and not that big, insignificant number?</p>
<p>So that’s another great feature of test automation; it can report back to you <em>useful counter-examples</em> in the event of a bug. When you perform manual testing as above, you might remove a couple of your assert methods to help narrow down the bug. This is the hard way! This very act can be automated.</p>
<p>Imagine you wrote this property (<code>a + b == a - b</code>):</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="dt">final</span> Property p = <span class="fu">property</span>(arbInteger, arbInteger, <span class="kw">new</span> F2&lt;integer, Integer, Property&gt;() {
  <span class="kw">public</span> Property <span class="fu">f</span>(<span class="dt">final</span> Integer a, <span class="dt">final</span> Integer b) {
    <span class="kw">return</span> <span class="fu">prop</span>(a + b == a - b);
  }
});</code></pre>
<p>It turns out that this property is true for some values such as a == 0 and b == 0, but false for others:</p>
<ul>
<li><p><code>a = 1, b = 15</code></p></li>
<li><p><code>a = 147, b = 92582</code></p></li>
<li><p><code>a = 5923, b = 12</code></p></li>
</ul>
<p>But which of these counter-examples is going to be most useful to you, the tester? Any of the above? How about this counter-example: <code>a = 0, b = 1</code>? Isn’t this more useful to you than any of those above?</p>
<p>Good test automation software will report a reasonably small counter-example in the event of the falsification of a property.</p>
<h4 id="automated-mocking">Automated Mocking</h4>
<p>OK, is there more? Yes sorry to keep your attention. Test automation software will also generate <strong>instances of an interface</strong> for you. That’s right, you can <em>quantify across an interface</em> in your property expressions. This is a bit like mocking, except not so manual; you just pass in the arbitrary generator (Reductio provides them of course) just as we did above and you can wipe your hands clean of the remaining manual effort otherwise.</p>
<p>You might want to write a property where you say something like, “for all instances of my interface or class, then such and such…”. This might be an instance of the <code>HttpServletRequest</code> interface or perhaps one of your own classes. The good part is, no more manual mocking.</p>
<h4 id="want-to-learn-more">Want to Learn More?</h4>
<p>You can read the <a href="http://reductiotest.org/manual">Reductio Manual</a> or perhaps look at some <a href="http://reductiotest.org/examples/1.5">code examples</a>. If you’re a fan of the coming Java 7 BGGA closure syntax, you might prefer <a href="http://reductiotest.org/examples">these code examples</a>. Perhaps you’re into higher-level programming and prefer <a href="http://reductiotest.org/examples/scala">Scala code examples</a>. Whichever you choose, please feel free to jump on the <a href="http://reductiotest.org/community">Reductio mailing list or chat channel</a> and ask your question, no matter how silly it seems to you.</p>
    </div>
  </content>
</entry>
<entry>
  <title>What you call integration testing, I call sloppy programming</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/what-you-call-integration-testing-i-call-sloppy-programming/index.html"/>
  <id>http://blog.tmorris.net/posts/what-you-call-integration-testing-i-call-sloppy-programming/index.html</id>
  <published>2008-06-03T20:24:10Z</published>
  <updated>2008-06-03T20:24:10Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Re: Your insistence on distinguishing unit testing and integration testing.</p>
<p>You make the distinction between unit testing and integration because you are a sloppy programmer. You throw side-effects around like a 5 year old in a play pen. You do not care for intellectual discipline in your thinking process. Nor do you care for high-level abstraction or composition of your software. Instead, you insist on this dogmatic “test driven” nonsense. You do this because you are married to the FORTRAN family of programming languages. Your so-called integration tests exist because you have implicit free variables in your equations like a ‘good little imperative programmer’. If you did decide to apply discipline and consider your side-effects, you’d see no distinction between unit testing and integration testing. I realise that this possibility escapes your feeble and narrowed mind at this stage of the socratic midwife process.</p>
<p>When you do unit test, you’re using an awfully impoverished method. I mean, “assert this and assert that”. Give me a break! You think this is going to “drive” something? Anything? OK, it drives me bonkers to think that you insist on spreading mythological, pseudo-scientific, fanatical bullshit (excuse the term, but it is most accurate) and have followers repeat said myths in such an obedient I-cant-think-for-myself fashion. You think you’re contributing to the “design” and “quality” of your software? How mistaken you are and what empathy I feel for you.</p>
<p>I implore you to retract your silliness and take seriously the charge that you are a sloppy programmer (evidence forthcoming). Your dependence on “agile this” (I play A grade squash, I’m perfectly agile, thanks) and “test drive that” are entirely dependent on an existing sloppy form of programming. Furthermore, these workarounds not only rest on a flawed premise, but they are extremely diluted anyway. Even with the given silly premise you can significantly improve! But I won’t tell you how, no not yet. First you must prepare for an act of apostasy, which I understand can be very traumatic. So I can’t help you until then, but in the meantime, I kindly ask that you stop imposing your silly ideas on me, because yes, they are silly.</p>
<p>See you on the other side.</p>
    </div>
  </content>
</entry>
<entry>
  <title>JAOO Brisbane 2008</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/jaoo-brisbane-2008/index.html"/>
  <id>http://blog.tmorris.net/posts/jaoo-brisbane-2008/index.html</id>
  <published>2008-05-31T08:35:41Z</published>
  <updated>2008-05-31T08:35:41Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>When I saw the schedule for JAOO 2008, two names stood out for me; Erik Meijer (Haskell) and Don Syme (F#). My second thought was “why are the smart guys in Microsoft Research?”. I don’t really have an answer to that, but it’s an interesting question.</p>
<p>Meijer opened with a 1 hour talk on the software crisis and how we can solve it. A quick glance around the room quickly confirmed my suspicion that much of the audience was lost with the lambda-notation and various other squiggles on his slides, but deep inside, I could feel myself pushing him to continue. He had hit the nail <strong>right on the head</strong> with how to solve the so-called software crisis (perhaps an alarmist name, but there is a phenomenon of some sort).</p>
<p>I was disappointed that I could not disagree with Erik – not even in the slightest detail. When I saw him emphasising his displeasure with Haskell’s <code>unsafePerformIO</code>, I thought I had him. This was my opportunity to disagree with someone smarter than myself. But it wasn’t to be, he answered my question with almost exactly the same rhetoric that I would have used myself. I just think his emphasis on <code>unsafePerformIO</code> was because he knew he was standing in front of mostly Java/C# users. Perhaps that’s the lesson to learn; target your audience the way he did. A consolation prize at the very least.</p>
<p>From the introduction, I knew I was in for a great ride, however, I believe there were only two types of people in theatre during Meijer’s speech:</p>
<ul>
<li><p>those who understood what he was saying in his limited time slot</p></li>
<li><p>those who didn’t quite understand but really want to, whether they know that fact or not</p></li>
</ul>
<p>It is this second point that I wish to elaborate. I found many speakers thereafter had a common theme in trying to resolve some sort of crisis in software development; Dave Thomas and some of the problems he described, Rob Martin and his Clean Code, Michael Feathers and his Unit Testing and even Martin Fowler and his Enterprise Patterns. With some deeper thought, you can see that these speakers are – in some vague sense – highlighting the fact that there exists some kind of critical problem and each his trying to put forward his/her answer. Many of these speakers described the same problem, but then gradually and sometimes quickly diverged from what I think is the correct answer. Meijer nailed it guys! No seriously, the solution is in his slides and his exaggerated body language.</p>
<p>I know many people think Meijer’s solution and mainstream topics are disjoint and not unifiable. How could Meijer’s funny lambda symbols have any bearing on Fowler’s enterprise pattern or Feathers’ insistence on not testing that (<em>dang side-effecting</em>) database? No, there is no fence to jump. All these guys are just acknowledging the same problem in some vague notion and looking for an answer, believing they have found it. It is the realisation of the unification of this funny mathematical stuff with the euphemistic terms like “TDD” and “Agile” that brings the greatest reward. Is it not a big enough hint that the in-crowd is reinventing some of this stuff in a diluted and not-so-useful form?</p>
<p>Rob Martin, yes, the world is counter-intuitive and your analogy to Quantum Mechanics is perfect. However, what would Einstein say to your shunning of the application of thought experiment? You nailed the problem, but the solution was slightly misdirected. Meijer was pointing you to the answer. The theoreticians have it right and in the most practical sense; is history not a good indicator? No Rob, the jury is not in; you’ve screwed up. Are you open to this possibility? Any professional would be ready to accept an unheard argument, right?</p>
<p>If, as a participant of JAOO 2008, you were to take the time to truly and deeply understand the topic that Meijer was alluding to, then I give you an unreserved promise of a moment of realisation that will tingle your spine, fill your eyes with water and euphoria (you know that feeling right?) that far supersedes any other moment that you may have had in your programming journey so far. I say this with utmost confidence. And here’s the thing, there is an entire community of people waiting to help you to understand that funny lambda symbol, those strange arrows, what it means to write code from types, what code documentation and verification truly means and much more. We love answering your questions! The scientific community truly embraces ignorance; no really it does. Please don’t be afraid to express it; learning is fun.</p>
<p>So here’s my little contribution to the progress of software development; I’ll happily answer your questions about Meijer’s topic right here or by private email if you prefer (however, I don’t have the slides, so you’ll have to be specific in your query). Hopefully then, you can open JAOO 2009 and I can indulge myself by disagreeing with you in some way! :)</p>
<p>From a fellow programmer who wants to solve these problems too so please ask questions.</p>
    </div>
  </content>
</entry>
<entry>
  <title>'Reductio: Testing equals/hashCode'</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/reductio-testing-equalshashcode/index.html"/>
  <id>http://blog.tmorris.net/posts/reductio-testing-equalshashcode/index.html</id>
  <published>2008-05-27T10:40:39Z</published>
  <updated>2008-05-27T10:40:39Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="https://issues.workingmouse.com/view.php?id=30">So you wanna know how to test Java’s equals/hashCode huh?</a></p>
<p>Here is a true statement that should hold for any <code>equals</code> and <code>hashCode</code> implementation:</p>
<blockquote>
<p>forall x. forall y. x.equals(y) =&gt; x.hashCode() == y.hashCode()</p>
</blockquote>
<p><em>You can read =&gt; as <strong>implies</strong></em>. So if x equals y, then this implies that the hash code of x is equal to the hash code of y. This is called <em>logical implication</em> and is often written in English as “if p then q”, for some p and q, just like I did in the previous statement. Easy peasey eh?</p>
<p>How might we test the <code>equals</code> and <code>hashCode</code> implementation of <code>MyClass</code>? If we were using JUnit (or some other non-automated test tool):</p>
<pre><code>assertEqual(new MyClass(7, &quot;abc&quot;).hashCode(), new MyClass(7, &quot;abc&quot;).hashCode());
assertEqual(new MyClass(42, &quot;CBA&quot;).hashCode(), new MyClass(42, &quot;CBA&quot;).hashCode());
... etc. etc.</code></pre>
<p>What we would <strong>really</strong> like to say is something like:</p>
<blockquote>
<p>I assert that for any two equal instances of <code>MyClass</code> (call them x and y), then the hashCode of x is equal to the hashCode of y. Dear test tool (Reductio!), please try your best to show me why this is false if you find it to be so.</p>
</blockquote>
<p>Well, that’s just an English way of saying the logical implication statement above, right? We could write this statement in Java (boiler-plate omitted):</p>
<pre><code>Property p = property(arbMyClass, arbMyClass, { MyClass m1, MyClass m2 =&gt;
      bool(m1.equals(m2)).implies(m1.hashCode() == m2.hashCode()) })</code></pre>
<p><a href="http://wiki.workingmouse.com/index.php/Reductio_EqualsHashCode">Read on…</a></p>
    </div>
  </content>
</entry>
<entry>
  <title>'Reductio: Testing for the Top Java Programmers'</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/reductio-testing-for-the-top-java-programmers/index.html"/>
  <id>http://blog.tmorris.net/posts/reductio-testing-for-the-top-java-programmers/index.html</id>
  <published>2008-05-24T21:00:03Z</published>
  <updated>2008-05-24T21:00:03Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://reductiotest.org/">Reductio</a> is open source (BSD) software that provides some very clever ideas adapted from QuickCheck. In particular, Reductio allows you to write algebraic properties about your software and the software then attempts to falsify these properties using automation of function domain value generation. Reductio can run 1000 unit tests in 4 or 5 lines of code, and that is Java code! (No, I am not kidding; really take a look at some of the <a href="http://reductiotest.org/examples">code examples</a>)</p>
<p>Reductio also provides shrinking of counter-examples in the event of proving a property false; for example, <code>a + b == a - b</code> is not always going to be true (for all values of ‘a’ and ‘b’), but would you like Reductio to provide the counter-example <code>a = 1934, b = 4571</code>? I think you’d prefer a smaller counter-example such as <code>a = 1, b = 1</code> right? I would too :) By providing the smallest reasonable counter-example, Reductio makes it easier to debug your code in the event of finding fault.</p>
<p>Another extremely useful feature of Reductio is <em>automated mocking</em>. That is to say, Reductio can generate implementations of an interface for you so long as you provide the mapping from one or more transformations (this exploits a programming pattern called a Functor) to your type. Doing so is guaranteed to be a straight-forward task for the user (so straight-forward that you could automate it with reflection; an add-on feature perhaps?). This allows you to quantify across interface types. For example, you might state a property about your software using some interface, but you assert that the property holds regardless of the implementation of the interface. Reductio will generate hundreds of implementations if you like! All automated of course ;)</p>
<p>Reductio makes it trivial to write generators for user-defined types (again, another potentially automated task that requires Java’s meta-programming facility ala reflection), however, Reductio also provides many existing implementations. Following is a <em>non-exhaustive</em> list.</p>
<p>If you’re into robustness in the verification of the correctness of your Java software, take a look at Reductio. <a href="http://reductiotest.org/">http://reductiotest.org/</a></p>
<hr />
<h5 id="java.lang">java.lang</h5>
<ul>
<li><p>Boolean</p></li>
<li><p>Byte</p></li>
<li><p>Character</p></li>
<li><p>Double</p></li>
<li><p>Float</p></li>
<li><p>Integer</p></li>
<li><p>Long</p></li>
<li><p>Short</p></li>
<li><p>String</p></li>
<li><p>StringBuffer</p></li>
<li><p>StringBuilder</p></li>
</ul>
<h5 id="java.util">java.util</h5>
<ul>
<li><p>ArrayList</p></li>
<li><p>BitSet</p></li>
<li><p>Calendar</p></li>
<li><p>Date</p></li>
<li><p>EnumMap</p></li>
<li><p>EnumSet</p></li>
<li><p>GregorianCalendar</p></li>
<li><p>HashMap</p></li>
<li><p>HashSet</p></li>
<li><p>Hashtable</p></li>
<li><p>IdentityHashMap</p></li>
<li><p>LinkedHashMap</p></li>
<li><p>LinkedHashSet</p></li>
<li><p>LinkedList</p></li>
<li><p>PriorityQueue</p></li>
<li><p>Properties</p></li>
<li><p>Stack</p></li>
<li><p>TreeMap</p></li>
<li><p>TreeSet</p></li>
<li><p>Vector</p></li>
<li><p>WeakHashMap</p></li>
</ul>
<h5 id="java.util.concurrency">java.util.concurrency</h5>
<ul>
<li><p>ArrayBlockingQueue</p></li>
<li><p>ConcurrentHashMap</p></li>
<li><p>ConcurrentLinkedQueue</p></li>
<li><p>CopyOnWriteArrayList</p></li>
<li><p>CopyOnWriteArraySet</p></li>
<li><p>DelayQueue</p></li>
<li><p>LinkedBlockingQueue</p></li>
<li><p>PriorityQueue</p></li>
<li><p>SynchronousQueue</p></li>
</ul>
<h5 id="java.sql">java.sql</h5>
<ul>
<li><p>Date</p></li>
<li><p>Time</p></li>
<li><p>Timestamp</p></li>
</ul>
<h5 id="java.math">java.math</h5>
<ul>
<li><p>BigDecimal</p></li>
<li><p>BigInteger</p></li>
</ul>
    </div>
  </content>
</entry>
<entry>
  <title>ScalaCheck 1.3 yippee!</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/scalacheck-13-yippee/index.html"/>
  <id>http://blog.tmorris.net/posts/scalacheck-13-yippee/index.html</id>
  <published>2008-05-12T08:46:35Z</published>
  <updated>2008-05-12T08:46:35Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://code.google.com/p/scalacheck/">ScalaCheck 1.3 is available.</a></p>
<ul>
<li><p>ADDED Arbitrary instance for functions.</p></li>
<li><p>FIXED ConsoleReporter updated according to changes in Scala’s printf method.</p></li>
<li><p>CHANGED Properties and Commands now extend Prop, so they can be used as single properties.</p></li>
<li><p>ADDED Properties.include for grouping properties.</p></li>
<li><p>ADDED Prop.main for convenient test execution.</p></li>
<li><p>CHANGED Fixed Arbitrary for Option so that None does not occur so often.</p></li>
<li><p>ADDED Arbitrary instance for scala.Either (Added in Scala 2.7.1-RC2).</p></li>
<li><p>ADDED Existential quantifier in Prop.scala.</p></li>
</ul>
    </div>
  </content>
</entry>
<entry>
  <title>How to Share?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/how-to-share/index.html"/>
  <id>http://blog.tmorris.net/posts/how-to-share/index.html</id>
  <published>2008-05-08T09:10:14Z</published>
  <updated>2008-05-08T09:10:14Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I have a situation that I am wondering how others may have solved. I have an open source (BSD) project whose copyright is owned by the company I work for. Another person, working for another company (in another country!) wishes to contribute to this project, which I think is great.</p>
<p>How is the ownership of copyright usually sorted out in these situations? Is it shared by both parties? Does each party maintain copyright to their respective contributions? Does the party wishing to contribute sign over copyright ownership? Is there another alternative that I haven’t thought of? Surely this situation comes up a lot; how is it usually handled?</p>
    </div>
  </content>
</entry>
<entry>
  <title>QOTD (I found it amusing anyway)</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/qotd-i-found-it-amusing-anyway/index.html"/>
  <id>http://blog.tmorris.net/posts/qotd-i-found-it-amusing-anyway/index.html</id>
  <published>2008-04-24T10:59:23Z</published>
  <updated>2008-04-24T10:59:23Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://objectmix.com/programming-languages/171793-shootout-implementing-interpreter-simple-procedural-language-minim-16.html#post608486">How funny :)</a> Laziness is unpredictable!</p>
<blockquote>
<p>I lurk on the Haskell Cafe mailing list and eager evaluation is often the solution to reliability or performance problems: laziness is unpredictable.</p>
</blockquote>
    </div>
  </content>
</entry>
<entry>
  <title>Finding the Levenshtein Distance in Scala</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/finding-the-levenshtein-distance-in-scala/index.html"/>
  <id>http://blog.tmorris.net/posts/finding-the-levenshtein-distance-in-scala/index.html</id>
  <published>2008-04-24T09:01:59Z</published>
  <updated>2008-04-24T09:01:59Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>In the spirit of esoteric code snippets like <a href="http://www.poromenos.org/node/87">this one</a>, I thought I’d put my two bob in :)</p>
<p>I have written the Levenshtein Distance algorithm using <a href="http://scala-lang.org/">Scala</a> below. The Levensthein Distance algorithm is a <a href="http://en.wikipedia.org/wiki/Dynamic_programming">Dynamic Programming Algorithm</a> (DPA). This implementation is a little different to the Python one (which creates the arrays explicitly and fills them using loops):</p>
<ul>
<li><p>The code more closely represents the mathematical definition of the algorithm</p></li>
<li><p>The code is easier to reason about because the destructive updates occur behind the scenes (in the memoisation library)</p></li>
<li><p>The code below requires a third party library (Scalaz) <em>note that Scalaz comes with demo code including the levenshtein distance and other DPAs</em></p></li>
<li><p>The code has a better complexity than the typical loopy version by using lazy evaluation (notice that ‘c’ is not always evaluated)</p></li>
<li><p>While the code memoises with an array, you could use say, a map and save some space as well</p></li>
<li><p>The code builds the call stack as it traverses the matrix (the loopy one does not)</p></li>
</ul>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">import</span> scalaz.<span class="fu">memo</span>.<span class="fu">Memo</span>
<span class="kw">import</span> scalaz.<span class="fu">memo</span>.<span class="fu">SizedMemo</span>.<span class="fu">arraySizedMemo</span>

<span class="kw">object</span> Levenshtein {
  <span class="kw">def</span> levenshtein[A](x: Array[A], y: Array[A]): Int = {
    <span class="kw">val</span> im = arraySizedMemo
    <span class="kw">val</span> m = im[Memo[Int, Int]](x.<span class="fu">length</span> + <span class="dv">1</span>)
    <span class="co">// the call matrix</span>
    <span class="kw">def</span> <span class="fu">mx</span>(i: Int, j: Int): Int = <span class="kw">if</span>(i == <span class="dv">0</span>) j <span class="kw">else</span> <span class="kw">if</span>(j == <span class="dv">0</span>) i <span class="kw">else</span> {
      <span class="kw">def</span> f = (n: Int) =&gt; im[Int](y.<span class="fu">length</span> + <span class="dv">1</span>)
      <span class="kw">val</span> a = <span class="fu">m</span>(f)(i - <span class="dv">1</span>)(<span class="fu">mx</span>(i - <span class="dv">1</span>, _))(j) + <span class="dv">1</span>
      <span class="kw">val</span> b = <span class="fu">m</span>(f)(i - <span class="dv">1</span>)(<span class="fu">mx</span>(i - <span class="dv">1</span>, _))(j - <span class="dv">1</span>) + (<span class="kw">if</span>(<span class="fu">x</span>(i - <span class="dv">1</span>) == <span class="fu">y</span>(j - <span class="dv">1</span>)) <span class="dv">0</span> <span class="kw">else</span> <span class="dv">1</span>)
      <span class="kw">lazy</span> <span class="kw">val</span> c = <span class="fu">m</span>(f)(i)(<span class="fu">mx</span>(i, _))(j - <span class="dv">1</span>) + <span class="dv">1</span>
      <span class="kw">if</span>(a &lt; b) a <span class="kw">else</span> <span class="kw">if</span>(b &lt;= c) b <span class="kw">else</span> c
    }
    <span class="fu">mx</span>(x.<span class="fu">length</span>, y.<span class="fu">length</span>)
  }

  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]) =
    <span class="fu">println</span>(<span class="fu">levenshtein</span>(<span class="fu">args</span>(<span class="dv">0</span>).<span class="fu">toCharArray</span>, <span class="fu">args</span>(<span class="dv">1</span>).<span class="fu">toCharArray</span>))
}</code></pre>
<p>To run this code:</p>
<pre><code>$ wget http://projects.workingmouse.com/public/scalaz/artifacts/2.4/scalaz.jar # download Scalaz 2.4
$ scalac -classpath scalaz.jar Levenshtein.scala # compile
$ scala -classpath .:scalaz.jar Levenshtein algorithm altruistic # find the distance!
&lt;strong&gt;6&lt;/strong&gt;</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Another Call to Genocide</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/another-call-to-genocide/index.html"/>
  <id>http://blog.tmorris.net/posts/another-call-to-genocide/index.html</id>
  <published>2008-04-12T06:55:30Z</published>
  <updated>2008-04-12T06:55:30Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><em>Rabbi Yisrael Rosen, director of the Tsomet Institute</em> <a href="http://www.uruknet.de/?p=m42961&amp;hd=&amp;size=1&amp;l=e">says</a>:</p>
<blockquote>
<p>All of the Palestinians must be killed; men, women, infants, and even their beasts.</p>
</blockquote>
<p>Oh really? I didn’t know that! Thanks for letting me in on it.</p>
<blockquote>
<p>Rosen asserted that there is evidence in the Torah to justify this stand.</p>
</blockquote>
<p>Uh oh, an hallucinabating Rabbi.</p>
<blockquote>
<p>Rosen, an authority able to issue religious opinions for Jews…</p>
</blockquote>
<p>You mean, people who do not possess the ability to think independently? I had a few of those commenting on my blog recently!</p>
<blockquote>
<p>… wrote that Palestinians are like the nation of Amalekites that attacked the Israelite tribes on their way to Jerusalem after they had fled from Egypt under the leadership of Moses.</p>
</blockquote>
<p>Did you learn that at a nativity scene when you were being indoctrinated as a child?</p>
<blockquote>
<p>He wrote that the Lord sent down in the Torah a ruling that allowed the Jews to kill the Amalekites,…</p>
</blockquote>
<p>Oh the <strong>Lord</strong> did that? That’s OK then.</p>
<blockquote>
<p>The true outrage is that most of those authorised to issue Jewish religious opinions support the view of Rabbi Rosen, as confirmed by Haaretz newspaper.</p>
</blockquote>
<p><a href="http://en.wikipedia.org/wiki/Argumentum_ad_populum">Well it has to be right then!</a> I bet the aforementioned commenters agree too, so it’s super spectacularly right! Oh wait, the truth value of the proposition was never open for analysis. Sorry Authority.</p>
<blockquote>
<p>The danger of these religious opinions lies in the fact that the religious authorities issuing them have wide respect among religious Jewish youth.</p>
</blockquote>
<p>You mean, your children subscribe to views of self-appointed authority without question? Hey, we have children that do that too! Does your indoctrination scheme masquerade as an education system like ours?</p>
<blockquote>
<p>Wasil Taha, Arab Knesset member from the Tajammu Party led by Azmi Bishara, says that these religious opinions lead to the committal of crimes… Taha holds that the sectors of the Palestinian population most likely to be harmed by these religious opinions are those living in the various cities populated by both Jews and Palestinians, such as Haifa, Jaffa, Lod, Ramleh and Jerusalem.</p>
</blockquote>
<p>I feel sick, but not as much as the hallucstibating Rabbi appears to be.</p>
<p>Burning question: Do Atheists have cause to be angry, despite not bearing arms to express this anger (due to a more grounded sense of morality?)?</p>
    </div>
  </content>
</entry>
<entry>
  <title>Automated Unit Testing your Java using ScalaCheck</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/automated-unit-testing-your-java-using-scalacheck/index.html"/>
  <id>http://blog.tmorris.net/posts/automated-unit-testing-your-java-using-scalacheck/index.html</id>
  <published>2008-04-06T10:03:28Z</published>
  <updated>2008-04-06T10:03:28Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <h3 id="what-is-automated-unit-testing">What is automated unit testing?</h3>
<p>I’m assuming you’re familiar with traditional mainstream unit testing techniques such as that purported by JUnit, NUnit and so on. Automated unit testing automates the generation of elements to apply a function to, in light of a stated <em>algebraic property of that function</em>. This is in contrast to traditional unit testing, where a proposition is made about the application of a function to specific elements of the domain.</p>
<p>Take, for example, the <code>java.lang.String.endsWith</code> function. Using JUnit, we might write:</p>
<pre><code>  assertTrue(&quot;abc&quot;.endsWith(&quot;&quot;));
  assertTrue(&quot;abc&quot;.endsWith(&quot;bc&quot;));
  assertFalse(&quot;abc&quot;.endsWith(&quot;ab&quot;));
  // ...and so on</code></pre>
<p>Using automated testing, we might instead write something like this English statement:</p>
<blockquote>
<p>For any two Strings (x and y), then <code>(x + y).endsWith(y)</code> is <code>true</code>.</p>
</blockquote>
<p>Here is that same statement for formally:</p>
<pre><code>∀ x. ∀y. (x + y) endsWith y</code></pre>
<p>Note that we don’t have to declare x or y to be elements of the set <code>java.lang.String</code>, since the type system <em>proves</em> this fact. Note also that we assume correctness of <code>+</code> as a premise of the proposition, while the proposition itself is <em>open</em> (that is, this is the statement we are trying to disprove).</p>
<p>After putting forward the above open statement, the test software would automatically attempt to <em>falsify</em> (note that this is different to “prove”) this proposition by generating <em>arbitrary</em> values. As a user, you may wish to skew the distribution of these values, adjust the amount of attempts at falsification and various other configuration values. Many have reasonable defaults, such as when generating integer values, include 0, 1, -1, max, min, max-1 and min-1 and typically make 100 to 500 attempts at falsification by default (in critical code, for example, you may turn this up).</p>
<h3 id="credit-where-it-is-due">Credit where it is due</h3>
<p>This concept of automated testing did not originate with <a href="http://code.google.com/p/scalacheck/">ScalaCheck</a>. In fact, I have recently noticed the mainstream fraternity have started replicating watered down versions of automated testing (note that it is extremely cumbersome to achieve effectively in mainstream languages). Indeed, advanced programming concepts often take a lot of time to bubble down from research/academia to mainstream in a typically diluted form. This concept originated from a paper titled <a href="http://www.cs.chalmers.se/~rjmh/QuickCheck/">QuickCheck: Automated Specification-Based Unit Testing</a>. Note that JUnit et. al. is not automated, but (very) manual testing.</p>
<h3 id="on-with-the-story">On with the story</h3>
<p>The original language, Haskell, has language features called type-classes and higher-order functions, as does Scala. Both of these are required language features to use automated testing effectively, though it is possible to achieve in a lesser form in less useful languages. Note that Java does not have either of these language features. Are we hosed? No!</p>
<p>Take a look at this source file, which states our property about <code>endsWith</code> using Scala (see <code>endsWithProperty</code>):</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// CheckString.scala</span>

<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">Prop</span>.<span class="fu">_</span>
<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">ConsoleReporter</span>.<span class="fu">testStatsEx</span>
<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">Test</span>.<span class="fu">check</span>

<span class="kw">object</span> CheckString {
  <span class="co">// Here is the property</span>

  <span class="kw">val</span> endsWithProperty = <span class="fu">property</span>((x: String, y: String) =&gt;
    ((x + y) endsWith y)
  )

  <span class="co">// A List of properties - we only have one at the moment.</span>
  <span class="kw">val</span> tests = scala.<span class="fu">List</span>(
      (<span class="st">&quot;endsWithProperty&quot;</span>, endsWithProperty)
  )

  <span class="co">// Run all our properties with the default configuration.</span>
  <span class="co">// Are our properties false?</span>
  <span class="kw">def</span> <span class="fu">main</span>(args: scala.<span class="fu">Array</span>[String]) =
    tests foreach { <span class="kw">case</span> (name, p) =&gt; <span class="fu">testStatsEx</span>(name, <span class="fu">check</span>(p)) }
}</code></pre>
<p>You can run this source file by downloading <a href="http://scalacheck.googlecode.com/files/ScalaCheck-1.2.jar">ScalaCheck-1.2.jar</a> and compiling it with the <a href="http://www.scala-lang.org/downloads/index.html">Scala</a> compiler.</p>
<pre><code>$ scalac -classpath ScalaCheck-1.2.jar CheckString.scala</code></pre>
<p>Does our stated property falsify?</p>
<pre><code>$ scala -classpath .:ScalaCheck-1.2.jar CheckString
+ OK, passed 100 tests.</code></pre>
<p>No! After <strong>100 unit tests</strong>, the stated property cannot be shown to be false. We might assume its correctness now. Note that this is <code>java.lang.String</code> that we are testing here running on a Java Virtual Machine, not some other esoteric <code>String</code> – yes, the one you use in your Java enterprise applications ;) You can apply this technique to <strong>any Java type</strong>.</p>
<p>How about this proposition:</p>
<blockquote>
<p>For any two Strings (x and y), then <code>x.reverse.startsWith(y.reverse))</code> is equivalent (in truth) to <code>x.endsWith(y)</code>.</p>
</blockquote>
<p>Again, <code>startsWith</code> is assumed correct as a premise of the proposition (or theorem). Can the statement be falsified by the test automation?</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// CheckString.scala</span>

<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">Prop</span>.<span class="fu">_</span>
<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">ConsoleReporter</span>.<span class="fu">testStatsEx</span>
<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">Test</span>.<span class="fu">check</span>

<span class="kw">object</span> CheckString {
  <span class="kw">val</span> endsWithProperty = <span class="fu">property</span>((x: String, y: String) =&gt;
    ((x + y) endsWith y)
  )

  <span class="co">// Can you falsify this?</span>
  <span class="kw">val</span> endsWithProperty2 = <span class="fu">property</span>((x: String, y: String) =&gt;
    x.<span class="fu">endsWith</span>(y) == x.<span class="fu">reverse</span>.<span class="fu">startsWith</span>(y.<span class="fu">reverse</span>))

  <span class="kw">val</span> tests = scala.<span class="fu">List</span>(
      (<span class="st">&quot;endsWithProperty&quot;</span>, endsWithProperty),
      (<span class="st">&quot;endsWithProperty2&quot;</span>, endsWithProperty2)
  )

  <span class="kw">def</span> <span class="fu">main</span>(args: scala.<span class="fu">Array</span>[String]) =
    tests foreach { <span class="kw">case</span> (name, p) =&gt; <span class="fu">testStatsEx</span>(name, <span class="fu">check</span>(p)) }
}</code></pre>
<p>Well, can it? Oh come on, please tell me! :)</p>
<pre><code>$ scala -classpath .:ScalaCheck-1.2.jar CheckString
+ OK, passed 100 tests.
+ OK, passed 100 tests.</code></pre>
<p>No. We have now successfully executed 200 unit tests so we may be prepared to declare satisfaction with the correctness of the propositions under analysis. Note again, that we have not <em>proven</em> these properties to be true (we did prove others to be true using the type system). In fact, doing so for the general program is equivalent to solving the halting problem, so good luck if you’re looking for something more rigorous ;)</p>
<p>You may have observed that I called a method on <code>String</code> that does not exist in the Java API – reverse. In Scala, you can add methods to objects in a type-safe manner. The <code>reverse</code> method is added by default in the Scala runtime. In Java, you might instead have written reverse as a <code>static</code> method of a <code>StringUtils</code> class or something. This fact does not negate the fact that we are still using the same ol’ <code>java.lang.String</code> that Java Jim is using next door.</p>
<h3 id="what-were-the-string-values">What were the String values?</h3>
<p>The test automation supplied 100 <code>String</code> values for each of the two properties in an attempt to falsify; where did they come from? ScalaCheck includes an abstract type called <code>[Arbitrary](http://scalacheck.googlecode.com/svn/artifacts/1.2/doc/api/org/scalacheck/Arbitrary.html)</code> and an implementation for the <code>String</code> type is supplied by ScalaCheck. It is this that is used to generate <code>String</code> values. If we wish to generate values for our own types, we must write our own <code>Arbitrary</code> implementation for it.</p>
<p>I will state some properties now about <code>java.util.LinkedList</code> and its <code>addFirst</code> method. However, note that unlike <code>java.lang.String</code>, ScalaCheck does not include an arbitrary generator for linked lists, so we will have to write one. Luckily, generators are instances of what is known as a <em>functor</em> (also, a <em>monad</em>), so this task will be quite trivial. Let’s start with doing that.</p>
<p>We can generate arrays, since that ability comes with ScalaCheck, so we can use the <code>map</code> function (i.e. the essence of a functor) to take the generator for arrays to a generator for linked lists. Given an array, we can create a linked list using: <code>new LinkedList[A](Arrays.asList(array))</code>. This is precisely what the code below does using what is called a <em>higher-order function</em> inside the <code>Arbitrary</code> functor. You needn’t concern yourself with these advanced programming concepts in these demonstrations, but just acknowledge their existence and that the given code is trivial and it works.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">Arbitrary</span>
<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">Arbitrary</span>.<span class="fu">arbitrary</span>
<span class="kw">import</span> java.<span class="fu">util</span>.{LinkedList, Arrays}

<span class="kw">object</span> CheckLinkedList {
  <span class="kw">implicit</span> <span class="kw">def</span> arbitraryLinkedList[A](<span class="kw">implicit</span> a: Arbitrary[A]): Arbitrary[LinkedList[A]] =
    <span class="fu">Arbitrary</span>(arbitrary[Array[A]].<span class="fu">map</span>(array =&gt; <span class="kw">new</span> LinkedList[A](Arrays.<span class="fu">asList</span>(array))))
}</code></pre>
<p>Note the <code>implicit</code> declaration on the method. This is <em>required</em>, however, this language feature is very powerful and only a very lengthy discussion would do it justice, so we will say nothing more than it is required in this case, it is very powerful and Java has no equivalent (you can mildly emulate it with the singleton anti-pattern – another topic).</p>
<p>What properties can we state now about <code>addFirst</code>? How about for any list and any element, adding the element to the list adds 1 to its <code>size</code>? We call this property <code>addsLengthOne</code> below.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// CheckLinkedList.scala</span>

<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">Arbitrary</span>
<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">Arbitrary</span>.<span class="fu">arbitrary</span>
<span class="kw">import</span> java.<span class="fu">util</span>.{LinkedList, Arrays}
<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">Prop</span>.<span class="fu">_</span>
<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">ConsoleReporter</span>.<span class="fu">testStatsEx</span>
<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">Test</span>.<span class="fu">check</span>

<span class="kw">object</span> CheckLinkedList {
  <span class="kw">implicit</span> <span class="kw">def</span> arbitraryLinkedList[A](<span class="kw">implicit</span> a: Arbitrary[A]): Arbitrary[LinkedList[A]] =
    <span class="fu">Arbitrary</span>(arbitrary[Array[A]].<span class="fu">map</span>(array =&gt; <span class="kw">new</span> LinkedList[A](Arrays.<span class="fu">asList</span>(array))))

  <span class="kw">val</span> addsLengthOne = <span class="fu">property</span>((list: LinkedList[String], s: String) =&gt;
    list.<span class="fu">size</span> + <span class="dv">1</span> == { list.<span class="fu">addFirst</span>(s); list.<span class="fu">size</span> }
  )

  <span class="kw">val</span> tests = scala.<span class="fu">List</span>(
      (<span class="st">&quot;addsLengthOne&quot;</span>, addsLengthOne)
  )

  <span class="kw">def</span> <span class="fu">main</span>(args: scala.<span class="fu">Array</span>[String]) =
    tests foreach { <span class="kw">case</span> (name, p) =&gt; <span class="fu">testStatsEx</span>(name, <span class="fu">check</span>(p)) }
}</code></pre>
<p><em>I’ve copied and pasted the boilerplate to get the tests running for the demonstration, but please feel encouraged to put this kind of code in its own function to avoid this repetition.</em></p>
<p>How did we go?</p>
<pre><code>$ scala -classpath .:ScalaCheck-1.2.jar CheckLinkedList
+ OK, passed 100 tests.</code></pre>
<p>Yippee!!</p>
<p>We might state two more properties:</p>
<p>* For any list and any element (s), <code>list.add(s)</code> then <code>list.get(0)</code> will always yield <code>s</code>.</p>
<p>* For any list, any element (s) and any integer between 0 and list.length - 1 (n), then calling <code>list.get(n)</code> is equivalent to calling <code>list.addFirst(s).get(n + 1)</code>.</p>
<pre><code>$ scala -classpath .:ScalaCheck-1.2.jar CheckLinkedList
+ OK, passed 100 tests.
+ OK, passed 100 tests.
+ OK, passed 100 tests.</code></pre>
<p>I have left off the code for the moment and I will give a complete example toward the end. Note that we have 300 passing unit tests – the code is around 25 lines (excluding the boilerplate to get the tests running).</p>
<p>At this point, we have given <strong>an unambiguous specification for <code>addFirst</code></strong>. In other words, it is not possible to write a terminating function that does not satisfy these properties that is not equivalent to <code>addFirst</code>. However, this ignores the unfortunate potential for uncontrolled side-effects, which is an inherent property of Java (and Scala for that matter). We will assume it to be the case – no additional side-effects. It then follows that one additional benefit of automated testing is that we also obtain extremely valuable documentation for the function.</p>
<p>Consider being provided with:</p>
<p>* The type signature for <code>addFirst</code> (the properties which are proved).</p>
<p>* The three stated properties for <code>addFirst</code>.</p>
<p>Is there anything more useful to add in terms of documentation? Isn’t this unambiguous, highly readable specification more than you could possibly ask for? This is an interesting question to ponder, particularly in a more pure environment than the one we are discussing here, but I thought I would mention it anyway :)</p>
<p>I will state a property that is false, just to exemplify what happens. The idea is that it is extremely difficult (but not impossible – remember halting problem) to state a false property that ScalaCheck passes. I’m not going to look for a specific corner case that traditional unit testing is unlikely to pick up, but I encourage you to do so as an added exercise.</p>
<p>Instead, I will state an obviously false property; for any list and any element, adding the element with <code>addFirst</code> is equivalent to adding that element with <code>addLast</code>.</p>
<p>Here we go (note the fourth property – <code>thisIsFalse</code>):</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="co">// CheckLinkedList.scala</span>

<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">Arbitrary</span>
<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">Arbitrary</span>.<span class="fu">arbitrary</span>
<span class="kw">import</span> java.<span class="fu">util</span>.{LinkedList, Arrays}
<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">Prop</span>.<span class="fu">_</span>
<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">ConsoleReporter</span>.<span class="fu">testStatsEx</span>
<span class="kw">import</span> org.<span class="fu">scalacheck</span>.<span class="fu">Test</span>.<span class="fu">check</span>

<span class="kw">object</span> CheckLinkedList {
  <span class="kw">implicit</span> <span class="kw">def</span> arbitraryLinkedList[A](<span class="kw">implicit</span> a: Arbitrary[A]): Arbitrary[LinkedList[A]] =
    <span class="fu">Arbitrary</span>(arbitrary[Array[A]].<span class="fu">map</span>(array =&gt; <span class="kw">new</span> LinkedList[A](Arrays.<span class="fu">asList</span>(array))))

  <span class="kw">val</span> addsLengthOne = <span class="fu">property</span>((list: LinkedList[String], s: String) =&gt;
    list.<span class="fu">size</span> + <span class="dv">1</span> == { list.<span class="fu">addFirst</span>(s); list.<span class="fu">size</span> }
  )

  <span class="kw">val</span> getZero = <span class="fu">property</span>((list: LinkedList[String], s: String) =&gt;
    { list.<span class="fu">addFirst</span>(s); list.<span class="fu">get</span>(<span class="dv">0</span>) == s }
  )

  <span class="kw">val</span> getPlusOne = <span class="fu">property</span>((list: LinkedList[String], s: String, n: Int) =&gt;
    (n &gt;= <span class="dv">0</span> &amp;&amp; n &lt; list.<span class="fu">size</span>) ==&gt;
    (list.<span class="fu">get</span>(n) == { list.<span class="fu">addFirst</span>(s); list.<span class="fu">get</span>(n + <span class="dv">1</span>) })
  )

  <span class="kw">val</span> thisIsFalse = <span class="fu">property</span>((list: LinkedList[String], s: String) =&gt;
    {
      <span class="kw">val</span> listt = list.<span class="fu">clone</span>.<span class="fu">asInstanceOf</span>[LinkedList[String]]
      list.<span class="fu">addFirst</span>(s)
      listt.<span class="fu">addLast</span>(s)
      list == listt
    }
  )

  <span class="kw">val</span> tests = scala.<span class="fu">List</span>(
      (<span class="st">&quot;addsLengthOne&quot;</span>, addsLengthOne),
      (<span class="st">&quot;getZero&quot;</span>, getZero),
      (<span class="st">&quot;getPlusOne&quot;</span>, getPlusOne),
      (<span class="st">&quot;you&#39;re a big fat liar!&quot;</span>, thisIsFalse)
  )

  <span class="kw">def</span> <span class="fu">main</span>(args: scala.<span class="fu">Array</span>[String]) =
    tests foreach { <span class="kw">case</span> (name, p) =&gt; <span class="fu">testStatsEx</span>(name, <span class="fu">check</span>(p)) }
}</code></pre>
<p>And when we run:</p>
<pre><code>$ scala -classpath .:ScalaCheck-1.2.jar CheckLinkedList
+ OK, passed 100 tests.
+ OK, passed 100 tests.
+ OK, passed 100 tests.
! Falsified after 2 passed tests:
&gt; ARG_0 = &quot;[, a, b]&quot;
&gt; ARG_1 = &quot;&quot;
java.lang.Error: you&#39;re a big fat liar!: Failed(List(Arg(,[, a, b],0), Arg(,,0)))</code></pre>
<p>Our usual three properties pass just fine, but notice that ScalaCheck prints the <em>counter-example</em> to the false property. We can determine that this will never be the empty list since the property holds for the empty list (does it? don’t just take my word for it!). ScalaCheck likely tries the empty list one or two times before it declared to have “Falsified after 2 passed tests” using a non-empty list.</p>
<p>Imagine if ScalaCheck had printed a list of length 20 or 30. If our property was particularly complicated, it would be more difficult to reason about our code and the property to determine <em>why what we stated was false</em>. If the property is also false for a list of length 10, we’d probably want to see that counter-example instead to make debugging easier. Indeed, it would be even easier to have the shortest possible list length that still falsifies what we believed to be correct. This concept is known as <em>shrinking</em> and ScalaCheck certainly provides this ability – occasionally with some assistance from the user for user-defined types – a bit like having to declare your own <code>Arbitrary</code>, you also declare your own shrinking strategy and this is also typically trivial.</p>
<p>In our case, the linked list was not shrunk, since we hadn’t provided a shrinking strategy for linked list (and one is not supplied with ScalaCheck), so the first counter-example was used. In non-demonstration environments, it is encouraged to put this additional effort in to your testing practices by supplying a shrinking strategy for user-defined types (if possible and sensible – it is not always so).</p>
<h3 id="conclusion">Conclusion</h3>
<p>Automated unit testing is an incredibly important tool to any programmer – even when using Java. It serves as rigorous documentation at the very worst and more typically, as a robust unit testing platform (300 unit tests in 25 lines in a demo – it’s usually even better than that! <a href="http://projects.workingmouse.com/public/scalaz/tags/2.4/src/test/scalaz/CheckEither.scala">here is over 30,000 unit tests</a>).</p>
<p>Coming up with good properties is an extremely (this adverb cannot be exaggerated) disciplined task and I implore any programmer to strive to do it effectively. Note that stating one property may imply others, so stating those others is potentially redundant. In other words, it is the set of properties that make up the unit for analysis – you cannot necessarily declare the legitimacy of each one independently.</p>
<p>This form of testing is a physical manifestation of an integral part of computer programming – the formation of the logical theorem (see Curry-Howard Isomorphism) that makes up the program. We conclude by noting that this more disciplined, robust and formal approach to programming requires considerably less effort than traditional unit testing techniques, but rigorous mental discipline. It can also be observed that this approach de-emphasises the English description (i.e. function name, javadoc, etc.) as a meaningful method of extrapolating function behaviour.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Yes you are in a cult, no I don’t recognise its legitimacy</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/yes-you-are-in-a-cult-no-i-dont-recognise-its-legitimacy/index.html"/>
  <id>http://blog.tmorris.net/posts/yes-you-are-in-a-cult-no-i-dont-recognise-its-legitimacy/index.html</id>
  <published>2008-04-05T15:39:00Z</published>
  <updated>2008-04-05T15:39:00Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I was trolled yesterday – I think – I still don’t quite know what “troll” means, since it seems to be a universally applicable verb to describe an action that you dislike. Maybe I wasn’t trolled. I was in the #ocaml programming language channel when a user started displaying an ignorance of the Haskell programming language. I made a small effort to point out that the propositions being put forward were incorrect, but it turns out that “of course I would say that, I am a Haskeller” and so the truth value of the propositions were never explored.</p>
<p><strong>No, I am not a Haskeller.</strong> I am not an anti-Java, O’Caml hating, Scala using Haskell worshipper. I completely reject this attempt to assign cult status to the various programming languages. As a matter of fact, I completely reject the existence of the concept of X Programmer for any value of X such that X is an element of the set of all computer programming languages. Correct, Java programmers <strong>do not exist</strong>. Try telling that to your local recruitment agent.</p>
<p>The corporations are having a field day, while amateurs continue to repeat the many different brand/meme names. “Oh hi, I am a C# Programmer, what religion… err programming language fraternity do you belong to?”. My criticisms of Java do not stem from a personal distaste or apostasy; they stem from the fact that it is indeed, far removed from anything useful, practical or resembling soundness in the practice of computer programming.</p>
<p>Can you imagine two motor mechanics discussing their day jobs where one says, “I am an NGK spark plug installer”, to which the other replies, “oh, I am a Champion spark plug installer, but I use NGK on my own vehicle”? It is this degree of absurdity that I assign to any notion of Java Programmer, Haskeller or what-have-you. It is simply and extremely ridiculous. No really, it is. I won’t pretend otherwise despite any scoffing.</p>
<p>Take for example, the distinction between Java and C#, which is almost zero, <em>in the greater scheme of computer programming language theory</em>. What benefit does distinguishing a “C# Programmer” from a “Java Programmer” give? It serves only to resemble status and cult membership. They are both utterly useless as computer programming languages (yes, this is despite their <a href="http://en.wikipedia.org/wiki/Argumentum_ad_populum">popularity</a>). Members of both of these cults will scorn at this proposition simply because it appears provocative and causes offence – not because there is evidence to the contrary (there is an enormous amount of evidence supporting the affirmative position, but that’s another topic). What if it is true?</p>
<p>I predict that the many members of the current (why was I born in this era?!) anti-intellectualism establishment probably wouldn’t read this rant to this point, so I’m probably preaching to the choir when I point out that the practice of computer programming is founded on <a href="http://en.wikipedia.org/wiki/Lambda_calculus">various</a> <a href="http://en.wikipedia.org/wiki/Curry-Howard">fields</a> <a href="http://en.wikipedia.org/wiki/Combinatory_logic">of</a> mathematics.</p>
<p>What does this have to do with the latest advertisement on msdn.com or whatever bullshit marketing material you subscribe to? Nothing. Not a bit. So no, I’m not in your cult, I’m not in cults that rival you, I’m not in a cult that considers itself superior or inferior to yours. I’m an independent thinker.</p>
<p>Your inability to see beyond subscription to cleverly-constructed brand naming is complete bullshit, that’s what it is.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Pseudo-Science</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/pseudo-science/index.html"/>
  <id>http://blog.tmorris.net/posts/pseudo-science/index.html</id>
  <published>2008-03-24T07:56:38Z</published>
  <updated>2008-03-24T07:56:38Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>When I encounter pseudo-science, it is usually from the computer programming community perverting the mathematical discourse of computing science or the religious fraternity attempting to keep their logical absurdities propped up. I started reading about some of the amusing wonders of Homeopathy a few years ago and I recently came across this gem – a pure demonstration of utter stupidity and ignorance that will leave you flabbergasted. I don’t think this person is consciously lying, do you? Enjoy :)</p>
<p>P.S. It is Stephen <strong>Hawking</strong> (no ’s’)</p>
    </div>
  </content>
</entry>
<entry>
  <title>Which Scala Version?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/which-scala-version/index.html"/>
  <id>http://blog.tmorris.net/posts/which-scala-version/index.html</id>
  <published>2008-03-22T15:25:18Z</published>
  <updated>2008-03-22T15:25:18Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I am constantly checking the version of <code>scala-library.jar</code> and <code>scala-compiler.jar</code> when I am using Scala to verify that I am using the correct version. Here is a lookup table with the MD5 hash for myself and anyone else who does the same:</p>
<pre><code>2.7.0-final
79e45028a358f0deab9e569d3ba4ab70  lib/scala-library.jar
70c0fbd0f1f9b69e6073475ac815fed0  lib/scala-compiler.jar

2.7.0-RC3
9172d38ec2429f195f7c0d33f79f637b  lib/scala-library.jar
1531ca6819bc6cb9a22ff468255ed3a5  lib/scala-compiler.jar

2.7.0-RC2
8620b95f78e48f1ff1e84ebff4b3519e  lib/scala-library.jar
b4c7815aa711e7d810b8a1098f2952ca  lib/scala-compiler.jar

2.7.0-RC1
9284692b287677dc4d6535b0b58beac7  lib/scala-library.jar
52fdbf4c6848e8df235092c7c0d85de0  lib/scala-compiler.jar

2.6.1-final
b0b1f651acc03864d5c9aea8e2e8d37f  share/scala/lib/scala-library.jar
c546daad2358da9d00793ee6fa5a727e  share/scala/lib/scala-compiler.jar

2.6.0-final
ee5bc8b07c853eaff7ff5570a9a8e402  share/scala/lib/scala-library.jar
6486d3fd03d6223eca8230589372926a  share/scala/lib/scala-compiler.jar

2.5.1-final
958b1029fa5c016bb4d8cce61969dce5  share/scala/lib/scala-library.jar
7b078714f2bfda25b2c55adc0ce9ec47  share/scala/lib/scala-compiler.jar

2.5.0-final
a55fdd200521aaec309319c780d0acc3  share/scala/lib/scala-library.jar
d58909b8433137ce452cabe91c56b334  share/scala/lib/scala-compiler.jar</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>NEVER. EVER. AGAIN.</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/never-ever-again/index.html"/>
  <id>http://blog.tmorris.net/posts/never-ever-again/index.html</id>
  <published>2008-03-17T10:16:09Z</published>
  <updated>2008-03-17T10:16:09Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>* I will never again be put in a position where a client requirement cannot be met in effort proportional to its complexity, as a result of the incompetence and outright malpractice of a fellow self-proclaimed computer programmer.</p>
<p>* I will never again be put in a position where I must tell a client that their requirement is overdue as a result of the consequences implied by the incompetence of a fellow self-proclaimed programmer.</p>
<p>* I will never again be put in a position where I must hack at software in most unsavoury ways (i.e. likely defective; unable to decompose perpetually) in order to achieve a client requirement satisfactorily – this flows from exclusive competence and thus, the elimination of incompetence.</p>
<p>F.F.S., The bar is not that high!</p>
<p><strong>NEVER. EVER. AGAIN.</strong></p>
    </div>
  </content>
</entry>
<entry>
  <title>Religiosity is a neurological disorder.</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/religiosity-is-a-neurological-disorder/index.html"/>
  <id>http://blog.tmorris.net/posts/religiosity-is-a-neurological-disorder/index.html</id>
  <published>2008-03-16T13:55:37Z</published>
  <updated>2008-03-16T13:55:37Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <div class="figure">
<img src="http://i30.photobucket.com/albums/c342/zvoncic/SickChristian.jpg" alt="Religiosity is a neurological disorder" /><p class="caption">Religiosity is a neurological disorder</p>
</div>
    </div>
  </content>
</entry>
<entry>
  <title>Why is a web page suddenly taken off Google search results?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/why-is-a-web-page-suddenly-taken-off-google-search-results/index.html"/>
  <id>http://blog.tmorris.net/posts/why-is-a-web-page-suddenly-taken-off-google-search-results/index.html</id>
  <published>2008-03-12T12:10:11Z</published>
  <updated>2008-03-12T12:10:11Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I noticed once before that this site was taken off Google’s search results immediately after posting a number in hexadecimal format that was apparently a copyrighted work and therefore, a violation of some other country’s law – something about DMCA. I immediately retracted this post and the web site returned to Google search results.</p>
<p>So I ask, what have I done now? Why can’t I google up my own rantings? Anyone got any hints?</p>
    </div>
  </content>
</entry>
<entry>
  <title>Raf’s Problem</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/rafs-problem/index.html"/>
  <id>http://blog.tmorris.net/posts/rafs-problem/index.html</id>
  <published>2008-03-11T13:27:23Z</published>
  <updated>2008-03-11T13:27:23Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://rafs-blog.blogspot.com/">Raf</a> – a colleague – gave me the following problem:</p>
<blockquote>
<p>Given a String (x) containing only characters a-z, write a function (f) that returns a base 10 integer, which converts the String as if it were a base 26 numeral. Function f is bijective.</p>
</blockquote>
<p>Here are some example runs:</p>
<pre><code>x      | f(x)
empty  | 0
a      | 1
b      | 2
z      | 26
aa     | 27
az     | 52
ba     | 53
bz     | 78
aaa    | 703
aaz    | 728
aza    | 1353</code></pre>
<p>Using your preferred programming language, implement function f.</p>
<p>My solution is in a comment on this page. What is yours?</p>
    </div>
  </content>
</entry>
<entry>
  <title>Scalaz 2.4 Released</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/scalaz-24-released/index.html"/>
  <id>http://blog.tmorris.net/posts/scalaz-24-released/index.html</id>
  <published>2008-02-29T13:00:45Z</published>
  <updated>2008-02-29T13:00:45Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Scalaz 2.4 has been released and includes some significant updates.</p>
<p><a href="http://projects.workingmouse.com/public/scalaz/artifacts/2.4/scaladoc/index.html">Scalaz API Specification</a> <a href="http://projects.workingmouse.com/public/scalaz/artifacts/2.4/demo/">Scalaz Demonstration Code</a> <a href="http://projects.workingmouse.com/public/scalaz/artifacts/2.4/src/">Scalaz Source</a> <a href="http://projects.workingmouse.com/public/scalaz/artifacts/2.4/test-src/">Scalaz Specification Tests</a> <a href="http://wiki.workingmouse.com/index.php/Scalaz">Scalaz Home Page</a> <a href="http://wiki.workingmouse.com/index.php/Scalaz_Changes">Scalaz Change List</a></p>
<p><a href="http://projects.workingmouse.com/public/scalaz/artifacts/2.4/release/">Download Scalaz 2.4 Release</a></p>
    </div>
  </content>
</entry>
<entry>
  <title>'Christopher Hitchens: The Moral Necessity of Atheism'</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/christopher-hitchens-the-moral-necessity-of-atheism/index.html"/>
  <id>http://blog.tmorris.net/posts/christopher-hitchens-the-moral-necessity-of-atheism/index.html</id>
  <published>2008-02-27T19:27:17Z</published>
  <updated>2008-02-27T19:27:17Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Part 1 of 8</p>
<p>Part 2 of 8</p>
<p>Part 3 of 8</p>
<p>Part 4 of 8</p>
<p>Part 5 of 8</p>
<p>Part 6 of 8</p>
<p>Part 7 of 8</p>
<p>Part 8 of 8</p>
    </div>
  </content>
</entry>
<entry>
  <title>That’s what Monads are for</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/thats-what-monads-are-for/index.html"/>
  <id>http://blog.tmorris.net/posts/thats-what-monads-are-for/index.html</id>
  <published>2008-02-25T10:31:43Z</published>
  <updated>2008-02-25T10:31:43Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>After a heavy weekend of squash, my Magnesium and Zinc depleted body in all its tiredness offers the following universal law of pseudo-scientific claims for analysis:</p>
<blockquote>
<p>If someone claims that the concept of Monads (a computation model offered by Category Theory) are for side-effects, then you can be absolutely certain that the person making the claim has absolutely no idea what Monads are for. Not even the slightest. You should consider their credibility on the topic to be absolutely zero.</p>
</blockquote>
<p>Comments? Does this count as the ever common Monad Tutorial? :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>So I don’t lose it</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/so-i-dont-lose-it/index.html"/>
  <id>http://blog.tmorris.net/posts/so-i-dont-lose-it/index.html</id>
  <published>2008-02-18T12:14:38Z</published>
  <updated>2008-02-18T12:14:38Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Took me a while to recall the right keywords to come up with this excellent interview between a representative of the Canadian Government and Ezra Levant.</p>
    </div>
  </content>
</entry>
<entry>
  <title>The argument from oranges</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/the-argument-from-oranges/index.html"/>
  <id>http://blog.tmorris.net/posts/the-argument-from-oranges/index.html</id>
  <published>2008-02-17T15:34:38Z</published>
  <updated>2008-02-17T15:34:38Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>There are few things more amusing than listening to a theist coming to terms with the Theory of Evolution. As is often the case, there is either complete ignorance (and if honest, an admission to this extent) or an attempt to unify the fact with the dogma.</p>
<p>But this one is in a category of its own and had me laughing hours afterward:</p>
    </div>
  </content>
</entry>
<entry>
  <title>Great Quote Slava</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/great-quote-slava/index.html"/>
  <id>http://blog.tmorris.net/posts/great-quote-slava/index.html</id>
  <published>2008-02-07T10:21:21Z</published>
  <updated>2008-02-07T10:21:21Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Referring to this, <a href="http://weblogs.java.net/blog/kirillcool/archive/2008/02/evolving_the_la.html">er typical piece of er, collection of “thoughts”</a> (I’m being nice so as not to distract from the great quote) with emphasis on a quote from this piece.</p>
<p>Referring to Java closures (<em>sigh</em> can we just use Scala yet? please?):</p>
<blockquote>
<p>Extra verbosity makes sure that the code guides me along its intended path</p>
</blockquote>
<p><a href="http://factorcode.org/slava/">Slava Pestov</a> <a href="http://reddit.com/info/67w5n/comments/c033z18">responds in his typically brilliant fashion</a>:</p>
<blockquote>
<p>He’s absolutely right. Closures have no place in a low-level procedural language whose target audience consists of programmers unwilling to learn to be productive.</p>
</blockquote>
<p>So true Slava, so true.</p>
    </div>
  </content>
</entry>
<entry>
  <title>It’s just logic</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/its-just-logic/index.html"/>
  <id>http://blog.tmorris.net/posts/its-just-logic/index.html</id>
  <published>2008-02-01T16:03:24Z</published>
  <updated>2008-02-01T16:03:24Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <pre><code>*Don&#39;t do this*
**Do this**</code></pre>
<hr />
<p><strong>conjunction (∧)</strong></p>
<p><em>if(p) q else false</em></p>
<p><strong>p &amp;&amp; q</strong></p>
<p>p ∧ q</p>
<p><strong>conditional/implication (→)</strong></p>
<p><em>if(p) q else true</em> <strong>!p || q</strong> ¬p ∨ q</p>
<p><strong>negation of conditional/implication</strong></p>
<p><em>if(p) !q else false</em></p>
<p><strong>p &amp;&amp; !q</strong></p>
<p>p ∧ ¬q</p>
<p><strong>negation of conjunction</strong></p>
<p><em>if(p) !q else true</em></p>
<p><strong>!p || !q</strong></p>
<p>¬p ∨ ¬q</p>
<p><strong>disjunction (∨)</strong></p>
<p><em>if(p) true else q</em> <strong>p || q</strong> p ∨ q</p>
<p><strong>negation of inverse conditional/implication</strong></p>
<p><em>if(p) false else q</em> <strong>!p &amp;&amp; q</strong> ¬p ∧ q</p>
<p><strong>inverse conditional/implication</strong></p>
<p><em>if(p) true else !q</em> <strong>p || !q</strong> p ∨ ¬q</p>
<p><strong>negation of disjunction</strong></p>
<p><em>if(p) false else !q</em> <strong>!p &amp;&amp; !q</strong> ¬p ∧ ¬q</p>
<p><em>if(p) true else false</em> <strong>p</strong></p>
<p><em>if(p) false else true</em> <em>!p</em></p>
    </div>
  </content>
</entry>
<entry>
  <title>Scala operator names</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/scala-operator-names/index.html"/>
  <id>http://blog.tmorris.net/posts/scala-operator-names/index.html</id>
  <published>2008-01-22T13:04:21Z</published>
  <updated>2008-01-22T13:04:21Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Infix (<em>least to highest precedence</em>)</p>
<pre><code>|
^
&amp;
&lt; &gt;
= !
:
+ -
* / %
~</code></pre>
<p>Postfix (<em>unary</em>_)</p>
<pre><code>+
-
!
~</code></pre>
<p><em>Operators ending with colon (:) are right-associative.</em></p>
    </div>
  </content>
</entry>
<entry>
  <title>scala.Option Cheat Sheet</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/scalaoption-cheat-sheet/index.html"/>
  <id>http://blog.tmorris.net/posts/scalaoption-cheat-sheet/index.html</id>
  <published>2008-01-16T15:06:39Z</published>
  <updated>2008-01-16T15:06:39Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Many people who are coming in to Scala first encounter the <a href="http://www.scala-lang.org/docu/files/api/scala/Option.html">Option</a> type, which may be thought of (among other things) as a type-safe <code>null</code>. They also encounter pattern matching as both a new and (relatively) powerful concept, but also one that is easy to understand. This leads to quite a lot of use of pattern matching and often excessively so in what I have observed.</p>
<p>Particularly with a type as trivial as <code>Option</code>, it is almost always possible to do away with pattern matching by using a higher-order function. Use of this function is typically preferred over pattern matching as tighter code. In fact, it is important to observe that it is possible to encapsulate all forms of pattern matching over <code>Option</code> with one simple higher-order function:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">def</span> option[A, X](o: Option[A])(none: =&gt; X, some: =&gt; A =&gt; X): X = ...</code></pre>
<p>Then, all functions can be written in terms of this one and needn’t pattern match at all. For example, consider <code>Option.map</code>:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">def</span> map[A, B](o: Option[A], f: A =&gt; B) =
  <span class="fu">option</span>(o, None, a =&gt; Some(<span class="fu">f</span>(a)))</code></pre>
<p>In this post, I am going to give some common uses of pattern matching, which many developers might find themselves performing, followed by the use of a function that already exists on <code>Option</code> that encapsulates that given form of pattern matching. If you find yourself using pattern matching in a form not listed below, but feel it could be abstracted, then chances are that such a function exists in the <a href="http://code.google.com/p/scalaz/">Scalaz extension to scala.Option</a>.</p>
<p>I will use the identifier <code>foo</code> below to denote any particular function, including many functions composed, for example, <code>foo(x)</code> may represent the composition of two functions f and g: <code>f(g(x))</code>. I also use the identifier <code>option</code> to denote any value of the type <code>scala.Option</code>.</p>
<p>I hope this helps :)</p>
<hr />
<p><strong><code>flatMap</code></strong></p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option <span class="kw">match</span> {
  <span class="kw">case</span> None =&gt; None
  <span class="kw">case</span> Some(x) =&gt; <span class="fu">foo</span>(x)
}</code></pre>
<p>This code is equivalent to:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option.<span class="fu">flatMap</span>(<span class="fu">foo</span>(_))</code></pre>
<hr />
<p><strong><code>flatten</code></strong></p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option <span class="kw">match</span> {
  <span class="kw">case</span> None =&gt; None
  <span class="kw">case</span> Some(x) =&gt; x
}</code></pre>
<p>This code is equivalent to:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option.<span class="fu">flatten</span></code></pre>
<hr />
<p><strong><code>map</code></strong></p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option <span class="kw">match</span> {
  <span class="kw">case</span> None =&gt; None
  <span class="kw">case</span> Some(x) =&gt; Some(<span class="fu">foo</span>(x))
}</code></pre>
<p>This code is equivalent to:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option.<span class="fu">map</span>(<span class="fu">foo</span>(_))</code></pre>
<hr />
<p><strong><code>foreach</code></strong></p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option <span class="kw">match</span> {
  <span class="kw">case</span> None =&gt; {}
  <span class="kw">case</span> Some(x) =&gt; <span class="fu">foo</span>(x)
}</code></pre>
<p>This code is equivalent to:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option.<span class="fu">foreach</span>(<span class="fu">foo</span>(_))</code></pre>
<hr />
<p><strong><code>isDefined</code></strong></p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option <span class="kw">match</span> {
  <span class="kw">case</span> None =&gt; <span class="kw">false</span>
  <span class="kw">case</span> Some(_) =&gt; <span class="kw">true</span>
}</code></pre>
<p>This code is equivalent to:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option.<span class="fu">isDefined</span></code></pre>
<hr />
<p><strong><code>isEmpty</code></strong></p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option <span class="kw">match</span> {
  <span class="kw">case</span> None =&gt; <span class="kw">true</span>
  <span class="kw">case</span> Some(_) =&gt; <span class="kw">false</span>
}</code></pre>
<p>This code is equivalent to:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option.<span class="fu">isEmpty</span></code></pre>
<hr />
<p><strong><code>forall</code></strong></p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option <span class="kw">match</span> {
  <span class="kw">case</span> None =&gt; <span class="kw">true</span>
  <span class="kw">case</span> Some(x) =&gt; <span class="fu">foo</span>(x)
}</code></pre>
<p>This code is equivalent to:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option.<span class="fu">forall</span>(<span class="fu">foo</span>(_))</code></pre>
<hr />
<p><strong><code>exists</code></strong></p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option <span class="kw">match</span> {
  <span class="kw">case</span> None =&gt; <span class="kw">false</span>
  <span class="kw">case</span> Some(x) =&gt; <span class="fu">foo</span>(x)
}</code></pre>
<p>This code is equivalent to:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option.<span class="fu">exists</span>(<span class="fu">foo</span>(_))</code></pre>
<hr />
<p><strong><code>orElse</code></strong></p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option <span class="kw">match</span> {
  <span class="kw">case</span> None =&gt; foo
  <span class="kw">case</span> Some(x) =&gt; Some(x)
}</code></pre>
<p>This code is equivalent to:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option.<span class="fu">OrElse</span>(foo)</code></pre>
<hr />
<p><strong><code>getOrElse</code></strong></p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option <span class="kw">match</span> {
  <span class="kw">case</span> None =&gt; foo
  <span class="kw">case</span> Some(x) =&gt; x
}</code></pre>
<p>This code is equivalent to:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option.<span class="fu">getOrElse</span>(foo)</code></pre>
<hr />
<p><strong><code>toList</code></strong></p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option <span class="kw">match</span> {
  <span class="kw">case</span> None =&gt; Nil
  <span class="kw">case</span> Some(x) =&gt; x :: Nil
}</code></pre>
<p>This code is equivalent to:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option.<span class="fu">toList</span></code></pre>
<hr />
<p><strong><code>coflatMap</code></strong><sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup></p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option <span class="kw">match</span> {
  <span class="kw">case</span> None =&gt; None
  <span class="kw">case</span> Some(_) =&gt; Some(<span class="fu">foo</span>(option))
}</code></pre>
<p>This code is equivalent to:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option.<span class="fu">coflatMap</span>(<span class="fu">foo</span>(_))</code></pre>
<hr />
<p><strong><code>duplicate</code></strong><sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup></p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option <span class="kw">match</span> {
  <span class="kw">case</span> None =&gt; None
  <span class="kw">case</span> Some(_) =&gt; Some(option)
}</code></pre>
<p>This code is equivalent to:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">option.<span class="fu">duplicate</span></code></pre>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Unfortunately <code>coflatMap</code> is not part of the standard library. You will need to write it yourself or use Scalaz.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>Unfortunately, <code>duplicate</code> is not part of the standard library. You will need to write it yourself or use Scalaz.<a href="#fnref2">↩</a></p></li>
</ol>
</div>
    </div>
  </content>
</entry>
<entry>
  <title>scala.List.foldLeft for Java programmers</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/scalalistfoldleft-for-java-programmers/index.html"/>
  <id>http://blog.tmorris.net/posts/scalalistfoldleft-for-java-programmers/index.html</id>
  <published>2008-01-15T15:16:14Z</published>
  <updated>2008-01-15T15:16:14Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I recently ran another Scala training course and I produced a hand-out that seemed to help people understand what a foldLeft is. Here is a brief explanation of it.</p>
<p>Suppose you have the following Java code:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala">B b = start

<span class="kw">for</span>(<span class="kw">final</span> A a : listOfA) {
  b = <span class="fu">method</span>(b, a);
}

<span class="kw">return</span> b;</code></pre>
<p>You can have any value for <code>start</code>, <code>method</code> and <code>listOfA</code>. Also, <code>method</code> may ignore any of its arguments or even not have them passed at all. You’ll notice that a <strong>lot</strong> of Java code is written this way, so it would be fair to say that “left folds occur a lot in Java”, despite being encoded as loops.</p>
<p>The above Java code is equivalent to the following Scala code, again for all values of the given identifiers (so long as they type check of course):</p>
<pre><code>listOfA.foldLeft(start)(method)</code></pre>
<p>…which is also equivalent to:</p>
<pre><code>(start /: listOfA)(method)</code></pre>
<p>…which by the way, is a perfectly sound approach to performing a list reduction, despite what some clowns rubbish on with.</p>
<p>That’s all, hope it helped :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>Offending Religiosity</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/offending-religiosity/index.html"/>
  <id>http://blog.tmorris.net/posts/offending-religiosity/index.html</id>
  <published>2008-01-01T09:50:22Z</published>
  <updated>2008-01-01T09:50:22Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>In my <a href="http://blog.tmorris.net/scala-262-getting-support-for-java-generics/">recent post</a>, I made the following introductory statement:</p>
<blockquote>
<p>Scala is a far superior language to Java.</p>
</blockquote>
<p>Sadly, but most predictably, some people took issue with this fact. It seems I have “stepped on someone’s meme” so-to-speak. Programming languages, unfortunately, have formed cliques who defend their territory with classic religious devotion.</p>
<p>It is certainly not difficult to conceive two programming languages where one is inferior to the other, and so long as neither language has any devoted followers, it is acceptable and makes perfect sense to anyone willing to hear it. I invent a language called Plus and it has one function + and integral literals; I invent another language PlusMinus and it has two functions, + and - and integral literals also. PlusMinus is superior to Plus.</p>
<p>We can traverse the futile path of “Actually, whether PlusMinus is superior to Plus depends on whether - is of any value. The non-existence of the - function in Plus may make it superior under some circumstances”, but I’m hoping, perhaps too optimistically, any objectors can see straight through this misnomer.</p>
<p>It is cases like these where the similarities to the typical religious organisations becomes astounding. I am charged with religiosity, because I am completely atheistic (i.e. null hypothesis) about my meme membership, by those who themselves are more religious than ever! Something about pots, kettles and blackness seems apt here. Furthermore, it is quite often the case that when the charges roll in, in defence of Java, those making the charges know Java quite poorly anyway (most so-called Java programmers do in my observations) – another religious theme that seems to be deeply embedded.</p>
<p>The status of “Java” has been artificially elevated by its groupthink members such that any attack or suggestion of inferiority is reviled, even if the suggestion is perfectly rational and able to be supported with evidence. I could simply discredit their understanding of their belief system by demonstrating how little they know about it (I am always surprised at how easy this is), but it does seem somewhat distasteful. Alternatively, I could present aforementioned evidence, only to have it (predictably so) misunderstood and misrepresented in various forms of logical fallacy.</p>
<p>No, I’d rather work toward abandoning religiosity itself and demonstrating that reason trumps. After all, like most religious memberships, I don’t think these charges have any kind of malicious intent or deceptive techniques behind them, invoke Hanlon’s Razor:</p>
<blockquote>
<p>Never attribute to malice that which can be adequately explained by stupidity.</p>
</blockquote>
    </div>
  </content>
</entry>
<entry>
  <title>Doomsday in Scala</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/doomsday-in-scala/index.html"/>
  <id>http://blog.tmorris.net/posts/doomsday-in-scala/index.html</id>
  <published>2008-01-01T08:03:31Z</published>
  <updated>2008-01-01T08:03:31Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Just for kicks, from <a href="http://en.wikipedia.org/wiki/Doomsday_algorithm">http://en.wikipedia.org/wiki/Doomsday_algorithm</a></p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">sealed</span> <span class="kw">trait</span> Day {
  <span class="kw">def</span> +(n: Int): Day
}
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> Sunday <span class="kw">extends</span> Day {
  <span class="kw">override</span> <span class="kw">def</span> +(n: Int) = n % <span class="dv">7</span> <span class="kw">match</span> {
    <span class="kw">case</span> <span class="dv">0</span> =&gt; Sunday
    <span class="kw">case</span> <span class="dv">1</span> =&gt; Monday
    <span class="kw">case</span> <span class="dv">2</span> =&gt; Tuesday
    <span class="kw">case</span> <span class="dv">3</span> =&gt; Wednesday
    <span class="kw">case</span> <span class="dv">4</span> =&gt; Thursday
    <span class="kw">case</span> <span class="dv">5</span> =&gt; Friday
    <span class="kw">case</span> <span class="dv">6</span> =&gt; Saturday
  }
}
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> Monday <span class="kw">extends</span> Day {
  <span class="kw">override</span> <span class="kw">def</span> +(n: Int) = n % <span class="dv">7</span> <span class="kw">match</span> {
    <span class="kw">case</span> <span class="dv">6</span> =&gt; Sunday
    <span class="kw">case</span> <span class="dv">0</span> =&gt; Monday
    <span class="kw">case</span> <span class="dv">1</span> =&gt; Tuesday
    <span class="kw">case</span> <span class="dv">2</span> =&gt; Wednesday
    <span class="kw">case</span> <span class="dv">3</span> =&gt; Thursday
    <span class="kw">case</span> <span class="dv">4</span> =&gt; Friday
    <span class="kw">case</span> <span class="dv">5</span> =&gt; Saturday
  }
}
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> Tuesday <span class="kw">extends</span> Day {
  <span class="kw">override</span> <span class="kw">def</span> +(n: Int) = n % <span class="dv">7</span> <span class="kw">match</span> {
    <span class="kw">case</span> <span class="dv">5</span> =&gt; Sunday
    <span class="kw">case</span> <span class="dv">6</span> =&gt; Monday
    <span class="kw">case</span> <span class="dv">0</span> =&gt; Tuesday
    <span class="kw">case</span> <span class="dv">1</span> =&gt; Wednesday
    <span class="kw">case</span> <span class="dv">2</span> =&gt; Thursday
    <span class="kw">case</span> <span class="dv">3</span> =&gt; Friday
    <span class="kw">case</span> <span class="dv">4</span> =&gt; Saturday
  }
}
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> Wednesday <span class="kw">extends</span> Day {
  <span class="kw">override</span> <span class="kw">def</span> +(n: Int) = n % <span class="dv">7</span> <span class="kw">match</span> {
    <span class="kw">case</span> <span class="dv">4</span> =&gt; Sunday
    <span class="kw">case</span> <span class="dv">5</span> =&gt; Monday
    <span class="kw">case</span> <span class="dv">6</span> =&gt; Tuesday
    <span class="kw">case</span> <span class="dv">0</span> =&gt; Wednesday
    <span class="kw">case</span> <span class="dv">1</span> =&gt; Thursday
    <span class="kw">case</span> <span class="dv">2</span> =&gt; Friday
    <span class="kw">case</span> <span class="dv">3</span> =&gt; Saturday
  }
}
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> Thursday <span class="kw">extends</span> Day {
  <span class="kw">override</span> <span class="kw">def</span> +(n: Int) = n % <span class="dv">7</span> <span class="kw">match</span> {
    <span class="kw">case</span> <span class="dv">3</span> =&gt; Sunday
    <span class="kw">case</span> <span class="dv">4</span> =&gt; Monday
    <span class="kw">case</span> <span class="dv">5</span> =&gt; Tuesday
    <span class="kw">case</span> <span class="dv">6</span> =&gt; Wednesday
    <span class="kw">case</span> <span class="dv">0</span> =&gt; Thursday
    <span class="kw">case</span> <span class="dv">1</span> =&gt; Friday
    <span class="kw">case</span> <span class="dv">2</span> =&gt; Saturday
  }
}
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> Friday <span class="kw">extends</span> Day {
  <span class="kw">override</span> <span class="kw">def</span> +(n: Int) = n % <span class="dv">7</span> <span class="kw">match</span> {
    <span class="kw">case</span> <span class="dv">2</span> =&gt; Sunday
    <span class="kw">case</span> <span class="dv">3</span> =&gt; Monday
    <span class="kw">case</span> <span class="dv">4</span> =&gt; Tuesday
    <span class="kw">case</span> <span class="dv">5</span> =&gt; Wednesday
    <span class="kw">case</span> <span class="dv">6</span> =&gt; Thursday
    <span class="kw">case</span> <span class="dv">0</span> =&gt; Friday
    <span class="kw">case</span> <span class="dv">1</span> =&gt; Saturday
  }
}
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> Saturday <span class="kw">extends</span> Day {
  <span class="kw">override</span> <span class="kw">def</span> +(n: Int) = n % <span class="dv">7</span> <span class="kw">match</span> {
    <span class="kw">case</span> <span class="dv">1</span> =&gt; Sunday
    <span class="kw">case</span> <span class="dv">2</span> =&gt; Monday
    <span class="kw">case</span> <span class="dv">3</span> =&gt; Tuesday
    <span class="kw">case</span> <span class="dv">4</span> =&gt; Wednesday
    <span class="kw">case</span> <span class="dv">5</span> =&gt; Thursday
    <span class="kw">case</span> <span class="dv">6</span> =&gt; Friday
    <span class="kw">case</span> <span class="dv">7</span> =&gt; Saturday
  }
}

<span class="co">// From http://en.wikipedia.org/wiki/Doomsday_algorithm</span>
<span class="kw">object</span> Doomsday {
  <span class="kw">def</span> <span class="fu">anchor</span>(y: Int) = y / <span class="dv">100</span> % <span class="dv">4</span> <span class="kw">match</span> {
    <span class="kw">case</span> <span class="dv">0</span> =&gt; Tuesday
    <span class="kw">case</span> <span class="dv">1</span> =&gt; Sunday
    <span class="kw">case</span> <span class="dv">2</span> =&gt; Friday
    <span class="kw">case</span> <span class="dv">3</span> =&gt; Wednesday
  }

  <span class="kw">def</span> <span class="fu">doomsday</span>(y: Int) = {
    <span class="kw">val</span> a = y % <span class="dv">100</span> / <span class="dv">12</span>
    <span class="kw">val</span> b = y % <span class="dv">100</span> % <span class="dv">12</span>
    <span class="kw">val</span> c = b / <span class="dv">4</span>
    <span class="kw">val</span> d = a + b + c
    <span class="fu">anchor</span>(y) + d
  }
}</code></pre>
<blockquote>
<p>scala&gt; import Doomsday._ import Doomsday._</p>
</blockquote>
<p>scala&gt; doomsday(1966) res0: Day = Monday</p>
<p>scala&gt; doomsday(2008) res1: Day = Friday</p>
    </div>
  </content>
</entry>
<entry>
  <title>Scala 2.6.2 getting support for Java generics</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/scala-262-getting-support-for-java-generics/index.html"/>
  <id>http://blog.tmorris.net/posts/scala-262-getting-support-for-java-generics/index.html</id>
  <published>2007-12-29T08:46:16Z</published>
  <updated>2007-12-29T08:46:16Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Scala is a far superior language to Java. In fact, of all the languages that I have investigated, it is the most powerful language that also targets the JVM and Java libraries easily (sorry CAL). I have long held the position that <em>there are no (with one corner case) rational justifications for using the Java programming language for anything but educating our children on how not to design a programming language even when targetting legacy code</em>. This has of course, been met with ‘what about this?’ and ‘what about that?’[1] all of which I have been able to refute, except for one niggling corner case.</p>
<p>Client code of existing Java-compiled code would not receive the benefits of generics, since they were erased. For example, if you were to call a Java-compiled method that returned a <code>List&lt;Integer&gt;</code> from Scala, you’d have a reference to <code>java.util.List</code> without the type argument. If you were to call this method from Java, then many methods on the returned <code>List</code> would return <code>Integer</code> in place of the type argument, however, for Scala, you’d have a type <code>AnyRef</code> (an alias for <code>java.lang.Object</code>) just like Java did in the pre-1.5 days. This gave Java one (and only one) case where its use was an improvement over the use of Scala.</p>
<p>This has been the only remaining use case where Scala does not match or exceed Java in ability, however, Martin Odersky (creator of Scala) has revealed that the next version of Scala is to do away with this limitation! Furthermore, we can use the feature today! That is, we can start moving over any Scala &lt;= 2.6.1 code to 2.6.2 right now and have the full advantages of a powerful language and do away with Java forever, unless of course, you’re still out there appeasing the irrationalities of the suits (you poor buggers, no really, I mean it).</p>
<p>From Martin on the Scala mailing list:</p>
<blockquote>
<p>Just to confirm:</p>
</blockquote>
<p>The nightly build of Scala contains now support for Java generics. The first official release supporting this will be 2.6.2. For instance java.util.List is considered a generic type in Scala in this release. I announce now so that you can experiment with the new feature. Maybe you also already want to start to migrate your codebase to the new scheme.</p>
<p>More precisely, the following things have changed: <em>continues</em></p>
<p>[1] Here are some that I have met and convincingly (and often quite easily) debunked in conversation. Perhaps I could write about them some time.</p>
<ul>
<li>From the CTO of X Corporation, “I don’t have any programmers capable of using Scala”. This myth is both easily falsified, but also extremely detrimental to the interests of the organisation – far more than is initially realised. That is to say, after debunking this myth, my opponent in the argument often has an enlightening experience and then an “Oh no! Given this (new understanding), look at what (detrimental decisions) I have been doing to the organisation!”. Of all fallacies, this is the one I’d like to put in the box of past events from which to learn.</li>
</ul>
<p>* But Java is enterprise-ready</p>
<p>* But Java is a robust language with many libraries</p>
    </div>
  </content>
</entry>
<entry>
  <title>Scalaz</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/scalaz/index.html"/>
  <id>http://blog.tmorris.net/posts/scalaz/index.html</id>
  <published>2007-12-18T18:25:02Z</published>
  <updated>2007-12-18T18:25:02Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://code.google.com/p/scalaz">Scalaz</a> is a library written using the Scala Programming Language and tested using <a href="http://code.google.com/p/scalacheck/">ScalaCheck</a> (maintained by myself and Rickard Nilsson) automated specification-based testing. It is released under a BSD open source licence.</p>
<p><strong>Features include:</strong></p>
<ul>
<li><p>The <a href="http://projects.workingmouse.com/public/scalaz/artifacts/2.1/scaladoc/scalaz/Either.html">Either</a> Algebraic Data Type and general functions over that type</p></li>
<li><p><a href="http://projects.workingmouse.com/public/scalaz/artifacts/2.1/scaladoc/scalaz/Maybe.html">Enhanced Option</a> type</p></li>
<li><p>Control package (Functor, Monad, MonadPlus, Foldable, etc.)</p></li>
<li><p>Transparent memoisation, loosley inspired by a <a href="http://research.microsoft.com/Users/simonpj/Papers/weak.ps.gz">paper</a> written by Simon Peyton-Jones, Simon Marlow, and Conal Elliott (IFL ’99) titled, “Stretching the storage manager: weak pointers and stable names in Haskell”</p></li>
<li><p>Validation package for web form field validation (using Either and monadic functions across it)</p></li>
</ul>
<p><strong>Links:</strong></p>
<ul>
<li><p><a href="http://projects.workingmouse.com/public/scalaz/artifacts/2.1/scaladoc/index.html">Scalaz API Specification</a></p></li>
<li><p><a href="http://projects.workingmouse.com/public/scalaz/artifacts/2.1/scalaz.jar">Download JAR file</a></p></li>
<li><p><a href="https://svn.workingmouse.com/listing.php?repname=Projects&amp;path=%2Fpublic%2Fscalaz%2F#_public_scalaz_">Browse Scalaz Subversion repository <em>(user/pass: guest/guest)</em></a></p></li>
</ul>
    </div>
  </content>
</entry>
<entry>
  <title>No no, I said ‘critical examination’</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/no-no-i-said-critical-examination/index.html"/>
  <id>http://blog.tmorris.net/posts/no-no-i-said-critical-examination/index.html</id>
  <published>2007-12-06T08:49:37Z</published>
  <updated>2007-12-06T08:49:37Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>The expected tripe has rolled in after my previous post was publicised on reddit (thanks gst whoever you are ;)).</p>
<p>Here are some of the wonderful accusations:</p>
<blockquote>
<p>What a controlling, elitist piece of shit. Worthless article.</p>
</blockquote>
<p>Elitist? I’ll accept that and so what? There is nothing wrong with elitism; in fact, I encourage it. Of course, bragging about it publicly is a little distasteful, but that was never the intention. Controlling? I seem to have controlled you, but nobody else. What else can I say? The response is full of gems of insight!</p>
<blockquote>
<p>What else did you expect? It is Tony Morris, after all.</p>
</blockquote>
<p>Ever heard the term, Ad Hominem fallacy? Such… a critical examination, um, yeah.</p>
<blockquote>
<p>…here we have a Haskell zealot…</p>
</blockquote>
<p>WTF? I use many languages, one of which is Haskell, but certainly nothing that could be described as ‘zealous’. This seems to be an outright statement of ‘I have tricked myself into describing something other than reality’, since I find absolutely no evidence to support it.</p>
<blockquote>
<p>…banned Java from his 6 year-old son’s computer, lest it pollutes his mind. And then he criticises people for being closed-minded!</p>
</blockquote>
<p>I concede on this one and should have made my point clear. I have no intention of hiding Java from my son indefinitely. I’m not going to show him a horror film until he a sound moral basis to conduct himself with his peers for the same reason that I will not show him Java until he has a sound basis with which to apply reason and understands the foundations of what it is he is doing (programming).</p>
<blockquote>
<p>Well I think we’ve all seen this kind of attitude to some extent, but it all seems to proliferate quite extensively from the ivory towers of academia, i.e. the functional programming community.</p>
</blockquote>
<p>They look down on other people who dirty their hands doing “real work” instead of spending time worrying about how pure their language is.</p>
<p>This one is a classic! First, I’d like to dissolve the apparent rift between ‘the functional programmers’ and ‘the imperative programmers’. There simply is no clear distinction and it’s a pointless exercise anyway. Second, I am a member of both communities.</p>
<p>Finally, I’d like you to describe for me what “real work” is. Is it repeating yourself indefinitely because your programming language demands it? No really, I’m asking for a formal definition that we can have a discussion about. You do realise that almost all of Java’s language features started off in “the academic world” (i.e. someone though of a clever idea) and were subsequently perverted before finalising in a JSR (i.e. they were dumbed down to appeal to the masses), right? The results of these JSR teams are merely acts of intellectual fraud. I wish they gave public tours of these circuses so you could see for yourself.</p>
<blockquote>
<p>So Tony hangs around mediocre programmers. Big deal.</p>
</blockquote>
<p>Perhaps I do, but there is no evidence supporting this position. I have only described quite a small subset of all programmers that I could potentially know of. I think that most people only know one language, but I could be mistaken (from the samples I have anyway). i.e. Java, C#, VB, C, etc. are all the same language under this description. How many people do you know who look to advanced languages for insight?</p>
<blockquote>
<p>He only hit the grey mass of average programmers. These used to program in C++ and Visual Basic, and before that in FORTRAN. This grey mass of programmers never have in depth knowledge of the programming language or tools they are using, and are too intelectually lazy to actually learn it. I don’t think java create this kind of guys, but it seems to have the qualities that attracts them.</p>
</blockquote>
<p>On a positive note, this response is one that I have not considered enough to my own satisfaction and I thank that respondent for it! ;) Specifically, the response that Java may not create self-delusion, but attracts those who seek it. I’ll have to think about it some more, thanks again.</p>
<p>Thanks for some of the other positive responses that attempt to refute my argument (read: outburst of frustration) with a rational response, it is most appreciated. THINK</p>
    </div>
  </content>
</entry>
<entry>
  <title>Does Java cause self-delusion?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/does-java-cause-self-delusion/index.html"/>
  <id>http://blog.tmorris.net/posts/does-java-cause-self-delusion/index.html</id>
  <published>2007-12-05T13:32:06Z</published>
  <updated>2007-12-05T13:32:06Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Finally, the mainstream media is starting to consider the possibility that Java is not only the crappiest language available on this planet (or at least up there with others such as C#), but also has <a href="http://www.theserverside.com/news/thread.tss?thread_id=47732">the capacity for adversely affecting one’s learning capacity</a>.</p>
<p>My 6 year old son is learning computer programming by first understanding the mathematical foundations, then applying what he has learned using Haskell, because it is short and natural (he doesn’t even know what Haskell is). I know many people claim to struggle with this language, but I have always held the position that this is because they are tainted will ill-conceived ideas that are internalised to the point of failing critical examination. My son uses a Linux machine for his <em>work</em> (read: fun), but importantly, Java is and has always been banned on his computer. As his trusted carer, I have a moral obligation to protect him from what could cause possible harm and from my observations, potential self-delusion.</p>
<p>Yes, that’s right. Java appears to me to cause an extreme state of delusion. Too often, I find myself in a conversation with someone who only knows one language (or a few others that are superficially different i.e. strict, imperative, poor type system), but most importantly, they don’t know it that well. I have the unfortunate and shameful scar of knowing Java quite well having worked on the implementation, but it always fascinates me to watch someone argue against what I am telling them <em>even though they are not introducing any new information into the discussion</em>. The conversation often quickly denigrates into chest-beating nonsense by making outlandish claims such as “my having never worked on a large Java application” (so what? and, I’ve worked on the largest Java application on the planet, but again, so what?) and various other forms of logical fallacy. I think we’ve all seen this behaviour to some extent, but it seems to proliferate quite extensively from the bottom of the intellectual pool i.e. the Java community.</p>
<p>It is a logical notion that the most well-versed person on the origins of Christianity is an Atheist (and observations support this), likewise, the most well-versed Java programmer wouldn’t touch such a useless (albeit popular) tool unless under extreme duress. This naturally leads to a conclusion where one attempts to explain the observed irrational behaviour from the Java Junkies who don’t understand the ins and outs of Java that well anyway (seriously, this boggles my mind). I certainly don’t think these people are committing acts of intellectual fraud by trying to deceive me. I am convinced that they have deceived themselves (again, Monotheistic belief systems – such a sound analogy), but to this extent?</p>
<p>The psychology of the human brain continues to fascinate me. The ability for self-delusion is extraordinary. I throw out the hypothesis that Java potentially causes brain damage for examination by anyone who cares. Certainly, I find no other explanation for such irrational behaviour.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Discipline in Thought</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/discipline-in-thought/index.html"/>
  <id>http://blog.tmorris.net/posts/discipline-in-thought/index.html</id>
  <published>2007-12-05T09:02:30Z</published>
  <updated>2007-12-05T09:02:30Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Professor Edsger Dijkstra</p>
<p>…who once said the following wise words,</p>
<blockquote>
<p>It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.</p>
</blockquote>
<p>Replace BASIC with Java/C# these days.</p>
    </div>
  </content>
</entry>
<entry>
  <title>God in the Brain?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/god-in-the-brain/index.html"/>
  <id>http://blog.tmorris.net/posts/god-in-the-brain/index.html</id>
  <published>2007-10-13T08:05:33Z</published>
  <updated>2007-10-13T08:05:33Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Finding reason to explain the outward and proactive denial of the evidence that surrounds us by members of religious organisations has always fascinated me. How could an apparently rational person be suffering a sickness of such a magnitude? I have watched Christians deny Evolution without even knowing what it is! I have watched Muslims deny the origin of the Quran. I have wondered what a Christian would say to the charge that the bible is nothing more than a mythological personification of cosmological events and that we still celebrate the birth of the Sun/Son 3 days after its death on the winter solstice (December 22 in the northern hemisphere by the way fellow Australians :)). These questions and many more have fascinated me since I can remember even having independent thoughts as a child.</p>
<p>Aside from those who are not genuine in their delusion for the obvious gains in money and power (i.e. their pawns), I have always been in awe when observing a person suffer such severe delusions with incredible conviction. Having a keen interest in Psychology, I have also wondered if we would ever have a rational explanation for this observation.</p>
<p>Maybe we have found one? As many are now outwardly hypothesising (and others, once did it in silence), religious conviction and psychological disorder are not that unlike.</p>
<p><a href="http://www.sciam.com/print_version.cfm?articleID=434D7C62-E7F2-99DF-37CC9814533B90D7">http://www.sciam.com/print_version.cfm?articleID=434D7C62-E7F2-99DF-37CC9814533B90D7</a></p>
<p>Of course, this does not detract from the sheer awe.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Yeah but speed kills!</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/yeah-but-speed-kills/index.html"/>
  <id>http://blog.tmorris.net/posts/yeah-but-speed-kills/index.html</id>
  <published>2007-09-17T11:08:28Z</published>
  <updated>2007-09-17T11:08:28Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://www.news.com.au/couriermail/story/0,23739,22427799-5007200,00.html">http://www.news.com.au/couriermail/story/0,23739,22427799-5007200,00.html</a></p>
<blockquote>
<p>PHILIP Lamattina’s spectacular effort at Willowbank near Ipswich on Saturday night has already assumed legend status among Australia’s drag racing fraternity.</p>
</blockquote>
<p>He miraculously escaped unscathed from the 500km/h smash that destroyed his $250,000 Top Fuel dragster.</p>
<p>The publisher(s) of this story oughtta be ashamed of themselves. Everyone knows (note: I am exempt from accusations of argumentum ad populum fallacies because I am (and circular reasoning too, got it?)) that SPEED KILLS! Here these journalists are implicitly refuting the known established perversion… er… correction, of the laws of Physics and our understanding of space and time! This is nothing short of failure of reason and I now expect deaths on our roads to increase substantially. All because of some irresponsible journalist(s)!</p>
<p>Actually, I take it back. You see, it was a <strong>miracle</strong>. Yes, notice the use of the adverb, ‘miraculous’ in the second paragraph. Instead of contradicting our government’s established scientimplistic (yes, I made that up :)) understanding, the article exonerates itself by attributing the whole affair to a miracle. This is permitted under the laws of illogic, which any person is free to invent for themselves, right? Of course.</p>
<p>So you see, that makes sense now. Phew!</p>
    </div>
  </content>
</entry>
<entry>
  <title>Type-safe Scala sequence comprehensions</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/type-safe-scala-sequence-comprehensions/index.html"/>
  <id>http://blog.tmorris.net/posts/type-safe-scala-sequence-comprehensions/index.html</id>
  <published>2007-09-13T10:27:00Z</published>
  <updated>2007-09-13T10:27:00Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>On page 85 of <a href="http://www.scala-lang.org/docu/index.html">Scala By Example</a>, the last paragraph states the following in reference to generalising sequence (aka for) comprehensions:</p>
<blockquote>
<p>It would be attractive to enforce these types statically in the Scala compiler, for instance by requiring that any type supporting for-comprehensions implements a standard trait with these methods 1 . The problem is that such a standard trait would have to abstract over the identity of the class C, for instance by taking C as a type parameter. Note that this parameter would be a type constructor, which gets applied to several different types in the signatures of methods map and flatMap. Unfortunately, the Scala type system is too weak to express this construct, since it can handle only type parameters which are fully applied types.</p>
</blockquote>
<p>This type system feature being described is called <em>higher-kinded types</em>. Sadly, none of the mainstream, statically-typed languages offer this feature, which leads to enormous amounts of repetition.</p>
<p>In fact, many of the arguments in favour of dynamic languages that I have seen, are refuted simply with the introduction of this very key, but relatively simple (to other type system features) feature. In other words, I only have to batter an eyelid before I have refuted those arguments, which brings me great suspicion of any underlying plausibility. Perhaps there are other arguments that are more plausible, but I have yet to hear any. I digress…</p>
<p>Higher-kinded types would be available in Java/C# if you could write something like this:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="dt">static</span> &lt;C&lt;_&gt;, A, B&gt; C&lt;B&gt; <span class="fu">map</span>(Convert&lt;A, B&gt; c, C&lt;A&gt; container) {
  ...</code></pre>
<p>Again, sadly, you cannot. But in Scala you can! In other words, the paragraph quoted above is, at least from how I interpret it, false. However, do understand that at the time the paragraph was written, it may have been true (I can neither confirm nor deny this), but my reckoning is that this piece of documentation needs updating at the least.</p>
<p>Without further ado, I introduce the my refutation:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> Functor[f[_], a] {
  <span class="kw">def</span> map[b](f: a =&gt; b)(ft: =&gt; f[a]): f[b]
}

<span class="kw">trait</span> Monad[m[_], a] {
  <span class="kw">def</span> flatMap[b](ma: =&gt; m[a])(f: a =&gt; m[b]): m[b]
}

<span class="kw">trait</span> Filter[c[_], a] {
  <span class="kw">def</span> <span class="fu">filter</span>(f: a =&gt; Boolean)(c: =&gt; c[a]): c[a]
}</code></pre>
<p>My assertion now, is that a Scala sequence comprehension could indeed be written to be type-safe if it only accepted types that adhered to the above interfaces. Am I wrong and if so, what have I misunderstood?</p>
<p>Here are some example (incomplete) implementations of <code>foreach</code>:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> Comprehension {
  <span class="kw">type</span> Comprehension[c[_], a] = Functor[c[a], a] <span class="kw">with</span> Monad[c[a], a] <span class="kw">with</span> Filter[c[a], a]
  <span class="kw">def</span> foreach[c[_], a](c: c[a], e: a =&gt; Unit, p: a =&gt; Boolean)(<span class="kw">implicit</span> ca: Comprehension[c[a], a]): Unit = ca.<span class="fu">map</span>(a =&gt; <span class="kw">if</span>(<span class="fu">p</span>(a)) <span class="fu">e</span>(a))(c)
  <span class="kw">def</span> foreach[c[_], a](c: c[a], e: a =&gt; Unit)(<span class="kw">implicit</span> ca: Comprehension[c[a], a]): Unit = foreach[c[a], a](c, e, (a: a) =&gt; <span class="kw">true</span>)
  <span class="kw">def</span> foreach[c[_], a, b](c: c[a], f: a =&gt; b, p: a =&gt; Boolean)(<span class="kw">implicit</span> ca: Comprehension[c[a], a]): c[b] = ca.<span class="fu">map</span>(a =&gt; <span class="fu">f</span>(a))(ca.<span class="fu">filter</span>(p)(c))
  <span class="kw">def</span> foreach[c[_], a, b](c: c[a], f: a =&gt; b)(<span class="kw">implicit</span> ca: Comprehension[c[a], a]): c[b] = ca.<span class="fu">map</span>(a =&gt; <span class="fu">f</span>(a))(c)
}</code></pre>
<p>I await an explanation for what I think is the unwarranted undermining of Scala’s value by Scala’s own documentation!</p>
    </div>
  </content>
</entry>
<entry>
  <title>Negative Zero to Hero</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/negative-zero-to-hero/index.html"/>
  <id>http://blog.tmorris.net/posts/negative-zero-to-hero/index.html</id>
  <published>2007-09-12T10:15:30Z</published>
  <updated>2007-09-12T10:15:30Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Kathy Griffin goes from being annoying at worst to an international hero overnight!</p>
<blockquote>
<p>a lot of people come up here and thank Jesus for this award. I want you to know that no one had less to do with this award than Jesus.</p>
</blockquote>
<p><a href="http://news.yahoo.com/s/ap/20070911/ap_en_tv/tv_emmys_griffin;_ylt=AtkypF3j3vo2jS83e_CIcqJpMhkF">Check it out!</a></p>
<p>Kathy, you have redeemed yourself of any debt that you may have owed the community. I take my hat off to you for your courage. Well done.</p>
<p>On a lighter and hilarious note, check this comment out:</p>
<blockquote>
<p>The comedian’s remarks were condemned Monday by Catholic League President Bill Donohue, who called them a “vulgar, in-your-face brand of hate speech.”</p>
</blockquote>
<p>OK, you can stop laughing at the irony now, STOP! :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>A Fling with Lazy Evaluation</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/a-fling-with-lazy-evaluation/index.html"/>
  <id>http://blog.tmorris.net/posts/a-fling-with-lazy-evaluation/index.html</id>
  <published>2007-09-04T11:13:28Z</published>
  <updated>2007-09-04T11:13:28Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Lazy evaluation is a core topic in computer programming that is also <em>widely</em> misunderstood and often, erroneously trivialised. Here, I will attempt to demonstrate some of the attributes of many common mainstream programming languages; namely strict programming languages. I will also attempt to distinguish <em>intrinsically</em> strict languages from optionally lazy languages by focusing on what intrinsically strict means. As a note, strict evaluation (or strictness) is what lazy evaluation (or laziness) is not.</p>
<p>Some languages are optionally lazy, including one that I use quite a lot in my work called Scala. This means I have the option of laziness, however, the default in all cases is strictness. I have to explicitly annotate laziness (=&gt; in Scala). Some languages are optionally strict; one that I use a lot is Haskell. Laziness is the default, while strictness is explicitly annotated (seq or ! in Haskell). There are many debates about which is the correct default, but whatever the outcome of such a debate, the issue I describe next is one that demands much more attention.</p>
<p>Some languages are <strong>forcibly</strong> strict. It is these languages that I intend to focus on for the remainder of this post. I assume that my reader either understands or is at least open to just how debilitating a language is that does not support user-defined lazy evaluation in any form whatsoever. I will explicitly discuss the Java programming language, though what I describe is equally applicable to C, C# and many other languages.</p>
<p>In Java, the <em>only</em> lazy constructs are:</p>
<ul>
<li><p>if/else</p></li>
<li><p>while</p></li>
<li><p>for</p></li>
<li><p>? : (ternary operator)</p></li>
<li><p>&amp;&amp;</p></li>
<li><p>||</p></li>
</ul>
<p>This is extremely limiting. To make the case clear, I will focus on a particular example of this. Consider the &amp;&amp; function of type (Boolean x Boolean) -&gt; Boolean. Here is a profound assertion:</p>
<blockquote>
<p>It is impossible to write &amp;&amp; in Java yourself.</p>
</blockquote>
<p>Some of you might be quick to rebut:</p>
<blockquote>


</blockquote>
<blockquote>
<pre><code>
// Sure I can!
boolean and(boolean b, boolean c) {
  return b &amp;&amp; c;
}</code></pre>
</blockquote>
<p>This is a very crucial mistake as you will soon see.</p>
<p>Since the domain of the &amp;&amp; function is so small, there is room enough to enumerate it below:</p>
<pre><code>a   b   a &amp;&amp; b
t   t   t
t   f   f
f   t   f
f   f   f
t   ⊥   ⊥
⊥   t   ⊥
f   ⊥   f
⊥   f   ⊥</code></pre>
<p>Wait just a minute!! What are those last 4 entries in the table and just WTF is that upside-down T doing!? That upside-down T represents what is called the <code>bottom element</code>, sometimes also written as <em>|</em> when only ASCII is available. It is an extremely important part of the &amp;&amp; function (and all functions in fact!). In Java, the bottom element is typically represented by throwing an exception (or sometimes, with <code>null</code>).</p>
<p>Remember, two functions are equivalent if for every element of the domain, the result of function application to that element on either function is equivalent. Here is a more formal definition for function equivalence:</p>
<blockquote>
<p>Two functions, f and g, are equivalent if the following property holds:</p>
</blockquote>
<blockquote>
<pre><code>
∀ x. f x ⇔ g x</code></pre>
</blockquote>
<p>We could rewrite the + function for <code>int</code> as follows:</p>
<pre><code>int sum(int a, int b) {
  return a + b;
}</code></pre>
<p>I won’t list out the table for each element in the domain of +, since it is so long, so you’ll either have to do it yourself, or take my word for it that the <code>sum</code> function above is equivalent to + :)</p>
<p>However, why can’t we rewrite &amp;&amp;? If we look at the table for &amp;&amp; above and select the penultimate entry, we note the following:</p>
<blockquote>


</blockquote>
<blockquote>
<pre><code>
false &amp;&amp; ⊥ == false</code></pre>
</blockquote>
<p>It is <strong>this</strong> entry that disallows us from rewriting &amp;&amp;. Look at the following function:</p>
<pre><code>boolean bottom() {
  throw new Error();
}</code></pre>
<p>What is the result of <code>false &amp;&amp; bottom()</code>? It is false of course! This is because &amp;&amp; is lazy in its second argument (sometimes; specifically, when the first argument is false). This is <em>impossible</em> to emulate in your own Java function. If we take the earlier function that attempted (but failed) to rewrite &amp;&amp; and call:</p>
<blockquote>


</blockquote>
<blockquote>
<pre><code>
and(false, bottom())</code></pre>
</blockquote>
<p>The result of this function is ⊥ and not false, like it is with &amp;&amp;. Therefore, this function is <strong>not equivalent</strong> to &amp;&amp;. Further, I restate that it is not possible to write such a function in these languages. Unlike +. which is strict in both of its arguments, &amp;&amp; is not and this makes it impossible to write a user-defined version of &amp;&amp; and therefore, ||, if/else and ?: and importantly, many other potential functions that many Java programmers are probably not even aware of (Dynamic Programming Algorithms anyone?).</p>
<p>If you are ever forced to use these severely limited programming languages, you could be thankful that you have some primitive lazy constructs for doing very primitive operations (oppression), or you could be resentful for not having the expressive power of other, lazy languages (resistance against oppression) :)</p>
<p>Below is a session with my Scala interpreter to demonstrate that it is indeed possible to write &amp;&amp; in Scala (<code>lazyAnd</code>), but not Java. Note that the functions (def declarations) and final variables (val declarations) below are Java functions and final variables all running in a JVM (invoked by the Scala interpreter):</p>
<pre><code>scala&gt; val x = false &amp;&amp; error(&quot;bottom&quot;)
x: Boolean = false

scala&gt; def and(a: Boolean, b: Boolean) = a &amp;&amp; b
and: (Boolean,Boolean)Boolean

scala&gt; val y = and(false, error(&quot;bottom&quot;))
java.lang.Error: bottom

scala&gt; def lazyAnd(a: Boolean, b: =&gt; Boolean) = a &amp;&amp; b // can&#39;t do this in Java, C#, C, etc.
lazyAnd: (Boolean,=&gt; Boolean)Boolean

scala&gt; val z = lazyAnd(false, error(&quot;bottom&quot;))
z: Boolean = false</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Sam Harris at 2007 Aspen Ideas Festival</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/sam-harris-at-2007-aspen-ideas-festival/index.html"/>
  <id>http://blog.tmorris.net/posts/sam-harris-at-2007-aspen-ideas-festival/index.html</id>
  <published>2007-08-12T20:01:54Z</published>
  <updated>2007-08-12T20:01:54Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I am just keeping note of a great talk given by one of the most important people alive today on issues relating to the future of humanity, Sam Harris.</p>
<p><strong>Part 1</strong></p>
<p><strong>Part 2</strong></p>
<p><strong>Part 3</strong></p>
<p><strong>Part 4</strong></p>
<p><strong>Part 5</strong></p>
<p><strong>Part 6</strong></p>
<p><strong>Part 7</strong></p>
    </div>
  </content>
</entry>
<entry>
  <title>Imperative programming is a special type of functional programming</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/imperative-programming-is-a-special-type-of-functional-programming/index.html"/>
  <id>http://blog.tmorris.net/posts/imperative-programming-is-a-special-type-of-functional-programming/index.html</id>
  <published>2007-08-07T15:02:40Z</published>
  <updated>2007-08-07T15:02:40Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>There are a lot of things that, upon initial investigation, turn out to be false after some deeper analysis. There are a striking number of these propositions that not not only turn out to be false, but it is the inverse that turns out to be true!</p>
<p>One of these is many common descriptions of pure functional programming against imperative programming. Here are some that I have seen:</p>
<p>* functional programming <em>is on the other side of the fence of</em> (or some such) imperative programming. That is, there are two (or more) very distinct, non-unifiable methods or disciplines of programming.</p>
<p>* Functional programming is more restrictive than imperative programming.</p>
<p>I hope to address the first point another time and on the second point, for now, I will assert that:</p>
<blockquote>
<p>Not only is functional programming not more restrictive than imperative programming, but quite the opposite is true! Imperative programming is one specific type of functional programming that is relatively seldom worth using.</p>
</blockquote>
<p>In the relatively rare (though inevitable) case of performing I/O, only <em>then</em> will I resort to the imperative programming technique within pure functional programming. I will reason about my imperative code as if it were pure anyway, but I also understand that there are many destructive updates that must be appealed to – for example, the many common file system types that are used.</p>
<p>I don’t wish to elaborate on this statement right now, since I am still deciding how I will do it and I also know how this fact can fail to be recognised by many so I want to get it right. Importantly, it sets (one of) a premise for another issue that I’d like to write about some time.</p>
<p>In the meantime, I want to refer to <a href="http://blip.tv/file/325646">Part 2 of Simon Peyton-Jones’, “A Taste of Haskell”</a>where he says at 1:06:42:</p>
<blockquote>
<p>[Referring to the IO data type] This is imperative programming, embedded within Haskell [pure functional programming].</p>
</blockquote>
<p>There it is, right there, in one sentence ;)</p>
    </div>
  </content>
</entry>
<entry>
  <title>Saturday night laugh</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/saturday-night-laugh/index.html"/>
  <id>http://blog.tmorris.net/posts/saturday-night-laugh/index.html</id>
  <published>2007-08-04T20:29:08Z</published>
  <updated>2007-08-04T20:29:08Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>It is Saturday night and I get to sit at home and read a book by one my favourite authors, Sam Harris. Half my family are currently suffering from influenza, so I’m bound to the house tonight.</p>
<p>I thought I’d take a peek at a news website and I notice that Gwen Stefani is not permitted to wear “revealing costumes” when she performs in Malaysia because of a protest by a “Muslim student group”. Apart from all the usual absurdities of theistic dogma (and particularly, Islamic and Judæo-Christian dogma), this quote cracked me up in laughter:</p>
<blockquote>
<p>She [Stefani] will abide by the Malaysian authorities’ guidelines to ensure that her show will not be offensive to local sensibilities.</p>
</blockquote>
<p>The funny part, from my humble perspective, is the use of the word “sensibility”.</p>
<p>Watching a religious establishment manipulate its victims with such absurd and utterly transparent, blatant abuse of language usually causes me the most extreme alarm (because of the consequences to humanity), but on this night, after a couple of lonesome wines, I thought I’d take a laugh at just how sick and sad this world truly is. Sensibility!! Can you believe that!? You poor, sick bastards. Yes you, who has been robbed of the ability to think, yeah YOU.</p>
<p>Cheers :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>Algebraic Data Types again</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/algebraic-data-types-again/index.html"/>
  <id>http://blog.tmorris.net/posts/algebraic-data-types-again/index.html</id>
  <published>2007-08-04T14:23:33Z</published>
  <updated>2007-08-04T14:23:33Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I recently watched Simon Peyton-Jones’ presentation as OSCON 2007 titled, “A Taste of Haskell”. As usual for Simon, his enthusiastic and very animated presentation was of high quality in both content and the way that content was presented. If you have a spare 3 hours (a little over in fact) and you are interested in learning the basics of a very powerful programming language called Haskell, I recommend that you invest the time in this presentation, which is split into <a href="http://blip.tv/file/324976">Part 1</a> and <a href="http://blip.tv/file/325646">Part 2</a>. Be sure to keep <a href="http://conferences.oreillynet.com/presentations/os2007/os_peytonjones.pdf">the slides</a> available as well, since a lot of the time, the camera is focused on Simon and not on the slide that he is discussing.</p>
<p>During the presentation, the audience were asking questions of Simon as he was presenting Algebraic Data Types (ADTs), which are written in Haskell using the <code>data</code> keyword. As Simon pointed out, ADTs are a fundamental part of writing Haskell. I felt that members of the audience were perhaps considering the concept of an ADT to be more complicated than what it really is. It truly is quite simple and in this post, I hope to try a new tact to explain this very simple concept. As Simon also pointed out, ADTs are important, powerful and fundamental to programming, but I don’t expect this to be obvious at first. First, let’s understand exactly what an ADT is. If the following confuses you and you prefer Simon’s (or some other) approach, then please ignore it. I intend to use a (probably) familiar language to demonstrate what an ADT is.</p>
<p>In Haskell, ADTs are <em>closed</em>. That is, at the point of declaration you specify all the constructors of the ADT and it is not possible to dynamically add more constructors for that type. For example, the Haskell Maybe data type is written as follows:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Maybe</span> a <span class="fu">=</span> <span class="kw">Just</span> a <span class="fu">|</span> <span class="kw">Nothing</span></code></pre>
<p>Therefore, the Maybe data type has 2 <strong>and only 2</strong> constructors. It is the “and only 2” that makes this data type a closed algebraic data type.</p>
<p>If we consider a Java or C# <code>class</code> that can somehow enforce 2 <strong>and only 2</strong> subclasses, then we could emulate closed algebraic data types in these languages. Indeed, it is possible to do so, however, you have to get really quirky with the language at hand. <a href="http://blog.tmorris.net/maybe-in-java/">I have written about this before</a>, but instead of using this trick, I am going to invent a new keyword for these languages called <code>klass</code>.</p>
<p>A <code>klass</code> declaration is always abstract and all of its subtypes are always specified in the same source file and they are always implicitly final. An attempt to subclass a <code>klass</code> outside of its own source file or any subtypes of a <code>klass</code> is a compile-time error. Furthermore a <code>klass</code> cannot declare anything at all in its body – it simply takes on the default constructor and nothing more is permitted.</p>
<p>Given this new keyword, we can write the Haskell Maybe data type as follows:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">class</span> Maybe&lt;A&gt; {

}

<span class="kw">class</span> Just&lt;A&gt; <span class="kw">extends</span> Maybe&lt;A&gt; {
  <span class="dt">final</span> A a;
  <span class="fu">Just</span>(A a) {
    <span class="kw">this</span>.<span class="fu">a</span> = a;
  }
}

<span class="kw">class</span> Nothing&lt;A&gt; <span class="kw">extends</span> Maybe&lt;A&gt; {

}</code></pre>
<p>To reiterate, no other classes may subclass <code>Maybe</code>, <code>Just</code> or <code>Nothing</code> and there is a single type parameter that I have called <code>A</code> (and Haskell calls <code>a</code> by enforced convention). Therefore, if a function or method is passed an instance of <code>Maybe&lt;A&gt;</code>, we can be <strong>certain</strong> that it is either a <code>Nothing&lt;A&gt;</code> or a <code>Just&lt;A&gt;</code> and in the <code>Just</code> case, we might wish to access that <code>A</code> (which is a field called <code>a</code>).</p>
<p>Indeed, we might write code that is similar to the following:</p>
<pre class="sourceCode Java"><code class="sourceCode java">X <span class="fu">someFunction</span>(Maybe&lt;A&gt; m) {
  <span class="kw">if</span>(m <span class="kw">instanceof</span> Just) {
    Just&lt;A&gt; j = (Just&lt;A&gt;)m;
    <span class="fu">foo</span>(j.<span class="fu">a</span>);
  <span class="co">// this definitely holds, but see description below</span>
  } <span class="kw">else</span> <span class="kw">if</span>(m <span class="kw">instanceof</span> Nothing) {
    <span class="fu">bar</span>();
  }
}</code></pre>
<p>This code is effectively <em>pattern matching</em> (another topic that Simon talked about and the audience seemed unnecessarily confused). In the second <code>if</code> statement I have ensured <em>non-overlapping</em> pattern matching, which is a good practice that I follow. That is to say, the order of my <code>if</code> statements is not relevant to the outcome of the function. You might recall that Simon said that pattern matching occurs “top to bottom”, however, I prefer not to rely on this by not overlapping patterns. If I’d left out the second <code>if</code> condition as a simple <code>else</code> block, then I have effectively said, “and everything else” and the behaviour of the function would not change. However, this pattern overlaps with the <code>Just</code> case and the behaviour of the function would be affected if I swapped their order. This notion of “and everything else” is denoted in Haskell pattern matching with an underscore or sometimes, a variable to bind to.</p>
<p>The code above, written using Haskell pattern matching would look like this:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="ot">someFunction ::</span> <span class="dt">Maybe</span> a <span class="ot">-&gt;</span> <span class="dt">X</span> <span class="co">-- remember, this is a type declaration</span>
someFunction (<span class="kw">Just</span> a) <span class="fu">=</span> foo(a)
someFunction <span class="kw">Nothing</span> <span class="fu">=</span> bar</code></pre>
<p>Simon talked about pattern matching as “decomposing” a data type. You can see in the earlier code that I have pulled apart the <code>Maybe</code> into its components of <code>Just</code> or <code>Nothing</code> and I have “decomposed” the components of the <code>Just</code> further, by getting the <code>A</code> out of it. This is what Simon was referring to when he was talking about decomposition of a data type using its constructors.</p>
<p>Of course, in Haskell, you can create all sorts of data types and the <code>Maybe</code> data type is very common. There is another called <code>Either</code> that looks like this:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Either</span> a b <span class="fu">=</span> <span class="kw">Left</span> a <span class="fu">|</span> <span class="kw">Right</span> b</code></pre>
<p>It is almost like <code>Maybe</code> except that both constructor cases take an argument of any type.</p>
<p>Here’s the fun part :) If we take a look at all the excitement with “non-nullable types” using the type system in <a href="http://www.disi.unige.it/person/AnconaD/FTfJP06/paper03.pdf">Java</a> and <a href="http://codebetter.com/blogs/patricksmacchia/archive/2007/07/25/i-want-non-nullable-types-in-c-4.aspx">C#</a>, then we see that this is <strong>exactly</strong> what the <code>Maybe</code> data type does in Haskell, also using the type system. In fact, imagine “exceptionable types” in these languages, where returning one of these “non-exceptionable” types from a method cannot throw an exception. This is <strong>exactly</strong> what the <code>Either</code> data type above does also using the type system, since we can return “either the value to be returned or the exception that was thrown”. Furthermore, the <code>Maybe</code> and <code>Either</code> data types are one line of Haskell code and just 2 of many possible data types. In other words, and as is usual for previous industry trends, the excitement around Java/C# non-nullable types, is just a fundamental library feature of Haskell that has been there for years. How about that eh? :)</p>
<p>The next time a Haskeller just smiles and nods at a Jumping Java Joey or Shaggin’ C Sharpy who is all excited about non-nullable types (or any “revolutionary” language feature in fact), you’ll now know why since both <code>Maybe</code> and <code>Either</code> are so trivial and fundamental, that they are included in the default import of the Haskell standard library (like <code>java.lang.*</code>).</p>
<p>I hope you too can smile and nod after reading this post and understand Algebraic Data Types (and Pattern Matching) :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>Religious-Oriented Programming</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/religious-oriented-programming/index.html"/>
  <id>http://blog.tmorris.net/posts/religious-oriented-programming/index.html</id>
  <published>2007-07-27T08:56:06Z</published>
  <updated>2007-07-27T08:56:06Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I came across a thread today on javalobby. Actually, I was referred by Ricky Clarkson who seems to challenge the Java Religious Establishment with seemingly greater patience than I could possibly exercise. <a href="http://www.javalobby.org/forums/thread.jspa?messageID=92163333&amp;#92163326">Here is a link to the thread.</a></p>
<p>I have long postulated that programming in general and Java particularly, exhibits some strikingly similar attributes of religious establishments. I have discussed this hypothesis with a few people and we have even come up with the idea of finding a correlation between preferred programming language and religious conviction. Of course, this was all discussion and no “doing”, but it’s an interesting discussion nevertheless. We even entertain conjectures about what we believe the outcome to be. Mostly, correlating religious ideologies that are founded on the most powerful delusions and programming languages that are also founded on extreme delusion and then extrapolating along less mature religions with more transparent delusionary characteristics.</p>
<p>Many people point to some of the absurdities that come out of religious establishments for humiliation, because they are well, quite blatantly in violation of sound logical reasoning. As a side note, I often observe this violation being resolved by resorting to Fideism – a symptom of the religion sickness that I hope to write about soon. I actually empathise with the people who have been manipulated into such extreme delusions. I do not encourage human suffering and I do whatever I can in terms of self-discipline to ensure that I do not denigrate to the perverted practice of esteem boosts by pointing at the weaknesses of others – mostly, because I hope and expect the same from others (I am a moral Altruist).</p>
<p>I encourage you to do so as well as you read the following quotes from the aforementioned thread:</p>
<ul>
<li><p>Other languages have lots of problems that java just doesn’t have.</p></li>
<li><p>Most language concurrency models are inferior to Java’s.</p></li>
<li><p>Most languages don’t have as good functional programming as Java.</p></li>
<li><p>Java’s type system is precise and predictable, more so than many languages.</p></li>
</ul>
<p>Notice how this person is <em>convinced</em> that these statements are true. There is no act of conscious intellectual fraud here. Ask yourself why? How on earth could someone have been led into believing such absurdities? My point is for example, there are some very plausible explanations and methods of counselling for believers in the Judæo-Christian delusion; can we use these lessons to describe the behaviour of the person quoted above, and therefore, offer counsel to this person, who is also suffering delusions? Is the approach that Ricky Clarkson is taking – assumingly to heighten the awareness of the audience of his words – a sound one? Can we make predictions about its outcome?</p>
<p>The infamous Robert M. Pirsig (Zen and the Art of Motorcycle Maintenance) quote seems apt:</p>
<blockquote>
<p>When one person suffers from a delusion, it is called insanity. When many people suffer from a delusion, it is called Religion.</p>
</blockquote>
    </div>
  </content>
</entry>
<entry>
  <title>High Level Languages</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/high-level-languages/index.html"/>
  <id>http://blog.tmorris.net/posts/high-level-languages/index.html</id>
  <published>2007-07-24T09:15:43Z</published>
  <updated>2007-07-24T09:15:43Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>C, Java, C# et. al. (imperative with poor type systems) languages are low level languages. Many people are not aware of this fact, especially those who are only aware of languages that are imperative with poor type systems. This behaviour is probably best described by Psychologists than I will attempt, so I will not attempt any explanations for it.</p>
<p>I refer to pages 58-61 of Types and Programming Languages (0-262-16209-1) on the chapter about the untyped lambda calculus where author Benjamin Pierce notes that the the value false for the Church Boolean encoding is the same as the value zero for the Church Numeral encoding.</p>
<blockquote>
<p>λt. λf. f λs. λz. z</p>
</blockquote>
<p>Pierce then goes on to note that:</p>
<blockquote>
<p>Similar “puns” are common in assembly languages, where the same pattern of bits may represent many different values – an int, a float, an address, four characters, etc. – depending on how it is interpreted, and in <strong>low-level languages such as C</strong> [emphasis mine], which also identifies <code>0</code> and <code>false</code>.</p>
</blockquote>
<p>I wonder if the aforementioned programmers – those aware of only low-level languages, therefore call languages of “the highest level that I am aware of”, high-level languages – are willing to claim that Pierce has made a grave mistake, or if it will invoke the possibility that maybe there are <em>more levels</em> out there.</p>
<p>If, for just one person, it is the latter, then the objective of this post has been achieved ;)</p>
    </div>
  </content>
</entry>
<entry>
  <title>Perhaps not?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/perhaps-not/index.html"/>
  <id>http://blog.tmorris.net/posts/perhaps-not/index.html</id>
  <published>2007-07-22T07:01:13Z</published>
  <updated>2007-07-22T07:01:13Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>From <a href="http://cafe.elharo.com/java/internal-and-external-exceptions/">http://cafe.elharo.com/java/internal-and-external-exceptions/</a></p>
<blockquote>
<p>Perhaps the continuing confusion over the difference between checked and runtime exceptions in Java is because we haven’t named them properly.</p>
</blockquote>
<p>Yippeee! About time a Jumping Java Joey took notice of that fact that language has an enormous power to influence if you are incapable of independent thought.</p>
<blockquote>
<p>…I think we should should start calling checked exceptions “external exceptions” and runtime exceptions “internal exceptions”.</p>
</blockquote>
<p>Ugh.</p>
<p>How about type error? bottom? Or undefined partial function? Or ⊥</p>
<p>As abruptly as there was hope, that same hope was ripped away.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Inheritance dunrite</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/inheritance-dunrite/index.html"/>
  <id>http://blog.tmorris.net/posts/inheritance-dunrite/index.html</id>
  <published>2007-07-21T19:27:04Z</published>
  <updated>2007-07-21T19:27:04Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I am absolutely surprised at the number of failed examples of inheritance. What troubles me is the extent of ignorance prevailing on the subject of inheritance. <a href="http://www.manageability.org/blog/stuff/inheritance_revisited/">Every once in a while, I read an old rant by a Blub programmer making claims to an understanding of a topic while simultaneously proclaiming that there are so many others without this understanding.</a> Less often, I am compelled to write something myself.</p>
<p>I will start by using Blub grammar and syntax, but try to keep the usual euphemisms and loaded words to a minimum (I have two, annotated with warnings).</p>
<p>Look at the following interface declarations:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> I {
  T <span class="fu">i</span>();
}

<span class="kw">interface</span> J {
  U <span class="fu">j</span>();
}

<span class="kw">interface</span> K <span class="kw">extends</span> I, J {}</code></pre>
<p>If a method accepts a type K, what that method <strong>really</strong> means is that it accepts a type that is composed of both type I and J, <strong>which is more general than type K</strong>. I am ignoring the fact that interface K may have some additional restrictions that are not enforced by the type system, because well, this is Blub after all and using type systems to denote formal requirement specifications is well beyond Blub. If you have a type L that is composed of I and J, you will not be able to pass it to the method. Instead, you need to write an “Adapter” (WARNING: euphemism) from L to K.</p>
<p>I now propose a hypothetical language (still Blub though) that allows you to pass a “<code>I with J</code>”, which means it might be a K or it might be some other composition of I and J. Note that a compiler can not deduce that K is composed of I and J and generalise this type, since this requires the compiler to compile I, J, K and all compositions of I and J, which is potentially infinite. In other words, time goes this way —&gt;, not that way &lt;–, despite what the Blub type systems say.</p>
<p>In my hypothetical language, you do not explicitly give method arguments types. Instead, if you call both <code>i()</code> and <code>j()</code> within the aforementioned method, the compiler or <em>type inferencer</em> will determine that the method argument has type <code>I with J</code>. Surely, you have seen software in Blub languages, where you pass a type with a bazillion methods and only one or two of those methods are used when it is passed? It’s a problem, right? Ever used one of those “mock frameworks”? (WARNING: euphemism for “workaround”). Have you ever passed a K and only called <code>i()</code>?</p>
<p>In my hypothetical language, if you only call <code>i()</code>, then the method argument type will be inferred to I, not K, not even <code>I with J</code>, since remember, we do not explicitly annotate types on method arguments.</p>
<p>Now, is my hypothetical language really hypothetical? No! You see, there are (at least) not-so-crap type systems out there that permit this level of flexibility. They are far more powerful than this little rant purports, but you’ll just have to take my word for that. What I have effectively described is (one aspect of) <a href="http://en.wikibooks.org/wiki/Haskell/YAHT/Type_basics">Type Classes from a language called Haskell</a>, which can also <a href="http://blog.tmorris.net/the-power-of-type-classes-with-scala-implicit-defs/">be used in Scala</a> and other languages with at-least-reasonable type systems.</p>
<p>In other words, <em>inheritance dunrite</em> is as easy as putting down those languages that have got it all wrong and stop pretending that they are sensible or “industry grade”. Stop trying to understand their inherent contradictions through cognitive dissonance, write books about the nonsense, invent design patterns, refactorings, workarounds and mock this and that and framework foo and blah blah blah (can I breath now?). Furthermore, standing on a pedestal and proclaiming that “I know something that you don’t so na na!” is really quite silly, even if it is true (which it isn’t more often than not as has been seen!).</p>
<p>There is much more to inheritance than even the most expert Blub programmer can possibly imagine. I have only just touched the surface by introducing type classes here.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Most people prefer…</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/most-people-prefer/index.html"/>
  <id>http://blog.tmorris.net/posts/most-people-prefer/index.html</id>
  <published>2007-07-18T19:40:42Z</published>
  <updated>2007-07-18T19:40:42Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Most people prefer to believe that their leaders are just and fair, even in the face of evidence to the contrary, because once a citizen acknowledges that the government under which he lives is lying and corrupt, the citizen has to choose what he or she will do about it. To take action in the face of corrupt government entails risks of harm to life and loved ones. To choose to do nothing is to surrender one’s self-image of standing for principles. Most people do not have the courage to face that choice. Hence, most propaganda is not designed to fool the critical thinker but only to give moral cowards an excuse not to think at all.</p>
<p>– Michael Rivero</p>
    </div>
  </content>
</entry>
<entry>
  <title>Idempotence versus Referential Transparency</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/idempotence-versus-referential-transparency/index.html"/>
  <id>http://blog.tmorris.net/posts/idempotence-versus-referential-transparency/index.html</id>
  <published>2007-07-05T13:27:09Z</published>
  <updated>2007-07-05T13:27:09Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>There is <a href="http://programming.reddit.com/info/124kj/comments/c127nc">a lot of misunderstanding about the difference between idempotence and referential transparency</a>. My plan here, is to explain the key differences without going into any specific detail about either concept. I plan to write something about referential transparency in the future and when I do, I will refer here to dispel any myths regarding idempotence.</p>
<p>I will assume that my reader is roughly familiar with the concept of referential transparency, but not necessarily its implications (since there are many), even though some <a href="http://kawagner.blogspot.com/2007/01/real-functional-programming-or-why-io.html">clearly demonstrate a lack of understanding of this concept</a>, strangely accusing others of same (go figure?) and even trying to <a href="http://blog.tmorris.net/strong-type-systems/#comment-1851">proclaim that Java has higher-kinds while suggesting that others do not understand Java’s (mediocre) type system</a>. Ignorance is bliss and all that, anyway on with the story…</p>
<p>Here is a fact; all idempotent functions are also referentially transparent, but not necessarily the other way around. Let us express this fact by other means; a referentially transparent function is <em>not necessarily</em> idempotent, because it is <em>(only) possibly</em> idempotent.</p>
<p>Idempotence can be easily written as follows. A function (f) is idempotent if the following property holds:</p>
<blockquote>
<p>f o f = f</p>
</blockquote>
<p>That’s all there is to it. Since many of my audience are Java programmers, I will appeal to their potential misunderstanding here and elaborate. The o symbol means <em>function composition</em>. The statement can be read as “the function f composed with the function f is equivalent to (just) f”.</p>
<p>Function composition comes about by… well composing functions. Suppose a function (f) that accepts a type Y and returns a type Z and another function (g) that accepts a type X and a type Y that returns another function that accepts a type X and returns a type Z. We express this as f o g.</p>
<p>Here is an example in the favourite programming language of some:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">class</span> Foo {
  <span class="dt">static</span> String <span class="fu">f</span>(<span class="dt">int</span> i) {
    <span class="kw">return</span> Integer.<span class="fu">toString</span>(i);
  }

  <span class="dt">static</span> <span class="dt">int</span> <span class="fu">g</span>(<span class="dt">char</span> c) {
    <span class="kw">return</span> c + <span class="dv">7</span>;
  }

  <span class="dt">static</span> String <span class="fu">composeFG</span>(<span class="dt">char</span> c) {
    <span class="kw">return</span> <span class="fu">f</span>(<span class="fu">g</span>(c));
  }
}</code></pre>
<p>Easy Peasey right? In my statement above, the type X is <code>char</code>, Y is <code>int</code> and Z is <code>String</code>. Function composition is written in Java as <code>f(g(a))</code>. Back to the definition of idempotence, which states (in Java syntax), that f(f(a)) is equivalent to f(a). Clearly we see that f <strong>must</strong> at least have the same type in its argument and return type in order to satisfy idempotence. This means that our previous example has no idempotent functions, however, they were all referentially transparent. Furthermore, a function that is referentially transparent and having the same type in its argument and return type is <em>not necessarily</em> idempotent. A counter-example is easily produced:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">class</span> Bar {
  <span class="dt">static</span> <span class="dt">int</span> <span class="fu">add1</span>(<span class="dt">int</span> i) {
    <span class="kw">return</span> i + <span class="dv">1</span>;
  }
}</code></pre>
<p>Since there exists at least one (in fact, all in this case) arg for <code>add1(add1(arg))</code> such that it is not equivalent to <code>add1(arg)</code>, then <code>add1</code> is <strong>not</strong> idempotent. For example, <code>add1(add1(7))</code> is not equivalent to <code>add1(7)</code>, clearly.</p>
<p>Here are some insights. Adhering with my naming convention, suppose the function <code>add0</code>. Guess what? It <strong>is</strong> idempotent. Also, <code>multiply1</code> is idempotent. Every single function on this web page is referentially transparent, but only the two aforementioned hypothetical functions are idempotent.</p>
<p>We might write this using logic as follows for <code>add0</code></p>
<blockquote>
<p>∀ n | n ∈ Z. n + 0 = n</p>
</blockquote>
<p>For all n such that n is an element of the set of integers, n + 0 = n [is a true statement].</p>
<p>…and for <code>multiply1</code></p>
<blockquote>
<p>∀ n | n ∈ Z. n * 1 = n</p>
</blockquote>
<p>For all n such that n is an element of the set of integers, n * 1 = n [is a true statement].</p>
<p>For completeness, here is an actual idempotent function with the added twist of a polymorphic type parameter (generic parameter in Java speak):</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">class</span> Baz {
  <span class="dt">static</span> &lt;t&gt; T <span class="fu">identity</span>(T t) {
    <span class="kw">return</span> t;
  }
}</code></pre>
<p>I hope this clears some things up :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>Dear PM John Howard</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/dear-pm-john-howard/index.html"/>
  <id>http://blog.tmorris.net/posts/dear-pm-john-howard/index.html</id>
  <published>2007-06-26T14:41:27Z</published>
  <updated>2007-06-26T14:41:27Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Dear Prime Minister John Howard of Australia, Many of my readers may not be aware that all people over the age of 18 are required to vote in elections by law in Australia. The exceptions are (of course) the organisations with an artificially heightened religious status such as Jehovah’s Witnesses.</p>
<p>I was de-listed to vote years ago and when I contacted your Australian Electoral Commission (AEC) to apply for conscientious objector status, I was told I needed to belong to a religious cult in order to be eligible and that I am not permitted to think for myself under Australian law. I resented this implication and I have since not ever enrolled to vote. Nevertheless, the AEC operator told me that to be a conscientious objector and at the same time, exist independently of a religious cult/organisation, that I simply should not enrol to vote – to break the law – go figure? I hadn’t voted before this time, since I had always submitted an empty voting ballot form. I won’t bore you with my somewhat complicated reasons why (relative to your comprehension skills that is).</p>
<p>But this is not the reason I write to you. No, it is the very rare victory that Science has had recently. I am writing to you to make a deal. I will forgive the implication that Australians are not permitted to think for themselves if you follow the lead of the UK government and even more, I will submit one vote for you! I will even forgive you for taking away my firearm licence those many years ago just because <a href="http://en.wikipedia.org/wiki/Port_Arthur_massacre_%28Australia%29">some psycho 2500km away went berzerk with a semi-automatic rifle</a>. I know you do not possess critical thinking skills Mr. Howard, and neither do your nemeses, but I will forgive you for that.</p>
<p>You see, <a href="http://www.theregister.co.uk/2007/06/25/id_not_science/">the UK government have recently announced that Intelligent Design has no part in a school that teaches Science</a>; how great is that for our society!? This announcement has tipped me over the edge and given me some hope – I will do just about anything to have the same for our vulnerable Australian children. Please Mr. Howard!</p>
<p>So, I implore you, please follow suit, for the sake of my children and their well-being if anything. But of course, I know all you care about at the end of the day is my vote and believe me, you will get it! I will even vote for a government; that’s how desperate I am to save my children from the Monotheistic attacks that are conducted so readily and openly in so many civilisations today, including the one that you currently govern.</p>
<p>So, how about it?</p>
    </div>
  </content>
</entry>
<entry>
  <title>'abort: ‘http://foo/bar’ does not appear to be an hg repository!'</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/abort-httpfoobar-does-not-appear-to-be-an-hg-repository/index.html"/>
  <id>http://blog.tmorris.net/posts/abort-httpfoobar-does-not-appear-to-be-an-hg-repository/index.html</id>
  <published>2007-06-12T16:28:39Z</published>
  <updated>2007-06-12T16:28:39Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>If you receive this message from Mercurial when trying to do a <code>hg push</code>, ensure that the web server has write permissions to the repository. Had me stumped for a while ;)</p>
<blockquote>
<p>abort: ‘http://foo/bar’ does not appear to be an hg repository!</p>
</blockquote>
    </div>
  </content>
</entry>
<entry>
  <title>The Power of Type-classes with Scala implicit defs</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/the-power-of-type-classes-with-scala-implicit-defs/index.html"/>
  <id>http://blog.tmorris.net/posts/the-power-of-type-classes-with-scala-implicit-defs/index.html</id>
  <published>2007-05-23T11:02:15Z</published>
  <updated>2007-05-23T11:02:15Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>A core part of Haskell’s type system is that of type-classes. If you have never used type-classes, then there is <a href="http://en.wikibooks.org/wiki/Haskell/YAHT/Type_basics#Type_Classes">a pretty good description in Yet Another Haskell Tutorial (YAHT)</a>. Haskell type-classes have been likened to Java/C# interfaces or Scala traits, but there are some significant differences.</p>
<p>With Scala’s implicit definitions (defs), it is possible to come pretty close to emulating Haskell’s type-classes. This ability can make writing certain constructs very simple and also, extremely flexible. Imagine you were asked to write a function that found the maximum value in a List of values. In Scala, we might write it like this:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> O {
  <span class="kw">def</span> <span class="fu">maximum</span>(x: List[Int]): Int = x <span class="kw">match</span> {
    <span class="kw">case</span> Nil =&gt; <span class="fu">error</span>(<span class="st">&quot;maximum undefined for empty list&quot;</span>)
    <span class="kw">case</span> x :: y :: ys =&gt; <span class="fu">maximum</span>((<span class="kw">if</span>(x &gt; y) x <span class="kw">else</span> y) :: ys)
    <span class="kw">case</span> x :: _ =&gt; x
  }
}</code></pre>
<p>Notice that if we wish to write the function for some other type besides <code>Int</code>, we would have to start again. Or, we could <em>generalise</em> to the Scala <code>Ordered</code> type:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> O {
  <span class="kw">def</span> maximum[a &lt;: Ordered[a]](x: List[a]): a = x <span class="kw">match</span> {
    <span class="kw">case</span> Nil =&gt; <span class="fu">error</span>(<span class="st">&quot;maximum undefined for empty list&quot;</span>)
    <span class="kw">case</span> x :: y :: ys =&gt; <span class="fu">maximum</span>((<span class="kw">if</span>(x &gt; y) x <span class="kw">else</span> y) :: ys)
    <span class="kw">case</span> x :: _ =&gt; x
  }
}</code></pre>
<p>So we accept now that we can find the maximum of any type, so long as that type implements the <code>Ordered</code> trait/interface. But what if we have a type that doesn’t implement that interface? Worse still, what if our type does implement that interface, but we wish to redefine ordering? The only solution here is to create a new type that wraps the old type and redefines ordering. In Haskell, this is called “newtyping”, because it is done with the <code>newtype</code> keyword and is one line of very trivial code (<code>newtype T = T U</code>) plus the two or three for the redefinition of ordering. However, in other languages, this is a little cumbersome and can lead to the bloating of code that is difficult to understand.</p>
<p>Scala implicit defs come to the rescue here. But first, a little introduction to two core Haskell type-classes called <code>Eq</code> and <code>Ord</code>. Here is an excerpt of their definitions:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">class</span>  <span class="kw">Eq</span> a  <span class="kw">where</span>
  (<span class="fu">==</span>),<span class="ot"> (/=)   ::</span> a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Bool</span>
  <span class="co">-- omitted as superfluous to the topic</span>

<span class="kw">class</span>  (<span class="kw">Eq</span> a) <span class="ot">=&gt;</span> <span class="kw">Ord</span> a  <span class="kw">where</span>
<span class="ot">  compare      ::</span> a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Ordering</span>
  <span class="co">-- omitted as superfluous to the topic</span></code></pre>
<p>This first declaration is of the <code>Eq</code> type-class and states that to implement the class over an unbound type (a), one must define equality such that gives two instances of (a), return a boolean value indicating equality (or non-equality). The second declaration is of the <code>Ord</code> type-class and states that to implement the class over a type (a) that is bound by the type-class <code>Eq</code>, one must define ordering such that given two instances of (a), return a type <code>Ordering</code> (which has only three possible values; LT, EQ, GT).</p>
<p>We can express something similar in Scala. However, note that the type parameter (a) is not co-variant, while all Haskell type parameters are co-variant. This is because Haskell is a <em>pure functional programming language</em>, while Scala is not.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> Eq[a] {
  <span class="kw">def</span> <span class="fu">eq</span>(a1: a)(a2: a): Boolean
}

<span class="kw">trait</span> Ord[a] <span class="kw">extends</span> Eq[a] {
  <span class="kw">override</span> <span class="kw">def</span> <span class="fu">eq</span>(a1: a)(a2: a) = <span class="fu">compare</span>(a1)(a2) == EQ
  <span class="kw">def</span> <span class="fu">compare</span>(a1: a)(a2: a): Ordering
}

<span class="co">// for completeness</span>
<span class="kw">sealed</span> <span class="kw">abstract</span> <span class="kw">class</span> Ordering
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> LT <span class="kw">extends</span> Ordering
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> EQ <span class="kw">extends</span> Ordering
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> GT <span class="kw">extends</span> Ordering</code></pre>
<p>Now comes the interesting part (sorry to the impatient :)). Imagine now that we could write our maximum function, where we could say “the maximum of a list of any type (a) such that there exists <strong>one and only one implementation</strong> of the <code>Ord</code> trait for type (a) <strong>implicitly defined in compiler scope</strong>”. That is to say, if there exists two or more implementations of <code>Ord</code>, fail the compiler with an ambiguity error (indeed, many Scala newcomers have likely observed these ambiguity errors from the core Scala APIs). If there is no implementation within scope, fail as well.</p>
<p>Here is how we would write the function now:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> Maximum {
  <span class="kw">def</span> maximum[a](as: List[a])(<span class="kw">implicit</span> o: Ord[a]): a = as <span class="kw">match</span> {
    <span class="kw">case</span> Nil =&gt; <span class="fu">error</span>(<span class="st">&quot;maximum undefined for empty list&quot;</span>)
    <span class="kw">case</span> x :: y :: ys =&gt; <span class="fu">maximum</span>((o.<span class="fu">compare</span>(x)(y) <span class="kw">match</span> {
      <span class="kw">case</span> GT =&gt; x
      <span class="kw">case</span> _ =&gt; y
    }) :: ys)
    <span class="kw">case</span> x :: _ =&gt; x
  }
}</code></pre>
<p>Notice that the function takes two arguments, however, one of them is declared <strong>implicit</strong>. This means that we do not need to explicitly provide this argument (though we can and we might to resolve an ambiguity, but there are also other means). So long as there exists one implementation of <code>Ord[a]</code> implicitly defined in compiler scope, then this implementation is used.</p>
<p>Let us write such an implementation:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> Ord {
  <span class="kw">implicit</span> <span class="kw">def</span> intOrd = <span class="kw">new</span> Ord[Int] {
    <span class="kw">def</span> <span class="fu">compare</span>(a1: Int)(a2: Int) = <span class="kw">if</span>(a1 == a2) EQ <span class="kw">else</span> <span class="kw">if</span>(a1 &lt; a2) LT <span class="kw">else</span> GT
  }
}</code></pre>
<p>Notice that the definition of <code>intOrd</code> is declared with the <strong>implicit</strong> keyword. Now, if the <code>intOrd</code> function is in scope (and no other implementation is), then we can call the <code>maximum</code> function with a list of integers. Indeed, if we had some other definition of ordering for integers (which is rarely the case for integers, but imagine it were some other type), we would not have to rewrite anything to continue using our <code>maximum</code> function.</p>
<p>Also, be aware that implicit definitions are <strong>not</strong> transitive. This means that although we might have an implicit definition from <code>Int</code> to <code>Ord[Int]</code> and we might have some other implicit definition from T to <code>Int</code>, however, this does not imply that we have an implicit definition from T to <code>Ord[Int]</code>. This attribute is very unfortunate and quite limiting of the potential of implicit definitions, but one that is to be accepted nonetheless.</p>
<p>At this point, some would be thinking, “so what?”. After all, some have no problem with newtyping (or adapting or design patterning or whatever you want to call it). However, I draw your attention to one example of many where this approach would save much more work. Let us take a look at that <a href="http://www.scala-lang.org/docu/files/api/scala/List$object.html#range%28Int%2CInt%29"><code>List.range</code></a> function. Notice how the <code>range</code> function is defined over integers only? If I wanted to get a range for some other type, I’d have to rewrite the <code>range</code> function, or I’d have to write a conversion to type <code>Int</code> and use that. Both very annoying.</p>
<p>Indeed, the <code>range</code> function can be generalised to any type that has the notion of a successor (as well, a predecessor if we wish to support backward ranges). However, if we were to define a range function with a step n (default: n = 1), then invoking our successor or predecessor function n times may lead to an inefficiency that is resolved by the integer type, because it has the constant-time + function. Indeed, we would need another function successor(n) so that this efficiency gain could be utilised for types that support it, such as the integer type, where it would use the + function. By default, this implementation would simply invoke the successor function n times. We will acknowledged this fact but will ignore it hereon.</p>
<p>Let us define our successor function:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> Successor[a] {
  <span class="kw">def</span> <span class="fu">succ</span>(a: a): Option[a]

  <span class="co">// for efficiency reasons, we might define this function</span>
  <span class="co">// A default implementation invokes the succ function n times.</span>
  <span class="co">// The integer implementation would override and use +</span>
  <span class="co">// def succn(n: Int)(a: a): Option[a]</span>
}</code></pre>
<p>The <code>succ</code> function returns a succeeding value of type (a) if it exists, but no value if there is no successor i.e. the type is maximally bounded. This is the case for the integer type where <code>Integer.MAX_VALUE</code> has no successor. We would write the implementation like so:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> Successor {
  <span class="kw">implicit</span> <span class="kw">def</span> intSuccessor = <span class="kw">new</span> Successor[Int] {
    <span class="kw">override</span> <span class="kw">def</span> <span class="fu">succ</span>(a: Int) = a <span class="kw">match</span> {
      <span class="kw">case</span> Integer.<span class="fu">MAX_VALUE</span> =&gt; None
      <span class="kw">case</span> _ =&gt; Some(a + <span class="dv">1</span>)
    }
  }
}</code></pre>
<p>Now, we can write our <code>range</code> function such that it is defined over <strong>any</strong> type, so long as that type has one and only one implementation of both <code>Successor[a]</code> and <code>Ord[a]</code> in scope. The implementation of <code>Ord[a]</code> is required to determine the ordering of the <code>from</code> parameter to the <code>to</code> parameter. Also, the equality relation (defined by <code>Eq[a]</code>) is required to know when the range stops.</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> Range {
  <span class="kw">def</span> range[a](from: a)(to: a)(<span class="kw">implicit</span> e: Successor[a], o: Ord[a]): List[a] =
    <span class="kw">if</span>(o.<span class="fu">compare</span>(from)(to) == GT) Nil
    <span class="kw">else</span> <span class="kw">if</span>(o.<span class="fu">eq</span>(from)(to)) List(from)
    <span class="kw">else</span> e.<span class="fu">succ</span>(from) <span class="kw">match</span> {
      <span class="kw">case</span> None =&gt; List(from)
      <span class="kw">case</span> Some(s) =&gt; from :: <span class="fu">range</span>(s)(to)
    }
}</code></pre>
<p>Suppose we wish to find the range of a list of playing cards. Is it Aces high or Aces low? What about other card orderings used in the myriad of different card games? What about other types besides playing cards? It doesn’t matter, since <strong>our <code>range</code> function is as general as it can be</strong>. Yay! No more writing the same code over and over!</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">sealed</span> <span class="kw">abstract</span> <span class="kw">class</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> ACE <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> TWO <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> THREE <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> FOUR <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> FIVE <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> SIX <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> SEVEN <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> EIGHT <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> NINE <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> TEN <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> JACK <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> QUEEN <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> KING <span class="kw">extends</span> Rank

<span class="kw">object</span> Rank {
  <span class="kw">implicit</span> <span class="kw">def</span> acesHigh = <span class="kw">new</span> Successor[Rank] <span class="kw">with</span> Ord[Rank] {
    <span class="kw">val</span> ranks = Array(TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, JACK, QUEEN, KING, ACE)

    <span class="kw">override</span> <span class="kw">def</span> <span class="fu">compare</span>(a1: Rank)(a2: Rank) = <span class="kw">if</span>(a1 == a2) EQ <span class="kw">else</span> <span class="kw">if</span>(ranks.<span class="fu">indexOf</span>(a1) &lt; ranks.<span class="fu">indexOf</span>(a2)) LT <span class="kw">else</span> GT

    <span class="kw">override</span> <span class="kw">def</span> <span class="fu">succ</span>(a: Rank) = a <span class="kw">match</span> {
      <span class="kw">case</span> ACE =&gt; None
      <span class="kw">case</span> _ =&gt; Some(<span class="fu">ranks</span>(ranks.<span class="fu">indexOf</span>(a) + <span class="dv">1</span>))
    }
  }

  <span class="kw">implicit</span> <span class="kw">def</span> acesLow = <span class="kw">new</span> Successor[Rank] {
    <span class="kw">val</span> ranks = Array(ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, JACK, QUEEN, KING)

    <span class="kw">override</span> <span class="kw">def</span> <span class="fu">succ</span>(a: Rank) = a <span class="kw">match</span> {
      <span class="kw">case</span> KING =&gt; None
      <span class="kw">case</span> _ =&gt; Some(<span class="fu">ranks</span>(ranks.<span class="fu">indexOf</span>(a) + <span class="dv">1</span>))
    }
  }
}</code></pre>
<p>Notice here that we can bring either <code>acesHigh</code> or <code>acesLow</code> into compiler scope (but not both) and use the <code>range</code> function successfully. Indeed, the following code prints different output because of which function is in scope:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">object</span> Main {
  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]) = {
    {
      <span class="kw">import</span> Rank.<span class="fu">acesHigh</span>
      Console.<span class="fu">println</span>(<span class="fu">range</span>(TWO: Rank)(THREE)) <span class="co">// List(TWO,THREE)</span>
      Console.<span class="fu">println</span>(<span class="fu">range</span>(TWO: Rank)(ACE)) <span class="co">// List(TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,JACK,QUEEN,KING,ACE)</span>
      Console.<span class="fu">println</span>(<span class="fu">range</span>(ACE: Rank)(KING)) <span class="co">// List()</span>
    }

    {
      <span class="kw">import</span> Rank.<span class="fu">acesLow</span>
      Console.<span class="fu">println</span>(<span class="fu">range</span>(TWO: Rank)(THREE)) <span class="co">// List(TWO,THREE)</span>
      Console.<span class="fu">println</span>(<span class="fu">range</span>(TWO: Rank)(ACE)) <span class="co">// List(TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,JACK,QUEEN,KING)</span>
      Console.<span class="fu">println</span>(<span class="fu">range</span>(ACE: Rank)(KING)) <span class="co">// List()</span>
    }
  }
}</code></pre>
<p>Reader’s exercise: write a <code>range</code> function with step of type <code>Int</code>, which may be negative (and so step backward)</p>
<p>Here is a complete, compilable source code listing:</p>
<pre class="sourceCode Scala"><code class="sourceCode scala"><span class="kw">trait</span> Eq[a] {
  <span class="kw">def</span> <span class="fu">eq</span>(a1: a)(a2: a): Boolean
}

<span class="kw">sealed</span> <span class="kw">abstract</span> <span class="kw">class</span> Ordering
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> LT <span class="kw">extends</span> Ordering
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> EQ <span class="kw">extends</span> Ordering
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> GT <span class="kw">extends</span> Ordering

<span class="kw">trait</span> Ord[a] <span class="kw">extends</span> Eq[a] {
  <span class="kw">override</span> <span class="kw">def</span> <span class="fu">eq</span>(a1: a)(a2: a) = <span class="fu">compare</span>(a1)(a2) == EQ
  <span class="kw">def</span> <span class="fu">compare</span>(a1: a)(a2: a): Ordering
}

<span class="kw">object</span> Ord {
  <span class="kw">implicit</span> <span class="kw">def</span> intOrd = <span class="kw">new</span> Ord[Int] {
    <span class="kw">def</span> <span class="fu">compare</span>(a1: Int)(a2: Int) = <span class="kw">if</span>(a1 == a2) EQ <span class="kw">else</span> <span class="kw">if</span>(a1 &lt; a2) LT <span class="kw">else</span> GT
  }
}

<span class="kw">object</span> Maximum {
  <span class="kw">def</span> maximum[a](as: List[a])(<span class="kw">implicit</span> o: Ord[a]): a = as <span class="kw">match</span> {
    <span class="kw">case</span> Nil =&gt; <span class="fu">error</span>(<span class="st">&quot;maximum undefined for empty list&quot;</span>)
    <span class="kw">case</span> x :: y :: ys =&gt; <span class="fu">maximum</span>((o.<span class="fu">compare</span>(x)(y) <span class="kw">match</span> {
      <span class="kw">case</span> GT =&gt; x
      <span class="kw">case</span> _ =&gt; y
    }) :: ys)
    <span class="kw">case</span> x :: _ =&gt; x
  }
}

<span class="kw">trait</span> Successor[a] {
  <span class="kw">def</span> <span class="fu">succ</span>(a: a): Option[a]
}

<span class="kw">object</span> Successor {
  <span class="kw">implicit</span> <span class="kw">def</span> intSuccessor = <span class="kw">new</span> Successor[Int] {
    <span class="kw">override</span> <span class="kw">def</span> <span class="fu">succ</span>(a: Int) = a <span class="kw">match</span> {
      <span class="kw">case</span> Integer.<span class="fu">MAX_VALUE</span> =&gt; None
      <span class="kw">case</span> _ =&gt; Some(a + <span class="dv">1</span>)
    }
  }
}

<span class="kw">object</span> Range {
  <span class="kw">def</span> range[a](from: a)(to: a)(<span class="kw">implicit</span> e: Successor[a], o: Ord[a]): List[a] =
    <span class="kw">if</span>(o.<span class="fu">compare</span>(from)(to) == GT) Nil
    <span class="kw">else</span> <span class="kw">if</span>(o.<span class="fu">eq</span>(from)(to)) List(from)
    <span class="kw">else</span> e.<span class="fu">succ</span>(from) <span class="kw">match</span> {
      <span class="kw">case</span> None =&gt; List(from)
      <span class="kw">case</span> Some(s) =&gt; from :: <span class="fu">range</span>(s)(to)
    }
}

<span class="kw">sealed</span> <span class="kw">abstract</span> <span class="kw">class</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> ACE <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> TWO <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> THREE <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> FOUR <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> FIVE <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> SIX <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> SEVEN <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> EIGHT <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> NINE <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> TEN <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> JACK <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> QUEEN <span class="kw">extends</span> Rank
<span class="kw">final</span> <span class="kw">case</span> <span class="kw">object</span> KING <span class="kw">extends</span> Rank

<span class="kw">object</span> Rank {
  <span class="kw">implicit</span> <span class="kw">def</span> acesHigh = <span class="kw">new</span> Successor[Rank] <span class="kw">with</span> Ord[Rank] {
    <span class="kw">val</span> ranks = Array(TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, JACK, QUEEN, KING, ACE)

    <span class="kw">override</span> <span class="kw">def</span> <span class="fu">compare</span>(a1: Rank)(a2: Rank) = <span class="kw">if</span>(a1 == a2) EQ <span class="kw">else</span> <span class="kw">if</span>(ranks.<span class="fu">indexOf</span>(a1) &lt; ranks.<span class="fu">indexOf</span>(a2)) LT <span class="kw">else</span> GT

    <span class="kw">override</span> <span class="kw">def</span> <span class="fu">succ</span>(a: Rank) = a <span class="kw">match</span> {
      <span class="kw">case</span> ACE =&gt; None
      <span class="kw">case</span> _ =&gt; Some(<span class="fu">ranks</span>(ranks.<span class="fu">indexOf</span>(a) + <span class="dv">1</span>))
    }
  }

  <span class="kw">implicit</span> <span class="kw">def</span> acesLow = <span class="kw">new</span> Successor[Rank] {
    <span class="kw">val</span> ranks = Array(ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, JACK, QUEEN, KING)

    <span class="kw">override</span> <span class="kw">def</span> <span class="fu">succ</span>(a: Rank) = a <span class="kw">match</span> {
      <span class="kw">case</span> KING =&gt; None
      <span class="kw">case</span> _ =&gt; Some(<span class="fu">ranks</span>(ranks.<span class="fu">indexOf</span>(a) + <span class="dv">1</span>))
    }
  }
}

<span class="kw">object</span> Main {
  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]) = {
    <span class="kw">import</span> Ord.<span class="fu">intOrd</span>
    Console.<span class="fu">println</span>(Maximum.<span class="fu">maximum</span>(List.<span class="fu">range</span>(<span class="dv">1</span>, <span class="dv">10</span>)))

    <span class="kw">import</span> Range.<span class="fu">range</span>

    Console.<span class="fu">println</span>(<span class="fu">range</span>(<span class="dv">7</span>)(<span class="dv">8</span>))
    Console.<span class="fu">println</span>(<span class="fu">range</span>(<span class="dv">7</span>)(<span class="dv">7</span>))
    Console.<span class="fu">println</span>(<span class="fu">range</span>(<span class="dv">7</span>)(<span class="dv">6</span>))
    Console.<span class="fu">println</span>(<span class="fu">range</span>(Integer.<span class="fu">MAX_VALUE</span>)(Integer.<span class="fu">MAX_VALUE</span>))
    Console.<span class="fu">println</span>(<span class="fu">range</span>(Integer.<span class="fu">MAX_VALUE</span> - <span class="dv">1</span>)(Integer.<span class="fu">MAX_VALUE</span>))
    Console.<span class="fu">println</span>(<span class="fu">range</span>(Integer.<span class="fu">MAX_VALUE</span>)(<span class="dv">7</span>))
    Console.<span class="fu">println</span>(<span class="fu">range</span>(Integer.<span class="fu">MIN_VALUE</span>)(Integer.<span class="fu">MIN_VALUE</span> + <span class="dv">1</span>))

    {
      <span class="kw">import</span> Rank.<span class="fu">acesHigh</span>
      Console.<span class="fu">println</span>(<span class="fu">range</span>(TWO: Rank)(THREE))
      Console.<span class="fu">println</span>(<span class="fu">range</span>(TWO: Rank)(ACE))
      Console.<span class="fu">println</span>(<span class="fu">range</span>(ACE: Rank)(KING))
    }

    {
      <span class="kw">import</span> Rank.<span class="fu">acesLow</span>
      Console.<span class="fu">println</span>(<span class="fu">range</span>(TWO: Rank)(THREE))
      Console.<span class="fu">println</span>(<span class="fu">range</span>(TWO: Rank)(ACE))
      Console.<span class="fu">println</span>(<span class="fu">range</span>(ACE: Rank)(KING))
    }
  }
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>You Lazy Thunk!</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/you-lazy-thunk/index.html"/>
  <id>http://blog.tmorris.net/posts/you-lazy-thunk/index.html</id>
  <published>2007-05-16T14:43:24Z</published>
  <updated>2007-05-16T14:43:24Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I recently read an article (on C programming) that made the following claim:</p>
<blockquote>
<p>Either f() or g() gets called twice. This is inefficient [where both f and g are equivalent functions.]</p>
</blockquote>
<p>Unfortunately, these kind of statements are very common among programmers who generally only use a certain class of programming languages (strict and imperative; C, Java, C# etc.) and I have seen the statement in various forms many times before, but I have been compelled to dispel this myth. I don’t intend to pick on this particular article – after all, the intended topic of the article is unrelated to the fallacious statement, despite being a premise for the article’s conclusions and there are many other writers who are most capable of propagating this misinformation anyway. What the author of this statement might not know is that it contradicts some really interesting branches of mathematics including the Lambda Calculus and Complexity Theory (you may have noticed the lambda symbols in the title of this page and you may have seen the term λ-calculus written before).</p>
<p>The space versus computation trade is a standard problem for computer scientists, but recent industry trends have generalised this problem to the point of actually not appearing like a problem at all. You see, space has become cheap, <strong>really</strong> cheap – so cheap that it almost appears infinite. Let us consider the problem of finding the nth element of an array and a linked list. For the array, this will execute in <em>constant time</em>, however, for the linked list, the time to compute it will depend on the value of n. Notice how the array exists in-memory while the linked list might not (e.g. it may read from a file as it is traversed). That is, it has incurred a space cost. This cost has provided the benefit of computation speed. A trade has occurred, not an efficiency gain.</p>
<p>The use of the linked list is called <strong>lazy evaluation</strong> (or laziness) while the use of an array is called <strong>strict evaluation</strong> (or strictness). Traversing the linked list is sometimes called <strong>thunking</strong> (which is just an obscure word for invoking a function) and evaluating each of its elements is called <strong>Weak Head Normal Form (WHNF)</strong>, which is a term taken from the λ-calculus.</p>
<p>Given a lazily evaluated structure, it is possible to make it strict by bringing it to WHNF. This computation will occur once and its result may be placed in a universally-available table with constant time lookup to prevent computing the value again. This storage will incur space and is a process called <strong>memoisation</strong>. Unfortunately, a strict structure cannot be made lazy since the space cost has already been incurred. In fact, doing so yields no benefit whatsoever (other than to appeal to a type system).</p>
<p>We can observe laziness and strictness in some of our <em>poor-yet-popular</em> programming languages like Java, where an array represents a strict, homogenous list, while an InputStream or Iterator represents a lazy list. A ByteArrayInputStream is a (unfortunate) attempt to construct a lazy structure from a strict one with no additional benefit – in this case, it is to appeal to a type system (e.g. to use a method that must accept an InputStream instead of a byte[]). A Haskell list, which is lazy, is more like a Java iterator than a Java list or array (but still with a significant difference) and it is often better to think this way if you are learning a lazy language coming from a strict, imperative language. In fact, like a Haskell list, a Java iterator can have an infinite length where its <code>hasNext</code> method never returns <code>false</code>.</p>
<p>We can see now that if <em>f() or g() gets called twice</em>, then this is not inefficient, nor is it efficient. This is actually a trade. Computation has been spent while space has been gained, since the result of the computation of the first call of either function is not stored, but is recomputed. Similarly, purchasing a bottle of water for one dollar is not more or less efficient, assuming that the bottle of water is indeed worth one dollar. You are no more or less better off whether you purchased the water or not. Of course, we rarely see such purist forms of capitalism, but the analogy makes sense otherwise :)</p>
<p>Programmers of strict, imperative languages do not always elect to strictly evaluate from what is called a <em>universe (or domain) of discourse</em> (from Set Theory). That is to say, from the universe (U) that is passed to the programmer, each expression is not necessarily brought to WHNF. Ideally, only what is necessary is evaluated to complete the computation and anything else from U is left untouched, however, the decision of what to evaluate is often (at least in my observations) totally arbitrary due to a lack of formal reasoning and inexperience with the foundations of computer programming – on the part of the programmer. If a subset of the universe is evaluated that is never needed to complete the computation, then this <strong>is</strong> an inefficiency and it happens very often in strict, imperative languages. (Think tip: Is it any wonder your Java application consumes all your volatile memory?)</p>
<p>Let’s demonstrate this. Suppose a Java programmer is asked to compute an int – the sum of the first 2 bytes from an InputStream, or compute 1024 if the bytes are not available. The InputStream represents a potentially infinite universe of discourse (|U| = ∞), however, not all of it is necessarily evaluated (if it were infinite, the function would never terminate). Here is a canonical solution:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="dt">int</span> <span class="fu">firstByte</span>(InputStream in) <span class="kw">throws</span> IOException {
  <span class="dt">final</span> <span class="dt">int</span> i = in.<span class="fu">read</span>();
  <span class="dt">final</span> <span class="dt">int</span> j = in.<span class="fu">read</span>();
  <span class="kw">return</span> i == -<span class="dv">1</span> || j == -<span class="dv">1</span> ? <span class="dv">1024</span> : i + j;
}</code></pre>
<p>Notice how the entire InputStream is not read until the end (if there is one), <em>simply because you can</em>, since this would be an inefficiency. The domain or universe is an InputStream, but only two reads occur. Indeed, if this InputStream were infinite, the function would still terminate. Similarly, the following equivalent Haskell function will terminate:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">let</span> first (i<span class="fu">:</span>j<span class="fu">:</span>_) <span class="fu">=</span> i <span class="fu">+</span> j; first _ <span class="fu">=</span> <span class="dv">1024</span></code></pre>
<p>…even if passed an infinite list:</p>
<pre><code>&gt; first [20..] -- from 20 to infinity
41</code></pre>
<p>If a byte[] were passed to the <code>firstByte</code> function instead and the entire array were never evaluated for the computation (why would it?), we would have an inefficiency. If the array was fully evaluated during computation, then we have neither an efficiency, nor an inefficiency. Certainly, evaluating beyond the universe of discourse yields no benefit whatsoever while incurring a space cost. Unfortunately, this is not immediately obvious because <em>poor-yet-popular</em> programming languages sometimes make it cumbersome to write the desired expression without incurring this inefficiency and so it appears as if it were a necessary trade with the language itself. That is, the reasoning “because this language is cumbersome to such an extreme, it will force you to incur inefficiencies by evaluating outside your domain for computation so as to avoid writing code that is cumbersome” is often overlooked, typically because the alternatives are not known. Also, the more elegant solution, even in that cumbersome programming language, is often overlooked. Nevertheless, I find this behaviour of both the programming language and the programmer using that language, completely absurd (I love you Alex ;))</p>
<p>However, languages such as C/Java often make laziness very easy. Suppose you write an <code>if/else</code>. The runtime will not evaluate both the if and else block before executing one or the other. This is lazy behaviour. Similarly, the ternary operator (?:) is also lazy. Finally, the &amp;&amp; and || operators are also lazy, since their second argument is only evaluated on-demand. Therefore, we see clearly that laziness is not a completely foreign concept to (mostly :)) strict, imperative languages and is often preferred, since the contrary may certainly result in an inefficiency.</p>
<p>I leave now with the following transcript from my GHC/Haskell interpreter (which is inherently lazy):</p>
<pre><code>&gt; take 5 [1..] -- take the first 5 elements from the list of 1 to infinity
[1,2,3,4,5]
&gt; foldr (&amp;&amp;) True $ repeat False -- fold the conjunction of True and an infinite list of False
False
&gt; foldr (||) False $ repeat True -- fold the disjunction of False and an infinite list of True
True
&gt; -- foldr (||) True $ repeat False -- eek! this will never terminate!
&gt; take 5 $ map (*2) [1..] -- take the first 5 elements from the list with the function (*2) mapped across 1 to infinity
[2,4,6,8,10]</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Obstruction</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/obstruction/index.html"/>
  <id>http://blog.tmorris.net/posts/obstruction/index.html</id>
  <published>2007-04-04T12:37:31Z</published>
  <updated>2007-04-04T12:37:31Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>On 28 April 2006, I was charged by a police officer for obstruction under <a href="http://www.austlii.edu.au/au/legis/qld/consol_act/ppara2000365/">Police Powers and Responsibilities Act 2000</a> Section 444 (since amended to <a href="http://www.austlii.edu.au/au/legis/qld/consol_act/ppara2000365/s790.html">Section 790</a>). The police officer alleged at the time that my holding of a sign that reads ‘Police Speed Trap Ahead 50’ – with emphasis on the 50 indicating the speed limit in that area – constituted an offence, obstruction.</p>
<p>I subsequently entered a plea of <em>not guilty</em> (after one adjournment) and made several attempts to obtain a Brief of Evidence from the police prosecution. Their incompetence would normally astound me, but these days I just roll my eyes – in fact, a demonstration of competence itself <em>would</em> invoke surprise (know of one?). Of course, no brief was available, for days, then weeks, then months and in the meantime, I had spent countless hours on putting together a defence.</p>
<p>Finally, the day before the trial, still without a brief (<em>roll eyes now</em>), the police prosecutor rings me and attempts to negotiate – in the usual friendly/manipulative manner as expected. After the usual banter (trying to obtain information from me), I am offered a ‘guilty plea for no conviction’ deal, which I immediately decline and hang up the phone with, ‘see ya tomorrow mate’. I then travelled to the police station to request a brief of evidence, knowing I wouldn’t receive one, but adding to my record of attempts to obtain it, that I would be presenting to the magistrate the following day. A couple of hours later, I receive another phone call to be notified that the charge has been dropped.</p>
<p>This occurred for two reasons.</p>
<ol style="list-style-type: decimal">
<li><p>The police prosecution was too incompetent to get their act together to pursue the charge</p></li>
<li><p>But <strong>most importantly</strong>, the police do not want to set a legal (lawful) precedent for this behaviour</p></li>
</ol>
<p>The police prosecution clearly believed that there was a strong possibility that my not guilty plea would pay off. If it were successful, a subsequent appearance on television (see the first one below) would have propagated the legality of this activity among the public and <strong>the police definitely do not want an informed public</strong> even if it means that I ‘get off’. Instead, it is best to leave the issue ‘blurred’ and continue pursuing ‘offenders’ such as myself, who otherwise do not know any better and enter a guilty plea on the day in court (I understand that many police officers genuinely believe that they are performing a public duty, but let’s leave that side issue).</p>
<p>Although I am not a lawyer, this activity is <strong>not</strong> illegal if it is executed correctly. I encourage any member of the public who is concerned about road-safety in Australia to engage in this lawful behaviour, although I do not accept any liability for any adverse consequences that you may encounter, including, among other things, a criminal conviction.</p>
<p>To engage in this behaviour legally in Queensland (other states may be similar), ensure the following:</p>
<ul>
<li><p>stand well away from the police speed trap, a few hundred metres at least</p></li>
<li><p>if approached by <strong>anyone</strong>, do not offer comment under any circumstances</p></li>
<li><p>if approached by a police officer, he/she may request your name, address and may also request “evidence of the correctness of the stated name and address” (see <a href="http://www.austlii.edu.au/au/legis/qld/consol_act/ppara2000365/s40.html">PPRA2000 Section 40</a>)</p></li>
<li><p>Comply if you are asked for name and address, but under no circumstances should you offer further comment on the matter – police are very well trained at extracting this information to ensure your conviction, so it is up to you exercising discipline to keep yourself safe. This request is almost certainly a demand under <a href="http://www.austlii.edu.au/au/legis/qld/consol_act/ppara2000365/s41.html">PPRA 2000 Section 41</a> where the police officer “reasonably suspects the person has committed an offence”, even though you probably haven’t. Do not pursue this ambiguity with the police officer at the scene.</p></li>
</ul>
<p>What about flashing vehicle headlights? If you flash your headlights to warn other motorists of an impending speed trap, a police officer will almost certainly issue you with an infringement notice of Rule 218 of the <a href="http://www.ntc.gov.au/ViewPage.aspx?page=A022075053009400200.com">Australia Road Rules</a> (<a href="http://www.legislation.qld.gov.au/LEGISLTN/CURRENT/T/TrantOpRURR99.pdf">Transport Operations Regulation 1999</a> in Queensland). It is important in this case to fulfill your legal obligations (name, address and produce valid driver’s licence) but <strong>offer no other comment</strong> – why? Because you may not have committed an offence, that’s why.</p>
<p>Let’s take a look at Rule 218 of the ARR (Part 13 Division 1):</p>
<blockquote>
<p>218 Using headlights on high-beam (1) The driver of a vehicle must not use the vehicle’s headlights on high-beam, or allow the vehicle’s headlights to be used on high-beam, if the driver is driving: (a) less than 200 metres behind a vehicle travelling in the same direction as the driver; or (b) less than 200 metres from an oncoming vehicle. Offence provision. Note High-beam and oncoming vehicle are defined in the dictionary. (2) However, if the driver is overtaking a vehicle, the driver may briefly switch the headlights from low-beam to high-beam immediately before the driver begins to overtake the vehicle. Note Low-beam and overtake are defined in the dictionary. <em>Diagrams follow</em></p>
</blockquote>
<p>Your infringement notice is for part (1) of Section 218, but a police officer almost certainly will not ask you if you used your signals for part (2). Have you ever asked yourself why ADR (Australian Design Rules) compliant vehicles have a high-beam flasher switch? Of course, because it is entirely legal to flash your high-beam headlights under some circumstances.</p>
<p>If you wish to warn opposing traffic of an impending speed trap, ensure that you flash your headlights under legal circumstances – while overtaking a vehicle, briefly from low-beam to high-beam and immediately before overtaking the vehicle. Do not feel tempted to justify this action on the side of the road with a manipulative police officer! Simply enter your not guilty plea in the court and explain to the magistrate that you were acting legally and responsibly under Rule 218 of the ARR.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Glue?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/glue/index.html"/>
  <id>http://blog.tmorris.net/posts/glue/index.html</id>
  <published>2007-02-24T08:59:57Z</published>
  <updated>2007-02-24T08:59:57Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I recently noted that I’d had stitches in 23 sites on my body – including, among other things, an amputation of my right-index finger. It was last Saturday (17 Feb 07) that I was training as usual at <a href="http://wavellsquash.com.au/">my squash club,</a> when I was struck just above the eye by the end of my opponent’s swing, drawing lots of blood as you would expect with an elevated heart rate during squash and sending my opponent into mild shock at the sight of it (te he :)).</p>
<p>Anyway, my count still remains at 23 – why? Because the emergency department used glue! I suppose the injury was not large enough to warrant the use of sutures, but glue!? Who’d uv thunk?! It has healed perfectly and my first match in this weekend’s Charles Butcher Tournament starts in a couple of hours. Revenge is <em>definitely</em> on the agenda! Watch your back Brad :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>Statefulness and the Abstract Universe</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/statefulness-and-the-abstract-universe/index.html"/>
  <id>http://blog.tmorris.net/posts/statefulness-and-the-abstract-universe/index.html</id>
  <published>2007-02-22T11:50:01Z</published>
  <updated>2007-02-22T11:50:01Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Quite often, I hear comments from people who are trying to get a grasp on functional programming about entities which are “inherently stateful” or “intrinsically mutable” (<a href="http://programming.reddit.com/info/14m2o/comments/c14pqp">example</a>). The commenters often point to a disk or network to make the point. In this post, I am going to attempt to portray a slightly deeper understanding of this topic to erase the facade and bring to fruition the fact that this “inherent state” (or whatever) is in fact an illusion. This will require some <em>thought experiment</em> and the manipulation of some abstract entities in order to attain this insight.</p>
<p>I will first start off by describing the distinction between the physical universe as we observe it and the abstract universe. The physical universe is made up of matter; for example, a house, a typewriter and even a hard disk. The abstract universe is one that is, well, abstract – one that is not physical. If we consider the number 2. We call it ‘a number’, a physical entity, yet we cannot hold it in our hands or point to its physical representation. Therefore, 2 is better described as a representation of “twoness” or “the concept of two”. The symbol ‘2’ is used to denote the concept of two, among other possible representations of the same concept:</p>
<ul>
<li><p>two</p></li>
<li><p>. .</p></li>
<li><p>00000010</p></li>
</ul>
<p>…and so on. Anyone interested in defining the concept of two, with a bent for history, might be interested in learning about <a href="http://www.google.com.au/search?q=the+discovery+of+zero">the discovery of zero</a>.</p>
<p>Now, this point touches on some philosophical grounds that I’d rather not go into, so instead, I will make a note of the fact that a pure evolutionary Atheist might not accept this distinction (perhaps claiming that 2 is in fact physical as a chemical signal in the brain), while a Theologian would describe the abstract universe as your ‘Soul’ (or some such). I don’t mean to encroach on this philosophical point and I am hoping I can get away with using terminology that can be translated to the relevant philosophical view.</p>
<p>So, when you write a function, in any language, f(2), you’re not passing a 2 or 2 itself to that function, but instead, a representation of the concept of two to the concept of your function and nothing further. Here’s the clincher: <strong>All software exists in the abstract universe</strong>. Even your C program that does clever pointer arithmetic and your assembly program that moves the hard disk head. Yes, that FILE* is in fact, an abstraction of a pointer, <em>not</em> a pointer itself. None of these are physical entities, but abstractions of physical entities that manifest themselves somehow – none of these manifestations are relevant to the software author.</p>
<p>It’s all quite simple so far, but if you can pass ‘a representation of the concept of two’, then what is to stop you from passing ‘a representation of the concept of the file system’? or the network? <strong>Nothing, that’s what.</strong> In fact, you could quite plausibly argue that this is exactly what <a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t%3AIO">Haskell’s IO monad</a> is doing – an abstraction that represents these physical entities using the expressive type system of Haskell. In exactly the same way that 2 is an abstraction that represents a physical entity i.e. it will eventually manifest itself as electrical signals in your computer hardware (or physically manifest somehow anyway).</p>
<p>Those of you who are concerned about passing an entire file system as a function argument and the impact on performance might be interested in delving further into a topic called Lazy Evaluation and Weak Head Normal Form (WHNF). I’d rather not reiterate the work of many others who are more dedicated, so I’ll just point out that concerns for performance are definitely valid, but the impact on performance is not there (in fact, often quite the contrary – <a href="http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&amp;lang=all">performance improves!</a>).</p>
<p>The distinction between ‘2’ and ‘the file system’ and ‘the network’ from a software developer’s perspective is entirely superficial and should be abandoned. One cannot be ‘inherently stateful’ while the other isn’t. It’s one or the other, so which is it? (hint: n**ther :))</p>
    </div>
  </content>
</entry>
<entry>
  <title>Refunctoring</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/refunctoring/index.html"/>
  <id>http://blog.tmorris.net/posts/refunctoring/index.html</id>
  <published>2007-02-15T16:51:42Z</published>
  <updated>2007-02-15T16:51:42Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Ask your average Java (or C#) programmer to ‘write a method that takes a list of integers, adds 10 to each element, converts the result to a String, prepends <em>*</em> to it and returns the resulting list’. It’s quite easy and you can certainly postulate what kind of start would be made on this. Here is how I suspect most Java programmers would solve this problem:</p>
<pre class="sourceCode Java"><code class="sourceCode java">...
<span class="dt">static</span> List&lt;string&gt; <span class="fu">addTenAndConvert</span>(List&lt;integer&gt; list) {
  List&lt;string&gt; result = <span class="kw">new</span> LinkedList&lt;string&gt;();

  <span class="kw">for</span>(Integer i : list) {
    String s = <span class="st">&quot;***&quot;</span> + String.<span class="fu">valueOf</span>(i + <span class="dv">10</span>);
    result.<span class="fu">add</span>(s);
  }

  <span class="kw">return</span> result;
}</code></pre>
<p>Simple enough. Many people would also write so-called ‘unit tests’ to assist in verifying that the method meets the specified requirement. It is interesting to note at this point that ‘for all’ (<a href="http://en.wikipedia.org/wiki/Universal_quantification">hint</a>) list arguments, the length of the return value will always be equal. So for the argument, {1,2,3} with a length of 3, the result is {“<strong>*11&quot;, &quot;</strong><em>12&quot;, &quot;</em>**13”} also with a length of 3 and this property holds across all lists.</p>
<p>But then, I ask for another method that does all the same, but this time, prepends “AAA” instead of “<em>*</em>”. Whatchya gunna do? Copy/paste/change? No, you’re going to refunctor (to be defined in time to come), that’s what. You might pass an additional argument of type String and prepend that. Sounds fair enough. But then I will ask instead that you append “BBB” instead of prepending “AAA”. Pass an additional argument of type boolean?</p>
<p>Let’s take a look at what we’ve got:</p>
<pre class="sourceCode Java"><code class="sourceCode java">...
<span class="dt">static</span> List&lt;string&gt; <span class="fu">addTenAndConvert</span>(
  List&lt;integer&gt; list, String s, <span class="dt">boolean</span> prepend) {
  List&lt;string&gt; result = <span class="kw">new</span> LinkedList&lt;string&gt;();

  <span class="kw">for</span>(Integer i : list) {
    String ss = prepend ? s + String.<span class="fu">valueOf</span>(i + <span class="dv">10</span>) :
        i.<span class="fu">toString</span>() + s;
    result.<span class="fu">add</span>(ss);
  }

  <span class="kw">return</span> result;
}</code></pre>
<p>But then, I ask you for another requirement – this time devastating. I ask instead that it is not a List argument, but a List argument and a List return type. Going to copy/paste this time, right? The conversion from each String element to the new Integer element is left unspecified for now, but feel free to dream something up. In fact, feel free to ‘refactor’ it out:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> Convert {
  Integer <span class="fu">convert</span>(String s);
}</code></pre>
<p>…then change the method like so:</p>
<pre class="sourceCode Java"><code class="sourceCode java">...
<span class="dt">static</span> List&lt;integer&gt; <span class="fu">stringListToIntegerList</span>(
    Convert c, List&lt;string&gt; list) {
  List&lt;integer&gt; result = <span class="kw">new</span> LinkedList&lt;integer&gt;();

  <span class="kw">for</span>(String s : list) {
    Integer i = c.<span class="fu">convert</span>(s);
    result.<span class="fu">add</span>(i);
  }

  <span class="kw">return</span> result;
}</code></pre>
<p>Notice that our method’s name is becoming less specific as it is refactored and becoming more abstract in behaviour. Further, we cannot write our method <code>addTenAndConvert</code> in terms of our method <code>stringListToIntegerList</code> by passing a different implementation of <code>Convert</code> because our types do not match. However, notice that the transformation on each list has nothing to do with specific types – these types are actually <em>unbounded polymorphic</em> types. Let’s try again.</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> Convert&lt;T, U&gt; {
  U <span class="fu">convert</span>(T t);
}

<span class="dt">static</span> &lt;T, U&gt; List&lt;u&gt; <span class="fu">fooForNow</span>(Convert&lt;T, U&gt; c, List&lt;t&gt; list) {
  List&lt;u&gt; result = <span class="kw">new</span> LinkedList&lt;u&gt;();

  <span class="kw">for</span>(T t : list) {
    U u = c.<span class="fu">convert</span>(t);
    result.<span class="fu">add</span>(u);
  }

  <span class="kw">return</span> result;
}</code></pre>
<p>How’s that look!!? What shall we call this method? I have called it <code>fooForNow</code>, but if you’ll just let me call it <code>map</code> instead, just because. We can now write our method <code>addTenAndConvert</code> with our newly found abstraction – the <code>map</code> function:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="dt">static</span> List&lt;string&gt; <span class="fu">addTenAndConvert</span>(List&lt;integer&gt; list) {
  Convert&lt;Integer, String&gt; c = <span class="kw">new</span> Convert&lt;Integer, String&gt;() {
    <span class="kw">public</span> String <span class="fu">convert</span>(Integer i) {
      <span class="kw">return</span> <span class="st">&quot;***&quot;</span> + String.<span class="fu">valueOf</span>(i + <span class="dv">10</span>);
    }
  };

  <span class="kw">return</span> <span class="fu">map</span>(c, list);
}</code></pre>
<p>How funky is that? Funky enough for you to start looking at funktional programming? I’ll let you in on a little secret. This relatively high euphoric point of using Java/C# (et. al.) is the very basis and starting point of most functional programming languages. In fact, the <code>map</code> function is typically included in the standard libraries! Functional programming is Java version 42, seriously. It is a natural extension to what it is that most Java/C# programmers are already doing. It is not some esoteric, orthogonal, unrelated paradigm that has nothing to do with anything except the point of singularity.</p>
<p>If we consider our <code>Convert</code> type to actually represent ‘anything that can convert a T to a U’, we call <code>map</code> a higher-order function, since it takes a function (from T to U) as an argument. Whether or not to name this function argument (to <code>Convert</code> in our example) and hide the behaviour of this conversion behind some implementation sets the premise for the ‘DD (Dynamic Dispatch) versus HOF (Higher-Order Function) issue’.</p>
<p>If we look at the type for the Haskell <code>map</code> function, we see it like this:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="fu">map</span><span class="ot"> ::</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> [a] <span class="ot">-&gt;</span> [b]</code></pre>
<p>That is, as the first argument, it takes a function from a type ‘a’ to a type ‘b’ (we called these T and U, but Haskell type parameters must be lower-case). The second argument is a list of the type ‘a’ and the return type is a list of the type ‘b’. That’s exactly what we just wrote in 43 trillion lines of Java code! OK, maybe I am exaggerabating a bit there.</p>
<p>And in case you’re wondering, here is how <code>addTenAndConvert</code> looks in Haskell:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">let</span> addTenAndConvert <span class="fu">=</span> <span class="fu">map</span> ((<span class="st">&quot;***&quot;</span> <span class="fu">++</span>) <span class="fu">.</span> <span class="fu">show</span> <span class="fu">.</span> (<span class="fu">+</span><span class="dv">10</span>)) <span class="co">-- tidy eh?</span></code></pre>
<p>Why ‘Refunctoring’? First, I refuse to reuse euphemistic terms that have served only to denigrate the standard of the software development industry, therefore, I cannot use ‘Refactoring’ (oooh! did I just say that!!?). To show this, consider the fact that the entire notion of ‘Refactoring’ is done away with one simple phrase ‘Functional Programming’ in the case shown and hundreds more. Of course, you might decide to redefine Refactoring to a different context, but then, redefining terms often leads to confusion (the term ‘function’ is itself a perfect example). To further demonstrate this point, open <a href="http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672">the book</a> or <a href="http://www.refactoring.com/catalog/index.html">catalog</a> on Refactoring and turn to the section titled, ‘Replace Parameter with Method’. Then say out loud, ‘partial application’ – if you don’t know why you’re saying that, learn what partial application is, then perhaps it might dawn on you. A useful exercise is to apply this technique to all so-called ‘Refactorings’ and see how many are eliminated by existing programming techniques that don’t get very much air time in advertising material (though, this might be changing thankfully). More useful might be to see how many are left standing (want to know my conjecture?).</p>
<p>Anyway, Refunctoring is what most people <strong>really are doing</strong>. They are converting their code that is written in not-too-powerful programming languages to mimic the power that is already available in functional programming languages. They are representing higher-order functions with (<em>importantly, co-variant</em>) polymorphic type parameters, refactoring out what partial application already provides and much more. This is being done, despite having been invented many, many years ago, but the fact that it <em>is</em> being done mandates a name, albeit how absurd it might be. I use the term Refunctoring, for no other reason than it was suggested to me by a bemused colleague (you know who you are :)) one day and upon reflection, I have decided that it is entirely appropriate.</p>
<p>You don’t think the <code>map</code> function is a special case do you?</p>
    </div>
  </content>
</entry>
<entry>
  <title>Ignorance is mostly bliss, but not always</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/ignorance-is-mostly-bliss-but-not-always/index.html"/>
  <id>http://blog.tmorris.net/posts/ignorance-is-mostly-bliss-but-not-always/index.html</id>
  <published>2007-02-09T13:30:51Z</published>
  <updated>2007-02-09T13:30:51Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I have been using <a href="http://www.scala-lang.org/">Scala</a> for the past few weeks to write a web framework that ‘fixes’ the convoluted Java Servlet Specification. I have succeeded in doing so and I have a prototype running on Apache Tomcat right now as I write this post, however I didn’t get to this point easily; not without first having to do such things as:</p>
<ul>
<li><p>write a lazy cons list <strong>without</strong> any methods declared on the type – rather, functions over the type that are declared in a Scala <em>object</em> (roughly analogous to Java static methods)</p></li>
<li><p>conceding to using mutable state/destructive update at some points – particularly converting strict and/or side-effecting Java types to nice, lazy, pure types</p></li>
<li><p>missing out on the syntactic niceties that monads provide – Scala does not support higher-order kinds</p></li>
</ul>
<p>Scala is what I consider a very pragmatic (to steal a buzzword from the hype generators) approach to software development as it exists today. It satisfies the incompetent assertions of the illegitimate authority (aka management) – “you must use Java (et al.)”, while still allowing a reasonably concise expression and programming paradigm e.g. Scala has pattern matching, case classes, variance annotations, higher-order functions and implicit defs (similar to Haskell type-classes). These features alone dramatically reduce the amount of repetitious work that you otherwise do in more mainstream languages by one of those crazy orders of magnitude that would never be believed by a mainstream programmer and so could easily be explained away as nonsense with support from other ill-informed peers (those who know what I mean, know what I mean).</p>
<p>I had read about <a href="http://labs.businessobjects.com/cal/">CAL</a>, but didn’t ever give it much consideration until today. And it is today that I realise that my blissful ignorance has cost me. CAL is very <em>Haskell-like</em> with full support for using Java types (just as Scala does) and compiles straight to the JVM (just as Scala does) – making up for the deficiencies of the Java runtime compiler using techniques such as tail recursive call elimination (again, just as Scala does).</p>
<p>However, upon further reading (I admit to not having used it in great detail just yet), CAL does more – much more. It is lazily evaluated and it is pure functional. It has higher-order kinds <a href="http://blog.tmorris.net/strong-type-systems/">and we know how important that is</a>. It has monads and even the <code>Monad</code> data type subtypes the <code>Functor</code> data type! Not even Haskell does that (though I’m sure things would be different given hindsight ala CAL)! Type parameters are covariant, given its pure functional nature and it makes expressing strictness much easier than it does in other lazy languages (apparently). Of course, this is all potentially a reiteration of hyperbole, since I’ve yet to try it out – but it does look promising, especially given that it has now been released under a BSD licence.</p>
<p>The point is, my ignorance (of CAL) has cost me, since I have a well thought-out, very usable web application framework (sorry <a href="http://happs.org/">HAppS</a>) that has been written in a possibly (probably) inferior language. Here I was thinking I had the best of both worlds – satisfying the pointy-haired boss, while still getting on with writing software. Though, it could be worse, <strong>much</strong> worse – I could have written it in Java/C# like many other participants in this circus are doing.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Free Thinking</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/free-thinking/index.html"/>
  <id>http://blog.tmorris.net/posts/free-thinking/index.html</id>
  <published>2007-01-30T16:08:11Z</published>
  <updated>2007-01-30T16:08:11Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I have 2 children, (almost) 6 and 4 years old, who have recently come under attack by the pawns of an elitist minority-led Christian organisation that is supported by our government and other elitist organisations. The sad part is that these so-called ‘pawns’ are unaware that indeed they are acting as pawns. The internalisation of the legitimacy of their ignorant stance has surpassed the point of conscious denial and is so prolific, that I very much doubt that this realisation will ever come to fruition. Despite this sad state of affairs, I must maintain the well-being of my children – at all costs – and this may require the absolute refusal to permit even the most remote hint of indoctrination of the purported filth to my children who are in no position to defend themselves against it. The persistence of the manipulators, and most importantly, those being manipulated, often requires quite a fervent and directed response from me – the protector of my children.</p>
<p>I am writing this post to address these people who are conducting these attacks, even though I know that it is probably futile, given their own lack of recognition of their actions. You may accuse me of “not giving my children a chance to make up their own mind” or blatantly disallowing established beliefs, despite their widespread proliferation. I accept these allegations, thank you for your (no doubt conscious) concern, but reject the legitimacy of the accusations, <strong>without further explanation</strong>. Unlike the religious establishment, free thinkers have absolutely no problem whatsoever shifting position in light of compelling evidence. My children are, and will be, free thinkers and your actions are detrimental to this objective. I withdraw any attempts to justify my position, not because I am arrogant or have some kind of personal conviction with my stance – simply, I do not wish to engage in your war. Call me Switzerland, call me a coward, call me whatever, heck, cast me to a furnace for eternity, but please don’t do it in front of my children. Please (oh please) understand.</p>
<p>Nevertheless, to express my dissent and fear for the well-being of my children is not the primary objective of this post. Instead, it is to express a common misnomer. Often times, I am accused of undermining the value of those who conduct blatant attacks with their irrational beliefs as human beings. Please be assured, I do not think less of you than another, even myself. You are an equal.</p>
<p>Some people don’t like pain – when they watch someone else smack their head on a tree, they cringe with empathy. In fact, if the poor victim could be warned of the impending danger somehow, I am sure that an empathetic person would make every effort to make it the case to prevent the infliction of pain. This is <strong>exactly</strong> my response to those who have been robbed of the ability to think critically. I have absolute, paramount sympathy for your position, well beyond that of any other position that I could possibly imagine – even extreme pain (I have had stitches in 23 separate sites on my body, including one amputation and one ‘sewing it back on’ – I have felt pain).</p>
<p>Please also be assured that my response to the attack of my children must take priority over the expression of this sympathy. My response may appear to be in complete contradiction to what I have just declared – but it is not the case universally. I must put aside my own self-indulgences in expressing sympathy when protecting my children – they are just so vulnerable and trusting.</p>
<p>Please, please understand, just for a brief moment even.</p>
<p>“None are more hopelessly enslaved than those who falsely believe they are free” -Johann Wolfgang von Goethe …and they receive my sincere condolences for the loss of control of their own mind.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Folds for Imperative Programmers</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/folds-for-imperative-programmers/index.html"/>
  <id>http://blog.tmorris.net/posts/folds-for-imperative-programmers/index.html</id>
  <published>2007-01-05T16:37:51Z</published>
  <updated>2007-01-05T16:37:51Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Coming from an imperative language such as Java/C/C# and moving to a functional language, you will almost certainly encounter ‘folding functions’. There are usually two folding functions (sometimes there are minor variants) – one folds to the right and the other folds to the left. In Haskell, these functions are named <code>foldr</code> and <code>foldl</code>.</p>
<p>This first encounter with folding functions can often be quite daunting, but I propose an alternative approach. In fact, these folding functions are almost certainly quite familiar to the imperative programmer – just without consciousness. If I had a dollar for every time I saw something like this (I’d buy every CS student a book on the lambda calculus :)):</p>
<pre class="sourceCode Java"><code class="sourceCode java">...
B accum = b;
<span class="kw">for</span>(<span class="dt">final</span> A a : as) {
  accum = f.<span class="fu">f</span>(a, accum);
}
<span class="kw">return</span> accum;</code></pre>
<p>Look familiar? Not so daunting? Great, because it’s a fold – specificially, a fold to the left. It is a fold to the left because the sequence (list, array, whatever) is iterated from the left/start to the right/end. Conversely, a fold right iterates from the right/end of the sequence to the left/start.</p>
<p>Let’s take a closer look at the ‘fold left’ above. The first line initialises an accumulator of type <code>B</code> to the given argument. Then the sequence (of <code>A</code>) is iterated and each element is passed to some function and its result assigned to the accumulator. Finally, the accumulated value is returned.</p>
<p>Have I just trivialised a seemingly complicated concept? Not at all! I have undermined its apparent complexity perhaps. On the contrary, it is the imperative language version that has complicated a trivial concept. Let’s take a look at a complete and compilable example:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">class</span> Foldr {
  <span class="dt">static</span> <span class="kw">interface</span> F&lt;A, B&gt; {
    B <span class="fu">f</span>(A a, B b);
  }

  <span class="dt">static</span> &lt;A, B&gt; B <span class="fu">foldr</span>(<span class="dt">final</span> F&lt;A, B&gt; f, <span class="dt">final</span> B b, <span class="dt">final</span> A[] as) {
    B accum = b;

    <span class="kw">for</span>(<span class="dt">int</span> i = as.<span class="fu">length</span> - <span class="dv">1</span>; i &gt;= <span class="dv">0</span>; i--) {
      accum = f.<span class="fu">f</span>(as[i], accum);
    }

    <span class="kw">return</span> accum;
  }
}

<span class="kw">class</span> Foldl {
  <span class="dt">static</span> <span class="kw">interface</span> F&lt;A, B&gt; {
    A <span class="fu">f</span>(A a, B b);
  }

  <span class="dt">static</span> &lt;A, B&gt; A <span class="fu">foldl</span>(<span class="dt">final</span> F&lt;A, B&gt; f, <span class="dt">final</span> A a, <span class="dt">final</span> B[] bs) {
    A accum = a;

    <span class="kw">for</span>(<span class="dt">final</span> B b : bs) {
      accum = f.<span class="fu">f</span>(accum, b);
    }

    <span class="kw">return</span> accum;
  }
}

<span class="kw">public</span> <span class="kw">class</span> Folds {
  <span class="kw">public</span> <span class="dt">static</span> <span class="dt">void</span> <span class="fu">main</span>(<span class="dt">final</span> String[] args) {
    <span class="dt">final</span> Integer[] i = <span class="kw">new</span> Integer[]{<span class="dv">7</span>,<span class="dv">8</span>,<span class="dv">9</span>,<span class="dv">42</span>,<span class="dv">11</span>,<span class="dv">13</span>,<span class="dv">45</span>,<span class="dv">54</span>,<span class="dv">45</span>,<span class="dv">46</span>,<span class="dv">64</span>,<span class="dv">74</span>};

    <span class="dt">final</span> Integer right = Foldr.<span class="fu">foldr</span>(<span class="kw">new</span> Foldr.<span class="fu">F</span>&lt;Integer, Integer&gt;() {
      <span class="kw">public</span> Integer <span class="fu">f</span>(<span class="dt">final</span> Integer a, <span class="dt">final</span> Integer b) {
        <span class="kw">return</span> a - b;
      }
    }, <span class="dv">79</span>, i);

    System.<span class="fu">out</span>.<span class="fu">println</span>(right);

    <span class="dt">final</span> Integer left = Foldl.<span class="fu">foldl</span>(<span class="kw">new</span> Foldl.<span class="fu">F</span>&lt;Integer, Integer&gt;() {
      <span class="kw">public</span> Integer <span class="fu">f</span>(<span class="dt">final</span> Integer a, <span class="dt">final</span> Integer b) {
        <span class="kw">return</span> a - b;
      }
    }, <span class="dv">97</span>, i);

    System.<span class="fu">out</span>.<span class="fu">println</span>(left);
  }
}</code></pre>
<p>Phew! What an effort – pass me a beer!</p>
<p>We notice in the <code>main</code> method that the types of both <code>A</code> and <code>B</code> are the same (<code>Integer</code>). This is purely consequential and these types may, and often do, differ. Also notice that our function in each case is <strong>not</strong> commutative. That is, <code>f(a, b)</code> is not necessarily equivalent to <code>f(b, a)</code>. We know this because <code>a - b</code> is not necessarily equivalent to <code>b - a</code>. If the functions were commutative, then the result of a fold right would be equivalent to the result of a fold left. If you execute the code above, you will not get the same output for each fold. Try changing the implementation of each function to be commutative (like +) and observe the equivalent results.</p>
<p>Let’s take a look at the Haskell equivalent at an interpreter:</p>
<pre><code>Prelude&gt; let i = [7,8,9,42,11,13,45,54,45,46,64,74]
Prelude&gt; foldr (-) 97 i
41
Prelude&gt; foldl (-) 79 i
-321</code></pre>
<p>Same outputs as the imperative code? Good, so that’s folds out of the way – easy peasey :)</p>
<p>By the way, yes the Haskell equivalent is supposed to be 100 times shorter – that is the nature of a relatively expressive programming language.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Strong Type Systems</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/strong-type-systems/index.html"/>
  <id>http://blog.tmorris.net/posts/strong-type-systems/index.html</id>
  <published>2007-01-01T09:32:23Z</published>
  <updated>2007-01-01T09:32:23Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I have been reading articles lately that make a case for or against ‘strong type systems’ by referring to artifacts that purport the exact opposite of a strong type system such as Java, C/C++, C# or a few other weak type systems. This is unfortunate, since the remainder of the article becomes immediately invalid within the first two or three sentences and I doubt that the author is even aware of the fact that they are wasting their own time while at the same time, misleading any potential readers. Quite often, these articles have trendy or appealing writing styles, such as “<a href="http://steve-yegge.blogspot.com/2006/12/parabola.html">Parabola</a>”, which attempts to universally refute the legitimacy of type safe (T.S. in the article) systems by making a rather clever, albeit erroneous, metaphor with a scenario in an airport.</p>
<p><a href="http://eureka3d.com/blog/?p=21">There</a> <a href="http://www.cs.oberlin.edu/~jwalker/nullObjPattern/">are</a> <a href="http://today.java.net/pub/a/today/2004/12/10/refactor.html">countless</a> articles that talk about the problems with <code>null</code>, but is this a problem with type systems? No, <strong>it is a very poor solution to work around one of the fundamental contradictions that plagues imperative programming</strong>. That is, even if we must keep this contradiction and imperative programming for some reason (which we don’t), there are better solutions than <code>null</code>. So this leaves a problem for any author who wishes to provide a higher understanding for their readers; do they explain all the problems with <code>null</code> in more formal, concise and correct terms knowing that the whole problem disappears with a better foundational grounding (eliminating imperative programming), or do they simply present some alternatives that may be unfamiliar and hope for initiative on the part of the reader who will use (the ever so common) <em>gut instinct</em> to <em>feel</em> that they have a superior solution? A horrible problem that is thankfully not mine.</p>
<p>Just what denotes Java et. al. having a weak type system? On what basis is this statement made? The answer to this question is not trivial by any means and answering it requires a reasonable amount of foundational mathematics knowledge, which leads to specialisation in type theory – both of which not many software developers have, nor have the initiative to acquire (this is sad :(). In any case, a brief attempt can be made. There is no doubting that these weak type systems disallow a certain amount of expressivity and force a rigid and sometimes unreasonable method of development. That is <strong>not</strong> to say that dynamic typing is the solution. Just like Dawkins said that since the beginning of life is so improbable as to be impossible (on the surface), then the existence of a supernatural creator is <strong>not</strong> the only alternative solution – referring to Darwinism. Whether or not you believe in a supernatural creator, it would be obscene and somewhat ignorant to immediately jump to such a conclusion without rational reason – such as critically analysing alternatives. Likewise, it is obscene to jump to the conclusion that dynamic typing solves the problems of (weak) existing type systems without considering alternatives, such as expressive type systems.</p>
<p>Using Java et. al., it is impossible to express certain fundamental programming concepts and many more concepts that are specific to the problem at hand. One such fundamental programming concept is the <em>monadic bind computation</em>. Before I start going into detail about this, I am compelled to first dispel a very common myth. Many ‘programmers’ believe that monads (and therefore, monadic bind) are not relevant to their problem, since their language does not support such a concept directly. Few programmers actually realise that they are in fact using monads, just without language support and often in a somewhat contrived manner – a result of the lack of formality in reasoning. In fact, I postulate that in my time working on IBM WebSphere 6 and the IBM JDK 1.5, I saw somewhere in the order of hundreds of monads littered throughout thousands of lines of code. Furthermore, <a href="http://blog.tmorris.net/maybe-monad-in-java">Java/C# has one particular monad built right into the language</a>. Providing concrete examples is worthy of a topic on its own, so I will instead take the liberty of claiming that if anyone were to send me their 2^gazillion LOC application, I would be capable of finding one monad per one thousand LOC – worst case scenario. At least, please assume so for now. <strong>Yes, monads are extremely important and common to programming, even if you don’t ever know it explicitly</strong>. Great, glad that is out of the way :)</p>
<p>We cannot express monadic bind with these weak type systems because they do not have <em>higher-order types</em>. What is a higher-order type? <a href="http://www.google.com/search?q=higher-order+types">A few people with much more time, specialisation and knowledge have done a better job than I am at least willing and probably capable, of doing</a>. Instead, I will attempt to demonstrate what happens when you attempt to generalise monadic bind with a weak type system. Haskell is a purely functional language that <em>does</em> have higher-order types. If we ask a Haskell interpreter for the type of bind (&gt;&gt;=), we get the following:</p>
<pre><code>Prelude&gt; :type (&gt;&gt;=)
(&gt;&gt;=) :: (Monad m) =&gt; m a -&gt; (a -&gt; m b) -&gt; m b</code></pre>
<p>This is akin to a Java/C# interface (called <code>Monad</code>) containing one function (&gt;&gt;=) or ‘bind’, however, we will note that <strong>there is no analogy for this expression in a weak type system</strong>. This fact, along with many others, seems to be quite a hurdle in grasping the very concept of the bind computation itself. If we examine this type expression, we could say that the bind function (&gt;&gt;=) takes two arguments:</p>
<ol style="list-style-type: decimal">
<li><p>a monad with a type parameter ‘a’</p></li>
<li><p>a function from ‘a’ to a monad with a type parameter ‘b’</p></li>
</ol>
<p>The function returns a monad with a type parameter ‘b’. ‘Implementing this interface’ would make the class itself an instance of <code>Monad</code> and so itself can be used as the function arguments. This is one of many things that <em>higher-order types</em> gives us.</p>
<p>Let’s attempt this with a weak type system, Java. First, we acknowledge that Java has no first-class functions (cannot pass functions as arguments), but we can loosely emulate it (good enough for our purposes) with a single interface:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> F&lt;X, Y&gt; {
  Y <span class="fu">f</span>(X x);
}</code></pre>
<p>Let’s attempt to write the <code>Monad</code> interface:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> Monad&lt;A&gt; {
  &lt;B&gt; Monad&lt;B&gt; <span class="fu">bind</span>(Monad&lt;A&gt; ma, F&lt;A, Monad&lt;B&gt;&gt; f);
}</code></pre>
<p>Looking good so far. But don’t be fooled – there is a huge problem. Namely, that the interface cannot be implemented correctly. Keeping with tradition, let’s attempt to write the <a href="http://blog.tmorris.net/maybe-in-java">Maybe monad</a>:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="dt">final</span> <span class="kw">class</span> Maybe&lt;A&gt; <span class="kw">implements</span> Monad&lt;A&gt; {
  <span class="co">// BZZT! WRONG!</span>
  Maybe&lt;A&gt; <span class="fu">bind</span>(<span class="dt">final</span> Maybe&lt;A&gt; ma, <span class="dt">final</span> F&lt;A, Maybe&lt;B&gt;&gt; f) {</code></pre>
<p>We hit our first problem, can we work around it? In Java, we have co-variant return types, but we do not have higher-order types. This means that we can keep our return type declaration, but not the types of our arguments – they <strong>must</strong> match the interface. Then, we can resort to casting – an abomination that indicates a flaw of the type system.</p>
<p>Let’s try again:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="dt">final</span> <span class="kw">class</span> Maybe&lt;A&gt; <span class="kw">implements</span> Monad&lt;A&gt; {
  <span class="kw">public</span> &lt;B&gt; Maybe&lt;B&gt; <span class="fu">bind</span>(<span class="dt">final</span> Monad&lt;A&gt; ma, <span class="dt">final</span> F&lt;A, Monad&lt;B&gt;&gt; f) {
    <span class="kw">if</span>(ma <span class="kw">instanceof</span> Maybe) {
    ...</code></pre>
<p>This solution works, but we have to admit to having to work around the type system by resorting to casting. As a result, I will no longer call it a solution, but instead, it is a work around – a flaw in the expressitivity of the type system. The lack of higher-order types in common type systems is one of many problems with quite devastating consequences. In attempting to model a fundamental computational concept, we find that the type system of Java (and many other programming languages with weak type systems) is not a sound premise from which to extrapolate conclusions about type systems in general. If we were to do so, we would be making a fundamental mistake. In fact, this particular problem is one that dynamic typing appears to solve. But don’t let these superficial appearances delude you. A stronger type system is the correct solution.</p>
<p>Here are some conclusions from these findings:</p>
<ul>
<li><p>Higher-order types are fundamental to a strong type system</p></li>
<li><p>Java/C/C++/C# et. al. do not support higher-order types, therefore, do not have a strong type system</p></li>
<li><p>Monadic bind is a relatively trivial, yet extremely common programming concept</p></li>
<li><p>Monadic bind cannot be easily expressed in common weak type systems</p></li>
<li><p>Dynamic typing is not the only apparent solution to resolving the problems of weak type systems</p></li>
</ul>
<p>Here are some questions to ponder:</p>
<ul>
<li><p>What if we tried to model a concept that is not as trivial as the bind computation? Does the difficulty of expression grow linearly to the complexity of the concept?</p></li>
<li><p>What other concepts are supported by strong type systems but not our common weak type systems?</p></li>
<li><p>Can we come up with other examples of common, trivial concepts that cannot be expressed because these weak type systems are missing some other feature besides higher-order types?</p></li>
<li><p><strong>Most importantly, what does a comparison between a type system that exemplifies sound, strong and expressive type safety with dynamic typing (or no typing) give us?</strong></p></li>
</ul>
<p>It is this latter question that needs to be explored before drawing any potentially misleading conclusions about type systems. <strong>It is a crucial mistake to make a comparison to weak type systems that do not in any way exemplify soundness, as anything else but unsound examples of type systems. The implication that dynamic typing is a correct solution is a blind-man’s fallacy.</strong></p>
<p>A compilable solution follows:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> F&lt;X, Y&gt; {
  Y <span class="fu">f</span>(X x);
}

<span class="kw">interface</span> Monad&lt;A&gt; {
  &lt;B&gt; Monad&lt;B&gt; <span class="fu">bind</span>(Monad&lt;A&gt; ma, F&lt;A, Monad&lt;B&gt;&gt; f);
}

<span class="dt">final</span> <span class="kw">class</span> Maybe&lt;A&gt; <span class="kw">implements</span> Monad&lt;A&gt; {
  <span class="kw">public</span> &lt;B&gt; Maybe&lt;B&gt; <span class="fu">bind</span>(<span class="dt">final</span> Monad&lt;A&gt; ma, <span class="dt">final</span> F&lt;A, Monad&lt;B&gt;&gt; f) {
    <span class="kw">if</span>(ma <span class="kw">instanceof</span> Maybe) {
      <span class="dt">final</span> A j = ((Maybe&lt;A&gt;)ma).<span class="fu">just</span>();
      <span class="kw">if</span> (j == <span class="kw">null</span>) {
        <span class="kw">return</span> <span class="kw">new</span> Maybe&lt;B&gt;();
      } <span class="kw">else</span> {
        <span class="dt">final</span> Monad&lt;B&gt; b = f.<span class="fu">f</span>(j);

        <span class="kw">if</span>(b <span class="kw">instanceof</span> Maybe) {
          <span class="kw">return</span> (Maybe&lt;B&gt;)b;
        } <span class="kw">else</span> {
          <span class="kw">throw</span> <span class="kw">new</span> Error(<span class="st">&quot;Just because we don&#39;t have higher-order types,&quot;</span> +
            <span class="st">&quot;doesn&#39;t mean we start doing silly stuff&quot;</span>);
        }
      }
    } <span class="kw">else</span> {
      <span class="kw">throw</span> <span class="kw">new</span> Error(<span class="st">&quot;I said stop doing silly stuff! Please!&quot;</span>);
    }
  }

  <span class="co">// Let&#39;s just hack for now.</span>
  <span class="co">// null denotes &#39;Nothing&#39;.</span>
  <span class="co">// Many programmers will be familiar</span>
  <span class="co">// with this idiom (did I say hack?)</span>
  <span class="co">// anyway.</span>
  <span class="co">//</span>
  <span class="co">// A more complete solution is provided at</span>
  <span class="co">// http://blog.tmorris.net/revisiting-maybe-in-java</span>
  <span class="kw">private</span> <span class="dt">final</span> A a;

  <span class="kw">public</span> <span class="fu">Maybe</span>() {
    <span class="kw">this</span>.<span class="fu">a</span> = <span class="kw">null</span>;
  }

  <span class="kw">public</span> <span class="fu">Maybe</span>(<span class="dt">final</span> A a) {
    <span class="kw">this</span>.<span class="fu">a</span> = a;
  }

  <span class="kw">public</span> A <span class="fu">just</span>() {
    <span class="kw">return</span> a;
  }
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>The Dawkins Delusion</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/the-dawkins-delusion/index.html"/>
  <id>http://blog.tmorris.net/posts/the-dawkins-delusion/index.html</id>
  <published>2006-12-30T13:57:05Z</published>
  <updated>2006-12-30T13:57:05Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>While the Dawkins argument against Agnosticism is the usual and incredibly weak and contradictory proposition with a touch of cognitive dissonance (sound familiar Dawkins?), I must otherwise extend an overriding congratulations and approval of any concise, calculated and importantly, successful, attack against Abrahamic theism. I strongly urge anyone of any faith to consider <a href="http://en.wikipedia.org/wiki/The_God_Delusion">The God Delusion</a> if only to learn what “all the fuss is about”, but do approach with extreme scepticism - as I’d imagine Dawkins himself would recommend.</p>
    </div>
  </content>
</entry>
<entry>
  <title>The most ironic logical proposition on the internet</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/the-most-ironic-logical-proposition-on-the-internet/index.html"/>
  <id>http://blog.tmorris.net/posts/the-most-ironic-logical-proposition-on-the-internet/index.html</id>
  <published>2006-12-20T16:55:39Z</published>
  <updated>2006-12-20T16:55:39Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I generally don’t like to dabble in silliness that can be easily misconstrued as elitist (or some other negative label), but nevertheless, I feel compelled to record what I believe is the most ironic logical proposition that is available on the internet. I am not recording this so that we can all point and laugh or anything mindless like that, but instead, to reflect on just how easy it is to make a crucial mistake in judgment particularly when you least expect it. I believe that the irony of this statement supersedes that of any propositions that have exited from the mouth of President Bush or any other equally vulnerable world leader, etc. though many have come close.</p>
<p>If we pop on over to a document titled, <a href="http://www.paulgraham.com/avg.html">Beating the Averages</a>, we find a proposition (or assumption for the remainder of the section) that is somewhat striking. Here it is:</p>
<blockquote>
<p>Lisp is so great not because of some magic quality visible only to devotees, but because it is simply the most powerful language available.</p>
</blockquote>
<p>I have lost a little bit of the context in citing this statement, so I encourage anyone to read the full script. The irony lies in the fact that the author (Paul Graham) sets about describing what he calls the “Blub Paradox”, which is defined by how computer programmers can only look back at what they once knew about computer programming languages, but cannot make sense of what might be ahead - or might not even be aware that there is anything ahead! What the author probably does not know, is that in attempt to describe the “Blub Programmer” in the third person, he has inadvertently labelled himself a Blub Programmer by his very own definition.</p>
<p>I wonder if Mr. Graham has learned of this mistake, but I sure hope someone points it out to me if (when) I make it! :)</p>
    </div>
  </content>
</entry>
<entry>
  <title>Fix it Sun!</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/fix-it-sun/index.html"/>
  <id>http://blog.tmorris.net/posts/fix-it-sun/index.html</id>
  <published>2006-12-19T13:59:41Z</published>
  <updated>2006-12-19T13:59:41Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>This is a call out to renew pressure for Sun to fix the <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4726340">tail call elimination defect/RFE</a> that has existed in HotSpot since inception and still exists today. The IBM JIT is very much capable of tail call elimination, as is the .NET CLR (it even has an instruction built-in!) but still Sun’s weak compiler dominates our industry and stifles further innovation in software development.</p>
<p>It has long been known that imperative programming has some inherent weaknesses and <a href="http://scala.epfl.ch/docu/files/ScalaByExample.pdf">people</a> <a href="http://docs.msdnaa.net/ark_new/Webfiles/WhitePapers/Babel01/bab12.pdf">all</a> <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=176597">around</a> <a href="http://citeseer.ist.psu.edu/schinz01tail.html">the</a> <a href="http://www.delorie.com/gnu/docs/kawa/scm2java.html">place</a>, who recognise this weakness, are trying to remedy it, only to be stopped in their tracks by the fact that this industry continues to use a very poorly implemented compiler.</p>
<p>Today, fixing this defect is not in Sun’s interest (nor that of IBM). In fact, doing so may well speed up the death of its programming language by many orders of magnitude. I postulate that as <a href="http://gafter.blogspot.com/2006/08/closures-for-java.html">Sun squeezes its last few breaths out of Java</a> and as more and more people enlighten themselves with much more powerful alternatives, Sun will inevtiably concede to this pressure. I declare that I have an agenda to speed up this process. Therefore, I would like to apply pressure to Sun to fix this defect so that thousands of existing software clients across the world have a smoother migration path into a more innovative and ultimately, more productive, software development environment. After all, corporations are not necessarily all about stifling innovation, <a href="http://www.google.com/corporate/tenthings.html">are they</a>?</p>
    </div>
  </content>
</entry>
<entry>
  <title>Maybe Monad in Java</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/maybe-monad-in-java/index.html"/>
  <id>http://blog.tmorris.net/posts/maybe-monad-in-java/index.html</id>
  <published>2006-12-18T14:06:35Z</published>
  <updated>2006-12-18T14:06:35Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>As <a href="http://blog.tmorris.net/maybe-in-java">I have shown previously</a>, the problem of partial function in Java is not easily solved. The solution of the Maybe algebraic data type, while definitely superior to existing options, is cumbersome to implement and requires some functions defined over the type (isJust, isNothing, etc.) in order to be complete. As some point out, there is a preference for continuation passing to prevent the need for a cast (even though this cast would be hidden). This prompted me to provide a <em><a href="http://blog.tmorris.net/revisiting-maybe-in-java">more complete, yet still incomplete</a></em> solution.</p>
<p>It is also worth noting that the solution with continuation passing <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4726340">will not work on the Sun VM due to its lack of tail call elimination</a>. i.e. some concessions must be made somewhere - manual compiler optimisations if you will :) There were also some observers who <a href="http://programming.reddit.com/info/qt96/comments/cqx5q">didn’t quite get it</a>. Nevertheless, many of us will go on using null/exceptions in Java or their own implementation of Maybe in Java (feel free to steal mine if you like), while others will use Haskell’s Data.Maybe, Scala’s Some/None, Nice’s option types or whatever.</p>
<p>All this aside, I am writing this post to introduce the Maybe Monad in Java, not to demonstrate anything meaningful or clever. Rather, I wish to simply point out to Java programmers what this abstract and apparently mystical notion of a monad - taken from the mathematical branch of category theory - really is. We now know that exceptions are <strong>only ever</strong> used for representing a partial function (even for I/O!) and we know that the Java programming language has built-in language and API support for exceptions. Let’s just revisit what the concept of a ‘partial function’ means exactly. It means that “there exists”[<em>see note 1</em>] some x take from our <em>universe of discourse</em> (U) such that f(x) is undefined.</p>
<p>Sound scary? It’s not really. Suppose we have a data type, <code>int</code>. The size of our universe of discourse is finite; it is 2^32. We can represent this as |U| = 2^32. The notation f(x) represents some function with x applied. Having a universe of discourse of finite size implies that we can do an exhaustive proof for behaviour of the function, though not necessarily in a reasonable amount of time.</p>
<p>Let’s call a function ‘divide’ and x can be two ints, a and b. The size of our universe of discourse of our arguments is 2^32 * 2^32 (i.e. 2 ^ 64) because that is the total number of combinations for the values of its arguments that are available. We can say that for our function, divide, it holds that for all[<em>see note 2</em>] a and for b = 0, the function is undefined. That is, regardless of the value of a, if the value of b is 0, the function is undefined:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="dt">int</span> a = <span class="kw">... </span><span class="co">// anything</span>
<span class="dt">int</span> b = <span class="dv">0</span>;
<span class="fu">divide</span>(a, b); <span class="co">// undefined</span></code></pre>
<p>If we try to use this function with b = 0, we will observe an exception (ArithmeticException). If we were using reference types, we could write our own divide function that instead returns <code>null</code> or returns <code>Maybe&lt;Integer&gt;</code> and Nothing for the case of an undefined function application.</p>
<p>Have we got it? Great! :) The Maybe Monad is used for defining a partial function that might call 2 or more partial functions; if any of those functions called are undefined, then our function that we are writing is undefined. This might be called, “<em>threading partial function through a computation</em>”. We could write it in pseudo-code:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">f x <span class="fu">=</span> <span class="kw">if</span> isNothing (g x)
            <span class="kw">then</span> <span class="fu">return</span> <span class="kw">Nothing</span>
            <span class="kw">else</span> <span class="kw">if</span> isNothing (h (g x))
              <span class="kw">then</span> <span class="fu">return</span> <span class="kw">Nothing</span>
              <span class="kw">else</span> <span class="fu">return</span> maybeToJust (h (g x))</code></pre>
<p>Very cumbersome to write and I sure hope that the function f doesn’t need to use more than 2 partial functions (g and h) in order to define! It would be great if you could write something similar to this instead…</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">f x <span class="fu">=</span> h (g x)</code></pre>
<p>…and not have to worry about “<em>threading partial function through the computation</em>”. Those familiar with Haskell, or those who are trying to understand monads in a Haskell context, should hopefully recognise the latter syntax as <em>do-notation</em>. Those who are not familiar with do-notation can just know that Haskell provides language support for this notion of threading computation, represented by the more familiar term, monads. This support is provided with a language keyword called <code>do</code> (<strong>very</strong> different to do/while in an imperative language!).</p>
<p>Anyway, this post is getting a bit long and I still haven’t introduced Java’s monad for threading partial function through a computation. Luckily, it is not very long to write so without further ado, I introduce it as follows:</p>
<pre><code>throws</code></pre>
<p>“WTF!!? You mean I have been using monads all along!!? How can that be!?” Well, it has been stated more than once, that many people <a href="http://sigfpe.blogspot.com/2006/08/you-could-have-invented-monads-and.html">have already used monads</a>, even if they didn’t call it that. In recent years, fundamental computer programming concepts have often been confused with euphemisms like “design patterns” or some such, so rather than speculate at an analogy that might be familiar, I will instead turn focus on the Java <code>throws</code> keyword.</p>
<p>Consider the following rough Java code:</p>
<pre class="sourceCode Java"><code class="sourceCode java">T <span class="fu">foo</span>() <span class="kw">throws</span> IOException {
  H handle = <span class="fu">openFile</span>(); <span class="co">// this method declares throws IOException</span>

  <span class="kw">try</span> {
    <span class="fu">maybeDoSomeStuff</span>(handle); <span class="co">// this method declares throws IOException</span>
    <span class="co">// then</span>
    <span class="kw">return</span> <span class="fu">someFunction</span>(handle); <span class="co">// this method declares throws IOException</span>
  } <span class="kw">finally</span> {
    <span class="fu">close</span>(handle); <span class="co">// this method declares throws IOException</span>
  }
}</code></pre>
<p>We see quite clearly that if any of the invoked methods are undefined then our entire method (<code>foo</code>) is also undefined - by returning with an exception instead of a type T. Sound familiar yet? Since we know that exceptions are only ever used to represent partial function, then we can infer that the <code>throws</code> keyword is indeed a (poor man’s) Maybe Monad in disguise. I note at this point that the Maybe Monad is one of a possible squillion monads that are used in every day programming; <em>even</em> in the weakest of programming languages. Here are a couple that are used very often though not necessarily with built-in language support:</p>
<ul>
<li><p>The list monad - building up a list or threading a list through a computation</p></li>
<li><p>The state monad - passing “state” through a computation</p></li>
</ul>
<p>The lesson from this somewhat lossy representation of a monad - that is hopefully familiar to most people - is that monads are not anything overly complicated or abstruse despite initial appearances. It requires very little brain power to digest the concept coming from a nil set of knowledge, but unfortunately, it appears to take a considerable effort if the subject has been “tainted” with ill-conceived presuppositions such as imperative programming languages.</p>
<p>Be assured, the lesson is brief. Be warned, the lesson is very self-confrontational.</p>
<p>[1] This is called existential quantification and is often denoted by the symbol ∃ [2] This is called universal quantification and is often denoted by the symbol ∀</p>
    </div>
  </content>
</entry>
<entry>
  <title>Software requirements do not change</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/software-requirements-do-not-change/index.html"/>
  <id>http://blog.tmorris.net/posts/software-requirements-do-not-change/index.html</id>
  <published>2006-12-10T21:19:33Z</published>
  <updated>2006-12-10T21:19:33Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>There is quite a prolific myth that seems to have a grip on the collective software development industry. Often in communication with another software developer, the notion of a “change in requirement” will surface and I am forced to remind that developer that no such thing ever occurs - that the internalisation of this logical fallacy is in fact, quite detrimental to the purpose of creating software, fulfilling software requirements and should be abandoned. Since no such thing as a software requirement change ever occurs, the remainder of the conversation is invalidated making communication very difficult. Who’s responsibility is it to establish a sound knowledge in the fundamental concepts of their selected profession? Not mine - I am forced to cease the conversation. After all, I don’t explain to my doctor what my problem is - only my symptoms - hence, I am not a doctor. But I’ll bet doctors speak in a “language” that is beyond my capability of comprehending (though I have picked up a term or two having lived with a midwife for years :)). We software developers should be doing the same, but it does not seem to be the case.</p>
<p>Software is a function from some given inputs to some given outputs (a lambda if you will) and importantly, given some inputs, the same output should always result, <strong>always</strong>. It should not return some other result; it should not format your hard disk every second time and it shouldn’t cause the universe to implode or anything crazy like that - just consistently return the same value for its given inputs. This property is called <em>referential transparency</em>. Let’s look at a specific piece of software called ‘touch’. It takes as input:</p>
<ol style="list-style-type: decimal">
<li><p>a file system</p></li>
<li><p>a list of characters</p></li>
</ol>
<p>It provides one output - a new file system. If a file of the given name exists on the given file system, return the new file system with that file having an updated modified time stamp, otherwise, return the new file system with an additional empty file of the given name. That’s it - nothing more to it. We might even express this software more formally as follows:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="co">-- &quot;Given a FileSystem,</span>
<span class="co">--   then a list of characters (Char),</span>
<span class="co">--   return a new FileSystem.&quot;</span>
<span class="co">-- :: means &#39;is of type&#39;</span>
<span class="ot">touch ::</span> <span class="dt">FileSystem</span> <span class="ot">-&gt;</span> [<span class="dt">Char</span>] <span class="ot">-&gt;</span> <span class="dt">FileSystem</span>
touch fs filename <span class="fu">=</span> <span class="kw">if</span> fs <span class="ot">`contains`</span> filename
  <span class="kw">then</span> fs <span class="ot">`updateTimestamp`</span> filename
    <span class="kw">else</span> fs <span class="ot">`addEmptyFile`</span> filename</code></pre>
<p>The ‘touch’ software is so fundamental, that most reasonable operating systems provide it without any explicit user intervention - try running it and see.</p>
<p>While you are free to come up with all sorts of wild and complex examples of software, I’m going to simplify a little with a new example. Suppose a client approaches you, a software developer, on Monday, with the following requirement; “given two integers, sum them, multiply by 4 and give me the result.” Here is the software written in Java:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="dt">int</span> <span class="fu">software</span>(<span class="dt">int</span> a, <span class="dt">int</span> b) {
    <span class="kw">return</span> (a + b) * <span class="dv">4</span>;
}</code></pre>
<p>Easy peasey! On a side note, write it in Haskell, then play ‘spot the difference’ with the client problem statement and the code. Fun hey? :)</p>
<p>If the client approaches you on Tuesday with the following, “given two integers, subtract the first from the last. multiply by 4 and give me the result.”, then it is <strong>imperative</strong> to understand that this is <strong>a new requirement</strong>. A software requirement holds from inception until the collapse of the universe. You might argue, “but the old one and the same one look almost the same”, in which case, feel free to write the second one by applying your favourite delta compression algorithm, but by no means should the former be <em>replaced</em> by the latter. You might also argue, “but the client said it is a change”. Well I hope my doctor doesn’t follow any advice that I give him on my condition at the time since I am not well versed in medical practice. I do not say, “I have a headache, I need to fix it with these drugs” or if I did, the doctor, being aware of my naivety, would ignore my advice and only consider the symptom (I would hope!). Likewise, clients do not project their false view of software into their final product and instead, trust the better judgment of a more trained practitioner (ideally).</p>
<p>If we take the common (not that I accept its legitimacy in this form) approach of unit testing and I write <code>assert(software(42, 43) == 340)</code>, then this statement should hold forever. If it does not, then you have broken your contract to all clients of your software. The typical refutation to this assertion involves the developer ascertaining that no software clients have ever existed and so it is safe to continue. For example, if there is even a slight suspicion of a client, that developer might first deduce that if there is, then those client(s) are in the room. Then that developer asks all people in the room to commit their code so that she can search for occurrences of its use. If none are found, the software is removed, code committed and all persons in the room are instructed to update. Otherwise, if it is found that one or more clients exist, manual contingency measures are engaged.</p>
<p>The regularity of the occurrence of no clients bound to your software is often over-estimated. Just take a look at <a href="http://www.drizzle.com/~lettvin/2006/11/windows-shutdown-crapfest.html">the mess that Microsoft has itself in with an attempt to ‘separate out the components of Windows’</a> or any of the other countless examples that surround us. You might say, “but I am a consultant with only one client”. This is not true; in fact, the client/provider relationship can often be self-referential. It is <em>entirely coincidental</em> that no clients have bound to your software, but rarely is it so.</p>
    </div>
  </content>
</entry>
<entry>
  <title>defmacro[1] = defmacro[0] + 1</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/defmacro1-defmacro0-1/index.html"/>
  <id>http://blog.tmorris.net/posts/defmacro1-defmacro0-1/index.html</id>
  <published>2006-12-06T11:33:57Z</published>
  <updated>2006-12-06T11:33:57Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I read an article a while back that made some claims that were <strong>oh so true</strong>. One such claim I will reproduce here because it is one that is in violation of mainstream, but portrays so much truth in so few words. I hope my reproduction is OK with the original author.</p>
<blockquote>
<p>Most people I’ve met have read the Design Patterns book by the Gang of Four. Any self respecting programmer will tell you that the book is language agnostic and the patterns apply to software engineering in general, regardless of which language you use. This is a noble claim. Unfortunately it is far removed from the truth.</p>
</blockquote>
<p>Doesn’t it look shiny? No polish required :) I think it would make a great wall hanging.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Is There Anybody Out There?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/is-there-anybody-out-there/index.html"/>
  <id>http://blog.tmorris.net/posts/is-there-anybody-out-there/index.html</id>
  <published>2006-11-28T13:43:52Z</published>
  <updated>2006-11-28T13:43:52Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I have met thousands of people in my life. Of all those people, each can be described in one of four ways:</p>
<ol style="list-style-type: decimal">
<li><p>The person understands monads and would never, without duress, use an imperative programming language</p></li>
<li><p>The person does not understand monads, would like to and has embarked on doing so in some form</p></li>
<li><p>The person does not understand monads and would not like to (my doctor for example)</p></li>
<li><p>The person does not understand monads and in an attempt to do so, has created erroneous simplifications since “not knowing” should be defended at all costs - even if it implies the creation of a false and somewhat convenient reality</p></li>
</ol>
<p>I implore any person <strong>not</strong> to fall into the latter category, but I do understand that this imploration is based on <strong>my</strong> value system, which has a strong emphasis on the philosophy of epistemology. If the phrase, “ignorance is bliss” (without the negative connotation), is valuable to you, then so be it. I am also very keen to know of any persons who cannot be described this way, but to date, I have found none.</p>
<p>My school friends were sad when they found out that Santa Claus was not real - I was angry.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Australians in sport</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/australians-in-sport/index.html"/>
  <id>http://blog.tmorris.net/posts/australians-in-sport/index.html</id>
  <published>2006-11-22T11:27:18Z</published>
  <updated>2006-11-22T11:27:18Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>If you live in Australia and you own a television, you’ll likely be aware of the retirement of Ian Thorpe - one of our best swimmers. As per usual for the media, the coverage of “Thorpy’s” retirement is disproportionate to the event and no doubt we (Australians) will be hearing about it for days to come, with follow ups of course. Personally, I do not enjoy watching swimming, regardless of the speed of the “fish” at hand - I find it boring, though I do admire the athleticism, training and dedication of its participants.</p>
<p>While Thorpe’s achievements in swimming should not be undermined, I turn attention to a sport that over the last couple of decades has lost the spotlight with respect to the media and remind Australians of some of our other courageous sports-persons. I hope Thorpey is grateful for my attempted diversion :) It must be horrible having a live and detailed personal profile plastered nation-wide.</p>
<p>David Palmer is an Australian who has held the world number 2 - repeat, <strong>world number 2</strong> - position on the Professional Squash Association rankings list for <strong>almost all of 2006</strong>. I say “almost” because he achieved <strong>world number 1</strong> in February and world number 4 in January. While his profile is not as high as our beloved Thorpe, he is just as strong an athlete and being a competition squash player myself, I have a personal admiration for the skill of players at his level, since they are skills that I aspire to.</p>
<p>If we take a look at the <a href="http://www.psa-squash.com/entry/ranking.php">PSA World Rankings</a>, we also note some other Australians; Anthony Ricketts, Stewart Boswell and Cameron Pilley, all of which I watch with awe as they perform on a squash court. If we turn our attention then to women, we have the two “Grinham sisters” within the top 5 and some rising Australian stars following on the <a href="http://www.wispa.net/view_rankings.asp">WISPA World Rankings</a>.</p>
<p>As Australia becomes the 52nd state of America (culturally and politically), we lose some of our tradition and along with it, our love of the sport of squash - Americans have a negative stigma attached to squash as they generally prefer racquetball, though I believe or at least, hope, that this is changing with some “education” i.e. Trying It And Seeing. You’ll note many British and Middle-Easterners on the world rankings list. Nevertheless, Australians need to be reminded of some of our equally talented athletes in other disciplines besides “getting from one end of the pool to the other as quick as you can”.</p>
<p>Cheers to Thorpey.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Revisiting Maybe in Java</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/revisiting-maybe-in-java/index.html"/>
  <id>http://blog.tmorris.net/posts/revisiting-maybe-in-java/index.html</id>
  <published>2006-11-16T15:36:30Z</published>
  <updated>2006-11-16T15:36:30Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>I posted the link to <a href="http://blog.tmorris.net/maybe-in-java">Maybe in Java</a> to programming.reddit.com and waited a good… hour or so, before giving up and going to bed. Actually, I happened to lose interest in posting it and by-chance, noticed my web browser still hadn’t completed the request on the way to bed. Nevertheless, it seems my HTTP request managed to make it there and when I woke up the next morning, there were all sorts of comments floating around. A few in particular asking something along the lines of, “what exactly has been achieved?”.</p>
<p>I will answer this question with “I have pointed out to Java programmers the concept of a very basic <em>algebraic data type</em> and importantly, in their language”. No mathematics, no type theory, nothing that will scare away your average J2EE Joey Jumper. I have also made a subliminal point of “hey! there are languages that already do this, only better!”. In particular, I have not provided anything that you should all go out and start using on your next WebSphere-fronted, RDBMS-backed, one-trillion-gazillion LOC web application. It seems the following points were missed in my original writing:</p>
<ul>
<li><p>Throwing an exception is one of our possible options for evaluation of a partial function in Java. Here are all our options available in Java: … Emulate continuation passing style (CPS)</p></li>
<li><p><code>data Maybe a = Just a | Nothing</code> (the Haskell equivalent i.e. omitting instances)</p></li>
<li><p>I’ll let your imagination run wild with possibilities from here :)</p></li>
</ul>
<p>To remedy this situation, I have added further to the original Maybe type <em>which was intentionally left incomplete</em>, and it is <strong>still not complete</strong>. I hope this will help those who haven’t made the leap to do so and those who have made the leap, to understand my objective in this writing.</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">abstract</span> <span class="kw">class</span> Maybe&lt;t&gt; {
  <span class="kw">private</span> <span class="fu">Maybe</span>() {
  }

  <span class="kw">public</span> <span class="kw">abstract</span> &lt;q&gt; Q <span class="fu">maybe</span>(JustC&lt;Q, T&gt; jc, NothingC&lt;q&gt; nc);

  <span class="kw">public</span> <span class="dt">static</span> <span class="kw">abstract</span> <span class="kw">class</span> Nothing&lt;t&gt; <span class="kw">extends</span> Maybe&lt;t&gt; {
    <span class="kw">private</span> <span class="fu">Nothing</span>() {
    }
  }

  <span class="kw">public</span> <span class="dt">static</span> <span class="kw">abstract</span> <span class="kw">class</span> Just&lt;t&gt; <span class="kw">extends</span> Maybe&lt;t&gt; {
    <span class="kw">private</span> <span class="fu">Just</span>() {
    }

    <span class="kw">public</span> <span class="kw">abstract</span> T <span class="fu">just</span>();
  }

  <span class="kw">public</span> <span class="dt">static</span> &lt;r&gt; Maybe&lt;r&gt; <span class="fu">_just</span>(<span class="dt">final</span> R r) {
    <span class="kw">return</span> <span class="kw">new</span> Just&lt;r&gt;() {
      @Override
      <span class="kw">public</span> R <span class="fu">just</span>() {
        <span class="kw">return</span> r;
      }

      @Override
      <span class="kw">public</span> &lt;q&gt; Q <span class="fu">maybe</span>(<span class="dt">final</span> JustC&lt;Q, R&gt; jc, <span class="dt">final</span> NothingC&lt;q&gt; nc) {
        <span class="kw">return</span> jc.<span class="fu">c</span>(r);
      }
    };
  }

  <span class="kw">public</span> <span class="dt">static</span> &lt;r&gt; Maybe&lt;r&gt; <span class="fu">_nothing</span>() {
    <span class="kw">return</span> <span class="kw">new</span> Nothing&lt;r&gt;() {
      @Override
      <span class="kw">public</span> &lt;q&gt; Q <span class="fu">maybe</span>(<span class="dt">final</span> JustC&lt;Q, R&gt; jc, <span class="dt">final</span> NothingC&lt;q&gt; nc) {
        <span class="kw">return</span> nc.<span class="fu">c</span>();
      }
    };
  }
}

<span class="kw">public</span> <span class="kw">interface</span> JustC&lt;Q, R&gt; {
  Q <span class="fu">c</span>(R r);
}

<span class="kw">public</span> <span class="kw">interface</span> NothingC&lt;q&gt; {
  Q <span class="fu">c</span>();
}</code></pre>
<p>Those of you familiar with the Visitor Design Pattern (or any other GoF design euphemism) will immediately recognise the modification - hence the title of the post :). Please feel free to replace identifiers with your preferred view of the world; continuation, quasi-continuation, visitor, whatever.</p>
<p>For those who <em>insist</em> on returning <code>null</code> or throwing an exception/error, or more so, insist on failing to recognise the distinction, I have yielded to your pressure:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">public</span> <span class="dt">final</span> <span class="kw">class</span> NullNothingC&lt;t&gt; <span class="kw">implements</span> NothingC&lt;t&gt; {
  <span class="kw">public</span> T <span class="fu">c</span>() {
    <span class="kw">return</span> <span class="kw">null</span>;
  }
}

<span class="kw">public</span> <span class="dt">final</span> <span class="kw">class</span> ErrorNothingC&lt;t&gt; <span class="kw">implements</span> NothingC&lt;t&gt; {
  <span class="kw">public</span> T <span class="fu">c</span>() {
    <span class="kw">throw</span> <span class="kw">new</span> Error();
  }
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>Maybe in Java</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/maybe-in-java/index.html"/>
  <id>http://blog.tmorris.net/posts/maybe-in-java/index.html</id>
  <published>2006-11-13T21:02:42Z</published>
  <updated>2006-11-13T21:02:42Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>In Haskell, there is an <em>algebraic data type</em> called <code>Maybe</code> to represent evaluation of a partial function. That is, if you have a function, say f(x), and f(x) is defined for some x, but not <strong>all</strong> x, you return either:</p>
<ul>
<li><p>A type Maybe that has a value available - called Just a where a is the value - representing defined function evaluation.</p></li>
<li><p>A type Maybe that has no value available - called Nothing - representing undefined function evaluation.</p></li>
</ul>
<p>In fact, if we were to look at the source for the Maybe algebraic data type in <a href="http://www.haskell.org/ghc/">GHC</a>, we’d see this:</p>
<p><code>data Maybe a = Just a | Nothing</code></p>
<p>Not much to it, eh!? This Haskell snippet can be read as “Declare type Maybe with one polymorphic unbound variable ‘a’ that can be constructed as either Just ‘a’ or Nothing”.</p>
<p>Consider a real Java example, <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html#get(int)"><code>List.get(int index)</code></a>, which returns a type T where T is a type parameter (it once returned type Object prior to 1.5). For some Lists and some ints, this function is undefined. For example, for the list [1,2,3] and the int 7, List.get is undefined. In fact, this will throw an <code>IndexOutOfBoundsException</code> if attempted:</p>
<p><code>java.util.Arrays.asList(new Integer[]{1, 2, 3}).get(7);</code></p>
<p>Throwing an exception is one of our possible options for evaluation of a partial function in Java. Here are all our options available in Java:</p>
<ul>
<li><p>Return <code>null</code></p></li>
<li><p>Throw a compile-time checked exception</p></li>
<li><p>Throw an unchecked exception</p></li>
<li><p>Emulate continuation passing style (CPS)</p></li>
</ul>
<p>I have distinguished checked and unchecked exceptions for a specific reason that I’ll leave for another day and I won’t go into great detail about any of these options in specific, since I am currently in the middle of documenting all this in more detail along with some basic type theory. However I will note that each of these options for evaluation of a partial function have some kind of nasty consequence. For example, the value <code>null</code> is assignable to any reference type and so can inadvertently be passed along to a method (I am sure you have seen this before):</p>
<pre class="sourceCode Java"><code class="sourceCode java">T t = <span class="fu">f</span>(x);
<span class="co">// is t null?</span>
<span class="co">// the compiler doesn&#39;t force us to check!</span>
<span class="co">// how does the method behave now?</span>
<span class="fu">method</span>(t);</code></pre>
<p>And how long has that checked/unchecked exception debate been going? Yes there is a reason it has been going for so long - in fact, it is riding on a flawed premise so it will continue on forever until its participants realise this flaw - but we’ll leave that for another day and smile and nod in the meantime. :)</p>
<p>With a Maybe data type, we might instead write our function/method as:</p>
<p><code>Maybe List.get(int index)</code></p>
<p>…where undefined behaviour is denoted by returning Nothing and defined behaviour is denoted with Just T. We should also be assured that only one of these two things will occur. No more returning null, no more throwing exceptions!! How wonderful would that be!? Well, if you’ve ever dabbled in Haskell or type theory, you’ll know immediately how great that would be - but what about Java?</p>
<p>An initial and naive attempt to emulate Maybe fails immediately:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> Maybe&lt;t&gt; {
  T <span class="fu">get</span>();
}</code></pre>
<p>We see that we have isolated our apparent anomaly that we are trying to resolve. We must still either return null or throw an exception from the Maybe.get method, but no other method ever need do so - as long as we (hopefully) remember to check for null for any given Maybe. While a slight improvement, this of course, does not solve our problem. We are still returning null or throwing exceptions and importantly, suffering the adverse consequences of doing so (we want the compiler to fail, not have to remember to do stuff!). Instead, we need to use types to represent Just and Nothing. Let’s try another attempt.</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> Maybe&lt;t&gt; {
}

<span class="kw">interface</span> Just&lt;t&gt; <span class="kw">extends</span> Maybe&lt;t&gt; {
  T <span class="fu">get</span>();
}

<span class="kw">interface</span> Nothing&lt;t&gt; <span class="kw">extends</span> Maybe&lt;t&gt; {
}</code></pre>
<p>Done!! Or not. There is a specific guarantee that our Haskell data type makes that our Java attempt doesn’t. Specifically, if a Maybe is not Just, then it is definitely Nothing and vice versa in Haskell - this is important if we are to continue. We can see that this constraint does not hold for our Java Maybe because it can have any number of sub-types - of course - since it is an interface. We know how to constrain a type to have zero sub-types; by using a class with the <code>final</code> keyword. We know how to free a type to have infinite sub-types; without the <code>final</code> keyword or an interface. But what about constraining a type to 2 <strong>and only 2</strong> sub-types?</p>
<p>This can be achieved by exploiting a little known Java language feature - a type cannot be sub-typed if it has only private constructors <strong>unless those sub-types are nested in the super-type</strong>. It seems we can indeed have a Maybe algebraic data type in Java by having 2 and only 2 sub-types!</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">abstract</span> <span class="kw">class</span> Maybe&lt;t&gt; {
  <span class="kw">private</span> <span class="fu">Maybe</span>() {
  }

  <span class="kw">public</span> <span class="dt">static</span> <span class="kw">abstract</span> <span class="kw">class</span> Nothing&lt;t&gt; <span class="kw">extends</span> Maybe&lt;t&gt; {
    <span class="kw">private</span> <span class="fu">Nothing</span>() {
    }
  }

  <span class="kw">public</span> <span class="dt">static</span> <span class="kw">abstract</span> <span class="kw">class</span> Just&lt;t&gt; <span class="kw">extends</span> Maybe&lt;t&gt; {
    <span class="kw">private</span> <span class="fu">Just</span>() {
    }

    <span class="kw">public</span> <span class="kw">abstract</span> T <span class="fu">just</span>();
  }
}</code></pre>
<p>Looking good so far. We now know for sure that <strong>every</strong> instance of Maybe is either Just or Nothing and if it is Just, we have a value available through the get method - exactly what we ordered. As it stands though, we cannot create instances - let’s expose these through public methods.</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">abstract</span> <span class="kw">class</span> Maybe&lt;t&gt; {
  <span class="kw">private</span> <span class="fu">Maybe</span>() {
  }

  <span class="kw">public</span> <span class="dt">static</span> <span class="kw">abstract</span> <span class="kw">class</span> Nothing&lt;t&gt; <span class="kw">extends</span> Maybe&lt;t&gt; {
    <span class="kw">private</span> <span class="fu">Nothing</span>() {
    }
  }

  <span class="kw">public</span> <span class="dt">static</span> <span class="kw">abstract</span> <span class="kw">class</span> Just&lt;t&gt; <span class="kw">extends</span> Maybe&lt;t&gt; {
    <span class="kw">private</span> <span class="fu">Just</span>() {
    }

    <span class="kw">public</span> <span class="kw">abstract</span> T <span class="fu">just</span>();
  }

  <span class="kw">public</span> <span class="dt">static</span> &lt;t&gt; Maybe&lt;t&gt; <span class="fu">_just</span>(<span class="dt">final</span> T t) {
    <span class="kw">return</span> <span class="kw">new</span> Just&lt;t&gt;() {
      <span class="kw">public</span> T <span class="fu">just</span>() {
        <span class="kw">return</span> t;
      }
    };
  }

  <span class="kw">public</span> <span class="dt">static</span> &lt;t&gt; Maybe&lt;t&gt; <span class="fu">_nothing</span>() {
    <span class="kw">return</span> <span class="kw">new</span> Nothing&lt;t&gt;() {
    };
  }
}</code></pre>
<p>And so there we have it - an algebraic data type in Java for evaluation of a partial function. How does our List method look now? How about this:</p>
<p><code>Maybe List.get(int index)</code></p>
<p>Clients of this method will now check if the return type is either Just or Nothing and in the case of Just, perform a downcast and retrieve the value. No more returning null. No more throwing exceptions. Not ever!</p>
<p>I’ll let your imagination run wild with possibilities from here :)</p>
<p>As I have mentioned, I plan to go into greater detail about this problem by documenting it in detail so keep an eye out on the <a href="http://workingmouse.com/research">Workingmouse Research</a> page.</p>
<p>Until then, I’ll keep you wondering will a small piece of interesting code:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">import java.util.List;</span>
<span class="kw">import java.util.LinkedList;</span>
<span class="kw">import java.util.Map;</span>
<span class="kw">import java.util.Hashtable;</span>

<span class="kw">class</span> ListMap {
  <span class="kw">public</span> <span class="dt">static</span> <span class="dt">void</span> <span class="fu">main</span>(String[] args) {
    Map&lt;Integer, String&gt; map =
      <span class="kw">new</span> Hashtable&lt;Integer, String&gt;();
    map.<span class="fu">put</span>(<span class="dv">0</span>, <span class="st">&quot;x&quot;</span>);
    map.<span class="fu">put</span>(<span class="dv">1</span>, <span class="st">&quot;y&quot;</span>);
    map.<span class="fu">put</span>(<span class="dv">2</span>, <span class="st">&quot;z&quot;</span>);

    List&lt;string&gt; list =
      <span class="kw">new</span> LinkedList&lt;string&gt;();
    list.<span class="fu">add</span>(<span class="dv">0</span>, <span class="st">&quot;x&quot;</span>);
    list.<span class="fu">add</span>(<span class="dv">1</span>, <span class="st">&quot;y&quot;</span>);
    list.<span class="fu">add</span>(<span class="dv">2</span>, <span class="st">&quot;z&quot;</span>);

    <span class="co">// xyz</span>
    System.<span class="fu">out</span>.<span class="fu">println</span>(map.<span class="fu">get</span>(<span class="dv">0</span>) + map.<span class="fu">get</span>(<span class="dv">1</span>) + map.<span class="fu">get</span>(<span class="dv">2</span>));
    <span class="co">// xyz</span>
    System.<span class="fu">out</span>.<span class="fu">println</span>(list.<span class="fu">get</span>(<span class="dv">0</span>) + list.<span class="fu">get</span>(<span class="dv">1</span>) + list.<span class="fu">get</span>(<span class="dv">2</span>));

    <span class="co">// returns null</span>
    System.<span class="fu">out</span>.<span class="fu">println</span>(map.<span class="fu">get</span>(<span class="dv">7</span>));
    <span class="co">// throws IndexOutOfBoundsException</span>
    System.<span class="fu">out</span>.<span class="fu">println</span>(list.<span class="fu">get</span>(<span class="dv">7</span>));
  }
}</code></pre>
    </div>
  </content>
</entry>
<entry>
  <title>APLAS ‘06</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/aplas-06/index.html"/>
  <id>http://blog.tmorris.net/posts/aplas-06/index.html</id>
  <published>2006-11-09T07:46:21Z</published>
  <updated>2006-11-09T07:46:21Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>After surviving day 1 of the <a href="http://www.cse.unsw.edu.au/~aplas06/">Fourth ASIAN Symposium on Programming Languages and Systems</a>, I have to say it is refreshing to be reminded of how much academic work is being put into providing solutions to the diverse set of software problems that exist today. I use the term “surviving” to annotate my lack of coherence as a result of attending the <a href="http://www.u2-vertigo-tour.com/">U2 Vertigo concert in Brisbane</a> the night before and having received a total of 90 minutes sleep (0230-0400) before heading to the airport bound for Sydney on a 0530 (GMT +1000) flight. Since my spatial ability is generally proportional to the quality of my sleep, I have had to memorise much of the latter part of day 1 of APLAS ’06 - ready for processing at a later date - batch processing if you will :)</p>
<p>There were some excellent presentations - all of extremely high quality - and more than expected in my specific areas of interest. There seemed to also be a pre-requisite understanding of the Haskell programming language and much of the theory behind it, which was also great to see, since it allowed some presentations to go into great detail about various topics. The invited presentation scheduled for 0930 (GMT +11) was given by Professor Peter Stuckey titled, Type Processing by Constraint Reasoning. It is in this talk that I learned of a project titled, <a href="http://www.comp.nus.edu.sg/~sulzmann/chameleon/download/haskell.html">Chameleon</a>, which goes about providing a rich set of information for type errors. Professor Stuckey also seemed to highlight the common misunderstanding that comes with a type error as being interpreted as “something is wrong” with the correction “at least one of two things went wrong, since you have at least one contradiction that cannot be resolved” - at least, this is my translation of his emphasis. I think this distinction is extremely important and I applaud anyone who sets about making it. I won’t continue paraphrasing what appears to be a massive amount of work in understanding and then implementing an artifact of Type Theory, so if you have a chance, I encourage anyone to take a look at <a href="http://www.comp.nus.edu.sg/~sulzmann/publications/aplas06-invited.pdf">the paper</a>.</p>
<p>It is also during this presentation that I learned of <a href="http://www.cs.uu.nl/people/daan/download/papers/helium.pdf">Helium</a> for teaching Haskell to beginners. I have yet to take a detailed peek at Helium, but since I have an interest in teaching at the tertiary level as well as “weaning people of the mainstream guff”, I have hopes that Helium can be an extremely useful tool in achieving my objectives.</p>
    </div>
  </content>
</entry>
<entry>
  <title>Have you ever wanted to do this?</title>
  <link rel="alternate" href="http://blog.tmorris.net/posts/have-you-ever-wanted-to-do-this/index.html"/>
  <id>http://blog.tmorris.net/posts/have-you-ever-wanted-to-do-this/index.html</id>
  <published>2006-11-07T14:57:27Z</published>
  <updated>2006-11-07T14:57:27Z</updated>
  <author>
    <name>$author$</name>
  </author>
  <content type="xhtml" xml:base="http://blog.tmorris.net/posts/">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>You’re working away on your Java (or .NET for that matter) project and you want to redefine the equality for some type; let’s say, for a String. The new requirement mandates that two Strings are “equal” as per usual except that if they have a length greater than or equal to 3, then it is only the first 3 characters that need to be equal for the Strings to be equal. For example:</p>
<ul>
<li><p>“abcdef” and “abcxyz” are equal</p></li>
<li><p>“abc” and “abcdef” are equal</p></li>
<li><p>“ab” and “abc” are <strong>not</strong> equal</p></li>
<li><p>“ab” and “ab” are equal</p></li>
<li><p>“” and “a” are <strong>not</strong> equal</p></li>
<li><p>“” and “” are equal</p></li>
</ul>
<p>Make sense so far? Good! :) If our problem was related to the ordering of instances of our type, we already have <code>Comparator</code> in the core API to cater for this scenario and best of all, the collections supports the use of our <em>comparing strategy</em> e.g. we can pass an instance to the constructor of <code>TreeSet</code>. However, our problem is related to testing for equality, not ordering. How would the analogous Comparator interface look for equality? How about this:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> Equalable&lt;t&gt; {
    <span class="dt">boolean</span> <span class="fu">isEqual</span>(T t1, T t2);
}</code></pre>
<p>It’s too bad the collections don’t support this type, ain’t it? We can’t plug in our own <em>strategy for testing for equality</em> like we can for comparing for order if we intend on using collections. Instead, the only way we can meet our requirement and still use collections (or anything that uses the inherent <code>equals</code> method) is by declaring a new type:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">public</span> <span class="dt">final</span> <span class="kw">class</span> XString
{
  <span class="kw">private</span> <span class="dt">final</span> String str;

  <span class="kw">public</span> <span class="fu">XString</span>(<span class="dt">final</span> String str) {
    <span class="kw">this</span>.<span class="fu">str</span> = str;
  }

  <span class="kw">public</span> String <span class="fu">getStr</span>() {
    <span class="kw">return</span> str;
  }

  <span class="kw">public</span> <span class="dt">boolean</span> <span class="fu">equals</span>(<span class="dt">final</span> Object o) {
    ...
  }
}</code></pre>
<p>Now we can have collections of this type as it defines its own equality test strategy in accordance with our original requirement. What if the collection types allowed you to pass an instance of <code>Equalable</code> instead? Much easier than having to write our <code>XString</code> type!? Instead of having to create the <code>XString type</code>, we might be creating <code>HashSet</code> instances like so <code>new HashSet(new MyEqualable());</code> and be done.</p>
<p>Let’s take a look at how this would look in another programming language - with <a href="http://haskell.org/">Haskell</a> - a <em>purely functional</em> programming language. In Haskell, we have the same two choices, we might implement the type-class <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t%3AEq">Eq</a> or we might pass a <em>first-class function</em> of type a -&gt; a -&gt; Bool</p>
<pre><code>newtype XString = XString String

instance Eq XString where
  ...</code></pre>
<p>Now, if we had a function of type <code>a -&gt; b</code> <em>[see note 1]</em> and that function needed a strategy for equality over the type <code>a</code> to evaluate, we have two choices:</p>
<ol style="list-style-type: decimal">
<li><p>we could bound the parameter by the <code>Eq</code> type-class, which would look like so as a function definition <code>Eq a =&gt; a -&gt; b</code> and reads as “takes an argument of type a, where a is bound by the type-class Eq, and evaluates to an unbound type b”</p></li>
<li><p>we could leave the parameter <code>a</code> unbound and pass a function as an argument. This function would be of type <code>(a -&gt; a -&gt; Bool)</code> and would define the strategy for determining if two <em>a’s</em> are equal. Thus our entire function definition would look like so <code>(a -&gt; a -&gt; Bool) -&gt; a -&gt; b</code> where we see that <code>a</code> is not bound by any type-class i.e. it is unbound.</p></li>
</ol>
<p>Back into Java land… these two options in Haskell can be likened to <code>java.lang.Comparable</code> and <code>java.util.Comparator</code>. Suppose now you have a reference of type <code>Set</code> and you wish to call an existing method of type <code>m(Set)</code>. It is only sensible that you are able to call this method, since (let’s assume) it has nothing at all to do with the only differentiator between the two types - the strategy for determining equality. Gotta write a new type right?</p>
<p>Now, since this is my first blog post ever, I reserve the right to throw out some incredibly bold and apparently absurd postulations :). Since such a simple requirement mandates the creation of so much code to fulfill accurately, I postulate, with more formal reasons forthcoming, that approximately 99.9999% of the content of the J2SE API Specification [see note 2] is a result of this problem that is inherent in a language such as Java with a substandard type system. I might name this problem, “Gotta write a new type, right?” for future reference and just to take the piss out of the dominant programming language(s) of our evolving <em>[see note 3]</em> industry. So that’s its name, OK? Great.</p>
<p>I do not envy you oh Senior J2EE Architect/.NET Super-duper Spanky Star (what do they call those anyway?).</p>
<p>[1] This can be read as “takes an argument of type a and evaluates to a type b where a and b are both polymorphic and unbound”. The analogous Java is:</p>
<pre class="sourceCode Java"><code class="sourceCode java"><span class="kw">interface</span> I&lt;a, b&gt; {
  b <span class="fu">f</span>(a arg);
}</code></pre>
<p>[2] The “thing” (monolithic abominable creature?) that I used to laboriously implement for IBM <a href="http://java.sun.com/j2se/1.5.0/docs/api/">http://java.sun.com/j2se/1.5.0/docs/api/</a></p>
<p>[3] I must have backspaced 50 or so times before finally settling on the conservative adjective, “evolving” :)</p>
    </div>
  </content>
</entry>

</feed>
