<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title><![CDATA[programming (and other) musings - programming]]></title>
<description><![CDATA[programming (and other) musings - programming]]></description>
<link>https://jao.io/blog//tag-programming.html</link>
<atom:link href="https://jao.io/blog/programming-rss.xml" rel="self" type="application/rss+xml" />
<lastBuildDate>Mon, 04 May 2026 20:18:56 +0100</lastBuildDate>
<item>
  <title><![CDATA[inline snippets and grouping in consult-recoll]]></title>
  <description><![CDATA[
<p>
I've just released a new version of <a href="https://codeberg.org/jao/consult-recoll">consult-recoll</a>, which implements a couple
of features that i am really liking, namely, grouping of search results by
mime type:
</p>


<figure id="orgdd11142">
<img src="../img/consult-recoll-group.png" alt="consult-recoll-group.png">

</figure>

<p>
and inline snippets:
</p>


<figure id="org1c42db9">
<img src="../img/consult-recoll-inline.png" alt="consult-recoll-inline.png">

</figure>

<p>
Happy searches!
</p>

<!-- preview-end -->
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-emacs.html">emacs</a> <a href="https://jao.io/blog/tag-programming.html">programming</a> </div>]]></description>
  <category><![CDATA[emacs]]></category>
  <category><![CDATA[programming]]></category>
  <link>https://jao.io/blog/inline-snippets-and-grouping-in-consult-recoll.html</link>
  <guid>https://jao.io/blog/inline-snippets-and-grouping-in-consult-recoll.html</guid>
  <pubDate>Thu, 04 Aug 2022 18:29:00 +0100</pubDate>
</item>
<item>
  <title><![CDATA[let's talk lisp]]></title>
  <description><![CDATA[
<!-- preview-start -->

<p>
I just got a second-hand copy of this classic.  Sometimes, used books
are more charming than new ones:
</p>

<table>


<colgroup>
<col  class="org-left">

<col  class="org-left">
</colgroup>
<tbody>
<tr>
<td class="org-left"><img src="https://jao.io/img/lets-talk-lisp-0.jpg" alt="lets-talk-lisp-0.jpg"></td>
<td class="org-left"><img src="https://jao.io/img/lets-talk-lisp-1.jpg" alt="lets-talk-lisp-1.jpg"></td>
</tr>
</tbody>
</table>

<!-- preview-end -->
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-books.html">books</a> <a href="https://jao.io/blog/tag-programming.html">programming</a> </div>]]></description>
  <category><![CDATA[books]]></category>
  <category><![CDATA[programming]]></category>
  <link>https://jao.io/blog/lets-talk-lisp.html</link>
  <guid>https://jao.io/blog/lets-talk-lisp.html</guid>
  <pubDate>Sat, 16 Apr 2022 20:41:00 +0100</pubDate>
</item>
<item>
  <title><![CDATA[fun with dependent types]]></title>
  <description><![CDATA[
<!-- preview-start -->


<figure id="org8ae89e2">
<img src="https://jao.io/img/the-little-typer.jpg" alt="the-little-typer.jpg">

</figure>

<!-- preview-end -->

<p>
It had been a while since i last had this much fun with a programming
languages book, and learnt so much in the process.  It sure helped
that i am a complete neophyte on the subject matter of dependent
types: i had recently started playing with <a href="https://www.idris-lang.org/">Idris</a>, but reading this
book really clarified the basics for me.  I still remember how, after
<i>The little schemer</i> kindled my love for parenthesis, <i>The seasoned
schemer</i> made me finally grasp the meaning of continuations.  I've got
the feeling that the <i>typer</i> has done again the trick, this time giving
me the jump start i needed on Curry-Howard, programs as proofs and the
beauty of dependent types.  As with continuations back in the day, i
had read a lot about those things, and thought i had understood them,
only to realise that i had not really.
</p>

<p>
The authors, Daniel P. Friedman and David Thrane Christiansen, have
also created a language, Pie, and implemented it in Racket and <a href="https://github.com/david-christiansen/pie-hs">in
Haskell</a>.  I've used the latter in a couple of ways: first, it's a very
fun learning experience as a weak haskeller (or as a fading racketeer,
for that matter) to go over the code (make sure to check <a href="http://www.davidchristiansen.dk/tutorials/nbe/">Checking
Dependent Types with Normalization by Evaluation: A Tutorial</a>, by David
himself, if you're interested in how these things are implemented).
And, second, the Haskell-based REPL has been my constant companion
while reading the book, thanks to <a href="https://codeberg.org/jao/epie">a little package that i put together</a>
to use it in Emacs, complete with syntax highlighting and a bit of
completion for the predefined forms of Pie (it might have a couple of
rough corners, but the plan is to submit it to MELPA at some point).
</p>

<p>
Or you can also use the DrRacket interface if that's your thing, but,
be it as it may, don't miss this book!
</p>
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-books.html">books</a> <a href="https://jao.io/blog/tag-programming.html">programming</a> <a href="https://jao.io/blog/tag-emacs.html">emacs</a> </div>]]></description>
  <category><![CDATA[books]]></category>
  <category><![CDATA[programming]]></category>
  <category><![CDATA[emacs]]></category>
  <link>https://jao.io/blog/the-little-typer.html</link>
  <guid>https://jao.io/blog/the-little-typer.html</guid>
  <pubDate>Mon, 17 May 2021 05:29:00 +0100</pubDate>
</item>
<item>
  <title><![CDATA[reading source code is fun]]></title>
  <description><![CDATA[
<p>
From a recent checkout of the Emacs source code:
</p>

<div class="org-src-container">
<pre class="src src-emacs-lisp"><span style="color: #005555;">;;; desktop.el --- save partial status of Emacs when killed </span><span style="color: #666666; font-style: italic;">-*- lexical-binding: t -*-</span><span style="color: #005555;">
</span>
<span style="color: #666666; font-style: italic;">;; </span><span style="color: #666666; font-style: italic;">Copyright (C) 1993-1995, 1997, 2000-2021 Free Software Foundation,
</span><span style="color: #666666; font-style: italic;">;; </span><span style="color: #666666; font-style: italic;">Inc.
</span>
<span style="color: #666666; font-style: italic;">;; </span><span style="color: #666666; font-style: italic;">Author: Morten Welinder <a href="mailto:terra%40diku.dk">&lt;terra@diku.dk&gt;</a>
</span><span style="color: #666666; font-style: italic;">;; </span><span style="color: #666666; font-style: italic;">Keywords: convenience
</span><span style="color: #666666; font-style: italic;">;; </span><span style="color: #666666; font-style: italic;">Favorite-brand-of-beer: None, I hate beer.
</span>
<span style="color: #666666; font-style: italic;">;; </span><span style="color: #666666; font-style: italic;">This file is part of GNU Emacs.</span>
</pre>
</div>

<p>
Mine is Guinness :)
</p>

<!-- preview-end -->
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-emacs.html">emacs</a> <a href="https://jao.io/blog/tag-programming.html">programming</a> </div>]]></description>
  <category><![CDATA[emacs]]></category>
  <category><![CDATA[programming]]></category>
  <link>https://jao.io/blog/reading-source-code-is-fun.html</link>
  <guid>https://jao.io/blog/reading-source-code-is-fun.html</guid>
  <pubDate>Mon, 05 Apr 2021 21:45:00 +0100</pubDate>
</item>
<item>
  <title><![CDATA[what's not to like]]></title>
  <description><![CDATA[
<p>
I've just discovered <a href="https://blog.codeberg.org/">Codeberg</a>, a code hosting site that, <i>finally</i>, has
let me create a user with plain emacs-w3m, shows me content reasonably
well there, with a refreshingly uncluttered layout, handles graciously
org files (why, it's even generating a table of contents for me), has
a good privacy policy, it's not under the wings of any corporation and
had my preferred username free for grabs.
</p>

<p>
So i'm definitely testing the waters for it to become my default site
for (newish) published code: here's my <a href="https://codeberg.org/jao/elibs">jao/elibs: Emacs libraries and
little utilities</a> repository for starters (and, if you look closely,
you'll find also my emacs config nearby).  If and when that happens,
they're going to <a href="https://join.codeberg.org/">to get my humble contribution too</a>, i reckon.
</p>
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-programming.html">programming</a> <a href="https://jao.io/blog/tag-emacs.html">emacs</a> </div>]]></description>
  <category><![CDATA[programming]]></category>
  <category><![CDATA[emacs]]></category>
  <link>https://jao.io/blog/whats-not-to-like.html</link>
  <guid>https://jao.io/blog/whats-not-to-like.html</guid>
  <pubDate>Tue, 29 Dec 2020 20:53:00 +0000</pubDate>
</item>
<item>
  <title><![CDATA[two decades of gnu mdk]]></title>
  <description><![CDATA[
<p>
I've just published <a href="https://www.gnu.org/software/mdk">GNU MDK 1.3.0</a>, its <a href="https://www.gnu.org/software/mdk/NEWS.txt">28th release</a>, which finally
migrates MDK's graphical user interface to GTK+ 3, to keep up with
the, ahem, not-so-modern times and see to it that MDK keeps alive for
at least another decade or two.
</p>


<figure id="org3df1642">
<img src="https://jao.io/img/mdk.png" alt="mdk.png">

</figure>

<!-- preview-end -->

<p>
Twenty years ago on this day, the first version of MDK 0.1 was
released.  Back then, it didn't have an Emacs or graphical
interface<sup><a id="fnr.1" class="footref" href="#fn.1" role="doc-backlink">1</a></sup>, support for internationalization or any integration
with Guile, and the debugger was really bare bones (it still is, but
not <i>that</i> much).  It wasn't yet a GNU package.  But all those things,
and then more, came in rapid succession, as i used the project to
discover the Free Software world, both at a technical and a human
level.
</p>

<p>
As a physicist out of grad school, i wasn't young, but i was just
starting in the world of software and everything was fresh and new and
exciting.  I remember the thrill of receiving emails from total
strangers willing to help and offering insightful advice (hi there,
Philip King, wherever you are these days), and of thinking that
someone else, out there, was finding my little program fun and
useful<sup><a id="fnr.2" class="footref" href="#fn.2" role="doc-backlink">2</a></sup>.  Or of exchanging messages with RMS, that guy i had read
about in <i>Hackers</i> and admired so much; and then see in the process MDK
entering the GNU umbrella.  And of seeing it shortly afterwards on
<a href="https://www-cs-faculty.stanford.edu/~knuth/taocp.html">Knuth's own page on TAOCP</a>, up there in the <i>MIXware</i> list.
</p>

<p>
MDK was my first project developed entirely in Emacs running on Debian
(twenty years ago, that felt bolder than it sounds now), two constant
companions up to ths day.  Seeing it as a <a href="https://tracker.debian.org/pkg/mdk">maintained Debian package</a>
was another big satisfaction and milestone for memory lane.
</p>

<p>
I also have vivid recollections of the mind-bending experience of
discovering Scheme, because i learnt that Guile was the extension
language of choice for GNU, and my baby steps on writing a lexer or an
interpreter, and how humbled i felt when i took a proper compilers
course a few years later and looked back at my clumsily rediscovered
wheels<sup><a id="fnr.3" class="footref" href="#fn.3" role="doc-backlink">3</a></sup>.
</p>

<p>
MDK was also my gateway to publishing <a href="https://dl.acm.org/doi/book/10.5555/1215741">a book</a> for the first time,
thanks to the nice guys of the GNU Press, with a polished version of
its manual. Okay, it's more of a booklet, and out of press by now, but
it was an enriching experience nonetheless; for instance i got a
chance of seeing an editor in action.
</p>

<table>


<colgroup>
<col  class="org-left">

<col  class="org-left">
</colgroup>
<tbody>
<tr>
<td class="org-left"><img src="https://jao.io/img/mdk.jpg" alt="mdk.jpg"></td>
<td class="org-left"><img src="https://jao.io/img/mdk-source.png" alt="mdk-source.png"></td>
</tr>
</tbody>
</table>

<p>
After two decades, having grown older and bitter, all those things
look small and of little importance, but as a freshman i truly had the
best of times.  I think that maybe the most important thing i learned
was to <a href="https://www.gnu.org/software/mdk/manual/html_node/Acknowledgments.html">collaborate with other people</a>, and i've since been always very
fond of the kindness of strangers, and how much one can learn from
them.
</p>

<p>
Anyway, here's to the next twenty years. Happy hacking!
</p>
<div id="footnotes">
<h2 class="footnotes">Footnotes: </h2>
<div id="text-footnotes">

<div class="footdef"><sup><a id="fn.1" class="footnum" href="#fnr.1" role="doc-backlink">1</a></sup> <div class="footpara" role="doc-footnote"><p class="footpara">
To be honest, i almost never use MDK's graphical interface, and
prefer to comfortably <a href="https://www.gnu.org/software/mdk/manual/mdk.html#Emacs-tools">use it within emacs</a>, but a bit of eye candy is
not bad every now and then.
</p></div></div>

<div class="footdef"><sup><a id="fn.2" class="footnum" href="#fnr.2" role="doc-backlink">2</a></sup> <div class="footpara" role="doc-footnote"><p class="footpara">
Keep in mind that those were ancient times, more so on my side
of th world: the cool new thing to learn and use for me was CVS, and
there were rumors about something called subversion.  And then
SourceForge felt like the best thing ever.
</p></div></div>

<div class="footdef"><sup><a id="fn.3" class="footnum" href="#fnr.3" role="doc-backlink">3</a></sup> <div class="footpara" role="doc-footnote"><p class="footpara">
Shortly after, SICP would be the eye-opener it's been for many
and would make everything make sense (i talked a bit about that
process in <a href="https://jao.io/blog/2006-01-14-the-joy-of-repl.html">one of my very first blog posts</a>).  In retrospect, i think
the journey that i then started is the main reason i never went on to
complete an MMDK for MMIX, which was planned and going to be written
in OCaml.
</p></div></div>


</div>
</div><div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-programming.html">programming</a> </div>]]></description>
  <category><![CDATA[programming]]></category>
  <link>https://jao.io/blog/two-decades-of-gnu-mdk.html</link>
  <guid>https://jao.io/blog/two-decades-of-gnu-mdk.html</guid>
  <pubDate>Sat, 31 Oct 2020 04:52:00 +0000</pubDate>
</item>
<item>
  <title><![CDATA[unlearn]]></title>
  <description><![CDATA[
<p>
For years, i've been using <code>C-x p</code>, <code>C-x o</code> and <code>C-c &lt;n&gt;</code> to move to other
windows, but with <a href="https://jao.io/blog/2020-05-12-ace-window.html">ace window</a> i am substituting all of them with <code>M-o</code>.
Problem is, muscle memory interferes and i find myself clumsily moving
around (and often lost) with the former ones.  Or i did, before i
followed an advice from <a href="https://www.iro.umontreal.ca/~monnier/">Stefan Monnier</a> in emacs-devel: unbind those
keys you want to forget, and you'll get an error when you relapse.
</p>

<p>
In my case, that was just
</p>

<div class="org-src-container">
<pre class="src src-emacs-lisp">(global-set-key (kbd <span style="color: #023770;">"C-x o"</span>) nil)
</pre>
</div>

<p>
together with commeting out the other one's definitions.  For the
record, in Stefan's case, he was trying to remember to use the newer
<code>C-h o</code> (symbol help) instead of <code>C-h f</code> (function help) or <code>C-h v</code>
(variable help), so he unbound the last two.
</p>

<p>
After a while, when one's muscles have forgotten, one can re-enable
the old bindings, for the few cases where they're justified.
</p>
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-emacs.html">emacs</a> <a href="https://jao.io/blog/tag-programming.html">programming</a> </div>]]></description>
  <category><![CDATA[emacs]]></category>
  <category><![CDATA[programming]]></category>
  <link>https://jao.io/blog/unlearn.html</link>
  <guid>https://jao.io/blog/unlearn.html</guid>
  <pubDate>Wed, 13 May 2020 00:02:00 +0100</pubDate>
</item>
<item>
  <title><![CDATA[imagine]]></title>
  <description><![CDATA[
<div class="org-src-container">
<pre class="src src-nil">                       ((I m a g i n e)
                     (shriram@cs.rice.edu)
               (((Imagine there's no FORTRAN)
                   (It's easy if you try)
           (No SML below us) (Above us only Y)
          (Imagine all              the people)
         (Living for                their Chez))
      ((Imagine there's          no memory leaks)
                             (It isn't hard to do)
                              (Nothing to malloc(3)
                                    or free(3) for)
                               (And no (void *) too)
                             (Imagine all the people)
                              (Living in parentheses))
                           ((You may say I'm a Schemer)
                             (But I'm not the only one)
                         (I hope someday you'll join us)
                               (And the world will be as
                        (lambda (f) (lambda (x) (f x)))))
                          ((Imagine those   continuations)
                         (I wonder              if you can)
                   (No need for              C or pointers)
               (A brotherhood                        of Dan)
                (Imagine all                      the people)
                (GCing all                          the world))
           ((You may say                          I'm a Schemer)
          (But I'm not                              the only one)
     (I hope someday                                you'll join us)
    (And the world                                        will be as
(lambda (f)                                     (lambda (x) (f x)))))))
</pre>
</div>

<p>
Posted to comp.lang.scheme on January 17, 1996, for Scheme's twentieth birthday.
</p>
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-programming.html">programming</a> </div>]]></description>
  <category><![CDATA[programming]]></category>
  <link>https://jao.io/blog/imagine.html</link>
  <guid>https://jao.io/blog/imagine.html</guid>
  <pubDate>Thu, 27 Feb 2020 15:09:00 +0000</pubDate>
</item>
<item>
  <title><![CDATA[donald stewart on haskell in the large]]></title>
  <description><![CDATA[
<p>
Last October Don Stewart gave <a href="https://skillsmatter.com/skillscasts/9098-haskell-in-the-large-the-day-to-day-practice-of-using-haskell-to-write-large-systems#video">a very interesting talk</a> at <i>CodeNode</i> on
his experience using Haskell at a large scale. And by large, he means
millions of lines of code.  Although he wasn't allowed to talk about
the very specifics of the code, his talk is full of interesting
remarks that i found resonate with my experience. They actually
convinced me that the next language i should try in production should
be OCaml.
</p>

<p>
The first thing that drew my attention in this talk was the sheer
amount of code they've written: 3.4 millions of lines of code. Taking
into account Haskell's conciseness, that's quite a lot. I've got
experience with very substantial projects written in functional
languages such as Clojure with two orders of magnitude less code!
Althouth it's true that running on top of the JVM lets you reuse
hundreds of libraries, and that might be closing the gap a bit.
</p>

<p>
A second interesting point was the fact that Don's team is using
interpreted code (via their own Haskell compiler): virtual machines
have many advantages, yes.
</p>

<p>
And i wasn't surprised at all to learn that their code is strict by
default: my experience with the limited laziness of Clojure has been
bad enough to reinforce my exasperation with space leaks in my
hobbyist Haskell. Laziness is pretty cool, but also the source of the
most difficult to track down bugs i've encountered in the latest
years. More difficult in fact than any memory leak i can remember in
those dreadful C++ years: there at least i had a very clear,
fool-proof methodology to avoid those problems (unlike the case of
mutable state: the peace of mind bought by immutability is priceless).
</p>

<p>
I also found myself nodding enthusiastically at Don's plea for
sticking to basic, simple constructs and to avoid as much as possible
the line noise of excessive infix operators. One can write Perl in any
language.  And, for an old lisper, his advocacy of a programming style
based on writing interpreters for little languages, sounded right on
the money.
</p>

<p>
The thing he mentions over and over that i haven't experienced
first-hand in a real-life, sizeable project is the power of a real
type system (no, Java's or C++'s aren't), and that's something i'd
really like to try.
</p>

<p>
Then at some point he mentions they have their own module system, not
as good as ML's, but&#x2026; and i realised that there's a language out
there that has all the good things the talk mentions and needs none of
the workarounds they use. It's called OCaml, and i've been meaning to
use it in earnest for some years now. Maybe it's finally time i dust
that part of my bookshelf, if only to compare real-world development
in a properly typed language with my experience with dynamic languages
such as Clojure (which has not been by any means as bad as static
typists seem to fear).
</p>

<p>
At any rate, there's lots more in this talk that is surely more
interesting than my ramblings: recommended!
</p>
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-programming.html">programming</a> </div>]]></description>
  <category><![CDATA[programming]]></category>
  <link>https://jao.io/blog/donald-steward-on-haskell-in-the-large.html</link>
  <guid>https://jao.io/blog/donald-steward-on-haskell-in-the-large.html</guid>
  <pubDate>Wed, 30 Nov 2016 21:59:48 +0000</pubDate>
</item>
<item>
  <title><![CDATA[spj's y-combinator in scheme]]></title>
  <description><![CDATA[
<p>
Recently i bought a second-hand copy of Simon Peyton Jones' classic
<a href="http://research.microsoft.com/en-us/um/people/simonpj/papers/slpj-book-1987/">The implementation of functional programming languages</a>, and i've been
having some very pleasant reading hours during the last week.
</p>

<p>
For instance, i've enjoyed Simon's clear and to-the-point introduction
to the lambda calculus and, more concretely, his really lucid
explanation of <a href="http://research.microsoft.com/en-us/um/people/simonpj/papers/slpj-book-1987/PAGES/026.HTM">the workings of recursion and the Y combinator</a>. As a
matter of fact, i've enjoyed it so much that i just wanted to briefly
reproduce it here, paraphrased in my surely poorer style, just for the
fun of it.
</p>

<p>
In the pure lambda calculus, there's no direct way of defining a
function that refers to itself: all you have is the ability to define
anonymous lambda abstractions. Using Scheme's syntax, that means that
you can use <code>lambda</code> as much as you want, as in
</p>

<div class="org-src-container">
<pre class="src src-scheme">((<span style="color: #023770;">lambda</span> (x) (+ 1 x)) 3)
</pre>
</div>

<p>
but <code>define</code> (recursive or not) is not available. For instance, you
cannot define a <code>list-length</code> recursive function like this:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">define</span> <span style="color: #005555;">list-length</span>
  (<span style="color: #023770;">lambda</span> (lst) (<span style="color: #023770;">if</span> (null? lst) 0 (+ 1 (list-length (cdr lst))))))
</pre>
</div>

<p>
the main problem being the appearance of <code>list-length</code> in the lambda
expression's body. So the general issue we want to solve is how to
define a function <code>f</code> of the form
</p>

<div class="org-src-container">
<pre class="src src-scheme">f = (... f ...)
</pre>
</div>

<p>
without referring to <code>f</code> in the body. When all you have is lambda
calculus, everything looks like a function: we can rewrite the right
hand side of the above equation as a lambda application:
</p>

<div class="org-src-container">
<pre class="src src-scheme">f = ((<span style="color: #023770;">lambda</span> (x) (... x ...)) f) <span style="color: #023770;">:=</span> (h f)
</pre>
</div>

<p>
where we've defined <code>h := (lambda (x) (... x ...))</code>. For instance, in
our length example, <code>h</code> is the function
</p>

<div class="org-src-container">
<pre class="src src-scheme">h = (<span style="color: #023770;">lambda</span> (x)
      (<span style="color: #023770;">lambda</span> (lst)
        (<span style="color: #023770;">if</span> (null? lst) 0 (+ 1 (x (cdr lst))))))
</pre>
</div>

<p>
and we're trying to solve the equation <code>(h list-length) = list-length</code>.
In other words, you give me <code>h</code>, a function taking a function as
argument and returning another function, and i need to give you back an
<code>f</code> that is its fixed point, i.e., an <code>f</code> satisfying <code>f = (h f)</code>.
</p>

<p>
So all i need to do is finding a function (let's call it <code>Y</code>) that takes
<code>h</code> as its argument and returns <code>f</code>, that is, by definition of <code>Y</code>:
</p>

<div class="org-src-container">
<pre class="src src-scheme">f = (Y h)
</pre>
</div>

<p>
but, as we've seen <code>f</code> equals <code>(h f)</code>, which in turn is <code>(h (Y h))</code>
which gives us the defining equation of <code>Y</code>:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(h (Y h)) = (Y h)
</pre>
</div>

<p>
If i had that magic <code>Y</code> function (or combinator, since it won't use any
global variables), i could for instance immediately compute
<code>list-length</code> as:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(Y (<span style="color: #023770;">lambda</span> (x) (<span style="color: #023770;">lambda</span> (lst) (<span style="color: #023770;">if</span> (null? lst) 0 (+ 1 (x (cdr lst)))))))
</pre>
</div>

<p>
The nicest kind of wishful thinking is the one that comes true: we
actually know of a lambda expression that satifies the Y combinator's
defining equation <code>(Y h) = (h (Y h))</code>, namely:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">lambda</span> (h) ((<span style="color: #023770;">lambda</span> (x) (h (x x))) (<span style="color: #023770;">lambda</span> (y) (h (y y)))))
</pre>
</div>

<p>
You can check it by yourself: <code>(Y h)</code> is just the body of the expression
above:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(Y h) =&gt; ((<span style="color: #023770;">lambda</span> (x) (h (x x))) (<span style="color: #023770;">lambda</span> (y) (h (y y))))
</pre>
</div>

<p>
and now apply the first lambda to its argument (the second lambda) to
obtain:
</p>

<div class="org-src-container">
<pre class="src src-scheme">=&gt; (h ((<span style="color: #023770;">lambda</span> (y) (h (y y))) (<span style="color: #023770;">lambda</span> (y) (h (y y)))))
=&gt; (h (Y h))
</pre>
</div>

<p>
as desired! The only wrinkle left is that, as defined, our Y
combinator cannot be directly coded in Scheme, because Scheme is a
strict language and those pesky <code>(x x)</code> and <code>(y y)</code> applications cause an
infinite recursion.
</p>

<p>
But that's just an accidental difficulty due to Scheme's evaluation
strategy being too eager that has a standard solution: a beta
abstraction. If you have a function <code>F</code> in Scheme, you can define a
totally equivalent function <code>G</code> by <code>(define G (lambda (x) (F x)))</code>. We say
that G is a beta abstraction of F, or that F is a beta reduction of
G. And the usual reason you would beta abstract a function in Scheme
is in order to delay the evaluation of its body, just what the doctor
ordered.
</p>

<p>
Remember, <code>h</code> is a function taking another function as an argument, so
<code>(x x)</code> and <code>(y y)</code>, which are used as <code>h</code>'s arguments, must be
functions, so they're equivalent to <code>(lambda (a) ((x x) a))</code> and
<code>(lambda (a) ((y y) a))</code>, so we can define Y, if we're so inclined, also
as:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">define</span> <span style="color: #005555;">Y</span>
  (<span style="color: #023770;">lambda</span> (h)
    ((<span style="color: #023770;">lambda</span> (x) (h (<span style="color: #023770;">lambda</span> (a) ((x x) a))))
     (<span style="color: #023770;">lambda</span> (x) (h (<span style="color: #023770;">lambda</span> (a) ((x x) a)))))))
</pre>
</div>

<p>
and now
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">define</span> <span style="color: #005555;">list-length</span>
  (Y (<span style="color: #023770;">lambda</span> (f) (<span style="color: #023770;">lambda</span> (lst) (<span style="color: #023770;">if</span> (null? lst) 0 (+ 1 (f (cdr lst))))))))
</pre>
</div>

<p>
As you see, <code>list-length</code>'s body doesn't mention itself and, as you can
check by yourself with your favourite interpreter, the last two
definitions are valid and working scheme code.
</p>

<p>
In case you still feel a bit unsure as to how our <code>Y</code> is pulling its
trick, you can dispel any misgivings just by seeing how the combinator
transforms the given <code>h</code> step by step, always reproducing <code>h</code> in the
process (it's only the branch in <code>h</code> that doesn't call its argument, the
recursion's base case, that breaks the implicit infinite loop induced by
<code>Y</code>). Let's do it with our <code>list-length</code> example, reducing its
application to, say, the list '(1 2), step by step:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">define</span> <span style="color: #005555;">W</span> (<span style="color: #023770;">lambda</span> (f) (<span style="color: #023770;">lambda</span> (a) ((f f) a))))

(list-length '(1 2))
  <span style="color: #666666; font-style: italic;">;; </span><span style="color: #666666; font-style: italic;">definition of list-length as (Y h)
</span>  =&gt; ((Y h) '(1 2))
  <span style="color: #666666; font-style: italic;">;; </span><span style="color: #666666; font-style: italic;">definiton of Y and W
</span>  =&gt; (((<span style="color: #023770;">lambda</span> (f) (h (W f))) (<span style="color: #023770;">lambda</span> (f) (h (W f)))) '(1 2))
  <span style="color: #666666; font-style: italic;">;; </span><span style="color: #666666; font-style: italic;">beta-reduction of the first lambda applied to the second
</span>  =&gt; ((h (W (<span style="color: #023770;">lambda</span> (f) (h (W f))))) '(1 2))
  <span style="color: #666666; font-style: italic;">;; </span><span style="color: #666666; font-style: italic;">definition of h for the case of list-length
</span>  =&gt; ((<span style="color: #023770;">lambda</span> (lst)
        (<span style="color: #023770;">if</span> (null? lst) 0 (+ 1 ((W (<span style="color: #023770;">lambda</span> (f) (h (W f)))) (cdr lst)))))
      '(1 2))
  <span style="color: #666666; font-style: italic;">;; </span><span style="color: #666666; font-style: italic;">function application
</span>  =&gt; (+ 1 ((W (<span style="color: #023770;">lambda</span> (f) (h (W f)))) '(2)))
  <span style="color: #666666; font-style: italic;">;; </span><span style="color: #666666; font-style: italic;">definition of W
</span>  =&gt; (+ 1 (((<span style="color: #023770;">lambda</span> (f) (h (W f))) (<span style="color: #023770;">lambda</span> (f) (h (W f)))) '(2)))
</pre>
</div>

<p>
and notice what just happened: we started with
</p>

<div class="org-src-container">
<pre class="src src-scheme">(((<span style="color: #023770;">lambda</span> (f) (h (W f))) (<span style="color: #023770;">lambda</span> (f) (h (W f)))) '(1 2))
</pre>
</div>

<p>
and, after one iteration of the implicit recursion, reduced it to:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(+ 1 (((<span style="color: #023770;">lambda</span> (f) (h (W f))) (<span style="color: #023770;">lambda</span> (f) (h (W f)))) '(2)))
</pre>
</div>

<p>
i.e., 1 plus the same form we started with but applied to the list <code>(2)</code>
instead of the list <code>(1)</code>. By following the exact same reduction steps,
we can simplify the above to:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(+ 1 1 (((<span style="color: #023770;">lambda</span> (f) (h (W f))) (<span style="color: #023770;">lambda</span> (f) (h (W f)))) '()))
</pre>
</div>

<p>
and now, when expanding the same form to the right applied to the
empty list, the base case of the recursion (the true branch of the
<code>(null? lst)</code> test in <code>h</code>), will kick in and reduce the above to
</p>

<div class="org-src-container">
<pre class="src src-scheme">(+ 1 1 0) =&gt; 2
</pre>
</div>

<p>
avoiding that the self-reproducing Y forms keep reappearing ad
infinitum.
</p>
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-programming.html">programming</a> </div>]]></description>
  <category><![CDATA[programming]]></category>
  <link>https://jao.io/blog/spj-s-y-combinator.html</link>
  <guid>https://jao.io/blog/spj-s-y-combinator.html</guid>
  <pubDate>Wed, 06 Aug 2014 04:38:43 +0100</pubDate>
</item>
<item>
  <title><![CDATA[where my mouth is]]></title>
  <description><![CDATA[
<p>
For many years, i've been convinced that programming needs to move
forward and abandon the Algol family of languages that, still today,
dampens the field. And that that forward direction has been signalled
for decades by (mostly) functional, possibly dynamic languages with an
immersive environment. But it wasn't until recently that i was able to
finally put my money where my mouth has been all these years.
</p>

<p>
A couple of years ago i finally became a co-founder and started
working on a company i could call my own (i had been close in the
past, but not really there), and was finally in a position to <i>really</i>
influence our development decisions at every level. Even at the most
sensitive of them all: language choice.
</p>

<p>
During my previous professional career i had been repeatedly
dissapointed by the lack of conviction, when not plain mediocrity, of
the technical decision makers in what seemed all kinds of company, no
matter how cool, big or small: one would always end up eaten alive by
the Java/C++ ogre, with a couple testimonial scripts (or perhaps some
unused scheme bindings) to pay lip service to the hipsters around.
</p>

<p>
Deep down, the people in charge either didn't think languages make any
difference or, worse, bought into the silly "availability of
programmers" argument. I'm still surprised anyone would believe such a
thing. If i guy came telling me that he wanted to program only in,
say, Java because that's what he knows best and that he doesn't really
feel prepared or interested in learning and using, say, Clojure (or
any other language, really), i wouldn't hire him in a million years,
no matter what language my project were using, and no matter how many
thousands of candidates like this one i had at my disposal.
</p>

<p>
Give me programmers willing to learn and eager to use Lisp or Haskell
(or Erlang, ML, OCaml, Smalltalk, Factor, Scala&#x2026;) any day, even if
we happen to be using C++, for goodness sake! Those are the ones one
needs, scanty as they might be.
</p>

<p>
Given the sad precedents, when i embarked in my new adventure, i was
careful not to try to impose on anyone my heretical ideals: they had
to be accepted on their own grounds, not based on my authority. But i
was finally lucky enough to meet a team of people with enough
intellectual curiosity and good sense (which is, again, actually a
pre-condition to be in a startup). People, let me tell you, with no
experience whatsoever in languages outside the mainstream, but people
that, nonetheless, were <i>good</i> programmers. And when you give a good
programmer a good language, good things happen.
</p>

<p>
Come to think of it, it's true that, with good programmers, the
language doesn't matter: they'll choose the best one, or follow the
advice of more experienced colleagues, and quickly take advantage of
any extra power the novel environment has to offer.
</p>

<p>
Our experience so far could hardly be a better counterexample against
algol naysayers.
</p>

<p>
Our backend is 99.4% coded in Clojure, and 66% of the team had never
programmed seriously in any lisp, let alone Haskell or Prolog (heck,
not even i (the remaining 33%) had actually tried anything
non-mainstream for real in a big project!) Maybe some Ruby, and lots
and lots of Java and C and C++. But they accepted the challenge after
reading around and learning the basics, and 3 months later you
couldn't take Clojure from their prying hands. More importantly, they
had fun discovering they could also be Dr Jekyll.
</p>

<p>
Of course, lots of effort is a must, and someone with a bit of
experience to guide the newbies is probably necessary. In particular,
extensive code reviews were of the essence in our case, and i had
never read and criticised this many lines of code in a similar amount
of time.  But know what? I prefer to "waste" time in code reviews to
employ at least as much writing factories of factories of factories
and similar boilerplate (configured of course using XML) and chasing
bugs in the resulting soup. Not to mention that, again, you need code
reviews no matter the language you use: the trick of having a code
base so ugly that nobody would review it doesn't fly.
</p>

<p>
So yes, it's more difficult to find hackers, but you need to find them
anyway. And yes, it may require more serious software engineering,
but, again, you need it anyway. So why shouldn't we use the best tools
at our disposal? I can finally tell you: been there, done it, and it
does work.
</p>
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-programming.html">programming</a> </div>]]></description>
  <category><![CDATA[programming]]></category>
  <link>https://jao.io/blog/where-my-mouth-is.html</link>
  <guid>https://jao.io/blog/where-my-mouth-is.html</guid>
  <pubDate>Wed, 19 Jun 2013 21:43:41 +0100</pubDate>
</item>
<item>
  <title><![CDATA[enjoying haskell]]></title>
  <description><![CDATA[
<p>
I've been reading about Haskell quite a bit during the last months,
writing some actual code, and liking the language more and more. After
many years favouring dynamically typed languages, i'm beginning to
really appreciate Haskell's type system and the benefits it brings to
the table.
</p>

<p>
A common argument from the static typing camp is that the compiler is
catching a whole class of bugs for you, to which dynamic types answer
that a good test suite (which you need anyway for any serious
development) will catch those relatively trivial bugs for you. I tend
to agree with the dynamic faction on this issue, but then i think that
the strength of static typing (coupled with good type inference) is
not at all about the compiler catching typing bugs but, rather, as
enforcing useful constraints. When you write Haskell, you have to
think hard about your data types and the functions using them; and the
compiler will keep complaining and, most importantly, the code will
feel awkward and somehow ad hoc until you find a good set of types to
solve your problem.
</p>

<p>
The limits to your freedom imposed by the type system entail, in my
experience, a boost in the amount of thought and imagination that i
put in my design and implementation, in much the same way as the
constraints imposed by metric and rhythm to poetic writing boost
creativity and actually help producing a beautiful text. Or, in fact,
in the same way as any kind of constraint in any creative endeavour
helps (paradoxically, at first sight) in attaining beauty, or, at
least, in having fun during the process.
</p>

<p>
In my experience, the process of writing a program or library in any
language is always a struggle to find <i>the</i> right way of expressing the
solution to a problem, as the culmination of a series of
approximations.  The code feels better, more expressive and
easy-flowing with each rewrite, until something just clicks and i get
this feeling that i've finally captured the essence of the problem (a
litmus test being that then it's natural to extend the solution to
cases i hadn't thought of when writing the solution, as if, somehow,
the new solutions were already there, waiting for you to <i>discover</i>
them). And i'm finding that the powerful type system offered by
Haskell (think not only of vanilla Hindley-Milner, but also of
extensions such as GADTs or type families) is helping me reaching the
(local) optimum quicker, that satisfying constraints means i'm closer
to the final solution when my code compiles for the first time. You
often hear Haskell programmers saying something similar ("once my code
compiles, it works"), and i think it's mostly true, except that the
real reason is not that the compiler is catching trivial typing bugs,
but, rather, that the constraints imposed by the type system are
making you think harder and find the right solution.  Same thing with
monads, and the clean separation they provide for stateful
computations: again, you must think carefully about the right
combination of monads and pure code to solve the problem, and most of
the time your code will simply not type check if you don't get the
solution right.
</p>

<p>
There are two more ways that Haskell's type system is helping me
writing better programs. Two ways that are especially poignant when
the code becomes sizeable enough. The first one is self-documentation:
seeing the type of my functions (or asking the interpreter for them)
instantly informs me of almost everything i need to know to use them;
in fact, when writing in dynamic languages i keep annotating function
signatures with this same information, only that there i'm all by
myself to ensure that this information is right. PLT contract system
is but a recognition of the usefulness of typing in this regard,
although i much prefer the terseness and notational elegance of
Haskell's type signatures over the much more verbose and, to my eyes,
somewhat clunky notation used by PLT (which is not really PLT's fault,
being as it is a very schemish notation). Let me stress here that
having a REPL such as ghci is a god-send (and, to me, a necessity for
really enjoying the language): it will tell me the type of an
expression in much the same way as decent Lisp or Scheme environments
will report a function's signature.
</p>

<p>
The second way Haskell's lending a helping hand with non-trivial code
base is refactoring. As i mentioned above, i rewrite my programs
several times as a rule, and rewrites almost always involve modifying
data structures or adding new ones. As i grow older, i find it more
and more difficult to keep in my head all the places and ways a given
data structure is used in my programs, and with dynamic languages i'm
often falling back to grepping the source code to find them. And
again, their plasticity often works against me, in that they let me
use those data structures in crooked ways, or forget to take into
account new fields or constructors for a modified data type. Haskell's
compiler has proved an invaluable ally to my refactorings and, by
comparison, modifying and maintaining my bigger dynamic programs is
not as fun as it used to be.
</p>

<p>
As an aside, types are not the only thing i'm finding enjoyable about
Haskell. Its astonishing capabilities to express very abstract
problems with a remarkable economy of expression (due, in part, to its
highly tuned syntax) are extremely useful. To my mind, they mimic the
process by which in math we solve harder and harder problems by
abstracting more and more, cramming together more relevant information
in less space (some cognitive science writers will tell you that
thought and even consciousness consists on our ability to compress
information). That means that i can express my solutions by capturing
them in very high level description: initially, that makes them harder
to understand, but once i feel comfortable with the basic concepts and
operations, they scale up much, much better than more verbose, less
sophisticated ones.  Using these new hard-earned concepts, i can solve
much harder problems without adding to the complexity of the code in a
significant way (one could say, using a loose analogy, that the
solutions grow logarithmically with complexity instead of
polynomically or exponentially). A direct consequence of this
expressiveness is that some well-written Haskell programs are, hands
down, the most beautiful pieces of code i've ever seen (just pick a
random post at, say, <a href="http://blog.sigfpe.com/">a Neighbohood of Infinity</a> and you'll see what i
mean; or read Richard Bird's <a href="http://www.cs.tufts.edu/~nr/comp150fp/archive/richard-bird/sudoku.pdf">Sodoku solver</a> and compare his solution
with one written in your favourite programming language).
</p>

<p>
Finally, let me say that i find programming in Haskell more difficult
than programming in any other language i've used, with perhaps the
only exception of Prolog. Sometimes, considerably so. And that's
perfectly fine with me. For one thing, it makes it more interesting
and rewarding.  In addition, i'm convinced that that's the price to
pay for being able to solve harder problems. I take issue with the
frequent pleas to the effect that programming should be effortless or
trivial: writing good programs is hard, and mastering the tools for
doing it well takes, as with any other engineering or scientific
discipline, hard work (why, i don't heard anyone complaining that
building bridges or computing the effects of gravitational lensing is
too difficult). There's no silver bullet.
</p>

<p>
All that said, please don't read the above as an apostasy letter
announcing the embracement of a new religion. There's still much to be
said in favour of dynamic languages, specially those in the Lisp
family, whose malleability (fostered by their macro systems) is also a
strength, in that they allow you to replicate some of the virtues i've
been extolling in this post. Haskell lacks the power of homoiconicity,
its template mechanisms feeling all but cranky, and that's a serious
drawback in some contexts (i have yet to decide how serious, as i have
yet to decide how much i'm missing in reflection capabilities). As
always, it is a matter of trade-offs and, fortunately, nobody will
charge you for high treason for using the language better fit to the
problem at hand, or so i hope.
</p>
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-programming.html">programming</a> </div>]]></description>
  <category><![CDATA[programming]]></category>
  <link>https://jao.io/blog/enjoying-haskell.html</link>
  <guid>https://jao.io/blog/enjoying-haskell.html</guid>
  <pubDate>Thu, 03 Dec 2009 19:14:00 +0000</pubDate>
</item>
<item>
  <title><![CDATA[erlang now!]]></title>
  <description><![CDATA[
<p>
I don't know whether Monty Python ever wrote a gag on programming
languages, but if they did, <a href="https://www.youtube.com/watch?v=xrIjfIjssLE">this Erlang video</a> must be it. The funniest
thing is that it is pretty serious, and does a great job showing one
of my most cherished abilities when using dynamic languages, namely,
adding new functionality to a running system on the fly. As for the
Monty Python bit, well, you have to see the to know what i mean: i
kept laughing out loud during most of its twelve minutes (those
Ericsson engineers seem to be taken from <i>The Larch</i>, but then maybe
it's just my sense of humor).
</p>

<p>
<b>Update:</b> Mike, one of the engineers in the film, has been kind enough
<a href="http://jaortega.wordpress.com/2007/04/11/erlang-now/#comment-22038">to post a comment</a> about the experience, which I'm reproducing here for
your convenience:
</p>

<blockquote>
<p>
We gave a well received "demo" in 1990, conjunction with ISS90, a big
telecoms conference in Stockholm. We made this movie to record the
demo. We actually used a professional company to do the filming, but I
won't mention their names as they would probably sue me for libel.
</p>

<p>
The worse of it all, is that we were deadly serious at the time. The
Monty Python aspect must be due to our backgrounds. Of the people
involved, Joe is English, Robert is Swedish - but brought up in
Australia, Bjarne is also Swedish but spend some formative years in
Scotland and I'm half Welsh half Scottish with some Irish thrown in
somewhere.
</p>

<p>
In 1990, when we made the movie, the very idea of using anything other
than C, Plex, assembly language etc to design embedded concurrent
systems was heresy, we expected to take the world by storm. It seems
that the cheap communication and multi core processors are giving
Erlang a boost 16 years later. Well at least in the intervening time
we have tested the hell out of Erlang and its implementations!
</p>

<p>
/mike
</p>

<p>
PS. If you look carefully at the film, you can see that Erlang at that
time had a Prolog like syntax.
</p>

<p>
PPS. I can't watch the movie without laughing (at) myself
</p>
</blockquote>

<p>
While we're at it, let me mention that i like many a thing of Erlang.
It's a curious mix of good stuff: a simple syntax and kind of
minimalist flavor that reminds of Scheme, pattern matching and
functional variables like Haskell's, and what amounts to a programming
paradigm of its own based on mailboxes and processes (which, as you
surely know, are amazingly cheap). Also worth mentioning is <a href="http://web.mit.edu/erlang_vR10B-10/arch/sun4x_510/lib/erlang/lib/odbc-2.0.6/doc/html/error_handling.html">Erlang's
error handling philosophy</a>, which is, at first sight, a bit startling
(i'm not still sure if it makes perfect sense, but after playing with
the language a bit, it looks like it does--<a href="http://damienkatz.net/2006/04/error_code_vs_e.html">this</a> is an interesting post
on those matters). Definitely worth a look: see for instance <a href="http://www.sics.se/~joe/index.html">Joe
Armstrong</a>'s <a href="http://www.sics.se/~joe/thesis/armstrong_thesis_2003.pdf">thesis</a>, or, if you have some bucks to spare, the
forthcoming <a href="http://www.pragmaticprogrammer.com/titles/jaerlang/">Programming Erlang</a>.
</p>
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-programming.html">programming</a> <a href="https://jao.io/blog/tag-auld.html">auld</a> </div>]]></description>
  <category><![CDATA[programming]]></category>
  <category><![CDATA[auld]]></category>
  <link>https://jao.io/blog/erlang-now.html</link>
  <guid>https://jao.io/blog/erlang-now.html</guid>
  <pubDate>Tue, 10 Jul 2007 13:00:00 +0100</pubDate>
</item>
<item>
  <title><![CDATA[programmers go bananas]]></title>
  <description><![CDATA[
<div id="outline-container-org52f19d2" class="outline-2">
<h2 id="org52f19d2">Introduction: lists galore</h2>
<div class="outline-text-2" id="text-org52f19d2">
<p>
  I learned programming backwards, plunging right on into C and, shortly
after, C++ and Java from the very beginning. I was knee deep in
complex data structures, pointers and abstruse template syntax in no
time. And the more complex it all felt, the more i thought i was
learning. Of course, i was clueless.
</p>

<p>
Reading <a href="http://mitpress.mit.edu/sicp/">SICP</a> and learning about functional programming changed it
all. There were many occasions for revelation and awe, but one of my
most vivid recollections of that time is my gradual discovery of the
power of simplicity. At about half way into SICP i realised in wonder
that that beautiful and powerful world was apparently being
constructed out of extremely simple pieces.  Basically, everything was
a list. Of course there were other important ingredients, like
procedures as first-class objects, but the humble list was about the
only data structure to be seen. After mulling on it for a little bit,
i saw where lists draw their power from: recursion. As you know, lists
are data types recursively defined: a list is either the empty list or
an element (its <i>head</i>) followed by another list (its <i>tail</i>):
</p>

<div class="org-src-container">
<pre class="src src-haskell"><span style="color: #005555;">list</span> <span style="color: #000000;">=</span> <span style="color: #4d4d4d;">[]</span>
</pre>
</div>

<div class="org-src-container">
<pre class="src src-haskell"><span style="color: #005555;">list</span> <span style="color: #000000;">=</span> a <span style="color: #4d4d4d;">:</span> list
</pre>
</div>

<p>
where i'm borrowing Haskell's notation for the empty list ([]) and the
list constructor (:), also known by lispers as () and cons. So that was
the trick, i thought: lists have recursion built-in, so to speak, and
once you've read a little bit about functional programming you don't
need to be sold on the power and beauty of recursive programs.
</p>

<p>
It is often the case that powerful and beautiful yet simple constructs
have a solid mathematical foundation, and only when you grasp it do you
really realize how powerful, beautiful and amazingly simple that
innocent-looking construct is. Lists, and recursive operations on them,
are an excellent case in point. But the path connecting them to their
mathematical underpinnings is a long and winding one, which lays in the
realm of Category Theory.
</p>

<p>
I first became acquainted of the relationship between categories and
recursive programming reading <a href="http://citeseer.ist.psu.edu/meijer91functional.html">Functional Programming with Bananas,
Lenses, Envelopes and Barbed Wire</a>, by <a href="http://research.microsoft.com/%7Eemeijer/">Erik Meijer</a>, <a href="http://wwwhome.cs.utwente.nl/%7Efokkinga/index.html">Maarten Fokkinga</a>
and <a href="http://www.soi.city.ac.uk/%7Eross/">Ross Paterson</a>.  Albeit very enjoyable, this paper presupposes a
high degree of mathematical sophistication on the reader's side. I
will try in this article to give you a simplified overview of the
concepts involved, including Category Theory, its application to
programming languages and what funny names like catamorphism,
anamorphism or lambda-lifting have to do with your everyday list
manipulations. Of course, i'll be only scratching the surface:
interspersed links and the <a href="#org642f18b">Further reading section</a> provide pointers to
more in-depth explorations of this wonderland.
</p>
</div>
</div>
<div id="outline-container-org73f3f27" class="outline-2">
<h2 id="org73f3f27">Categorical interlude</h2>
<div class="outline-text-2" id="text-org73f3f27">
<p>
Categories are (relatively) simple constructs. A category consists of
a set <b>O</b> of objects, and a set <b>A</b> of arrows between elements of
<b>O</b>. Arrows are composable: if there's an arrow from <i>a</i> to <i>b</i>, and another
one from <i>b</i> to <i>c</i>, there must be an arrow from <i>a</i> to <i>c</i> (where <i>a</i>, <i>b</i> and <i>c</i>
are elements of <b>O</b>). Besides, they are <i>associative</i>: if you have arrows
from <i>a</i> to <i>b</i>, <i>b</i> to <i>c</i>, and <i>c</i> to <i>d</i>, you can go from <i>a</i> to <i>d</i> via two
different paths, namely, first from <i>a</i> to <i>c</i> and then from <i>c</i> to <i>d</i>, or
first from <i>a</i> to <i>b</i> and then from <i>b</i> to <i>d</i>.  Finally, for each element <i>a</i>
in <b>O</b> there's an <i>identity</i> arrow which goes from <i>a</i> to itself (called an
<i>identity</i>), such that following this arrow changes nothing. These
properties are better visualized with a diagram (or a bit of
mathematical notation), as shown in the image on the right.
</p>



<figure id="orge8e147e">
<img src="https://jao.io/img/categories.png" alt="categories.png">

</figure>


<p>
A category captures a <i>mathematical world</i> of objects and their
relationships. The canonical example of a category is <b>Set</b>, which
contains, as objects, (finite) sets and, as arrows, (total)
functions between them. But categories go far beyond modeling
sets. For instance, one can define a category whose objects are
natural numbers, and the 'arrows' are provided by the relation
"less or equal" (that is, we say that there is an arrow joining
two numbers <i>a</i> and <i>b</i> if <i>a</i> is less or equal than <i>b</i>)/./ What we are
trying to do with such a definition is to somehow capture the
essence of ordered sets: not only integers are ordered but also
dates, lemmings on a row, a rock's trajectory or the types of the
Smalltalk class hierarchy. In order to abstract what all those
categories have in common we need a way to go from one category to
another preserving the shared structure in the process. We need
what the mathematicians call an <i>isomorphism</i>, which is the
technically precise manner of stating that two systems are, in a
deep sense, analogous; this searching for commonality amounts to
looking for concepts or abstractions, which is what mathematics
and (good) programming is all about (and, arguably, intelligence
itself, if you are to believe, for instance, <a href="http://prelectur.stanford.edu/lecturers/hofstadter/">Douglas Hofstadter</a>'s
<a href="http://prelectur.stanford.edu/lecturers/hofstadter/analogy.html">ideas</a>).
</p>

<p>
To boot, our definition of a category already contains the concept
of isomorphic objects. Think of an arrow from <i>a</i> to <i>b</i> as an
operation that transforms <i>a</i> in <i>b</i>. An arrow from <i>b</i> to <i>a</i> will make
the inverse transformation. If composing both transformations
gives you the identity, you are back to the very same object <i>a</i>,
and we say that <i>a</i> and <i>b</i> are isomorphic: you can transform one into
the other and back at will. In a deep sense, this concept captures
a generic way of expressing equality that pervades all maths: if
you're not afraid of a little bit of maths, <a href="http://www.math.harvard.edu/%7Emazur/">Barry Mazur</a>'s essay
<a href="http://www.math.harvard.edu/%7Emazur/preprints/when_is_one.pdf">When is a thing equal to some other thing?</a> is an excellent
introduction to Category Theory with an emphasis in the concept of
equality. Among many other things, you will learn how the familiar
natural numbers can be understood as a category, or how an object
is completely defined by the set of its transformations (and,
therefore, how to actually get rid of objects and talk only of
transformations; i know this is stretching and mixing metaphors
(if not plain silly), but this stress in arrows, as opposed to
objects, reminded me of <a href="http://www.iam.unibe.ch/%7Edenker/AlanKayOOP.html">Alan Kay's insistence</a> on focusing on
messages rather than objects). Another introductory article with
emphasis on categories as a means to capture sameness is R. Brown
and T. Porter's <a href="http://www.informatics.bangor.ac.uk/public/mathematics/research/ftp/cathom/05_10.pdf">Category Theory: an abstract setting for analogy
and comparison</a>.
</p>

<p>
Not only objects inside a category can be transformed into each other.
We reveal the common structure of two disjoint categories by means of
a functor mapping across two categories. A functor consists of two
functions: one that maps each object of the first category to an
object in the second, and another one putting in correspondence arrows
in one category with arrows in the second. Besides, these functions
must preserve arrow composition. Let me spell this
mathematically. Consider to categories, C and C' with object sets <b>O</b>
and <b>O'</b> and arrow sets <b>A</b> and <b>A'</b>. A functor F mapping C to C' will
consist then of two functions (Fo, Fa); the first one taking elements
of <b>O</b> to elements of <b>O'</b>:
</p>

<p>
Fo: <b>O</b> -&gt; <b>O'</b>
</p>

<p>
Fo(a) in <b>O'</b> for every a in <b>O</b>
</p>

<p>
and the second one taking arrows from <b>A</b> to arrows in <b>A'</b>:
</p>

<p>
Fa: <b>A</b> -&gt; <b>A'</b>
</p>

<p>
Fa(<b>f</b>) in <b>A'</b> for every <b>f</b> in <b>A</b>
</p>

<p>
and such that, if <b>f</b> is an arrow from a to b in C, Fa(<b>f</b>) is an arrow
from Fo(a) to Fo(b) in C'. Moreover, we want that following arrows in C
is 'analogous' to following them in C', i.e., we demand that
</p>

<p>
Fa(<b>fg</b>) = Fa(<b>f</b>)Fa(<b>g</b>)
</p>

<p>
In the left hand side above, we are composing two arrows in C and then
going to C', while in the right hand side we first take each arrow to
C' and, afterwards, compose them in there. If C and C' have the same
structure, these two operations must be equivalent. Finally, F must
preserve identities: if <b>i</b> is the identity arrow for an element a in <b>O</b>,
Fa(<b>i</b>)must be the identity arrow for Fo(a) in <b>O'</b>. The diagram on the
left shows a partial graph (i'm not drawing the identity arrows and
their mappings) of a simple functor between two categories, and ways
of going from an object a in the first category to an object x in the
second one which are equivalent thanks to the functor's properties.
</p>


<figure id="org8d8177c">
<img src="https://jao.io/img/functors.png" alt="functors.png">

</figure>

<p>
As you can see in this simple example, the functor gives us the
ability of seeing the first category as a part of the second one. You
get a category isomorphism in the same way as between objects, i.e.,
by demanding the existence of a second functor from C' to C (you can
convince yourself that such a functor does not exist in our example,
and, therefore, that the two categories in the diagram are not
isomorphic).
</p>

<p>
You have probably guessed by now one nifty property of functors: they
let us going meta and define a category whose objects are categories
and whose arrows are functors. Actually, <a href="http://www-groups.dcs.st-and.ac.uk/%7Ehistory/Mathematicians/Eilenberg.html">Eilenberg</a> and <a href="http://www-groups.dcs.st-and.ac.uk/%7Ehistory/Mathematicians/MacLane.html">MacLane</a>'s
seminal paper General theory of natural transformations used functors
and categories of categories to introduce for the first time
categories (natural transformations are structure-preserving maps
between functors: <a href="http://en.wikipedia.org/wiki/Natural_transformation">this Wikipedia article</a> gives an excellent overview
on them).
</p>

<p>
But enough maths for now: it is high time to show you how this rather
abstract concepts find their place in our main interest, programming
languages.
</p>
</div>
</div>
<div id="outline-container-orge53977c" class="outline-2">
<h2 id="orge53977c">Categories and programming languages</h2>
<div class="outline-text-2" id="text-orge53977c">
<p>
About the only similarity between C and Haskell programming is that one
spends a lot of time typing ASCII arrows. But of course, Haskell's are
much more interesting: you use them to declare the type of a function,
as in
</p>

<div class="org-src-container">
<pre class="src src-haskell">floor<span style="color: #000000;">::</span> <span style="color: #4d4d4d;">Real</span> <span style="color: #000000;">-&gt;</span> <span style="color: #4d4d4d;">Int</span>
</pre>
</div>

<p>
The above stanza declares a function that takes an argument of type real
and returns an integer. In general, a function taking a single argument
is declared in Haskell following the pattern
</p>

<div class="org-src-container">
<pre class="src src-haskell">fun<span style="color: #000000;">::</span> a <span style="color: #000000;">-&gt;</span> b
</pre>
</div>

<p>
where <i>a</i> and <i>b</i> are types. Does this ring a bell? Sure it does: if we
identify Haskell's arrows with categorical ones, the language types
could be the objects of a category. As we have seen, we need identities
</p>

<div class="org-src-container">
<pre class="src src-haskell">id<span style="color: #000000;">::</span> a <span style="color: #000000;">-&gt;</span> a
</pre>
</div>

<div class="org-src-container">
<pre class="src src-haskell"><span style="color: #005555;">id</span> x <span style="color: #000000;">=</span> x
</pre>
</div>

<p>
and arrow composition, which in Haskell is denoted by a dot
</p>

<div class="org-src-container">
<pre class="src src-haskell">f<span style="color: #000000;">::</span> b <span style="color: #000000;">-&gt;</span> c
</pre>
</div>

<div class="org-src-container">
<pre class="src src-haskell">g<span style="color: #000000;">::</span> a <span style="color: #000000;">-&gt;</span> b
</pre>
</div>

<div class="org-src-container">
<pre class="src src-haskell">fg<span style="color: #000000;">::</span> a <span style="color: #000000;">-&gt;</span> b <span style="color: #000000;">-&gt;</span> c
</pre>
</div>

<div class="org-src-container">
<pre class="src src-haskell"><span style="color: #005555;">fg</span> <span style="color: #000000;">=</span> f <span style="color: #000000;">.</span> g
</pre>
</div>

<p>
Besides, associativity of arrow composition is ensured by Haskell's
referential transparency (no side-effects: if you preserve <a href="http://foldoc.org/foldoc.cgi?query=referential+transparency">referential
transparency</a> by writing side-effect free functions, it won't matter
the order in which you call them): we've got our category. Of course,
you don't need Haskell, or a statically typed language for that
matter: any strongly typed programming language can be modelled as a
category, using as objects its types and as arrows its functions of
arity one. It just happens that Haskell's syntax is particularly
convenient, but one can define function composition easily in any
decent language; for instance in Scheme one would have
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">define</span> (<span style="color: #005555;">compose</span> f g) (<span style="color: #023770;">lambda</span> (x) (f (g x)))
</pre>
</div>

<p>
Functions with more than one arguments can be taken into the picture
by means of <a href="http://en.wikipedia.org/wiki/Currying">currying</a>: instead of writing a function of, say, 2
arguments:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">define</span> (<span style="color: #005555;">add</span> x y) (+ x y))
</pre>
</div>

<div class="org-src-container">
<pre class="src src-scheme">(add 3 4)
</pre>
</div>

<p>
you define a function which takes one argument (x) and returns a
function which, in turn, takes one argument (y) and returns the final
result:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">define</span> (<span style="color: #005555;">add</span> x) (<span style="color: #023770;">lambda</span> (y) (+ x y)))
</pre>
</div>

<div class="org-src-container">
<pre class="src src-scheme">((add 3) 4)
</pre>
</div>

<p>
Again, Haskell offers a pretty convenient syntax. In Haskell, you can
define <code>add</code> as:
</p>

<div class="org-src-container">
<pre class="src src-haskell"><span style="color: #005555;">add</span> x y <span style="color: #000000;">=</span> x <span style="color: #000000;">+</span> y
</pre>
</div>

<p>
which gets assigned, when applied to integers, the following type:
</p>

<div class="org-src-container">
<pre class="src src-haskell">add<span style="color: #000000;">::</span> <span style="color: #4d4d4d;">Int</span> <span style="color: #000000;">-&gt;</span> (<span style="color: #4d4d4d;">Int</span> <span style="color: #000000;">-&gt;</span> <span style="color: #4d4d4d;">Int</span>)
</pre>
</div>

<p>
that is, <code>add</code> is not a function from pairs of integers to integers, but
a function that takes an integer and returns a function of type
<code>Int -&gt; Int</code>.
Finally, we can also deal with functions taking no arguments and
constant values by introducing a special type, called unit or 1 (or
void in C-ish), which has a unique value (spelled <code>()</code> in
Haskell). Constants of our language (as, e.g., <code>True</code> or 43.23) are then
represented by arrows from 1 to the constant's type; for instance,
<code>True</code> is an <code>1 -&gt; Boolean</code> arrow. The unit type is an example of what in
category theory is known as a <a href="http://planetmath.org/encyclopedia/TerminalObjectsAndZeroObjectsExamplesOfInitialObjects.html">terminal object</a>.
</p>

<p>
Now that we have successfully modelled our (functional) programming
language as a category (call it C), we can use the tools of the theory
to explore and reason about the language constructs and
properties. For instance, functors will let me recover the original
motivation of this post and explore lists and functions on them from
the point of view of category theory. If our language provides the
ability to create lists, its category will contain objects (types) of
the 'list of' kind; e.g.  <code>[Int]</code> for lists of integers, <code>[Boolean]</code> for
lists of Booleans and so on. In fact, we can construct a new
sub-category CL by considering list types as its objects and functions
taking and returning lists as its arrows. For each type a we have a
way of constructing a type, [a] in the sub-category, i.e., we have a
map from objects in C to objects in CL.  That's already half a
functor: to complete it we need a map from functions in C to functions
in CL. In other words, we need a way to transform a function acting on
values of a given type to a function acting on lists of values of the
same type. Using the notation of the previous section:
</p>

<div class="org-src-container">
<pre class="src src-nil">Fo(a) = [a]
</pre>
</div>

<div class="org-src-container">
<pre class="src src-nil">Fa(f: a -&gt; b) = f': [a] -&gt; [b]
</pre>
</div>

<p>
<code>Fa</code> is better known as <code>map</code> in most programming languages. We call the
process of going from <code>f</code> to <code>f'</code> lifting (not to be confused with a
related, but not identical, process known as <a href="http://citeseer.ist.psu.edu/johnsson85lambda.html">lambda lifting</a>), and it's
usually pretty easy to write an operator that lifts a function to a
new one in CL: for instance in Scheme we would write:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">define</span> (<span style="color: #005555;">lift</span> f) (<span style="color: #023770;">lambda</span> (lst) (<span style="color: #023770;">map</span> f lst)))
</pre>
</div>

<p>
and for <code>lift</code> to truly define a functor we need that it behaves well
respect to function composition:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(lift (compose f g)) = (compose (lift f) (lift g))
</pre>
</div>

<p>
We can convince ourselves that this property actually holds by means of
a simple example. Consider the function <code>next</code> which takes an integer to
its successor; its lifting <code>(lift next)</code> will map a list of integers to
a list of their successors. We can also define <code>prev</code> and <code>(lift prev)</code>
mapping (lists of) integers to (lists of) their predecessors.
<code>(compose next prev)</code> is just the identity, and, therefore,
<code>(lift (compose next prev))</code> is the identity too (with lifted
signature). But we obtain the same function if we compose <code>(lift next)</code>
and <code>(lift prev)</code> in CL, right? As before, there's nothing specific to
Scheme in this discussion. Haskell even has a
<a href="http://haskell.cs.yale.edu/haskellwiki/Functor">Functor</a> type class
capturing these ideas. The class defines a generic lift operation,
called <code>fmap</code> that, actually, generalizes our list lifting to arbitrary
type constructors:
</p>

<div class="org-src-container">
<pre class="src src-haskell"><span style="color: #005555;">fmap</span> <span style="color: #000000;">::</span> (a <span style="color: #000000;">-&gt;</span> b) <span style="color: #000000;">-&gt;</span> (f a <span style="color: #000000;">-&gt;</span> f b)
</pre>
</div>

<p>
where <code>f a</code> is the new type constructed from <code>a</code>. In our previous
discussion, <code>f a = [a]</code>, but if your language gives you a way of
constructing, say, tuples, you can lift functions on given types to
functions on tuples of those types, and repeat the process with any
other type constructor at your disposal. The only condition to name it a
functor, is that identities are mapped to identities and composition is
preserved:
</p>

<div class="org-src-container">
<pre class="src src-haskell"><span style="color: #005555;">fmap</span> id <span style="color: #000000;">=</span> id
</pre>
</div>

<div class="org-src-container">
<pre class="src src-haskell"><span style="color: #005555;">fmap</span> (p <span style="color: #000000;">.</span> q) <span style="color: #000000;">=</span> (fmap p) <span style="color: #000000;">.</span> (fmap q)
</pre>
</div>

<p>
I won't cover usage of type constructors (and their associated
functors) other than lists, but just mention a couple of them: monads,
another paradigmatic one beautifully (and categorically) discussed by
Stefan Klinger in his <a href="http://db.ewi.utwente.nl/Publications/PaperStore/db-utwente-0000003696.pdf">Programmer's Guide to the IO Monad - Don't Panic</a>
(also <a href="http://lambda-the-ultimate.org/node/1183">discussed at LtU</a>), and the creation of <a href="http://www.ittc.ku.edu/%7Ejenis/Dance1.pdf">a dance and music
library</a>, for those of you looking for practical applications.
</p>
</div>
</div>
<div id="outline-container-org02a2778" class="outline-2">
<h2 id="org02a2778">To be continued&#x2026;</h2>
<div class="outline-text-2" id="text-org02a2778">
<p>
Returning to lists, what the lifting and categorical description above
buys us is a way to formalize our intuitions about list operations,
and to transfer procedures and patterns on simple types to lists. In
SICP's section on <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-15.html#%_sec_2.2.3">Sequences as conventional interfaces</a>, you will find
a hands-on, non-mathematical dissection of the basic building blocks
into which any list operation can be decomposed: enumerations,
accumulators, filters and maps. Our next step, following the bananas
article i mentioned at the beginning, will be to use the language of
category theory to provide a similar decomposition, but this time we
will talk about catamorphisms, anamorphisms and similarly funny named
mathematical beasts. What the new approach will buy us is the ability
to generalize our findings beyond the list domain and onto the
so-called algebraic types. But this will be the theme of a forthcoming
post. Stay tunned.
</p>

<p>
<a id="org642f18b"></a>
</p>
</div>
</div>
<div id="outline-container-org2ab03c9" class="outline-2">
<h2 id="org2ab03c9">Further reading</h2>
<div class="outline-text-2" id="text-org2ab03c9">
<p>
The best introductory text on Category Theory i've read is <a href="http://www.amazon.com/exec/obidos/redirect?tag=ws%26link_code=xm2%26camp=2025%26creative=165953%26path=http://www.amazon.com/gp/redirect.html%253fASIN=0521478170%2526tag=ws%2526lcode=xm2%2526cID=2025%2526ccmID=165953%2526location=/o/ASIN/0521478170%25253FSubscriptionId=02ZH6J1W0649DTNS6002">Conceptual
Mathematics : A First Introduction to Categories</a> by <a href="http://www.acsu.buffalo.edu/%7Ewlawvere/">F. William Lawvere</a>
(one of the fathers of Category Theory) and Stephen Hoel Schanuel. It
assumes no sophisticated mathematical background, yet it covers lots
of ground. If you feel at home with maths, the best option is to learn
from the horse's mouth and get a copy of <a href="http://www.amazon.com/exec/obidos/tg/detail/-/0387984038?v=glance">Categories for the Working
Mathematician</a>, by Mac Lane.
</p>

<p>
The books above do not deal with applications to Computer Science,
though. For that, the canonical reference is Benjamin Pierce's <a href="http://www.amazon.com/exec/obidos/redirect?tag=ws%26link_code=xm2%26camp=2025%26creative=165953%26path=http://www.amazon.com/gp/redirect.html%253fASIN=0262660717%2526tag=ws%2526lcode=xm2%2526cID=2025%2526ccmID=165953%2526location=/o/ASIN/0262660717%25253FSubscriptionId=02ZH6J1W0649DTNS6002">Basic
Category Theory for Computer Scientists</a>, but i find it too short and
boring: a far better choice is, in my opinion, Barr and Well's
<a href="http://www.cwru.edu/artsci/math/wells/pub/ctcs.html">Category Theory and Computer Science</a>. A reduced version of Barr and
Well's book is available online in the site for their course
<a href="http://www.let.uu.nl/esslli/Courses/barr-wells.html">Introduction to Category Theory</a>. They are also the authors of the
freely available <a href="http://www.cwru.edu/artsci/math/wells/pub/ttt.html">Toposes, Triples and Theories</a>, which will teach you
everything about monads, and then more. Marteen Fokkinga is the author
of this 80-pages <a href="http://wwwhome.cs.utwente.nl/%7Efokkinga/mmf92b.html">Gentle Introduction to Category Theory</a>, with a stress
on the calculational and algorithmical aspects of the theory. Unless
you have a good mathematical background, you should probably take
gentle with a bit of salt.
</p>

<p>
Let me close by mentioning a couple of fun applications of Category
Theory, for those of you that know a bit about it. Haskell programmers
will like <a href="http://sigfpe.blogspot.com/2006/03/coalgebras-and-automata.html">this implementation of fold and unfold</a> (as a literate
program) using F-(co)algebras and applied to automata creation, while
those of you with a soft spot for Physics may be interested in John
Baez's musings on <a href="http://math.ucr.edu/home/baez/categories.html">Quantum Mechanics and Categories.</a>
</p>
</div>
</div>
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-programming.html">programming</a> <a href="https://jao.io/blog/tag-auld.html">auld</a> </div>]]></description>
  <category><![CDATA[programming]]></category>
  <category><![CDATA[auld]]></category>
  <link>https://jao.io/blog/programmers-go-bananas.html</link>
  <guid>https://jao.io/blog/programmers-go-bananas.html</guid>
  <pubDate>Fri, 17 Mar 2006 20:15:00 +0000</pubDate>
</item>
<item>
  <title><![CDATA[continuation kata]]></title>
  <description><![CDATA[
<p>
If you have a little Scheme under your belt, just plunge into the
challenge right now:
</p>

<p>
We want to find three integers, x y and z such that both are in the
range [2,9] and that they are the lengths of the sides of a right
triangle <code>(x^2 = y^2 + z^2)</code>. The challenge is to write two procedures,
in-range and fail such that the solution to the problem looks like
this:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">let</span> ((x (in-range 2 9))
      (y (in-range 2 9))
      (z (in-range 2 9)))
  (<span style="color: #023770;">if</span> (= (* x x) (+ (* y y) (* z z)))
      (list x y z)
      (fail <span style="color: #023770;">"no solution"</span>)))
</pre>
</div>

<p>
In other words, we are after an elegant way of implementing search
<i>backtracking</i>: the possible values of the (x, y, z) triplets must be
checked in turn, until a solution is found or we exhaust the search
space. This is the kind of problem that declarative languages like
Prolog solve in a breeze. Scheme does not fare bad, either: the right
solution is just a screenful long. Keep on reading if you feel like
getting some hints.
</p>

<p>
I've stolen this little exercise from an excellent talk by Marc Feeley
on writing a Scheme to C compiler. The example pops up when Marc is
discussing what makes such a compiler tricky (that is, what Scheme
features are missing in C): tail calls, garbage collection, closures and
first class continuations. So here goes the first hint: the solution
uses call/cc.
</p>
<div id="outline-container-org05fb2d1" class="outline-2">
<h2 id="org05fb2d1">Continuations 101</h2>
<div class="outline-text-2" id="text-org05fb2d1">
<p>
I couldn't put a finger on it, but there's something pesky about
continuations: in my experience, they're hard to grasp at first. And
yet, the concept is quite simple: whenever you are evaluating an
expression E, there's someone waiting to do <i>something</i> with the value
of E; for instance, in the process of evaluating:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(+ 3 (* 5 4))
</pre>
</div>

<p>
if you take E to be (* 5 4), the interpreter is waiting for your result
to add 3&#x2026; this thing to be done to the result of evaluating a
(sub)expression can be, quite naturally, represented by a procedure that
takes a single argument; in our example, this procedure could be:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">lambda</span> (v) (+ 3 v))
</pre>
</div>

<p>
or, if you are evaluating the whole thing on a REPL toplevel that will
print the result, maybe something roughly equivalent to:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">lambda</span> (v) (print (+ 3 v)))
</pre>
</div>

<p>
It is this (usually invisible) procedure what we call <i>the current
continuation</i>. Every expression has a continuation, but in many
languages it is only implicit. Scheme gives you the possibility of
accessing it. If you write:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(+ 3 (<span style="color: #023770;">call/cc</span> (<span style="color: #023770;">lambda</span> (cont) (* 5 4))))
</pre>
</div>

<p>
that could be translated as
</p>

<div class="org-src-container">
<pre class="src src-scheme">(+ 3
   (<span style="color: #023770;">let</span> ((cont (<span style="color: #023770;">lambda</span> (v) (+ 3 v)))
      (* 5 4)))
</pre>
</div>

<p>
Of course, things get only interesting when you use cont; for instance,
it is hopefully clear that
</p>

<div class="org-src-container">
<pre class="src src-scheme">(+ 3 (<span style="color: #023770;">call/cc</span> (<span style="color: #023770;">lambda</span> (cont) (* 5 4) (cont 18))))
</pre>
</div>

<p>
evaluates to 21. Besides writing silly examples and bore your readers to
tears, you can put this stuff to good use in a variety of ways. The most
immediate is to early scape from a long computation. This procedure
multiplies all the elements in a given list:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">define</span> (<span style="color: #005555;">mult</span> lon)
  (<span style="color: #023770;">cond</span> ((null? lon) 1)
        ((zero? (car lon)) 0)
        (<span style="color: #023770;">else</span> (* (car lon) (mult (cdr lon))))))
</pre>
</div>

<p>
but it will do a lot of useless work when lon contains a 0. First class
continuations allow a better way:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">define</span> (<span style="color: #005555;">mult-k</span> lon cont)
  (<span style="color: #023770;">cond</span> ((null? lon) 1)
        ((zero? (car lon)) (cont 0))
        (<span style="color: #023770;">else</span> (* (car lon) (mult-k (cdr lon) cont)))))

(<span style="color: #023770;">define</span> (<span style="color: #005555;">mult</span> lon) (<span style="color: #023770;">call/cc</span> (<span style="color: #023770;">lambda</span> (cont) (mult-k lon cont))))
</pre>
</div>

<p>
If you understand why this is better than the previous version, you're
on your way to understanding continuations as non-local exits. And if by
now you're thinking that continuations are not, after all, a big deal,
quick tell me what
</p>

<div class="org-src-container">
<pre class="src src-scheme">(((<span style="color: #023770;">call/cc</span> (<span style="color: #023770;">lambda</span> (k) k)) (<span style="color: #023770;">lambda</span> (x) x)) <span style="color: #023770;">"HEY!"</span>)
</pre>
</div>

<p>
evaluates to, and <i>why</i>. By the way, this nice micro-kata is from <a href="http://www.scheme.com/tspl3/further.html#./further:h3">TSPL's
section on continuations</a>, which provides a nice, if brief,
introduction to call/cc, including a description of another typical
use case: the implementation of threading via coroutines. A more
extended (but still not too long) discussion of the very same issues
can be found in Dann Friedman's beautiful paper <a href="http://www.cs.indiana.edu/~dfried/appcont.pdf">Applications of
Continuations</a>.
</p>

<p>
Finally, if you have a little time in your hands, read through <a href="http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg01318.html">this
interesting ll1 mail thread</a>, where guys like Mathias Felleisen, Avi
Bryant or Paul Graham have their say on continuations and their uses.
</p>
</div>
</div>
<div id="outline-container-org87dadc5" class="outline-2">
<h2 id="org87dadc5">Backtracking</h2>
<div class="outline-text-2" id="text-org87dadc5">
<p>
Since coroutines are not needed to solve our original kata, let me
gloss over them and jump to the next typical use of continuations:
backtracking. A key thing to remember about call/cc is that the
continuation passed to the lambda form is a first class value. Among
other things, that means that you can store it and use it in a totally
unrelated context. Or, in other words, Scheme introduces time-travel
in your toolset, with its associated wonders (as in <a href="http://www.ccs.neu.edu/home/dorai/schelog/schelog.html">Schelog</a>, a Prolog
implemented in Scheme) and <a href="http://srfi.schemers.org/srfi-18/mail-archive/msg00003.html">headaches</a>.
</p>

<p>
Let's see how backtracking can be implemented with the aid of
persistent continuations using an example adapted from Jacques
Chazarain's book <a href="http://www.amazon.fr/exec/obidos/ASIN/2841801314/aetherialnu0a-20?dev-t=1M21AJ49MF6Y0DJ4D1G2%26camp=2025%26link_code=xm2">Programmer avec Scheme</a> (which, by the way, makes for
an excellent second book on Scheme, provided you read French). Writing
a procedure that looks for the first occurrence of an element in a
list that satisfies a given predicate is a piece of cake:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">define</span> (<span style="color: #005555;">search</span> lst p?)
  (<span style="color: #023770;">cond</span> ((null? lst) #f)
        ((pair? lst) (<span style="color: #023770;">or</span> (search (car lst) p?)
                         (search (cdr lst) p?)))
        ((p? lst) lst)
        (<span style="color: #023770;">else</span> #f)))
</pre>
</div>

<p>
where we accept list of lists too. But what if i want to get all
findings one by one? I'd like to have a solution generator that
returns a procedure returning, in successive calls, each of the
occurrences of a solution in the given list. That is, we want to be
able to write code like this one:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">define</span> <span style="color: #005555;">solutions</span>
  (search-generator '(0 ((1 a) 2) b (b c) (((6)))) number?)
(solutions) =&gt; 0
(solutions) =&gt; 1
(solutions) =&gt; 2
(solutions) =&gt; 6
(solutions) =&gt; 'done
</pre>
</div>

<p>
Persistent continuations allow a very clean implementation of
search-generator. The strategy is to start the search, and each time
we find an element in the list satisfying the predicate store the
current continuation (which will keep on searching for more solutions)
for later invocations. We then return a procedure that calls the
continuation and stores a new one which will resume the search with
the rest of the list. You can have a little fun trying to find the
solution before reading it below. Or, if you get stuck, to read
Ferguson and Duego's excellent <a href="http://repository.readscheme.org/ftp/papers/PLoP2001_dferguson0_1.pdf">Call with Current Continuation
Patterns</a>, where you'll find examples of call/cc in action.  Got your
answer? Well, let's compare:
</p>

<div class="org-src-container">
<pre class="src src-scheme">(<span style="color: #023770;">define</span> (<span style="color: #005555;">search-generator</span> lst p?)
  (<span style="color: #023770;">let</span> ((success '?)) <span style="color: #666666; font-style: italic;">;; </span><span style="color: #666666; font-style: italic;">placeholder for the current continuation
</span>    (<span style="color: #023770;">letrec</span> ((cont-success <span style="color: #666666; font-style: italic;">;; </span><span style="color: #666666; font-style: italic;">next continuation
</span>              (<span style="color: #023770;">lambda</span> (x) (search lst)))
             (search
              (<span style="color: #023770;">lambda</span> (elem)
                (<span style="color: #023770;">cond</span> ((null? elem) 'done)
                      ((pair? elem) (search (car elem))
                                    (search (cdr elem)))
                      ((p? elem) (<span style="color: #023770;">call/cc</span>
                               (<span style="color: #023770;">lambda</span> (k) <span style="color: #666666; font-style: italic;">;; </span><span style="color: #666666; font-style: italic;">next search will continue from here
</span>                                 (<span style="color: #023770;">set!</span> cont-success k)
                                 (success elem))))
                      (<span style="color: #023770;">else</span> 'done)))))
      (<span style="color: #023770;">lambda</span> () (<span style="color: #023770;">call/cc</span> (<span style="color: #023770;">lambda</span> (k)
                       (<span style="color: #023770;">set!</span> success k)
                       (cont-success 'done)))))))
</pre>
</div>

<p>
Once you grasp how this works, you have all the ingredients to solve
our original kata.
</p>
</div>
</div>
<div id="outline-container-org0df2f64" class="outline-2">
<h2 id="org0df2f64">Not only Scheme</h2>
<div class="outline-text-2" id="text-org0df2f64">
<p>
There are other languages with support for first class continuations,
<a href="http://www.smlnj.org/doc/SMLofNJ/pages/cont.html">SML/NJ</a> and <a href="http://www-128.ibm.com/developerworks/java/library/os-lightweight9/">Ruby</a> being the most salient cases. Besides, <a href="http://seaside.st/">Seaside</a>
implements them for our beloved Smalltalk.
</p>

<p>
You don't need call/cc to play some of the tricks discussed above. For
instance, one can implement backtracking <a href="http://www.ps.uni-sb.de/~duchier/python/continuations.html">in Python</a> (the linked article
contains also an intro to continuations) or <a href="http://www.csse.monash.edu.au/~lloyd/tildeFP/1990BCJ/">Standard SML</a> (ditto, also
with examples in Pascal, and, of course, <a href="http://www.csse.monash.edu.au/~lloyd/tildeFP/SML/1997/Continuations/">SML</a>), using a technique known
as <i>Continuation Passing Style</i>, or CPS, that consist on passing
explicitly the continuation to each of your functions. Explaining CPS
would take another article, so, for now, i will let you explore it by
yourself, but i'll mention that armed with CPS you can, essentially,
play all the call/cc tricks. A few years ago, type theorist
extraordinaire Benjamin C. Pierce asked in the Caml mailing list about
cool CPS usages, and took the time <a href="http://caml.inria.fr/pub/ml-archives/caml-list/2002/04/a20d07d890dc2ebd525fbe3eed177492.en.html">to summarize the responses he
got</a>. It contains pointers to many mind-bending readings.
</p>
</div>
</div>
<div id="outline-container-org65cb78e" class="outline-2">
<h2 id="org65cb78e">The solution</h2>
<div class="outline-text-2" id="text-org65cb78e">
<p>
I almost forgot: if you give up finding our kata's solution or want to
check it out, you'll find it in <a href="http://www.iro.umontreal.ca/%7Eboucherd/mslug/meetings/20041020/minutes-en.html">Marc Feeley's talk</a> for the Montreal
Scheme/Lisp Users Group. As i've mentioned, it deals with the
implementation of a Scheme to C compiler (Marc is the lead developer
of Gambit-C), which is based on CPS. The site contains links to the
talk slides and videos, and a beautiful pure-scheme implementation of
the compiler. Enjoy.
</p>
</div>
</div>
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-programming.html">programming</a> </div>]]></description>
  <category><![CDATA[programming]]></category>
  <link>https://jao.io/blog/continuation-kata.html</link>
  <guid>https://jao.io/blog/continuation-kata.html</guid>
  <pubDate>Sun, 12 Feb 2006 23:39:00 +0000</pubDate>
</item>
<item>
  <title><![CDATA[beyond mainstream object-oriented programming]]></title>
  <description><![CDATA[
<div id="outline-container-org3cbc584" class="outline-2">
<h2 id="org3cbc584">Introduction</h2>
<div class="outline-text-2" id="text-org3cbc584">
<p>
After a few scheming years, i had come to view objects as little
more than <a href="http://okmij.org/ftp/Scheme/oop-in-fp.txt">poor-man closures</a>.  <a href="ftp://ftp.cs.indiana.edu/pub/scheme-repository/doc/pubs/swob.txt">Rolling a simple</a> (or <a href="http://www-spi.lip6.fr/~queinnec/WWW/Meroon.html">not so simple</a>)
object system in scheme is almost <a href="http://handgranat.se/lab/scheme/oscheme.scm">a textbook exercise</a>.  Once you've
got statically scoped, first-order procedures, you don't need no
built-in objects. That said, it is not that object-oriented
programming is not useful; at least in my case, i find myself often
implementing applications in terms of a collection of procedures
acting on requisite data structures. But, if we restrict ourselves
to single-dispatch object oriented languages, i saw little reason to
use any of them instead of my beloved Scheme.
</p>

<p>
Things started to change recently due to my discovering the
pleasures of Smalltalk. First and foremost, it offers a truly
empowering integrated ambient to live and develop in. Second, if
you're going to use objects, using the simplest, cleanest syntax
will not hurt. Add to that some reading on <a href="http://users.ipa.net/~dwighth/smalltalk/byte_aug81/design_principles_behind_smalltalk.html">the beautiful design
principles underlying Smalltalk</a>, and one begins to wonder if
closures aren't, in fact, <a href="http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html">poor-man objects</a>&#x2013;or at least i do,
whenever i fall in an object-oriented mood (i guess i'm yet not
ready <a href="http://www.kimbly.com/blog/000063.html">to reach satori</a>).
</p>

<p>
But Scheme is not precisely an ugly or bad designed language, so i
needed some other reason to switch language gears for my OO
programming.  I knew there's more than encapsulation or subtype
polymorphism in object-land from my readings on CLOS (the Common
Lisp Object System), or on <a href="http://homepages.cwi.nl/~ralf/OOHaskell/">Haskell's type classes</a> (and its built-in
<a href="http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Parametric_polymorphism">parametric polymorphism</a>), but i was after something retaining
Smalltalk's elegance. And then i remembered that, when i was a
regular lurker in the <a href="http://tunes.org/wiki/Main_Page">Tunes project</a>'s mailing lists and IRC channel,
a couple of smart guys were implementing an OO language whose syntax
was smalltalkish. That language (which, if memory servers, started
life with the fun name <i>who me?</i>) has evolved during the last few
years into a quite usable programming environment named <a href="slate.tunes.html">Slate</a>,
started by Lee Salzman and currently developed and maintained by
<a href="http://tunes.org/~water/">Brian Rice</a>.
</p>

<p>
I've been reading about Slate during the last few days, and decided
to learn it. What motivated me was discovering how Slate goes beyond
mainstream object-oriented programming by incorporating well-known
(but hardly used) and really powerful paradigms. In short, Slate
improves Smalltalk's single-dispatch model by introducing and
combining two apparently incompatible technologies: multiple
dispatch and prototype-based programming. To understand the whys and
hows of Slate, there's hardly a better way than reading Lee
Salzman's <a href="http://tunes.org/~eihrul/ecoop.pdf">Prototypes with Multiple Dispatch</a>. The following
discussion is, basically, an elaboration of Lee's explanation on the
limitations of mainstream OO languages, and how to avoid them with
the aid of PMD.
</p>

<p>
<i>Note</i>: the images are thumbnails of <a href="https://jao.io/docs/beyond-oop.pdf">this PDF file</a>, with clickable
links inside.
</p>
</div>
</div>
<div id="outline-container-org8735fc0" class="outline-2">
<h2 id="org8735fc0">Fishes and sharks</h2>
<div class="outline-text-2" id="text-org8735fc0">
<p>
Let's start by showing why on earth would you need anything beyond
Smalltalk's object system (or any of its <i>modern</i>
copycats). Consider a simple oceanographic ecosystem analyser,
which deals with (aquatic) Animals, Fishes and Sharks. These are
excellent candidates for class definitions, related by
inheritance. Moreover, we are after modeling those beasts'
behaviours and, in particular, their reactions when they encounter
each other: each time a Shark meets a Fish of other species, the
Shark will swallow the other Fish, while when a Shark meets Shark
they will fight.  As a result of such fighting, Sharks get
unhealthy, which regrettably complicates matters: wound sharks
won't try to eat other fishes, and will swim away other sharks
instead of fighting them. The image on the left provides a sketchy
representation of the code we need to model our zoo. Waters are
quickly getting muddled implementation-wise.
</p>


<figure id="org2720be7">
<img src="https://jao.io/img/pmd-motivation.png" alt="pmd-motivation.png">

</figure>

<p>
On the one hand, subtype polymorphism based just on the object
receiving the encounter message: we need, in addition, to take
into account the argument's concrete type to implement the desired
behaviour. This is a well-known issue in single-dispatch
languages, whose cure is, of course, going to multiple dispatching
(see below). In particular, we want to avoid the need to modify
existing classes whenever our hierarchy is extended.
</p>

<p>
On the second hand, varying state (exemplified here by the Shark's
isHealthy instance variable complicates the implementation
logic. As we will see, prototype-based languages offer a way to
factor out this additional complexity.
</p>
</div>
</div>
<div id="outline-container-org3672052" class="outline-2">
<h2 id="org3672052">Beyond single-dispatch</h2>
<div class="outline-text-2" id="text-org3672052">
<p>
The need to adjust behaviour on the basis of the type of both a
message receiver and its arguments arises frequently in practice. So
frequently, that a standard way of dealing with it has been
christened as the Visitor design pattern. The technique, also known
as double-dispatch, is well known: you can see, for instance, how
it's applied <a href="http://www.eli.sdsu.edu/courses/spring03/cs535/notes/dispatch/dispatch.html">to arithmetic expressions in Smalltalk</a>, or read about a
<a href="http://www.onlamp.com/lpt/a/3858">generic implementation of multimethods in Python</a> (which also
includes a basically language-independent discussion on the issues
at hand). If you happen to be a C++ programmer, you may be tempted
to think that global functions and overloading solve the problem in
that language. Well, <a href="http://www.usenet.com/newsgroups/comp.lang.dylan/msg00009.html">think twice</a>: a proper implementation of
multiple dispatch in C++ needs of RTTI and templates, as shown in
<a href="http://www.eptacom.net/pubblicazioni/pub_eng/mdisp.html">this article</a>.
</p>


<figure id="org0f22fc0">
<img src="https://jao.io/img/pmd-clos-dylan.png" alt="pmd-clos-dylan.png">

</figure>

<p>
<a href="http://www.n-a-n-o.com/lisp/cmucl-tutorials/CLOS-guide.html">CLOS</a> and <a href="http://www.gwydiondylan.org/gdref/tutorial/ch05.html">Dylan</a> are two examples of languages solving the issue from
the onset by including support for multi-methods. The idea is to
separate methods from classes (which only contain data slots). As
shown in the pseudo-code of the accompanying figure, methods are
defined as independent functions with the same name, but differing
in their arguments' types (in CLOS, a set of such methods is called
a <i>generic function</i>). When a generic function is called, the system
selects the actual method to be invoked using the types of <i>all the
arguments</i> used in the invocation. The encounter generic function in
our running example provides a typical example, as shown in the
figure on the right. The benefits of having multi-methods at our
disposal are apparent: the code is simpler and, notably, adding new
behaviours and classes to the system does not need modifications of
existing code. For instance, we can introduce a Piranha, which eats
unhealthy sharks instead of swimming away from them, by defining the
requisite class and methods, without any modification whatsoever to
the already defined ones.
</p>

<p>
On the downside, we have still to deal with the complications
associated with internal state. Enter the magic world of
prototype-based systems.
</p>
</div>
</div>
<div id="outline-container-org961f347" class="outline-2">
<h2 id="org961f347">The ultimate dynamic</h2>
<div class="outline-text-2" id="text-org961f347">
<p>
If you like dynamic languages, chances are you'll find
prototype-based system an almost perfect development
environment. Prototype-based languages emerged as an evolution of
Smalltalk with the invention of <a href="http://research.sun.com/self/language.html">Self</a> by <a href="http://research.sun.com/people/mybio.php?c=404">David Ungar</a> and <a href="http://research.sun.com/people/mybio.php?c=405">Randall
B. Smith</a> during the late eighties. The key idea behind Self is
noticing that, most of the time, class definitions needlessly coerce
and complicate your object model.
</p>

<p>
A class definition becomes a contract to be satisfied by any
instance, and it is all too easy to miss future or particular needs
of your objects (class-based inheritance is just a partial solution
to this problem, as shown, for instance, by the so-called <a href="http://www.cas.mcmaster.ca/~emil/publications/fragile/">fragile
base class problem</a>). But, if you look around you, objects change in
internal behaviour and data content continously, and our attempts at
distilling their Platonic nature are often in vain.
</p>

<p>
In prototype-based programming, instead of providing a <i>plan</i> for
constructing objects, you simply clone existing instances and modify
their behaviour by directly changing the new instance's slots (which
provide uniform access to methods and state). New clones contain a
pointer to their parent, from which they inherit non-modified slots:
there is no way to access state other than via messages sent to
instances, which simplifies tackling with state.
</p>

<p>
Class-based languages oblige you to keep two relationships in mind
to characterize object instances: the "is-a" relationship of the
object with its class, and the "kind-of" relationship of that class
with its parent. In self, inheritance (or behaviour <b>delegation</b>) is
the only one needed. As you can see, Self is all about making
working with objects as simple as possible. No wonder Ungar and
Smith's seminal paper was titled <a href="http://research.sun.com/self/papers/self-power.html">Self: The Power of
Simplicity</a>. Needless to say, a must read.
</p>


<figure id="org81d3c3c">
<img src="https://jao.io/img/pmd-proto.png" alt="pmd-proto.png">

</figure>

<p>
The figure above shows how our running example would look in selfish
pseudo-code. As promised, state is no longer surfacing in our method
implementation's logic. Unfortunately, we have lost the benefits of
multi-methods in the process. But fear not, for, as we will see, you
can eat your cake and have it too. Instead of pseudo-code, you can
use Self itself, provided you are the happy owner of a Mac or a Sun
workstation.  Or you can spend 20 fun minutes seeing <a href="http://video.google.com/videoplay?docid=5776880551404953752">the Self video</a>,
which features the graphical environment accompanying the
system. Like Smalltalk, Self provides you with a computing
environment where objects are created, by cloning, and interact with
you. The system is as organic and incremental as one can possibly
get.
</p>

<p>
Of course, you're not limited to Self. For instance, Ken Dickey
fleshed up Norman Adams' saying that objects are poor man closure's
by offering <a href="ftp://ftp.cs.indiana.edu/pub/scheme-repository/doc/pubs/swob.txt">a prototype-based object system in Scheme</a>, and, more
recently, Neil Van Dyke has released <a href="http://www.neilvandyke.org/protobj/">Protobj</a>. And you have probably
already used a very popular language in the family: Javascript. The
<a href="http://www.dekorte.com/docs/protos/">list goes on</a>, albeit, unfortunately, many of these languages lack
either Self's nice integrated environment, or a portable, up-to-date
implementation. Slate to the rescue.
</p>
</div>
</div>
<div id="outline-container-org40db5af" class="outline-2">
<h2 id="org40db5af">The best of both worlds</h2>
<div class="outline-text-2" id="text-org40db5af">
<p>
Prototyping and multiple dispatch are, at first sight, at odds. After
all, method dispatching based on arguments' type needs, well, a type
for each argument, doesn't it? As it happens, Lee Salzman and Brian
Rice have envisioned a way of combining the power of both paradigms
into Slate. In fact, proving how this is possible is the crux of Lee's
article. In addition, Slate aims at providing a complete development
environment in the vein of Smalltalk or Self. Too good to be true? In
future installments of this blog category, we'll see how and why it's
true, but, if you cannot wait, just run-not-walk to <a href="http://slate.tunes.org">Slate's
site</a>. You'll have a great time.
</p>
</div>
</div>
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-programming.html">programming</a> <a href="https://jao.io/blog/tag-auld.html">auld</a> </div>]]></description>
  <category><![CDATA[programming]]></category>
  <category><![CDATA[auld]]></category>
  <link>https://jao.io/blog/beyond-mainstream-object-oriented-programming.html</link>
  <guid>https://jao.io/blog/beyond-mainstream-object-oriented-programming.html</guid>
  <pubDate>Sun, 05 Feb 2006 06:36:00 +0000</pubDate>
</item>
<item>
  <title><![CDATA[as simple as possible...]]></title>
  <description><![CDATA[
<p class="verse">
<i>&#x2026; but not simpler</i>.<br>
</p>

<p>
<a href="http://www.quotationspage.com/subjects/simplicity/">Einstein's (attributed) quotation</a> has become an aphorism, taken for
granted by every mathematician or physicist i've ever met (to mention
two kinds of people i've been frequently involved with). One would
expect the same attitude from a community that invented the term <a href="http://www-inst.eecs.berkeley.edu/~maratb/readings/NoSilverBullet.html">'no
silver bullet'</a>, and yet, since i got into computer science, first for
fun and later on for a living, i've found lots of people with, er, a
different viewpoint. Take for instance this excerpt from <a href="http://blogs.msdn.com/sriram/archive/2006/01/15/lisp_is_sin.aspx">Lisp is sin</a>,
a widely cited and commented article by Sriram Krisnan:
</p>

<blockquote>
<p>
In Visual Studio, we look at 3 distinct categories of programmers. We
call them Mort, Elvis and Einstein - the 3 personas we take into
consideration whenever we create any developer technology. What is
difficult for some of us geeks to comprehend sometimes is - all 3 of
them are equally important. When you look at technology like Windows
Workflow Foundation, one of the driving forces was to let non-geeks
build software. Not everyone needs to be a Raymond Chen or a Dave
Cutler. Not everyone needs to understand the difference between the
various GC algorithms. However, everyone needs the ability to be
productive. And everyone needs to be able to get software working
without needing a CS degree.
</p>

<p>
We cannot afford to restrict software development only to those who
know Windows kernel internals or those who can understand what a
continuation is. It's not that other people are not smart - they just
have better things to do. That's the key piece of understanding I find
missing sometimes.
</p>
</blockquote>

<p>
Nonsense, if you ask me. And yet, i've been hearing this same argument,
in different dressings, once and again since i got into computer
science. Let's apply the same line of reasoning to other disciplines,
and see how well it fares:
</p>

<p>
Hey Albert, your General Relativity is awesome but, you know, with all
that jazz about differential geometry and curved spacetimes, it's too
hard; we're not as smart as you, pal, so we'd better use Newtonian or
Aristotelian mechanics to calculate those GPS satellite orbits and get
going with other important things we need to do. Hope you understand,
Albert.
</p>

<p>
Well Santiago, your ideas about neurons and surgery sound pretty deep
and mystifying, but please, think of the Galens among us: we don't have
the time to investigate every new fad, and, anyway, we wouldn't
understand it if we did. Know what? We'll keep using our old good cures
and stay away from untrodden venues. Our healing parchments are a bit of
a hack, but they get the work done&#x2026; most of the time, that is.
</p>

<p>
Does it make <i>any</i> sense? Now, maybe you think that i am exaggerating,
and that the comparisons above are stretching the point a bit too far.
If so, take a second to look back to the people that made your nice
computing environment possible. Take a look at <a href="http://www.answers.com/topic/charles-babbage?gwp=19">Charles Babagge
visions</a>; read about <a href="http://www.answers.com/topic/church-turing-thesis">Alan Turing and Alonzo Church</a> or <a href="http://www.answers.com/topic/john-von-neumann?gwp=19">John von Neumann</a>;
admire the elegance of <a href="http://www-formal.stanford.edu/jmc/recursive.html">McCarthy's original LISP</a> (1960); prepare to be
surprised with the things the people in Dough Engelbart's Augmentation
Research Center <a href="http://sloan.stanford.edu/MouseSite/1968Demo.html">were doing</a> during the sixties; try to find a modern
drawing program that matches <a href="http://www.guidebookgallery.org/articles/sketchpadamanmachinegraphicalcommunicationsystem">Sketchpad</a>'s algorithms (or see it in
action in <a href="http://www.archive.org/details-db.php?mediatype=movies&amp;identifier=AlanKeyD1987">this presentation</a> by Alan Kay); follow the fascinating
development of the overlapping windows interface, hand in hand with
Smalltalk history back at Xerox PARC, and do it <a href="http://gagne.homedns.org/~tgagne/contrib/EarlyHistoryST.html">from the horse's
mouth</a>; feel the thrill of the people that went beyond Xerox's big
wigs' shortsightedness and on to making <a href="http://folklore.org/StoryView.py?project=Macintosh&amp;story=The_Macintosh_Spirit.txt&amp;topic=Apple%20Spirit&amp;sortOrder=Sort%20by%20Date">a dent in the universe</a>: it was
1984, that same year <a href="http://www.donhopkins.com/drupal/node/109">the lisp machine wars</a> culminated in the creation
of the GNU project, which was all about ideals, about empowering
people, about freedom. When you're done, tell me whether i'm going
overboard when making parallelisms between computer science and
physics or medicine!
</p>

<p>
All those people had a vision, a dream, and pursued it with an amazing
display of hard work, stubbornness and intelligence. They took no
prisoners, and by the late eighties had pushed that new thing called,
for want of a better name, Computer Science to its modern standards.
</p>

<p>
Then winter came. Not just the AI winter. Compare the swift pace of CS
developments during the 1960-80 period with the subsequent
<i>advancements</i> in the field. We're using the same metaphors, the same
kind of systems that we inherited from those guys and gals. Why, we
even envy the power of Lisp Machines these days. It's been a long,
cold winter for CS. And the main reason was the appearance of the
mentality that i'm criticising in this post, what Alan Kay aptly
calls, in a <a href="http://acmqueue.com/modules.php?name=Content&amp;pa=showpage&amp;pid=273">recent interview</a>, a <i>pop culture</i> of computers:
</p>

<blockquote>
<p>

</p>

<p>
Perhaps it was commercialization in the 1980s that killed off the
next expected new thing [&#x2026;] But a variety of different things
conspired together, and that next generation actually didn't show
up. One could actually argue&#x2014;as I sometimes do&#x2014;that the
success of commercial personal computing and operating systems has
actually led to a considerable retrogression in many, many
respects.  You could think of it as putting a low-pass filter on
some of the good ideas from the '60s and '70s, as computing spread
out much, much faster than educating unsophisticated people can
happen. In the last 25 years or so, we actually got something like
a pop culture, similar to what happened when television came on
the scene and some of its inventors thought it would be a way of
getting Shakespeare to the masses. But they forgot that you have
to be more sophisticated and have more perspective to understand
Shakespeare. What television was able to do was to capture people
as they were.  So I think the lack of a real computer science
today, and the lack of real software engineering today, is partly
due to this pop culture.
</p>
</blockquote>

<p>
Dead on, i say. People advocating about making programming simpler than
possible are the hallmark of this pop culture. And when corporate and
economic interests enter the picture, things get even worse. The <i>Lisp
is sin</i> essay goes on to say:
</p>

<blockquote>
<p>
I frequently see on Slashdot "Windows is designed for stupid users".
That is quite insulting to the millions of moms and dads, teachers and
laywers and people from other walks of life who use Windows or even
the Mac. If we mandated that every new user understand Windows'
command line syntax or Emacs, we would have failed as an industry - we
would have locked out the rest of the world.
</p>
</blockquote>

<p>
In my opinion, this totally misses the point. There's nothing wrong in
making computers simpler to users. On the contrary, that's probably what
this endeavour is all about. Alan Kay saw it, Apple took head with its
<i>computer for the rest of us</i> mantra. But it does not follow that there
must be a <i>CS for the rest of us</i>. Making all this amazing technology
possible takes effort, and needs a high level of sophistication. Alan
didn't try to create systems usable by children inventing PHP. He
created Smalltalk striving to improve Lisp, he studied Piaget and
Papert, he has degrees in maths and biology. And he needed all that, and
then more.
</p>

<p>
The (trivial) point i'm trying to make is that not everybody has what
it takes to be a programmer. Just as not everybody can be a singer or
a painter (as an aside, i tend to agree with the opinions that link
<a href="http://www.onlamp.com/pub/a/onlamp/2005/06/30/artofprog.html">programming and art</a>). As a matter of fact, good programmers are rare
and need a quite peculiar combination of skills and talents. Donald
Knuth has put it far better than i could in the essay <i>Theory and
Practice, II</i> (from his <a href="http://www-cs-faculty.stanford.edu/~knuth/cs.html">Selected Papers on Computer Science</a>):
</p>

<blockquote>
<p>
The most important lesson [after developing TeX], for me, was that
<i>software is hard</i>; and it takes a long time. From now on I shall
have significantly greater respect for every successful software
tool that I encounter.[&#x2026;]  Software creation not only takes
time, it's also much more difficult that I thought it would
be. Why is this so? I think the main reason is that a longer
attention span is needed when working on a large computer program
than when doing other intellectual tasks. A great deal of
technical information must be kept in one's head, all at once, in
high-speed random-access memory somewhere in the brain.
</p>
</blockquote>

<p>
We don't solve the painter's <i>problem</i> by complaining that perspective
is hard to grasp and people should better use flat icons. In the same
way, we shouldn't be claiming for a trivialisation of CS both <a href="http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html">in
academia</a> and in the industry. The <i>we would have failed in the industry</i>
bit in the Sriram quote above is really sad: we're sacrificing an
admirable legacy in the name of industry and corporate profit. The
most remarkable feat of our current industry leaders is to have
convinced the rest of the world that having software systems that eat
incredible amounts of resources and explode without reason every now
and then is part of an acceptable, even top-notch,
technology. Fortunately, other disciplines show far more respect for
the people that, ultimately, is paying their wages.
</p>

<p>
If you've got this far, you already have one of the qualities needed
to become a programmer: stamina. You'll need more. Be prepared to
study hard, to learn maths, to <a href="http://jaortega.wordpress.com/2006/01/11/counting-by-lambdas/">live in abstract worlds</a>. If you feel
that you have "more important things to do", well, that's all very
well, but don't ask the rest of us to dumb down the subject so that
everybody can be a programmer. Lisp is not a sin. The sin would be to
betray the dreams, ideals and hard work of the people that have taken
us this far. We owe that to them, and to ourselves.
</p>

<p>
To end this never-ending diatribe, let me add a couple of things:
first, i should apologize for taking Sriram as the scapegoat to a long
honed rage: his essay contains many good points worth reading and
mulling on; second, i hope you're not thinking this is just an
arrogant rant by an old fart: i'm not that old.
</p>
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-programming.html">programming</a> <a href="https://jao.io/blog/tag-auld.html">auld</a> </div>]]></description>
  <category><![CDATA[programming]]></category>
  <category><![CDATA[auld]]></category>
  <link>https://jao.io/blog/as-simple-as-possible.html</link>
  <guid>https://jao.io/blog/as-simple-as-possible.html</guid>
  <pubDate>Thu, 19 Jan 2006 01:19:00 +0000</pubDate>
</item>
<item>
  <title><![CDATA[the joy of repl]]></title>
  <description><![CDATA[
<p>
Back in the old days i was a macho C++ programmer, one of those
sneering at Java or any other language but C, willing to manage my
memory and pointers and mystified by the complexity of the template
syntax (it was difficult and cumbersome, ergo it had to be
good). Everyone has a past.
</p>

<p>
Things began to change when i decided to add Guile extensibility to
<a href="http://www.gnu.org/software/mdk/mdk.html">GNU MDK</a>. I was using the project as an excuse to learn everything one
has to learn to write free software, from parsers with flex and bison,
to documentation generators like texinfo and doxygen or localisation
via gettext. Next thing was scriptability, and those days Scheme was
still <i>the way</i> to extend your GNU programs (last time i checked, GNOME
was full of XML, a windows-like registry and, oh my, C#&#x2026; no Scheme
(or good taste) to be seen).
</p>

<p>
So, when i first encountered Scheme i was high on static type
checking, object oriented programming in its narrow C++ flavour, and
all that jazz. I didn't understand immediately what was so cool about
having an interpreter, and defining functions without the compiler
checking their signature at every single call made me feel uneasy. I
was told that i still had strong type checking in Lisp, but that it is
deferred to run time, instead of at the apparently safer compile
phase. I didn't get it.  Thanks god, SICP was so fun that i kept on
learning, and i kept wondering for a while what was so great about
interpreters and dynamic typing.
</p>

<p>
Problem was, i was writing <i>C programs</i> in Scheme. In a compiled
language (a la C) and, to some degree, in any statically typed one,
your code is dead. You write pages and pages of inert code. You
compile it.  Still dead. Only when you launch that binary does it come
to life, only that it lives elsewhere, beyond your reach. Admittedly,
i'm exaggerating: you can reach it in a convoluted way via a
debugger. But still. A debugger is an awkward beast, and it will only
work with the whole lot: all your program compiled, linked and
whatnot.
</p>

<p>
Enter a dynamic language. Enter its <a href="http://www.lisp.org/table/top-level.htm">REPL</a>. When you have a, say, Lisp
interpreter at your disposal <i>you don't write your code first and load
it later</i> (that's what i was doing at first). You enter your code
piecewise, function by function, variable by variable at that innocent
looking prompt. You develop <i>incrementally</i>, and, at every single
moment, your objects and functions are alive: you can access them,
inspect them, <i>modify</i> them. Your code becomes an organic creature,
plastic. Its almost not programming, but experimenting.
</p>

<p>
Maybe you're raising a skeptical eyebrow. Maybe you have one of those
modern visual-something debugger that lets you modify your compiled
code on the fly and continue running your code using the new
definitions and you think that's what i'm talking about&#x2026; Well, no,
sorry, that's only <i>part</i> of what i'm talking about. To begin with, you
<i>continue</i> executing your program. I can do whatever i want. But that's
not all. We are talking about a dynamically typed language. That means
that me and my little REPL have much more leeway to modify the living
code, and thus much more margin to grow up and evolve the code.
</p>

<p>
At the end of the day, dynamically typed languages give me freedom.
Programming is a creative process and greatly benefits from that
freedom. At first, abandoning the safety net provided by static typing
was a little bit scary, but as i grew up as a programmer i felt more
and more confident, and gradually the initially uneasy feeling morphed
into joy. The joy of REPL.
</p>

<p>
<a href="http://www.dreamsongs.com/RPG.html">Richard P. Gabriel</a> has made a far better job in beautifully conveying
what i'm trying to express in his excellent introduction to David
Lamkins' book <a href="http://www.psg.com/~dlamkins/sl/cover.html">Successful Lisp</a>, entitled <i>The Art of Lisp and
Writing</i>. Unfortunately, i haven't found it online &#x2013; you can read the
first few pages in amazon.com's "look inside this book" section <a href="http://www.amazon.com/exec/obidos/ASIN/3937526005/daviblamkwebs-20?creative=327641&amp;camp=14573&amp;link_code=as1">for
this book</a>. And also in his essay <a href="http://www.dreamsongs.com/SeatBelts.html">Do Programmers Need Seat Belts?</a>. Paul
Graham has famously argued in favour of bottom-up development in many
of his essays, and specially in <a href="http://www.paulgraham.com/progbot.html">Programming Bottom-Up</a>:
</p>

<blockquote>
<p>
It's worth emphasizing that bottom-up design doesn't mean just writing
the same program in a different order. When you work bottom-up, you
usually end up with a different program. Instead of a single,
monolithic program, you will get a larger language with more abstract
operators, and a smaller program written in it. Instead of a lintel,
you'll get an arch.
</p>
</blockquote>

<p>
Finally, please note that i'm well aware that the <a href="http://lambda-the-ultimate.org/node/view/986">static vs. dynamic
typing debate</a> is still open, and that decent type systems like those
in Haskell and ML have, arguably, much to offer in the way to solid
software engineering.  <a href="http://en.wikipedia.org/wiki/Category:Type_theory">Type theory</a> has also a powerful and beautiful
mathematical foundation. The above is just my gut feeling and current
position on these issues, and i don't pretend to have backed it with
solid technical argumentation. Nor was it my goal. I'm more interested
here in programming as a creative activity than as engineering.
</p>
<div class="taglist"><a href="https://jao.io/blog/tags.html">Tags</a>: <a href="https://jao.io/blog/tag-programming.html">programming</a> <a href="https://jao.io/blog/tag-auld.html">auld</a> </div>]]></description>
  <category><![CDATA[programming]]></category>
  <category><![CDATA[auld]]></category>
  <link>https://jao.io/blog/the-joy-of-repl.html</link>
  <guid>https://jao.io/blog/the-joy-of-repl.html</guid>
  <pubDate>Sat, 14 Jan 2006 00:39:00 +0000</pubDate>
</item>
</channel>
</rss>
