<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="/stylesheets/rss.css" type="text/css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>Tom Moertel's Weblog: Category functional programming</title>
    <link>http://blog.moertel.com/articles/category/functional-programming</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>Quality rants on programming theory and stuff geeks like</description>
    <item>
      <title>Thinking algebraically: a functional-programming dividend that pays during your imperative-programming day job</title>
      <description>&lt;p&gt;Although at work I code mostly in Python &amp;#8211; a language from which
&lt;a href="http://www.artima.com/weblogs/viewpost.jsp?thread=98196"&gt;&lt;em&gt;lambda&lt;/em&gt; and &lt;em&gt;map&lt;/em&gt; were nearly removed&lt;/a&gt; &amp;#8211; I still find that functional-programming experience
has its benefits.  One of the
&amp;#8220;functional-programming dividends&amp;#8221; I notice most often is insight
gained from considering problems from an algebraic perspective.&lt;/p&gt;


	&lt;p&gt;Recently, for example, I had a small parsing problem.  I had to
write code that, given a simple grammar specification as input, emits
a regular expression that matches the language generated by the
grammar.&lt;/p&gt;


	&lt;p&gt;Here&amp;#8217;s a simplified version of the problem.  A grammar specification
is limited to a series of one or more &lt;em&gt;atoms&lt;/em&gt;.  For example, &amp;#8220;a b c&amp;#8221; 
represents the atom &amp;#8220;a&amp;#8221;, followed by the atom &amp;#8220;b&amp;#8221;, followed by the
atom &amp;#8220;c&amp;#8221;.  To generate the grammar, the series of atoms is interpreted
such that each atom (except the last) generates a production rule of
the following form:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;atom_rule ::=
  &amp;lt;the literal atom&amp;gt; (SPACE &amp;lt;the next rule&amp;gt; | NOTHING)
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;(SPACE represents literal white space and &lt;span class="caps"&gt;NOTHING&lt;/span&gt; represents an
empty string.)  The grammar as a whole is rooted in the first atom&amp;#8217;s
rule.&lt;/p&gt;


	&lt;p&gt;Thus the specification &amp;#8220;a b c&amp;#8221; represents the following grammar:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;grammar ::= a_rule
a_rule  ::= "a" (SPACE b_rule | NOTHING)
b_rule  ::= "b" (SPACE c_rule | NOTHING)
c_rule  ::= "c" 
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Note that the final atom&amp;#8217;s production matches only the literal atom
itself: it has no following rule on which to chain.&lt;/p&gt;


	&lt;p&gt;The grammar, in turn, generates the following language:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;a
a b
a b c
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Thus, given the grammar specification &amp;#8220;a b c&amp;#8221;, my code had to produce
a regular expression that would match &amp;#8220;a&amp;#8221;, &amp;#8220;a b&amp;#8221;, or &amp;#8220;a b c&amp;#8221;.&lt;/p&gt;


	&lt;p&gt;At this point, please stop for a moment and think about this little
programming exercise.  Do any solutions leap to mind?  How would you
approach the problem?  Form your opinions now, because I&amp;#8217;m going to
ask you about them later. (If you&amp;#8217;re feeling especially caffeinated, try
coding a solution before reading on.)&lt;/p&gt;&lt;p&gt;For me, the insight that made the exercise easy was seeing that the
grammar is given by folding a (suitably defined) right-associative
binary operator through the series of atoms.  The relationship might
be easier to see if you substitute away the intermediate production
rules from the grammar above:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;grammar ::= "a" (SPACE "b" (SPACE "c" | NOTHING) | NOTHING)
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;If you squint past the &lt;span class="caps"&gt;SPACE&lt;/span&gt; and &lt;span class="caps"&gt;NOTHING&lt;/span&gt; terms, you&amp;#8217;ll see that the
grammar has the form&lt;/p&gt;


&lt;p&gt;(&lt;em&gt;a&lt;/em&gt; + (&lt;em&gt;b&lt;/em&gt; + (&lt;em&gt;c&lt;/em&gt;)))&lt;/p&gt;

	&lt;p&gt;The + is a binary operator that generates the parts we squinted away.
Once you see what&amp;#8217;s going on structurally, the operator is easy to
define:&lt;/p&gt;


&lt;p&gt;&lt;em&gt;x&lt;/em&gt; + &lt;em&gt;y&lt;/em&gt;  =  &lt;em&gt;x&lt;/em&gt; (SPACE &lt;em&gt;y&lt;/em&gt; | &lt;span class="caps"&gt;NOTHING&lt;/span&gt;)&lt;/p&gt;

&lt;p&gt;Compare the operator&amp;#8217;s definition with that of the
&lt;code&gt;atom_rule&lt;/code&gt; I presented at the beginning of the article.
They&amp;#8217;re structurally the same: the operator&amp;#8217;s &lt;em&gt;x&lt;/em&gt; and
&lt;em&gt;y&lt;/em&gt; are the atom rule&amp;#8217;s &lt;code&gt;&amp;lt;the literal atom&amp;gt;&lt;/code&gt; and
&lt;code&gt;&amp;lt;the next rule&amp;gt;&lt;/code&gt;.&lt;/p&gt;

	&lt;p&gt;Now all that remains is to generalize the &amp;#8220;a b c&amp;#8221; formula into a
general formula that works for arbitrary grammar specifications.
Fortunately, this work has already been done for us.  The generalized
formula is nothing more than a &lt;a href="http://www.haskell.org/haskellwiki/Fold"&gt;right fold&lt;/a&gt;.  In Haskell, the
particular right-fold flavor we want is called &lt;em&gt;foldr1&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;Given a list of atoms, we can use &lt;em&gt;foldr1&lt;/em&gt; to construct its grammar as
follows:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;mk_grammar atoms = foldr1 (+) atoms
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;But Python, our implementation language, does not offer a &lt;em&gt;foldr1&lt;/em&gt;
function.  This wrinkle, however, is another thing we can iron out by
thinking algebraically.  Python doesn&amp;#8217;t have &lt;em&gt;foldr1&lt;/em&gt;, but it does
have a &lt;em&gt;reduce&lt;/em&gt; function, which represents a left fold, equivalent to
Haskell&amp;#8217;s &lt;em&gt;foldl&amp;#8217;&lt;/em&gt; or &lt;em&gt;foldl1&amp;#8217;&lt;/em&gt;.  Because our + operator is strict and
our list of atoms is finite, we can take advantage of the following
identity:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;foldr1 (+) xs == foldl1 (flip (+)) (reverse xs)
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;That is, we can convert a right fold into a left fold by flipping the
arguments of the operator and operating on the list in reverse.  Thus
we can implement the fold we &lt;em&gt;want&lt;/em&gt; in terms of the fold we &lt;em&gt;have&lt;/em&gt;:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;# Python code

def foldr1(f, xs):
    return reduce(flip(f), reversed(xs))

def flip(f):
    def g(x, y):
        return f(y, x)
    return g
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Now writing a Python-based solution is straightforward:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;def grammar_spec_to_re(spec):
    atoms = grammar_spec_to_atoms(spec)
    atom_res = map(atom_to_re, atoms)
    grammar_re = r'\A%s\Z' % foldr1(op, atom_res)
    return grammar_re

def op(x, y):
    # x + y = x (SPACE y | NOTHING)
    return r'%s(\s+%s)?' % (x, y)

def grammar_spec_to_atoms(spec):
    return spec.split()

def atom_to_re(atom):
    return re.escape(atom)
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Using our solution, let&amp;#8217;s compile the &amp;#8220;a b c&amp;#8221; grammar specification
into its corresponding regular expression:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; print grammar_spec_to_re('a b c')
\Aa(\s+b(\s+c)?)?\Z
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;And that&amp;#8217;s basically how I solved the problem.&lt;/p&gt;


	&lt;p&gt;To play around with the solution, here&amp;#8217;s a small helper class that compiles a grammar specification into a regular expression and then tests strings for matching the regexp:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;class GrammarMatcher(object):
    def __init__(self, spec):
        self.re = re.compile(grammar_spec_to_re(spec))
    def __call__(self, s):
        return not not self.re.match(s)
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Now, let&amp;#8217;s try out the regular expression generated for the grammar specification &amp;#8220;a b c&amp;#8221; :&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; matcher = GrammarMatcher('a b c')
&amp;gt;&amp;gt;&amp;gt; matcher('')
False
&amp;gt;&amp;gt;&amp;gt; matcher('a')
True
&amp;gt;&amp;gt;&amp;gt; matcher('ab')
False
&amp;gt;&amp;gt;&amp;gt; matcher('a b')
True
&amp;gt;&amp;gt;&amp;gt; matcher('a  b')
True
&amp;gt;&amp;gt;&amp;gt; matcher('a b c')
True
&amp;gt;&amp;gt;&amp;gt; matcher('a b c d')
False
&amp;gt;&amp;gt;&amp;gt; matcher('a c')
False
&amp;gt;&amp;gt;&amp;gt; matcher('b')
False
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Now, those questions I promised.  If you&amp;#8217;re a functional programmer,
did a fold-based solution leap out at you?  (Did you think of the
&lt;em&gt;problem&lt;/em&gt; in terms of folds?)  If you&amp;#8217;re not a functional programmer,
how did you see the problem?  Did the solution above seem twisted,
confusing, or overly clever?&lt;/p&gt;


	&lt;p&gt;(There are no right or wrong answers.  I&amp;#8217;m just curious about how
people with different backgrounds view the problem.)&lt;/p&gt;


&lt;div class="update"&gt;
&lt;strong&gt;Update:&lt;/strong&gt; Edited to clarify that the problem is to convert a grammar specification into a regular expression, not just test whether a string matches a specified grammar.
&lt;/div&gt;</description>
      <pubDate>Wed, 20 Aug 2008 21:50:00 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:a80d7a49-0278-48b0-badb-ffe38a216762</guid>
      <author>Tom Moertel</author>
      <link>http://blog.moertel.com/articles/2008/08/20/thinking-algebraically-a-functional-programming-dividend-that-pays-during-your-imperative-programming-day-job</link>
      <category>functional programming</category>
      <category>haskell</category>
      <category>fp</category>
      <category>python</category>
      <category>folds</category>
      <trackback:ping>http://blog.moertel.com/articles/trackback/766</trackback:ping>
    </item>
    <item>
      <title>Oleg's great way of explaining delimited continuations</title>
      <description>&lt;p&gt;There&amp;#8217;s a great way to explain delimited continuations in the notes of &lt;a href="http://okmij.org/ftp/Computation/Continuations.html#shift-cgi"&gt;Oleg&amp;#8217;s Continuation Fest talk on using delimited continuations for &lt;span class="caps"&gt;CGI&lt;/span&gt; programming&lt;/a&gt;.  Just so it doesn&amp;#8217;t get overlooked, here it is:&lt;/p&gt;


&lt;blockquote&gt;I&amp;#8217;m obsessed in pointing out that every programmer already knows
and understands the delimited continuations; they might not know that
word though.  Everyone knows that when a process executes a system
call like &lt;code&gt;read&lt;/code&gt;, it gets &lt;em&gt;suspended&lt;/em&gt;. When the disk
delivers the data, the process is &lt;em&gt;resumed&lt;/em&gt;. That suspension of a
process is its continuation. It is delimited: it is not the
check-point of the whole OS, it is the check-point of a process only,
from the invocation of &lt;code&gt;main()&lt;/code&gt; up to the point
&lt;code&gt;main()&lt;/code&gt; returns. Normally these suspensions are resumed
only once, but can be zero times (&lt;code&gt;exit&lt;/code&gt;) or twice
(&lt;code&gt;fork&lt;/code&gt;).&lt;/blockquote&gt;

&lt;p&gt;I especially like the final part about &lt;code&gt;exit&lt;/code&gt; and
&lt;code&gt;fork&lt;/code&gt;, which drives home the notion that something more
subtle than returning from a typical function call is going on. If
anybody is confused over what &lt;em&gt;suspended&lt;/em&gt; means, that last part
ought to clear things up.&lt;/p&gt;

&lt;p&gt;The next time I need to explain delimited continuations, I know how
I&amp;#8217;m going to do it.&lt;/p&gt;</description>
      <pubDate>Mon, 05 May 2008 09:58:00 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:9030a189-530b-48b3-b5e1-ed41ab5c2467</guid>
      <author>Tom Moertel</author>
      <link>http://blog.moertel.com/articles/2008/05/05/olegs-great-way-of-explaining-delimited-continuations</link>
      <category>functional programming</category>
      <category>continuations</category>
      <category>fp</category>
      <category>oleg</category>
      <trackback:ping>http://blog.moertel.com/articles/trackback/724</trackback:ping>
    </item>
    <item>
      <title>A simple directory-tree printer in Haskell</title>
      <description>&lt;p&gt;At a recent gathering, my friend &lt;a href="http://blog.caseywest.com/"&gt;Casey&lt;/a&gt;
mentioned that he was learning a new programming language and, as a
learning exercise, had written a directory-tree printer.  That&amp;#8217;s a program that recursively scans directory hierarchies and
prints out a tree representation for each:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;$ tlist cheating-hangman

cheating-hangman
|-- CVS
|   |-- Entries
|   |-- Repository
|   `-- Root
|-- Makefile
|-- cheating-hangman.lhs
`-- cheating-hangman.pl
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;I thought the problem sounded like fun, and so I wrote a small
solution in Haskell.  Let&amp;#8217;s take a look.&lt;/p&gt;&lt;p&gt;First, some documentation by way of comments.&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='comment'&gt;-- Tree list for directories&lt;/span&gt;
&lt;span class='comment'&gt;-- Tom Moertel &amp;lt;tom@moertel.com&amp;gt;&lt;/span&gt;
&lt;span class='comment'&gt;-- 2007-02-20&lt;/span&gt;
&lt;span class='comment'&gt;--&lt;/span&gt;
&lt;span class='comment'&gt;-- Compile:  ghc -O -o tlist --make tlist.hs&lt;/span&gt;
&lt;span class='comment'&gt;-- Usage:    ./tlist [dir...]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Next, we&amp;#8217;ll start a new module and import a few libraries that will
make our job easier.&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='keyword'&gt;module&lt;/span&gt; &lt;span class='conid'&gt;Main&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;main&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='keyword'&gt;where&lt;/span&gt;

&lt;span class='keyword'&gt;import&lt;/span&gt; &lt;span class='conid'&gt;Control&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='conid'&gt;Monad&lt;/span&gt;
&lt;span class='keyword'&gt;import&lt;/span&gt; &lt;span class='conid'&gt;Data&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='conid'&gt;List&lt;/span&gt;
&lt;span class='keyword'&gt;import&lt;/span&gt; &lt;span class='conid'&gt;System&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='conid'&gt;Directory&lt;/span&gt;
&lt;span class='keyword'&gt;import&lt;/span&gt; &lt;span class='conid'&gt;System&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='conid'&gt;Environment&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Now we arrive at the first real code, the &lt;em&gt;main&lt;/em&gt; function:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;main&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;args&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;getArgs&lt;/span&gt;
    &lt;span class='varid'&gt;mapM_&lt;/span&gt; &lt;span class='varid'&gt;tlist&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='keyword'&gt;if&lt;/span&gt; &lt;span class='varid'&gt;null&lt;/span&gt; &lt;span class='varid'&gt;args&lt;/span&gt; &lt;span class='keyword'&gt;then&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='str'&gt;"."&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt; &lt;span class='keyword'&gt;else&lt;/span&gt; &lt;span class='varid'&gt;args&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

The code gets the arguments from the command line, each representing a file
or directory.  Then it maps the &lt;em&gt;tlist&lt;/em&gt; function over the list of
arguments or, if the list is empty, over the default argument, which
represents the current working directory.  Because &lt;em&gt;tlist&lt;/em&gt; has side
effects (e.g., directory scanning and tree printing), it returns an
&lt;code&gt;IO&lt;/code&gt; action, and thus we must use a monadic flavor of map,
&lt;em&gt;mapM_&lt;/em&gt;, to sequence its effects.

	&lt;p&gt;Next, &lt;em&gt;tlist&lt;/em&gt; visits the file-system path it receives as
an argument, handing off to the &lt;em&gt;visit&lt;/em&gt; function, to which
it passes some sensible initial values.  We&amp;#8217;ll examine
what these values mean in a moment.&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;tlist&lt;/span&gt; &lt;span class='varid'&gt;path&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt;
    &lt;span class='varid'&gt;visit&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='keyword'&gt;if&lt;/span&gt; &lt;span class='str'&gt;"/"&lt;/span&gt; &lt;span class='varop'&gt;`isPrefixOf`&lt;/span&gt; &lt;span class='varid'&gt;path&lt;/span&gt; &lt;span class='keyword'&gt;then&lt;/span&gt; &lt;span class='str'&gt;""&lt;/span&gt; &lt;span class='keyword'&gt;else&lt;/span&gt; &lt;span class='str'&gt;"."&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='str'&gt;""&lt;/span&gt; &lt;span class='str'&gt;""&lt;/span&gt; &lt;span class='str'&gt;""&lt;/span&gt; &lt;span class='varid'&gt;path&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;The &lt;em&gt;visit&lt;/em&gt; function, in turn, &amp;#8220;visits&amp;#8221; a node, printing its
little portion of the tree.  Before we look at that function, however,
let&amp;#8217;s think about drawing a single node.&lt;/p&gt;


	&lt;p&gt;Say we&amp;#8217;re visiting the &amp;#8220;Repository&amp;#8221; node in the hierarchy:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;cheating-hangman
|-- CVS
|   |-- Entries
|   |-- Repository    &amp;lt;--- consider just this line

    ^   ^
    A   B
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;To connect the node to the tree, we need to draw three things:&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;the &lt;em&gt;leader&lt;/em&gt;, which connects the tree structure way above the node;&lt;/li&gt;
		&lt;li&gt;the &lt;em&gt;arm&lt;/em&gt;, which connects the node&amp;#8217;s siblings; and &lt;/li&gt;
		&lt;li&gt;the &lt;em&gt;tie&lt;/em&gt;, which connects the node to the arm.&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;In this particular case, the leader is everything to the left of point
&lt;strong&gt;A&lt;/strong&gt;.  Here it is &lt;code&gt;"|   "&lt;/code&gt;, but it will get
longer as we descend deeper into the hierarchy.  The arm is the single
character at point &lt;strong&gt;A&lt;/strong&gt;.  It&amp;#8217;s usually a vertical bar,
but for the final sibling it&amp;#8217;s rounded off into an elbow (a backquote
in &lt;span class="caps"&gt;ASCII&lt;/span&gt; art).  Finally the tie, which connects the name of the
current node to the arm, is everything between points
&lt;strong&gt;A&lt;/strong&gt; and &lt;strong&gt;B&lt;/strong&gt;.  It&amp;#8217;s always &lt;code&gt;"--
"&lt;/code&gt; except at the tree&amp;#8217;s root, which needs no tie.&lt;/p&gt;


	&lt;p&gt;With the tree&amp;#8217;s anatomy firmly in mind, we&amp;#8217;re ready to
visit a node and draw its contribution to the tree:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;visit&lt;/span&gt; &lt;span class='varid'&gt;path&lt;/span&gt; &lt;span class='varid'&gt;leader&lt;/span&gt; &lt;span class='varid'&gt;tie&lt;/span&gt; &lt;span class='varid'&gt;arm&lt;/span&gt; &lt;span class='varid'&gt;node&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;putStrLn&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;leader&lt;/span&gt; &lt;span class='varop'&gt;++&lt;/span&gt; &lt;span class='varid'&gt;arm&lt;/span&gt; &lt;span class='varop'&gt;++&lt;/span&gt; &lt;span class='varid'&gt;tie&lt;/span&gt; &lt;span class='varop'&gt;++&lt;/span&gt; &lt;span class='varid'&gt;node&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
    &lt;span class='varid'&gt;visitChildren&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;path&lt;/span&gt; &lt;span class='varop'&gt;++&lt;/span&gt; &lt;span class='str'&gt;"/"&lt;/span&gt; &lt;span class='varop'&gt;++&lt;/span&gt; &lt;span class='varid'&gt;node&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;leader&lt;/span&gt; &lt;span class='varop'&gt;++&lt;/span&gt; &lt;span class='varid'&gt;extension&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
  &lt;span class='keyword'&gt;where&lt;/span&gt;
    &lt;span class='varid'&gt;extension&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='keyword'&gt;case&lt;/span&gt; &lt;span class='varid'&gt;arm&lt;/span&gt; &lt;span class='keyword'&gt;of&lt;/span&gt; &lt;span class='str'&gt;""&lt;/span&gt;  &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='str'&gt;""&lt;/span&gt;&lt;span class='layout'&gt;;&lt;/span&gt; &lt;span class='str'&gt;"`"&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='str'&gt;"    "&lt;/span&gt;&lt;span class='layout'&gt;;&lt;/span&gt; &lt;span class='keyword'&gt;_&lt;/span&gt;   &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='str'&gt;"|   "&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Let&amp;#8217;s examine the arguments.  &lt;em&gt;Path&lt;/em&gt; is the path to the directory
we&amp;#8217;re listing, and &lt;em&gt;node&lt;/em&gt; is the item we&amp;#8217;re visiting within that
directory.  The remaining arguments are the tree-drawing parts
necessary to connect this node to the tree.&lt;/p&gt;


	&lt;p&gt;The first line of the function&amp;#8217;s body prints the node&amp;#8217;s addition to
the tree.  The second line visits the node&amp;#8217;s children, if any,
updating the &lt;em&gt;path&lt;/em&gt; and &lt;em&gt;leader&lt;/em&gt; accordingly.  The &lt;em&gt;path&lt;/em&gt; is updated
to point to the current &lt;em&gt;node&lt;/em&gt;.  The &lt;em&gt;leader&lt;/em&gt; is extended to ensure
that the current node&amp;#8217;s unvisited siblings, if any, will be connected
to the tree by the current node&amp;#8217;s children, if any.  In effect, the
current node&amp;#8217;s arm is projected into the children&amp;#8217;s leader to make the
connection.&lt;/p&gt;


	&lt;p&gt;Visiting the children is a little more complicated:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;visitChildren&lt;/span&gt; &lt;span class='varid'&gt;path&lt;/span&gt; &lt;span class='varid'&gt;leader&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt;
    &lt;span class='varid'&gt;whenM&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;doesDirectoryExist&lt;/span&gt; &lt;span class='varid'&gt;path&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
        &lt;span class='varid'&gt;contents&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;getDirectoryContents&lt;/span&gt; &lt;span class='varid'&gt;path&lt;/span&gt;
            &lt;span class='varop'&gt;`catch`&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='keyglyph'&gt;\&lt;/span&gt;&lt;span class='varid'&gt;e&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='varid'&gt;return&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='varid'&gt;show&lt;/span&gt; &lt;span class='varid'&gt;e&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
        &lt;span class='keyword'&gt;let&lt;/span&gt; &lt;span class='varid'&gt;visibles&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;sort&lt;/span&gt; &lt;span class='varop'&gt;.&lt;/span&gt; &lt;span class='varid'&gt;filter&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varop'&gt;`notElem`&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='str'&gt;"."&lt;/span&gt;&lt;span class='layout'&gt;,&lt;/span&gt; &lt;span class='str'&gt;".."&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='varid'&gt;contents&lt;/span&gt;
            &lt;span class='varid'&gt;arms&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;replicate&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;length&lt;/span&gt; &lt;span class='varid'&gt;visibles&lt;/span&gt; &lt;span class='comment'&gt;-&lt;/span&gt; &lt;span class='num'&gt;1&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='str'&gt;"|"&lt;/span&gt; &lt;span class='varop'&gt;++&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='str'&gt;"`"&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;
        &lt;span class='varid'&gt;zipWithM_&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;visit&lt;/span&gt; &lt;span class='varid'&gt;path&lt;/span&gt; &lt;span class='varid'&gt;leader&lt;/span&gt; &lt;span class='str'&gt;"-- "&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varid'&gt;arms&lt;/span&gt; &lt;span class='varid'&gt;visibles&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;The &lt;em&gt;whenM&lt;/em&gt; line tests to see if the path represents a directory.
If it&amp;#8217;s not, the remaining
code is ignored.  (Only directories have children to visit.)&lt;/p&gt;


&lt;p&gt;The remaining code, if it does run, gets the directory&amp;#8217;s contents
(catching and reporting errors, if any), filters out the
&lt;code&gt;"."&lt;/code&gt; and &lt;code&gt;".."&lt;/code&gt; directory entries, and stores
the sorted, remaining entries in &lt;em&gt;visibles&lt;/em&gt;.  Then it prepares a list
of &lt;em&gt;arms&lt;/em&gt;: straight arms for all but the last entry, which gets an
elbow.  Finally, &lt;em&gt;zipWithM_&lt;/em&gt; &amp;#8220;zips&amp;#8221; the prepared arms and
visible entries into one big, effectful computation that calls
(recursively) to the &lt;em&gt;visit&lt;/em&gt; function to zip each arm with its
corresponding entry.  And that completes our algorithm.&lt;/p&gt;

	&lt;p&gt;One final tidbit: the handy &lt;em&gt;whenM&lt;/em&gt;, which lamentably is not part
of the Haskell standard libraries (yet), is defined like so:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;whenM&lt;/span&gt; &lt;span class='varid'&gt;mtest&lt;/span&gt; &lt;span class='varid'&gt;ma&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;mtest&lt;/span&gt; &lt;span class='varop'&gt;&amp;gt;&amp;gt;=&lt;/span&gt; &lt;span class='varid'&gt;flip&lt;/span&gt; &lt;span class='varid'&gt;when&lt;/span&gt; &lt;span class='varid'&gt;ma&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;h3&gt; The complete code&lt;/h3&gt;


	&lt;p&gt;Here&amp;#8217;s the code, without the commentary:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='keyword'&gt;module&lt;/span&gt; &lt;span class='conid'&gt;Main&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;main&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='keyword'&gt;where&lt;/span&gt;

&lt;span class='keyword'&gt;import&lt;/span&gt; &lt;span class='conid'&gt;Control&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='conid'&gt;Monad&lt;/span&gt;
&lt;span class='keyword'&gt;import&lt;/span&gt; &lt;span class='conid'&gt;Data&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='conid'&gt;List&lt;/span&gt;
&lt;span class='keyword'&gt;import&lt;/span&gt; &lt;span class='conid'&gt;System&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='conid'&gt;Directory&lt;/span&gt;
&lt;span class='keyword'&gt;import&lt;/span&gt; &lt;span class='conid'&gt;System&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='conid'&gt;Environment&lt;/span&gt;

&lt;span class='varid'&gt;main&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;args&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;getArgs&lt;/span&gt;
    &lt;span class='varid'&gt;mapM_&lt;/span&gt; &lt;span class='varid'&gt;tlist&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='keyword'&gt;if&lt;/span&gt; &lt;span class='varid'&gt;null&lt;/span&gt; &lt;span class='varid'&gt;args&lt;/span&gt; &lt;span class='keyword'&gt;then&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='str'&gt;"."&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt; &lt;span class='keyword'&gt;else&lt;/span&gt; &lt;span class='varid'&gt;args&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;

&lt;span class='varid'&gt;tlist&lt;/span&gt; &lt;span class='varid'&gt;path&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt;
    &lt;span class='varid'&gt;visit&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='keyword'&gt;if&lt;/span&gt; &lt;span class='str'&gt;"/"&lt;/span&gt; &lt;span class='varop'&gt;`isPrefixOf`&lt;/span&gt; &lt;span class='varid'&gt;path&lt;/span&gt; &lt;span class='keyword'&gt;then&lt;/span&gt; &lt;span class='str'&gt;""&lt;/span&gt; &lt;span class='keyword'&gt;else&lt;/span&gt; &lt;span class='str'&gt;"."&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='str'&gt;""&lt;/span&gt; &lt;span class='str'&gt;""&lt;/span&gt; &lt;span class='str'&gt;""&lt;/span&gt; &lt;span class='varid'&gt;path&lt;/span&gt;

&lt;span class='varid'&gt;visit&lt;/span&gt; &lt;span class='varid'&gt;path&lt;/span&gt; &lt;span class='varid'&gt;leader&lt;/span&gt; &lt;span class='varid'&gt;tie&lt;/span&gt; &lt;span class='varid'&gt;arm&lt;/span&gt; &lt;span class='varid'&gt;node&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;putStrLn&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;leader&lt;/span&gt; &lt;span class='varop'&gt;++&lt;/span&gt; &lt;span class='varid'&gt;arm&lt;/span&gt; &lt;span class='varop'&gt;++&lt;/span&gt; &lt;span class='varid'&gt;tie&lt;/span&gt; &lt;span class='varop'&gt;++&lt;/span&gt; &lt;span class='varid'&gt;node&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
    &lt;span class='varid'&gt;visitChildren&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;path&lt;/span&gt; &lt;span class='varop'&gt;++&lt;/span&gt; &lt;span class='str'&gt;"/"&lt;/span&gt; &lt;span class='varop'&gt;++&lt;/span&gt; &lt;span class='varid'&gt;node&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;leader&lt;/span&gt; &lt;span class='varop'&gt;++&lt;/span&gt; &lt;span class='varid'&gt;extension&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
  &lt;span class='keyword'&gt;where&lt;/span&gt;
    &lt;span class='varid'&gt;extension&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='keyword'&gt;case&lt;/span&gt; &lt;span class='varid'&gt;arm&lt;/span&gt; &lt;span class='keyword'&gt;of&lt;/span&gt; &lt;span class='str'&gt;""&lt;/span&gt;  &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='str'&gt;""&lt;/span&gt;&lt;span class='layout'&gt;;&lt;/span&gt; &lt;span class='str'&gt;"`"&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='str'&gt;"    "&lt;/span&gt;&lt;span class='layout'&gt;;&lt;/span&gt; &lt;span class='keyword'&gt;_&lt;/span&gt;   &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='str'&gt;"|   "&lt;/span&gt;

&lt;span class='varid'&gt;visitChildren&lt;/span&gt; &lt;span class='varid'&gt;path&lt;/span&gt; &lt;span class='varid'&gt;leader&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt;
    &lt;span class='varid'&gt;whenM&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;doesDirectoryExist&lt;/span&gt; &lt;span class='varid'&gt;path&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
        &lt;span class='varid'&gt;contents&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;getDirectoryContents&lt;/span&gt; &lt;span class='varid'&gt;path&lt;/span&gt;
            &lt;span class='varop'&gt;`catch`&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='keyglyph'&gt;\&lt;/span&gt;&lt;span class='varid'&gt;e&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='varid'&gt;return&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='varid'&gt;show&lt;/span&gt; &lt;span class='varid'&gt;e&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
        &lt;span class='keyword'&gt;let&lt;/span&gt; &lt;span class='varid'&gt;visibles&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;sort&lt;/span&gt; &lt;span class='varop'&gt;.&lt;/span&gt; &lt;span class='varid'&gt;filter&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varop'&gt;`notElem`&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='str'&gt;"."&lt;/span&gt;&lt;span class='layout'&gt;,&lt;/span&gt; &lt;span class='str'&gt;".."&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='varid'&gt;contents&lt;/span&gt;
            &lt;span class='varid'&gt;arms&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;replicate&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;length&lt;/span&gt; &lt;span class='varid'&gt;visibles&lt;/span&gt; &lt;span class='comment'&gt;-&lt;/span&gt; &lt;span class='num'&gt;1&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='str'&gt;"|"&lt;/span&gt; &lt;span class='varop'&gt;++&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='str'&gt;"`"&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;
        &lt;span class='varid'&gt;zipWithM_&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;visit&lt;/span&gt; &lt;span class='varid'&gt;path&lt;/span&gt; &lt;span class='varid'&gt;leader&lt;/span&gt; &lt;span class='str'&gt;"-- "&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varid'&gt;arms&lt;/span&gt; &lt;span class='varid'&gt;visibles&lt;/span&gt;

&lt;span class='varid'&gt;whenM&lt;/span&gt; &lt;span class='varid'&gt;mtest&lt;/span&gt; &lt;span class='varid'&gt;ma&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;mtest&lt;/span&gt; &lt;span class='varop'&gt;&amp;gt;&amp;gt;=&lt;/span&gt; &lt;span class='varid'&gt;flip&lt;/span&gt; &lt;span class='varid'&gt;when&lt;/span&gt; &lt;span class='varid'&gt;ma&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;h3&gt;Next time: a refactoring&lt;/h3&gt;


	&lt;p&gt;Our program does two things: it scans directory hierarchies and it
prints trees.  You may have noticed, however, that those two things
are intertwined in the code.  There are  times when we might
want to scan a directory hierarchy or print a tree, but our code can&amp;#8217;t
be reused for those purposes.  It can only scan &lt;em&gt;and&lt;/em&gt; print as one
indivisible action.&lt;/p&gt;


	&lt;p&gt;Wouldn&amp;#8217;t it be better to separate the directory-scanning code from the
tree-printing code so that each formed a reusable module?  Next time,
we&amp;#8217;ll do just that.  Haskell&amp;#8217;s lazy magic makes it easy &lt;em&gt;and&lt;/em&gt;
efficient.&lt;/p&gt;


	&lt;p&gt;See you then.&lt;/p&gt;


&lt;div class="update"&gt;
&lt;strong&gt;Update 2007-02-23:&lt;/strong&gt; If you&amp;#8217;re interested in coding up an implementation,
please don&amp;#8217;t forget to round off corners and prune unnecessary connecting lines. For example:

&lt;pre&gt;&lt;code&gt;dir1
|-- file1
|-- subdir1
|   |-- file11
|   |-- file12
|   `-- subdir13
|       `-- file131
`-- zfile
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;</description>
      <pubDate>Thu, 22 Feb 2007 16:30:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:eb3e46da-1437-4588-b06b-7cc086f75651</guid>
      <author>Tom Moertel</author>
      <link>http://blog.moertel.com/articles/2007/02/22/a-simple-directory-tree-printer-in-haskell</link>
      <category>programming</category>
      <category>functional programming</category>
      <category>haskell</category>
      <category>haskell</category>
      <category>trees</category>
      <category>io</category>
      <category>directory_tree_series</category>
      <trackback:ping>http://blog.moertel.com/articles/trackback/387</trackback:ping>
    </item>
    <item>
      <title>Introductory Haskell: Solving the Sorting-It-Out Kata</title>
      <description>&lt;p&gt;Last Tuesday, my friend &lt;a href="http://caseywest.com/"&gt;Casey&lt;/a&gt; and I were hanging
out at &lt;a href="http://aldocoffee.com/"&gt;Aldo Coffee&lt;/a&gt;.  We planned on enjoying
some espresso, doing some work, and then heading over to the &lt;a href="http://pghcodingdojo.org/"&gt;Pittsburgh Coding
Dojo&lt;/a&gt;, where we could hang out with
other geekly folks.
We ended up
not having enough time to go to the meeting, but we decided to hack
on the challenge problem anyway, using Aldo&amp;#8217;s ever-handy free
wireless to access the Internet.&lt;/p&gt;


	&lt;p&gt;The Dojo problem was PragDave&amp;#8217;s &lt;a href="http://blogs.pragprog.com/cgi-bin/pragdave.cgi/Practices/Kata/KataEleven.rdoc"&gt;Kata Eleven &amp;#8211; Sorting it
Out&lt;/a&gt;.  (It&amp;#8217;s short;
read it now.)  We decided to use Haskell for our implementation
language.&lt;/p&gt;


	&lt;p&gt;In this post, I&amp;#8217;ll walk through our coding session and explain how our
solution evolved.  To better fit the session into a blog post, I
have removed a lot of back-and-forth micro iterations, and I have
edited some of the code for clarity.&lt;/p&gt;


	&lt;h3&gt; The first part of the problem&lt;/h3&gt;


	&lt;p&gt;The first part of the problem was &amp;#8220;Sorting Balls.&amp;#8221;  The story: You
need to implement a &amp;#8220;rack&amp;#8221; to hold the balls drawn at random (without
replacement) from a bin containing sixty balls, numbered 0 to 59.
Regardless of the order in which the balls are added to the rack, you
need to present them in sorted order whenever you&amp;#8217;re asked for them.&lt;/p&gt;


	&lt;p&gt;Upon reading this part of the challenge, a couple of thoughts sprung to mind:&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;Because the range of balls is so small, the problem was begging for a solution based on a &lt;a href="http://en.wikipedia.org/wiki/Counting_sort"&gt;counting sort&lt;/a&gt;.&lt;/li&gt;
		&lt;li&gt;Because the balls are uniquely numbered and drawn without replacement, we could even use a bit vector to represent counts.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;Nevertheless, we decided to ignore these thoughts and implement a
more-general solution that would work for any (orderable) values,
not just small ranges of integers.&lt;/p&gt;


	&lt;h3&gt; Sketching the interface&lt;/h3&gt;


	&lt;p&gt;The first step, then, was to sketch out an interface.  Our
interface mirrored the one from the problem statement but
was tweaked for Haskell:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;mkRack&lt;/span&gt; &lt;span class='keyglyph'&gt;::&lt;/span&gt; &lt;span class='conid'&gt;Rack&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt;
&lt;span class='varid'&gt;add&lt;/span&gt;    &lt;span class='keyglyph'&gt;::&lt;/span&gt; &lt;span class='conid'&gt;Ord&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt; &lt;span class='keyglyph'&gt;=&amp;gt;&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='conid'&gt;Rack&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='conid'&gt;Rack&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt;
&lt;span class='varid'&gt;balls&lt;/span&gt;  &lt;span class='keyglyph'&gt;::&lt;/span&gt; &lt;span class='conid'&gt;Rack&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='varid'&gt;a&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;The function &lt;em&gt;mkRack&lt;/em&gt; makes a new rack to hold values (&amp;#8220;balls&amp;#8221;) of
type &lt;em&gt;a&lt;/em&gt;.  It&amp;#8217;s equivalent to &lt;code&gt;Rack.new&lt;/code&gt; in Ruby.&lt;/p&gt;


	&lt;p&gt;The &lt;em&gt;add&lt;/em&gt; function adds a ball to a rack.  You give it a ball and a
rack, and it returns a new rack that is the same as the original rack
but also contains the ball.  (If you&amp;#8217;re accustomed to stateful
programming, this may seem weird.  Why return a new rack instead of
modifying the original rack? Because, in Haskell, you can&amp;#8217;t change
values: you can only create new values.  At first, this constraint may
seem limiting, but after you get used to it, you&amp;#8217;ll find it
empowering.)&lt;/p&gt;


	&lt;p&gt;Note: the&lt;code&gt; Ord a &lt;/code&gt;qualification on the type signature of
&lt;em&gt;add&lt;/em&gt; says that it will work for any type &lt;em&gt;a&lt;/em&gt; whose values can be
ordered.  The qualification is necessary because values of some types,
like IO actions, cannot be compared to see which are less than the
others.&lt;/p&gt;


	&lt;p&gt;The &lt;em&gt;balls&lt;/em&gt; function is an &amp;#8220;observer&amp;#8221;: it lets you observe the balls
in a rack by returning them as an ordered list.&lt;/p&gt;


	&lt;p&gt;And that&amp;#8217;s the interface.&lt;/p&gt;


	&lt;p&gt;With the interface sketched, we gave it meaning by defining its
properties.&lt;/p&gt;


	&lt;h3&gt; Giving our interface meaning: defining properties using QuickCheck&lt;/h3&gt;


	&lt;p&gt;&lt;a href="http://www.md.chalmers.se/~rjmh/QuickCheck/"&gt;QuickCheck&lt;/a&gt; is a
powerful, easy-to-use testing tool.  Instead of checking test cases,
it checks &lt;em&gt;properties&lt;/em&gt; &amp;#8211; statements about what your code ought to do
&lt;em&gt;in general&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;The great thing about QuickCheck properties is that they are
&lt;em&gt;testable documentation&lt;/em&gt;.  They tell the world what your code
is supposed to do,
and they do so in a concise, formal language that just happens to be
easily readable by humans and automatically testable by computers.&lt;/p&gt;


	&lt;p&gt;To specify the desired properties of our Rack interface, we first had
to import QuickCheck:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='keyword'&gt;import&lt;/span&gt; &lt;span class='conid'&gt;Test&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='conid'&gt;QuickCheck&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Then, we defined our first property.  It said, simply, that a new rack
must be empty when observed:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;prop_New&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt;
    &lt;span class='varid'&gt;balls&lt;/span&gt; &lt;span class='varid'&gt;mkRack&lt;/span&gt; &lt;span class='varop'&gt;=~&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Our second property said that, when you add a ball &lt;em&gt;x&lt;/em&gt; to
a rack, the resulting rack must contain the same
balls as the original rack plus &lt;em&gt;x&lt;/em&gt;:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;prop_AddAddsElement&lt;/span&gt; &lt;span class='varid'&gt;rack&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt;
    &lt;span class='varid'&gt;balls&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;add&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varid'&gt;rack&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;=~&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='conop'&gt;:&lt;/span&gt; &lt;span class='varid'&gt;balls&lt;/span&gt; &lt;span class='varid'&gt;rack&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Both of the properties above rely upon a special, order-insensitive
equality test that we defined for lists of &lt;code&gt;Int&lt;/code&gt; values:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varop'&gt;=~&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='keyglyph'&gt;::&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='conid'&gt;Int&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='conid'&gt;Int&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='conid'&gt;Bool&lt;/span&gt;
&lt;span class='varid'&gt;xs&lt;/span&gt; &lt;span class='varop'&gt;=~&lt;/span&gt; &lt;span class='varid'&gt;ys&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;sort&lt;/span&gt; &lt;span class='varid'&gt;xs&lt;/span&gt; &lt;span class='varop'&gt;==&lt;/span&gt; &lt;span class='varid'&gt;sort&lt;/span&gt; &lt;span class='varid'&gt;ys&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Note that under this test, &lt;code&gt;[1,2]&lt;/code&gt; &amp;#8220;equals&amp;#8221; 
both &lt;code&gt;[1,2]&lt;/code&gt; and &lt;code&gt;[2,1]&lt;/code&gt;, but it does not &amp;#8220;equal&amp;#8221; 
any other values.&lt;/p&gt;


	&lt;p&gt;The reason we defined this operator was to help us specify the two
essential properties of &lt;em&gt;add&lt;/em&gt; separately: (1) it must insert a ball
into a rack, and (2) the new ball&amp;#8217;s position, when observed, must
preserve the rack&amp;#8217;s ordering invariant.  The previous property
definition used the &lt;code&gt;=~&lt;/code&gt; operator to specify the first of
these two properties.  The next property we defined specified the
second:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;prop_AddPreservesOrdering&lt;/span&gt; &lt;span class='varid'&gt;rack&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt;
    &lt;span class='varid'&gt;isOrdered&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;balls&lt;/span&gt; &lt;span class='varid'&gt;rack&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;==&amp;gt;&lt;/span&gt; &lt;span class='varid'&gt;isOrdered&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;balls&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;add&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varid'&gt;rack&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;This definition specifies that, for all racks &lt;em&gt;rack&lt;/em&gt; and all balls
&lt;em&gt;x&lt;/em&gt;, if the balls in &lt;em&gt;rack&lt;/em&gt; are ordered, the balls in the rack that
results from adding &lt;em&gt;x&lt;/em&gt; to &lt;em&gt;rack&lt;/em&gt; must also be ordered.  If you
are familiar with &lt;a href="http://en.wikipedia.org/wiki/Mathematical_induction"&gt;proof by
induction&lt;/a&gt;, you&amp;#8217;ll
know why we went this route.  In short, if we can prove that this
property holds (and, trivially, that an empty rack is ordered), we can
prove that &lt;em&gt;add&lt;/em&gt; preserves the ordering invariant.&lt;/p&gt;


	&lt;p&gt;To round out the property definition, we needed to define the &lt;em&gt;isOrdered&lt;/em&gt; test:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;isOrdered&lt;/span&gt; &lt;span class='keyglyph'&gt;::&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='conid'&gt;Int&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='conid'&gt;Bool&lt;/span&gt;
&lt;span class='varid'&gt;isOrdered&lt;/span&gt; &lt;span class='varid'&gt;xs&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;xs&lt;/span&gt; &lt;span class='varop'&gt;==&lt;/span&gt; &lt;span class='varid'&gt;sort&lt;/span&gt; &lt;span class='varid'&gt;xs&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;And those are the properties we needed to check the correctness
of our implementation.  Of course, we still needed to &lt;em&gt;write&lt;/em&gt; our
implementation, and we turned to that task next.&lt;/p&gt;


	&lt;h3&gt; A simple, list-based Rack implementation&lt;/h3&gt;


	&lt;p&gt;For our first implementation, we decided upon a drop-dead-simple
list-based representation.  We would keep the elements of the list
in sorted order by inserting them into the correct positions when
&lt;em&gt;add&lt;/em&gt; was called.&lt;/p&gt;


	&lt;p&gt;Here, then, was our code:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='comment'&gt;-- Our list-based implementation of a Rack&lt;/span&gt;

&lt;span class='keyword'&gt;type&lt;/span&gt; &lt;span class='conid'&gt;Rack&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='varid'&gt;a&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;

&lt;span class='varid'&gt;mkRack&lt;/span&gt;   &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;
&lt;span class='varid'&gt;add&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varid'&gt;xs&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;insertList&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varid'&gt;xs&lt;/span&gt;
&lt;span class='varid'&gt;balls&lt;/span&gt;    &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;id&lt;/span&gt;

&lt;span class='varid'&gt;insertList&lt;/span&gt; &lt;span class='keyglyph'&gt;::&lt;/span&gt; &lt;span class='conid'&gt;Ord&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt; &lt;span class='keyglyph'&gt;=&amp;gt;&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='varid'&gt;a&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='varid'&gt;a&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;
&lt;span class='varid'&gt;insertList&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;     &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;
&lt;span class='varid'&gt;insertList&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;y&lt;/span&gt;&lt;span class='conop'&gt;:&lt;/span&gt;&lt;span class='varid'&gt;ys&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
    &lt;span class='keyglyph'&gt;|&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varop'&gt;&amp;lt;&lt;/span&gt; &lt;span class='varid'&gt;y&lt;/span&gt;         &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='conop'&gt;:&lt;/span&gt; &lt;span class='varid'&gt;y&lt;/span&gt; &lt;span class='conop'&gt;:&lt;/span&gt; &lt;span class='varid'&gt;ys&lt;/span&gt;
    &lt;span class='keyglyph'&gt;|&lt;/span&gt; &lt;span class='varid'&gt;otherwise&lt;/span&gt;     &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;y&lt;/span&gt; &lt;span class='conop'&gt;:&lt;/span&gt; &lt;span class='varid'&gt;insertList&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varid'&gt;ys&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;That&amp;#8217;s it.&lt;/p&gt;


	&lt;p&gt;We took our new implementation for a spin in GHCi:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;*Rack&amp;gt; balls mkRack
[]

*Rack&amp;gt; balls (add 3 mkRack)
[3]

*Rack&amp;gt; balls (add 4 (add 3 mkRack))
[3,4]

*Rack&amp;gt; balls (add 1 (add 4 (add 3 mkRack)))
[1,3,4]

*Rack&amp;gt; balls (foldr add mkRack [4,2,6,3,-9,0,33,9])
[-9,0,2,3,4,6,9,33]
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;To &lt;em&gt;really&lt;/em&gt; test our implementation, we asked QuickCheck to check its
properties:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;*Rack&amp;gt; quickCheck prop_New
OK, passed 100 tests.

*Rack&amp;gt; quickCheck prop_AddAddsElement
OK, passed 100 tests.

*Rack&amp;gt; quickCheck prop_AddPreservesOrdering
OK, passed 100 tests.
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;I should point out that QuickCheck did not &lt;em&gt;prove&lt;/em&gt; that our properties
held.  Rather, it gathered evidence that we could use to &lt;em&gt;argue&lt;/em&gt; that
our properties held.  The evidence was that each of our properties&amp;#8217;
claims was subjected to 100 randomly generated tests, and none of
the tests was able to disprove a claim.&lt;/p&gt;


	&lt;p&gt;Was this evidence sufficient for us to rest satisfied that our
implementation was correct?  Given how simple our implementation
was, I felt that the evidence was sufficient. Casey agreed, and we moved on.&lt;/p&gt;


	&lt;p&gt;With the first implementation done, we decided to try a more-sophisticated
implementation.&lt;/p&gt;


	&lt;h3&gt; Generalizing the interface&lt;/h3&gt;


	&lt;p&gt;Since we were about to have multiple implementations, it made sense
for us to define a generalized interface that any &amp;#8220;Rack-like&amp;#8221; 
implementation could use.  For that, Haskell&amp;#8217;s type classes were
perfect:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='comment'&gt;-- Our interface for "Rack-like" data types&lt;/span&gt;

&lt;span class='keyword'&gt;class&lt;/span&gt; &lt;span class='conid'&gt;Racklike&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt; &lt;span class='varid'&gt;ra&lt;/span&gt; &lt;span class='keyglyph'&gt;|&lt;/span&gt; &lt;span class='varid'&gt;ra&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt; &lt;span class='keyword'&gt;where&lt;/span&gt;
    &lt;span class='varid'&gt;mkRack&lt;/span&gt; &lt;span class='keyglyph'&gt;::&lt;/span&gt; &lt;span class='varid'&gt;ra&lt;/span&gt;
    &lt;span class='varid'&gt;add&lt;/span&gt;    &lt;span class='keyglyph'&gt;::&lt;/span&gt; &lt;span class='conid'&gt;Ord&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt; &lt;span class='keyglyph'&gt;=&amp;gt;&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='varid'&gt;ra&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='varid'&gt;ra&lt;/span&gt;
    &lt;span class='varid'&gt;balls&lt;/span&gt;  &lt;span class='keyglyph'&gt;::&lt;/span&gt; &lt;span class='varid'&gt;ra&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='varid'&gt;a&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;The interface was essentially the same as before, except that the data
type behind the rack implementation was not given by a specific type
&lt;em&gt;Rack a&lt;/em&gt; but rather by the type variable &lt;em&gt;ra&lt;/em&gt;, which represents some
type of rack container for balls of type &lt;em&gt;a&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;Note that &lt;em&gt;ra&lt;/em&gt; determines &lt;em&gt;a&lt;/em&gt;.  If, for example, you know that
the container type &lt;em&gt;ra&lt;/em&gt; equals &amp;#8220;a list of &lt;code&gt;Int&lt;/code&gt; values,&amp;#8221; 
you know that &lt;em&gt;a&lt;/em&gt; must equal &lt;code&gt;Int&lt;/code&gt;.  (To represent this
relationship, we used &lt;a href="http://haskell.org/haskellwiki/Functional_dependencies"&gt;functional
dependencies&lt;/a&gt;,
a popular extension to the Haskell 98 standard.)&lt;/p&gt;


	&lt;p&gt;With the &lt;em&gt;Racklike&lt;/em&gt; type class in place, we moved our list-based
implementation inside of the interface:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='comment'&gt;-- Our list-based implementation of a Rack&lt;/span&gt;

&lt;span class='keyword'&gt;type&lt;/span&gt; &lt;span class='conid'&gt;ListRack&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='varid'&gt;a&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;

&lt;span class='keyword'&gt;instance&lt;/span&gt; &lt;span class='conid'&gt;Racklike&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;ListRack&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='keyword'&gt;where&lt;/span&gt;
    &lt;span class='varid'&gt;mkRack&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;
    &lt;span class='varid'&gt;add&lt;/span&gt;    &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;insertList&lt;/span&gt;
    &lt;span class='varid'&gt;balls&lt;/span&gt;  &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;id&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Next, we modified our QuickCheck property definitions.  Where before
it was fine to assume that we would be testing our single, list-based
implementation, now we needed to allow for testing other
implementation types.  We did this by adding a &lt;em&gt;rackType&lt;/em&gt; parameter to
our property definitions.  We used the type, not the value, of this
parameter to determine the type of rack to test:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;prop_New&lt;/span&gt; &lt;span class='varid'&gt;rackType&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt;
    &lt;span class='varid'&gt;balls&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;mkRack&lt;/span&gt; &lt;span class='varop'&gt;`asTypeOf`&lt;/span&gt; &lt;span class='varid'&gt;rackType&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;=~&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;

&lt;span class='varid'&gt;prop_AddAddsElement&lt;/span&gt; &lt;span class='varid'&gt;rackType&lt;/span&gt; &lt;span class='varid'&gt;ballList&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt;
    &lt;span class='varid'&gt;balls&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;add&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varid'&gt;rack&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;=~&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='conop'&gt;:&lt;/span&gt; &lt;span class='varid'&gt;balls&lt;/span&gt; &lt;span class='varid'&gt;rack&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
  &lt;span class='keyword'&gt;where&lt;/span&gt;
    &lt;span class='varid'&gt;rack&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;rackFromList&lt;/span&gt; &lt;span class='varid'&gt;ballList&lt;/span&gt; &lt;span class='varop'&gt;`asTypeOf`&lt;/span&gt; &lt;span class='varid'&gt;rackType&lt;/span&gt;

&lt;span class='varid'&gt;prop_AddPreservesOrdering&lt;/span&gt; &lt;span class='varid'&gt;rackType&lt;/span&gt; &lt;span class='varid'&gt;ballList&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt;
    &lt;span class='varid'&gt;isOrdered&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;balls&lt;/span&gt; &lt;span class='varid'&gt;rack&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;==&amp;gt;&lt;/span&gt; &lt;span class='varid'&gt;isOrdered&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;balls&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;add&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varid'&gt;rack&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
  &lt;span class='keyword'&gt;where&lt;/span&gt;
    &lt;span class='varid'&gt;rack&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;rackFromList&lt;/span&gt; &lt;span class='varid'&gt;ballList&lt;/span&gt; &lt;span class='varop'&gt;`asTypeOf`&lt;/span&gt; &lt;span class='varid'&gt;rackType&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Because we could no longer assume the rack would be represented
as a list of integers, we wrote &lt;em&gt;rackFromList&lt;/em&gt; to convert such
a list into a rack:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;rackFromList&lt;/span&gt; &lt;span class='varid'&gt;xs&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;foldr&lt;/span&gt; &lt;span class='varid'&gt;add&lt;/span&gt; &lt;span class='varid'&gt;mkRack&lt;/span&gt; &lt;span class='varid'&gt;xs&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;With these modifications in place, we re-ran our tests, specifying
(via type annotations) that we wanted to run them for the &lt;em&gt;ListRack&lt;/em&gt;
implementation:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;*Rack&amp;gt; quickCheck $ prop_New (undefined :: ListRack Int)
OK, passed 100 tests.

*Rack&amp;gt; quickCheck $ prop_AddAddsElement (undefined :: ListRack Int)
OK, passed 100 tests.

*Rack&amp;gt; quickCheck $ prop_AddPreservesOrdering (undefined :: ListRack Int)
OK, passed 100 tests.
&lt;/code&gt;&lt;/pre&gt;

	&lt;h3&gt;A tree-based Rack implementation&lt;/h3&gt;


	&lt;p&gt;Now that we were free to add additional implementation types,
we created one based on binary trees.  We started by defining
the tree data type:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='keyword'&gt;data&lt;/span&gt; &lt;span class='conid'&gt;Tree&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt;
    &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='conid'&gt;Empty&lt;/span&gt;
    &lt;span class='keyglyph'&gt;|&lt;/span&gt; &lt;span class='conid'&gt;Root&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Tree&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Tree&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
    &lt;span class='keyword'&gt;deriving&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Ord&lt;/span&gt;&lt;span class='layout'&gt;,&lt;/span&gt; &lt;span class='conid'&gt;Eq&lt;/span&gt;&lt;span class='layout'&gt;,&lt;/span&gt; &lt;span class='conid'&gt;Show&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;This definition says that a tree can be either empty or a root node.
A root node has a single value and left and right sub-trees.&lt;/p&gt;


	&lt;p&gt;Further, root nodes must satisfy an ordering invariant: if a root
node&amp;#8217;s value is &lt;em&gt;x&lt;/em&gt;, all of the values in its left subtree must be
less than &lt;em&gt;x&lt;/em&gt;, and all of the values in its right subtree must be
greater than or equal to &lt;em&gt;x&lt;/em&gt;.  The data type doesn&amp;#8217;t enforce this
invariant, so we would need to enforce it in our implementation.&lt;/p&gt;


	&lt;p&gt;Next, we wrote the basic functions for creating, adding elements to,
and observing our trees.&lt;/p&gt;


	&lt;p&gt;We needed to be able to create empty trees:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;emptyTree&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt;
    &lt;span class='conid'&gt;Empty&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Inserting an element into a tree requires us to walk the tree and
append the element as a new leaf node in the correct location, being
mindful of our ordering invariant.  Because our data structure is
inherently recursive, a recursive implementation was straightforward
to code:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;insertTree&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='conid'&gt;Empty&lt;/span&gt;  &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='conid'&gt;Root&lt;/span&gt; &lt;span class='conid'&gt;Empty&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='conid'&gt;Empty&lt;/span&gt;
&lt;span class='varid'&gt;insertTree&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Root&lt;/span&gt; &lt;span class='varid'&gt;left&lt;/span&gt; &lt;span class='varid'&gt;y&lt;/span&gt; &lt;span class='varid'&gt;right&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
    &lt;span class='keyglyph'&gt;|&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varop'&gt;&amp;lt;&lt;/span&gt; &lt;span class='varid'&gt;y&lt;/span&gt;         &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='conid'&gt;Root&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;insertTree&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varid'&gt;left&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varid'&gt;y&lt;/span&gt; &lt;span class='varid'&gt;right&lt;/span&gt;
    &lt;span class='keyglyph'&gt;|&lt;/span&gt; &lt;span class='varid'&gt;otherwise&lt;/span&gt;     &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='conid'&gt;Root&lt;/span&gt; &lt;span class='varid'&gt;left&lt;/span&gt; &lt;span class='varid'&gt;y&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;insertTree&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varid'&gt;right&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Note that we don&amp;#8217;t try to ensure that the tree is balanced.  The
problem statement says that the balls are randomly selected, and thus
we can expect our trees, on average, to be balanced naturally.&lt;/p&gt;


	&lt;p&gt;Next, we wrote the code to observe the elements of a tree.
We used a functional-programming idiom
for efficiently flattening a tree into a list:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;elemsTree&lt;/span&gt; &lt;span class='varid'&gt;rx&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt;
    &lt;span class='varid'&gt;elemsTree'&lt;/span&gt; &lt;span class='varid'&gt;rx&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;

&lt;span class='varid'&gt;elemsTree'&lt;/span&gt; &lt;span class='conid'&gt;Empty&lt;/span&gt;               &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;id&lt;/span&gt;
&lt;span class='varid'&gt;elemsTree'&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Root&lt;/span&gt; &lt;span class='varid'&gt;left&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varid'&gt;right&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt;
    &lt;span class='varid'&gt;elemsTree'&lt;/span&gt; &lt;span class='varid'&gt;left&lt;/span&gt; &lt;span class='varop'&gt;.&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='conop'&gt;:&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;.&lt;/span&gt; &lt;span class='varid'&gt;elemsTree'&lt;/span&gt; &lt;span class='varid'&gt;right&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Finally, we defined a new tree-based rack type and declared
it to be an instance of the &lt;em&gt;Racklike&lt;/em&gt; type class:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='keyword'&gt;type&lt;/span&gt; &lt;span class='conid'&gt;TreeRack&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='conid'&gt;Tree&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt;

&lt;span class='keyword'&gt;instance&lt;/span&gt; &lt;span class='conid'&gt;Racklike&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;TreeRack&lt;/span&gt; &lt;span class='varid'&gt;a&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='keyword'&gt;where&lt;/span&gt;
    &lt;span class='varid'&gt;mkRack&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;emptyTree&lt;/span&gt;
    &lt;span class='varid'&gt;add&lt;/span&gt;    &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;insertTree&lt;/span&gt;
    &lt;span class='varid'&gt;balls&lt;/span&gt;  &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;elemsTree&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;With the implementation done, we took it for a test drive:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;*Rack&amp;gt; add 1 mkRack :: TreeRack Int
Root Empty 1 Empty

*Rack&amp;gt; add 3 (add 1 mkRack) :: TreeRack Int
Root Empty 1 (Root Empty 3 Empty)

*Rack&amp;gt; balls (add 3 (add 1 mkRack) :: TreeRack Int)
[1,3]
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Then, for the real test, we checked that our properties held for
TreeRacks:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;*Rack&amp;gt; quickCheck $ prop_New (undefined :: TreeRack Int)
OK, passed 100 tests.

*Rack&amp;gt; quickCheck $ prop_AddAddsElement (undefined :: TreeRack Int)
OK, passed 100 tests.

quickCheck $ prop_AddPreservesOrdering (undefined :: TreeRack Int)
OK, passed 100 tests.
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Satisfied with these results,  we moved on to part two of the problem.&lt;/p&gt;


	&lt;h3&gt; The second part of the problem&lt;/h3&gt;


	&lt;p&gt;The second part of the problem was about sorting the letters within a
block of text, ignoring white space and punctuation, and converting
upper case letters into lower case: &amp;#8220;Are there any ways to
perform this sort cheaply, and without using built-in libraries?&amp;#8221;&lt;/p&gt;


	&lt;p&gt;Again, a counting sort seemed like an obvious ideal solution, but
we decided to recycle our existing code since we had to leave soon.
Because our Rack implementations were generic, they would work on
letters just as well as on numbers or other kinds of balls:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;*Rack&amp;gt; balls (rackFromList "this is a test" :: TreeRack Char)
"   aehiisssttt" 
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;With our existing code already doing the hard work
for us, it was trivial to code up the letter-sorting function:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;sortLetters&lt;/span&gt; &lt;span class='varid'&gt;xs&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt;
    &lt;span class='varid'&gt;balls&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;rackFromList&lt;/span&gt; &lt;span class='varid'&gt;letters&lt;/span&gt; &lt;span class='keyglyph'&gt;::&lt;/span&gt; &lt;span class='conid'&gt;TreeRack&lt;/span&gt; &lt;span class='conid'&gt;Char&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
  &lt;span class='keyword'&gt;where&lt;/span&gt;
    &lt;span class='varid'&gt;letters&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='keyglyph'&gt;[&lt;/span&gt;&lt;span class='varid'&gt;toLower&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;|&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;xs&lt;/span&gt;&lt;span class='layout'&gt;,&lt;/span&gt; &lt;span class='varid'&gt;isAlpha&lt;/span&gt; &lt;span class='varid'&gt;x&lt;/span&gt;&lt;span class='keyglyph'&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;(Note: Because of the nature of the problem, I interpreted the
question&amp;#8217;s &amp;#8220;without using built-in libraries&amp;#8221; to mean &amp;#8220;without
built-in &lt;em&gt;sorting&lt;/em&gt; libraries.&amp;#8221;)&lt;/p&gt;


	&lt;p&gt;We took the new function for a test drive, and it worked
as expected:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;*Rack&amp;gt; sortLetters "This is a test, pal." 
"aaehiilpsssttt" 
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;And that ended our coding session.&lt;/p&gt;


&lt;div class="update"&gt;

&lt;p&gt;&lt;strong&gt;Update:&lt;/strong&gt; Tweaked the revised definition of the AddAddsElement
property for greater parallelism with the original.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Update 2007-03-03:&lt;/strong&gt; Minor edits for clarity.&lt;/p&gt;
&lt;/div&gt;</description>
      <pubDate>Tue, 31 Oct 2006 14:44:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:8704669e-0d37-4b41-9107-96f72ec20218</guid>
      <author>Tom Moertel</author>
      <link>http://blog.moertel.com/articles/2006/10/31/introductory-haskell-solving-the-sorting-it-out-kata</link>
      <category>programming</category>
      <category>functional programming</category>
      <category>haskell</category>
      <category>testing</category>
      <category>haskell</category>
      <category>testing</category>
      <category>kata</category>
      <category>sorting</category>
      <category>quickcheck</category>
      <trackback:ping>http://blog.moertel.com/articles/trackback/205</trackback:ping>
    </item>
    <item>
      <title>My code is &amp;quot;so clever as to be stupid&amp;quot;</title>
      <description>&lt;p&gt;In &lt;a href="http://liveatthewitchtrials.blogeasy.com/article.view.run?articleID=318294"&gt;Port Scanning Shootout&lt;/a&gt;, author &amp;#8220;cavedave&amp;#8221; provides a mini-review of my &lt;a href="http://blog.moertel.com/articles/2004/03/13/concurrent-port-scanner-in-haskell"&gt;Concurrent port scanner in Haskell&lt;/a&gt;.  The thing is, I am not sure what to make of it:&lt;/p&gt;


&lt;blockquote&gt;50 lines of indentation balancing monadic grappling goodness. Considering I started this quest after seeing this code and thinking it was good, in retrospect it seems very big and not very clever, or at least so clever as to be stupid.&lt;/blockquote&gt;

	&lt;p&gt;I am struck by the last statement. It seems the author is
channeling the timeless &lt;a href="http://www.imdb.com/title/tt0088258/quotes"&gt;David St. Hubbins&lt;/a&gt;, who said,
&amp;#8220;It&amp;#8217;s such a fine line between stupid, and clever.&amp;#8221;&lt;/p&gt;


	&lt;p&gt;Words to live by, if you ask me. &amp;#160; &lt;tt&gt;;-)&lt;/tt&gt;&lt;/p&gt;</description>
      <pubDate>Fri, 16 Jun 2006 08:21:00 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:07336683007bee6d598665a1cb50c1b1</guid>
      <author>Tom Moertel</author>
      <link>http://blog.moertel.com/articles/2006/06/16/my-code-is-so-clever-as-to-be-stupid</link>
      <category>programming</category>
      <category>functional programming</category>
      <category>haskell</category>
      <category>humor</category>
      <trackback:ping>http://blog.moertel.com/articles/trackback/68</trackback:ping>
    </item>
    <item>
      <title>Composing functions in Ruby</title>
      <description>&lt;p&gt;One of the things I miss when coding in Ruby is
inexpensive function composition.  In Haskell, for example,
I can compose functions using the dot (.) operator:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;inc        = (+1)
twice      = (*2)
twiceOfInc = twice . inc
&lt;/code&gt;&lt;/pre&gt;

Because of Ruby&amp;#8217;s open classes, however, I can easily
add the feature to the language.  In
the code below, I introduce
&lt;code&gt;Proc.compose&lt;/code&gt; and overload the
star (&lt;code&gt;*&lt;/code&gt;) operator for the purpose:

&lt;pre&gt;&lt;code&gt;# func_composition.rb
class Proc
  def self.compose(f, g)
    lambda { |*args| f[g[*args]] }
  end
  def *(g)
    Proc.compose(self, g)
  end
end
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;And that&amp;#8217;s all it takes:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;$ irb --simple-prompt -r func_composition.rb

&amp;gt;&amp;gt; inc = lambda { |x| x + 1 }
=&amp;gt; #&amp;lt;Proc:0x00002aaaaaad7810@(irb):1&amp;gt;

&amp;gt;&amp;gt; twice = lambda { |x| x * 2 }
=&amp;gt; #&amp;lt;Proc:0x00002aaaaabd2d18@(irb):2&amp;gt;

&amp;gt;&amp;gt; inc[1]
=&amp;gt; 2

&amp;gt;&amp;gt; twice[2]
=&amp;gt; 4

&amp;gt;&amp;gt; twice_of_inc = twice * inc
=&amp;gt; #&amp;lt;Proc:0x00002aaaaab32458@./func_composition.rb:3&amp;gt;

&amp;gt;&amp;gt; twice_of_inc[1]
=&amp;gt; 4

&amp;gt;&amp;gt; twice_of_inc[2]
=&amp;gt; 6
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Now, isn&amp;#8217;t that refreshing?&lt;/p&gt;


&lt;div class="update"&gt;
&lt;strong&gt;Update:&lt;/strong&gt; Vincent Foley &lt;a href="http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/6102f784210bdb32/05dfa12e07513a2c#05dfa12e07513a2c"&gt;pointed out on comp.lang.ruby&lt;/a&gt; that &lt;a href="http://facets.rubyforge.org/"&gt;Ruby Facets&lt;/a&gt; has a &lt;a href="http://facets.rubyforge.org/api/core/classes/Proc.html"&gt;nearly identical implementation&lt;/a&gt; that also uses the star operator for composition.  (Its version of &lt;em&gt;compose&lt;/em&gt;, however, is an instance method whereas my version is a class method.)
&lt;/div&gt;</description>
      <pubDate>Fri, 07 Apr 2006 11:55:00 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:0d98557f896ddc1d75ff1f85eb283602</guid>
      <author>Tom Moertel</author>
      <link>http://blog.moertel.com/articles/2006/04/07/composing-functions-in-ruby</link>
      <category>functional programming</category>
      <category>ruby</category>
      <category>ruby</category>
      <category>functional_programming</category>
      <category>fp</category>
      <trackback:ping>http://blog.moertel.com/articles/trackback/62</trackback:ping>
    </item>
    <item>
      <title>Wow! A Haskell-based first-person shooter!</title>
      <description>&lt;p&gt;As seen in &lt;a href="http://sequence.complete.org/hwn/20051122"&gt;Haskell Weekly
News&lt;/a&gt;, Mon Hon Cheong
announced &lt;a href="http://haskell.org/haskellwiki/Frag"&gt;Frag&lt;/a&gt;, a first-person
shooter written in &amp;#8211; wait for it &amp;#8211; &lt;em&gt;Haskell&lt;/em&gt;.  It uses
&lt;a href="http://www.haskell.org/haskellwiki/Opengl"&gt;HOpenGL&lt;/a&gt; for its OpenGL binding
and &lt;a href="http://www.haskell.org/yampa/"&gt;Yampa&lt;/a&gt; for reactive game
elements.&lt;/p&gt;


	&lt;p&gt;Cool!&lt;/p&gt;</description>
      <pubDate>Tue, 22 Nov 2005 17:26:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:8cc8b3dd2148b6c248bcf456794eada7</guid>
      <author>Tom Moertel</author>
      <link>http://blog.moertel.com/articles/2005/11/22/wow-a-haskell-based-first-person-shooter</link>
      <category>functional programming</category>
      <category>haskell</category>
      <category>haskell</category>
      <category>frag</category>
      <category>opengl</category>
      <category>yampa</category>
      <trackback:ping>http://blog.moertel.com/articles/trackback/16</trackback:ping>
    </item>
    <item>
      <title>Scope herding with delimited continuations</title>
      <description>&lt;p&gt;Recently I took advantage of delimited continuations to create a more
natural Haskell-based kernel for
&lt;acronym title="Genetics Information Manipulation Language"&gt;GIML&lt;/acronym&gt;.
The amazing scope-herding abilities of &lt;em&gt;reset&lt;/em&gt; and
&lt;em&gt;shift&lt;/em&gt; were the magic that made it possible.&lt;/p&gt;


	&lt;p&gt;Ready to get wild?  Grab an espresso and read on.&lt;/p&gt;&lt;p&gt;Consider the &lt;span class="caps"&gt;GIML&lt;/span&gt; code below.  A block, delimited by curly braces,
establishes a new evaluation frame.  Variable bindings (such as those
for &lt;em&gt;x&lt;/em&gt; below) shadow earlier bindings, and each remains in effect until
its enclosing block goes out of scope.&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;# GIML code (ex. 1)
x &amp;lt;- 1
{
    x &amp;lt;- 2   # local binding shadows earlier binding
    x        # evaluates to 2
}            # local binding goes out of scope with block
x   # evaluates to 1
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;The &lt;a href="http://www.haskell.org/hawiki/MonadReader"&gt;Reader monad&lt;/a&gt;
provides most of this block-scoping behavior for
free, and so it makes a natural part of the monad underlying the &lt;span class="caps"&gt;GIML&lt;/span&gt;
evaluator.  Its job is to make an environment &amp;#8211; in this case, a
Haskell &lt;a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data.Map.html"&gt;Data.Map&lt;/a&gt; containing our active bindings &amp;#8211; available to the
actions running within it.  The Reader monad provides the &lt;em&gt;ask&lt;/em&gt; and
&lt;em&gt;asks&lt;/em&gt; combinators, which we can use to get and work with our
bindings.  We can use &lt;em&gt;asks&lt;/em&gt;, for example, to write a combinator
&lt;em&gt;evalVar&lt;/em&gt; that takes a variable name and returns an action that looks
up the variable&amp;#8217;s value in the active bindings:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='comment'&gt;-- Haskell code (ex. 2)&lt;/span&gt;
&lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='varid'&gt;var&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;val&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;asks&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Map&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='varid'&gt;findWithDefault&lt;/span&gt; &lt;span class='num'&gt;0&lt;/span&gt; &lt;span class='varid'&gt;var&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
    &lt;span class='varid'&gt;return&lt;/span&gt; &lt;span class='varid'&gt;val&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;The Reader monad also supplies a combinator &lt;em&gt;local&lt;/em&gt; that can be used
to run actions within a locally modified environment.  The semantics
of &lt;em&gt;local&lt;/em&gt; ensure that the modifications cannot escape: after the local
actions have been executed, the local environment goes out of scope
and the previous, containing environment is restored.  And that&amp;#8217;s
the block-scoping behavior we want.&lt;/p&gt;


	&lt;p&gt;Let&amp;#8217;s use &lt;em&gt;local&lt;/em&gt; to represent the following &lt;span class="caps"&gt;GIML&lt;/span&gt; block:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;# GIML code (ex. 3)
{
    x &amp;lt;- 2
    x
}
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Here is a &lt;em&gt;local&lt;/em&gt;-based Haskell representation of the &lt;span class="caps"&gt;GIML&lt;/span&gt; block:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='comment'&gt;-- Haskell code (ex. 4)&lt;/span&gt;
&lt;span class='varid'&gt;local&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Map&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='varid'&gt;insert&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt; &lt;span class='num'&gt;2&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;The Haskell code above says, roughly translated, &amp;#8220;Create a local
environment by binding &lt;em&gt;x&lt;/em&gt; to 2 (on top of any bindings that may have
been effective within the outer environment) and then run the
&lt;em&gt;evalVar&lt;/em&gt; action within the local environment.&amp;#8221;&lt;/p&gt;


	&lt;p&gt;Any actions before or after the &lt;em&gt;local&lt;/em&gt; action will run in the outer
environment, which will be unaffected by the &lt;em&gt;local&lt;/em&gt; action.  For
example, consider the following Haskell code:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='keyword'&gt;do&lt;/span&gt;
&lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
&lt;span class='varid'&gt;local&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Map&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='varid'&gt;insert&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt; &lt;span class='num'&gt;2&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
&lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;In the code above, if the first &lt;em&gt;evalVar&lt;/em&gt; action results in 1, so must
the third &lt;em&gt;evalVar&lt;/em&gt; action because both run in the exact same
environment.  (The definition of &lt;em&gt;bind&lt;/em&gt; for the Reader monad
guarantees this.)  The second &lt;em&gt;evalVar&lt;/em&gt; action, however, runs in a
locally modified environment where &lt;em&gt;x&lt;/em&gt; is bound to 2, and so it will
result in 2.&lt;/p&gt;


	&lt;p&gt;Unfortunately, this translation scheme for blocks and bindings has a
limitation.  Once we enter a block, we can&amp;#8217;t change its environment
because the only way to make changes is via &lt;em&gt;local&lt;/em&gt;, and those changes
would be confined to a new, local environment and would not affect the
environment of the block&amp;#8217;s remaining actions.  Thus the only way we
can effect a mid-block binding is to introduce another block, nested
within the first.&lt;/p&gt;


	&lt;p&gt;For example, consider the following &lt;span class="caps"&gt;GIML&lt;/span&gt; code:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;# GIML code (ex. 5)
{
    x &amp;lt;- 2
    y &amp;lt;- x + 1
    x + y
}
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;How do we translate this into Haskell?  Our earlier translation method
doesn&amp;#8217;t work on this code because we have a mid-block binding.  If we
rewrite the &lt;span class="caps"&gt;GIML&lt;/span&gt; code to make the scope of each binding explicit,
however, we get an equivalent &lt;span class="caps"&gt;GIML&lt;/span&gt; expression that &lt;em&gt;can&lt;/em&gt; be translated:
&lt;a name="ex6"&gt;&lt;/a&gt;&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;# GIML code (ex. 6)
{
    x &amp;lt;- 2
    {
        y &amp;lt;- x + 1
        x + y
    }
}
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;The Haskell translation of the above: &lt;a name="ex7"&gt;&lt;/a&gt;&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='comment'&gt;-- Haskell code (ex. 7)&lt;/span&gt;
&lt;span class='varid'&gt;local&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Map&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='varid'&gt;insert&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt; &lt;span class='num'&gt;2&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
    &lt;span class='varid'&gt;local&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Map&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='varid'&gt;insert&lt;/span&gt; &lt;span class='str'&gt;"y"&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varop'&gt;+&lt;/span&gt; &lt;span class='num'&gt;1&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
        &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
        &lt;span class='varid'&gt;y&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"y"&lt;/span&gt;
        &lt;span class='varid'&gt;return&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varop'&gt;+&lt;/span&gt; &lt;span class='varid'&gt;y&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;This is, ultimately, the translation we want, but deriving it is
awkward. Who wants to scan the &lt;span class="caps"&gt;AST&lt;/span&gt; and insert scoping blocks?
Not me.&lt;/p&gt;


	&lt;p&gt;Instead, why not break the chains between binding and block-scoping?
We ought to be able to make a local binding anywhere, not just at the
point where a block begins.  Let&amp;#8217;s aim for code like the following, which is
a direct translation of the earlier &lt;span class="caps"&gt;GIML&lt;/span&gt; code and preserves the
user-supplied blocking:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='comment'&gt;-- Haskell code (ex. 8)&lt;/span&gt;
&lt;span class='varid'&gt;enterBlock&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;bindLocal&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt; &lt;span class='num'&gt;2&lt;/span&gt;
    &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
    &lt;span class='varid'&gt;bindLocal&lt;/span&gt; &lt;span class='str'&gt;"y"&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varop'&gt;+&lt;/span&gt; &lt;span class='num'&gt;1&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
    &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
    &lt;span class='varid'&gt;y&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"y"&lt;/span&gt;
    &lt;span class='varid'&gt;return&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varop'&gt;+&lt;/span&gt; &lt;span class='varid'&gt;y&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;The key to this more pleasant translation is the magic pair of
combinators &lt;em&gt;enterBlock&lt;/em&gt; and &lt;em&gt;bindLocal&lt;/em&gt;.  The &lt;em&gt;enterBlock&lt;/em&gt; combinator
creates a new block, and &lt;em&gt;bindLocal&lt;/em&gt; sets up a binding that goes out
of scope when the block that contains it does.  Note that &lt;em&gt;bindLocal&lt;/em&gt;
can be used anywhere, and not just at the beginning of a block.&lt;/p&gt;


	&lt;p&gt;How, then, do we implement these new combinators?  This is where
delimited continuations come in.  Take a look at the combinators&amp;#8217;
definitions:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='comment'&gt;-- Haskell code&lt;/span&gt;
&lt;span class='varid'&gt;enterBlock&lt;/span&gt; &lt;span class='varid'&gt;action&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;reset&lt;/span&gt; &lt;span class='varid'&gt;action&lt;/span&gt;
&lt;span class='varid'&gt;bindLocal&lt;/span&gt; &lt;span class='varid'&gt;var&lt;/span&gt; &lt;span class='varid'&gt;val&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;shift&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyglyph'&gt;\&lt;/span&gt;&lt;span class='varid'&gt;c&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='varid'&gt;local&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Map&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='varid'&gt;insert&lt;/span&gt; &lt;span class='varid'&gt;var&lt;/span&gt; &lt;span class='varid'&gt;val&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;c&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Before going further, let&amp;#8217;s review &lt;em&gt;reset&lt;/em&gt; and &lt;em&gt;shift&lt;/em&gt;, the dynamic
duo of delimited continuations.  The &lt;em&gt;reset&lt;/em&gt; combinator brackets an
action, drawing a boundary around it.  The &lt;em&gt;shift&lt;/em&gt; combinator is a bit
trickier.  (Quaff espresso now.)  When we invoke &lt;em&gt;shift&lt;/em&gt; within a
bracketed action, something amazing happens.  The bracketed action is
abortively replaced by another action that is constructed by the
template function that we supply to &lt;em&gt;shift&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;Now, here&amp;#8217;s where it gets wild.  Our template function constructs the
replacement action from an internal template, which can pull in the
&lt;em&gt;shift&lt;/em&gt; action&amp;#8217;s &lt;em&gt;context&lt;/em&gt;.  The context is a delimited continuation
that represents the &lt;em&gt;unexecuted&lt;/em&gt; portion of the &lt;em&gt;reset&lt;/em&gt;-bracketed
action &amp;#8211; except for the &lt;em&gt;shift&lt;/em&gt; action itself, which has been removed,
leaving a hole in the context.  Our template fills in the hole with a value by
passing the value to the context, which is really just another
function.&lt;/p&gt;


	&lt;p&gt;If it sounds confusing, the following example may help.  Consider this
code, which represents an action within a monad that supports
delimited continuations and IO:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='comment'&gt;-- Haskell code (ex. 9)&lt;/span&gt;
&lt;span class='varid'&gt;reset&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='str'&gt;"before"&lt;/span&gt;
    &lt;span class='varid'&gt;msg&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;shift&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyglyph'&gt;\&lt;/span&gt;&lt;span class='varid'&gt;cxt&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
        &lt;span class='comment'&gt;-- our "template"&lt;/span&gt;
        &lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='str'&gt;"template start"&lt;/span&gt;
        &lt;span class='varid'&gt;cxt&lt;/span&gt; &lt;span class='str'&gt;"template cxt(first)"&lt;/span&gt;
        &lt;span class='varid'&gt;cxt&lt;/span&gt; &lt;span class='str'&gt;"template cxt(second)"&lt;/span&gt;
        &lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='str'&gt;"template end"&lt;/span&gt; 
    &lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='varid'&gt;msg&lt;/span&gt;
    &lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='str'&gt;"after"&lt;/span&gt;
  &lt;span class='keyword'&gt;where&lt;/span&gt;
    &lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='keyglyph'&gt;=&lt;/span&gt; &lt;span class='varid'&gt;liftIO&lt;/span&gt; &lt;span class='varop'&gt;.&lt;/span&gt; &lt;span class='varid'&gt;putStrLn&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Let&amp;#8217;s break it down.  First, &lt;em&gt;reset&lt;/em&gt; brackets everything between it
and the &lt;em&gt;where&lt;/em&gt; clause.&lt;/p&gt;


	&lt;p&gt;Second, the initial &lt;em&gt;puts&lt;/em&gt; action prints &amp;#8220;before&amp;#8221; to the screen.&lt;/p&gt;


	&lt;p&gt;Third, the &lt;em&gt;shift&lt;/em&gt; action takes control.  &lt;em&gt;Blammo!&lt;/em&gt; The
&lt;em&gt;reset&lt;/em&gt;-delimited action is aborted.  Its unexecuted portion is
captured as the context, which we can approximate with an anonymous
function that looks like this:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='layout'&gt;(&lt;/span&gt; &lt;span class='keyglyph'&gt;\&lt;/span&gt;&lt;span class='varid'&gt;hole&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='varid'&gt;reset&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;msg&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;return&lt;/span&gt; &lt;span class='varid'&gt;hole&lt;/span&gt;
    &lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='varid'&gt;msg&lt;/span&gt;
    &lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='str'&gt;"after"&lt;/span&gt; &lt;span class='layout'&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;(I used the variable &lt;em&gt;hole&lt;/em&gt; above to represent the hole left by
removing the &lt;em&gt;shift&lt;/em&gt; action.)  This context function is then passed by
&lt;em&gt;shift&lt;/em&gt; to our template function, which binds the context function to
its &lt;em&gt;cxt&lt;/em&gt; variable.&lt;/p&gt;


	&lt;p&gt;Then the template function builds the action that will replace the
aborted action.  Before &amp;#8220;expansion,&amp;#8221; the template looks like this:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='keyword'&gt;do&lt;/span&gt;
&lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='str'&gt;"template start"&lt;/span&gt;
&lt;span class='varid'&gt;cxt&lt;/span&gt; &lt;span class='str'&gt;"template cxt(first)"&lt;/span&gt;
&lt;span class='varid'&gt;cxt&lt;/span&gt; &lt;span class='str'&gt;"template cxt(second)"&lt;/span&gt;
&lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='str'&gt;"template end"&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Each call to the &lt;em&gt;cxt&lt;/em&gt; function drops the captured context into
the template and fills in the context&amp;#8217;s hole with the supplied argument.
Expanding these calls results in the final template:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='keyword'&gt;do&lt;/span&gt;
&lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='str'&gt;"template start"&lt;/span&gt;
&lt;span class='varid'&gt;reset&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;msg&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;return&lt;/span&gt; &lt;span class='str'&gt;"template cxt(first)"&lt;/span&gt;
    &lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='varid'&gt;msg&lt;/span&gt;
    &lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='str'&gt;"after"&lt;/span&gt;
&lt;span class='varid'&gt;reset&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;msg&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;return&lt;/span&gt; &lt;span class='str'&gt;"template cxt(second)"&lt;/span&gt;
    &lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='varid'&gt;msg&lt;/span&gt;
    &lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='str'&gt;"after"&lt;/span&gt;
&lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='str'&gt;"template end"&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Because the &lt;em&gt;reset&lt;/em&gt;-delimited portions of the code above
do not contain any &lt;em&gt;shift&lt;/em&gt; actions, &lt;em&gt;reset&lt;/em&gt; acts like
an identity function, and the final expansion of our
template is thus as follows:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='keyword'&gt;do&lt;/span&gt;
&lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='str'&gt;"template start"&lt;/span&gt;
&lt;span class='varid'&gt;msg&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;return&lt;/span&gt; &lt;span class='str'&gt;"template cxt(first)"&lt;/span&gt;
&lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='varid'&gt;msg&lt;/span&gt;
&lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='str'&gt;"after"&lt;/span&gt;
&lt;span class='varid'&gt;msg&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;return&lt;/span&gt; &lt;span class='str'&gt;"template cxt(second)"&lt;/span&gt;
&lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='varid'&gt;msg&lt;/span&gt;
&lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='str'&gt;"after"&lt;/span&gt;
&lt;span class='varid'&gt;puts&lt;/span&gt; &lt;span class='str'&gt;"template end"&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;As we would now expect, running the original action results in the
following output:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;before
template start
template cxt(first)
after
template cxt(second)
after
template end
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;(Recall that the first line of output was emitted before the
&lt;em&gt;shift&lt;/em&gt; action was invoked.)&lt;/p&gt;


	&lt;p&gt;The ability to grab the remainder of an action and stuff it into a
template is what makes the magic of &lt;em&gt;enterBlock&lt;/em&gt; and &lt;em&gt;bindLocal&lt;/em&gt;
possible.  When they appear in our Haskellized &lt;span class="caps"&gt;GIML&lt;/span&gt; code from earlier:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='comment'&gt;-- Haskell code&lt;/span&gt;
&lt;span class='varid'&gt;enterBlock&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;bindLocal&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt; &lt;span class='num'&gt;2&lt;/span&gt;
    &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
    &lt;span class='varid'&gt;bindLocal&lt;/span&gt; &lt;span class='str'&gt;"y"&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varop'&gt;+&lt;/span&gt; &lt;span class='num'&gt;1&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
    &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
    &lt;span class='varid'&gt;y&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"y"&lt;/span&gt;
    &lt;span class='varid'&gt;return&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varop'&gt;+&lt;/span&gt; &lt;span class='varid'&gt;y&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;they expand into this:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;reset&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;shift&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyglyph'&gt;\&lt;/span&gt;&lt;span class='varid'&gt;c&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='varid'&gt;local&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Map&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='varid'&gt;insert&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt; &lt;span class='num'&gt;2&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;c&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
    &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
    &lt;span class='varid'&gt;shift&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyglyph'&gt;\&lt;/span&gt;&lt;span class='varid'&gt;c&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='varid'&gt;local&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Map&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='varid'&gt;insert&lt;/span&gt; &lt;span class='str'&gt;"y"&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varop'&gt;+&lt;/span&gt; &lt;span class='num'&gt;1&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;c&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
    &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
    &lt;span class='varid'&gt;y&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"y"&lt;/span&gt;
    &lt;span class='varid'&gt;return&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varop'&gt;+&lt;/span&gt; &lt;span class='varid'&gt;y&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;And that, thanks to delimited continuations, is &amp;#8220;re-scoped&amp;#8221; 
into to this:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;reset&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;reset&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='varid'&gt;local&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Map&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='varid'&gt;insert&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt; &lt;span class='num'&gt;2&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
        &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
        &lt;span class='varid'&gt;shift&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyglyph'&gt;\&lt;/span&gt;&lt;span class='varid'&gt;c&lt;/span&gt; &lt;span class='keyglyph'&gt;-&amp;gt;&lt;/span&gt; &lt;span class='varid'&gt;local&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Map&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='varid'&gt;insert&lt;/span&gt; &lt;span class='str'&gt;"y"&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varop'&gt;+&lt;/span&gt; &lt;span class='num'&gt;1&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;c&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
        &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
        &lt;span class='varid'&gt;y&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"y"&lt;/span&gt;
        &lt;span class='varid'&gt;return&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varop'&gt;+&lt;/span&gt; &lt;span class='varid'&gt;y&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;and then into this:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;reset&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;reset&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='varid'&gt;local&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Map&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='varid'&gt;insert&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt; &lt;span class='num'&gt;2&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
        &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
        &lt;span class='varid'&gt;reset&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='varid'&gt;local&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Map&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='varid'&gt;insert&lt;/span&gt; &lt;span class='str'&gt;"y"&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varop'&gt;+&lt;/span&gt; &lt;span class='num'&gt;1&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
            &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
            &lt;span class='varid'&gt;y&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"y"&lt;/span&gt;
            &lt;span class='varid'&gt;return&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varop'&gt;+&lt;/span&gt; &lt;span class='varid'&gt;y&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Finally, because the remaining &lt;em&gt;reset&lt;/em&gt; combinators contain no &lt;em&gt;shift&lt;/em&gt;
actions, we can treat them like identity functions to arrive at our
final code, which is identical to the Haskell code we wrote by hand
back in &lt;a href="#ex7"&gt;Example 7&lt;/a&gt; to represent the &lt;span class="caps"&gt;GIML&lt;/span&gt; code
that we added explicit blocking to (again, by hand) in
&lt;a href="#ex6"&gt;Example 6&lt;/a&gt;:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_haskell "&gt;&lt;span class='varid'&gt;local&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Map&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='varid'&gt;insert&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt; &lt;span class='num'&gt;2&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
    &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
    &lt;span class='varid'&gt;local&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='conid'&gt;Map&lt;/span&gt;&lt;span class='varop'&gt;.&lt;/span&gt;&lt;span class='varid'&gt;insert&lt;/span&gt; &lt;span class='str'&gt;"y"&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varop'&gt;+&lt;/span&gt; &lt;span class='num'&gt;1&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt; &lt;span class='varop'&gt;$&lt;/span&gt; &lt;span class='keyword'&gt;do&lt;/span&gt;
        &lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"x"&lt;/span&gt;
        &lt;span class='varid'&gt;y&lt;/span&gt; &lt;span class='keyglyph'&gt;&amp;lt;-&lt;/span&gt; &lt;span class='varid'&gt;evalVar&lt;/span&gt; &lt;span class='str'&gt;"y"&lt;/span&gt;
        &lt;span class='varid'&gt;return&lt;/span&gt; &lt;span class='layout'&gt;(&lt;/span&gt;&lt;span class='varid'&gt;x&lt;/span&gt; &lt;span class='varop'&gt;+&lt;/span&gt; &lt;span class='varid'&gt;y&lt;/span&gt;&lt;span class='layout'&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;And &lt;em&gt;that&lt;/em&gt;, my friends, is what we were after, all along.  Only this
time around, we didn&amp;#8217;t have to do it by hand &amp;#8211; our combinators did the
hard work for us.&lt;/p&gt;


&lt;div class="update"&gt;&lt;strong&gt;Update 2007-03-15:&lt;/strong&gt; Fixed typo.&lt;/div&gt;</description>
      <pubDate>Tue, 13 Sep 2005 10:24:00 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:802700ce48678d98209d89c4bb081cfa</guid>
      <author>Tom Moertel</author>
      <link>http://blog.moertel.com/articles/2005/09/13/scope-herding-with-delimited-continuations</link>
      <category>functional programming</category>
      <category>programming languages</category>
      <category>haskell</category>
      <category>languages</category>
      <category>continuations</category>
      <category>scope</category>
      <trackback:ping>http://blog.moertel.com/articles/trackback/6</trackback:ping>
    </item>
    <item>
      <title>Closures and the professional programmer</title>
      <description>&lt;p&gt;I came across &lt;a href="http://www.tbray.org/ongoing/When/200x/2005/08/27/Ruby"&gt;Tim Bray&amp;#8217;s thoughts on
Ruby&lt;/a&gt; via
the ever-delightful &lt;a href="http://lambda-the-ultimate.org/node/view/934"&gt;Lambda the Ultimate&lt;/a&gt; and found the following bit fascinating:&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;I&amp;#8217;ve had access to languages with closures and continuations and
suchlike constructs for years and years, and I&amp;#8217;ve never ever written
one. While I&amp;#8217;m impressed by how natural this stuff is in Ruby, &lt;em&gt;I&amp;#8217;m
still unconvinced that these are a necessary part of the professional
programmer&amp;#8217;s arsenal.&lt;/em&gt; [Emphasis mine.]&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;While Tim Bray may be unconvinced, I am a true believer.&lt;/p&gt;&lt;p&gt;I use closures so much that I feel cheated into doing busy work by
languages that do not support them.  I use continuations less often
but frequently enough to appreciate how much time they save me.
Neither is strictly required for professional work, but they are
potent tools, and a professional who knows how to use them has an
advantage over those who do not.&lt;/p&gt;


	&lt;p&gt;Closures, in particular, are something every professional ought to
master.  Besides their more celebrated uses, closures make refactoring practical on a small scale.  For
example, consider the following Ruby method, which we will assume is
one of several similar methods belonging to a class that implements some kind of Internet server:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_ruby "&gt;&lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;process&lt;/span&gt;
  &lt;span class="ident"&gt;sn&lt;/span&gt; &lt;span class="punct"&gt;=&lt;/span&gt; &lt;span class="ident"&gt;next_serial&lt;/span&gt;&lt;span class="punct"&gt;()&lt;/span&gt;
  &lt;span class="ident"&gt;log&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;info&lt;/span&gt; &lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;process/&lt;span class="expr"&gt;#{sn}&lt;/span&gt;: stage 1&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;
  &lt;span class="comment"&gt;# ... do some work&lt;/span&gt;
  &lt;span class="ident"&gt;log&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;info&lt;/span&gt; &lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;process/&lt;span class="expr"&gt;#{sn}&lt;/span&gt;: stage 2&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;
  &lt;span class="comment"&gt;# ... do some more work&lt;/span&gt;
  &lt;span class="ident"&gt;log&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;info&lt;/span&gt; &lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;process/&lt;span class="expr"&gt;#{sn}&lt;/span&gt;: finished&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;
&lt;span class="keyword"&gt;end&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;The method first gets a unique serial number, which is used during the processing of requests and also to relate log entries generated by the same processing call.  Then the method does its work, logging each stage in passing.&lt;/p&gt;


	&lt;p&gt;The method makes three logging calls that each hardcode the logger, the logging level, and the format of the log entries.  Since these things are repetitive and could very well change, we probably ought to factor them out into an isolated method.  After all, we don&amp;#8217;t want to rewrite a bucket of logging calls if the log-entry format changes.&lt;/p&gt;


	&lt;p&gt;Let&amp;#8217;s introduce a helper method &lt;em&gt;mylog&lt;/em&gt; to hold the common pieces:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_ruby "&gt;&lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;process&lt;/span&gt;
  &lt;span class="ident"&gt;sn&lt;/span&gt; &lt;span class="punct"&gt;=&lt;/span&gt; &lt;span class="ident"&gt;next_serial&lt;/span&gt;&lt;span class="punct"&gt;()&lt;/span&gt;
  &lt;span class="ident"&gt;mylog&lt;/span&gt;&lt;span class="punct"&gt;(&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;process&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;,&lt;/span&gt; &lt;span class="ident"&gt;sn&lt;/span&gt;&lt;span class="punct"&gt;,&lt;/span&gt; &lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;stage 1&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;)&lt;/span&gt;
  &lt;span class="comment"&gt;# ... do some work&lt;/span&gt;
  &lt;span class="ident"&gt;mylog&lt;/span&gt;&lt;span class="punct"&gt;(&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;process&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;,&lt;/span&gt; &lt;span class="ident"&gt;sn&lt;/span&gt;&lt;span class="punct"&gt;,&lt;/span&gt; &lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;stage 2&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;)&lt;/span&gt;
  &lt;span class="comment"&gt;# ... do some more work&lt;/span&gt;
  &lt;span class="ident"&gt;mylog&lt;/span&gt;&lt;span class="punct"&gt;(&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;process&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;,&lt;/span&gt; &lt;span class="ident"&gt;sn&lt;/span&gt;&lt;span class="punct"&gt;,&lt;/span&gt; &lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;finished&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;)&lt;/span&gt;
&lt;span class="keyword"&gt;end&lt;/span&gt;

&lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;mylog&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="ident"&gt;activity&lt;/span&gt;&lt;span class="punct"&gt;,&lt;/span&gt; &lt;span class="ident"&gt;sn&lt;/span&gt;&lt;span class="punct"&gt;,&lt;/span&gt; &lt;span class="ident"&gt;msg&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt;
  &lt;span class="ident"&gt;log&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;info&lt;/span&gt; &lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;&lt;span class="expr"&gt;#{activity}&lt;/span&gt;/&lt;span class="expr"&gt;#{sn}&lt;/span&gt; &lt;span class="expr"&gt;#{msg}&lt;/span&gt;&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;
&lt;span class="keyword"&gt;end&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;While we managed to isolate the logger, the logging level, and the
format of our logging messages, just &lt;em&gt;calling&lt;/em&gt; our helper method &lt;em&gt;mylog&lt;/em&gt; still
requires much redundancy.  Worse, the redundancy is on such a low
level that we can&amp;#8217;t factor it out with another helper method &amp;#8211; calling
the new helper would be as expensive and redundant as calling &lt;em&gt;mylog&lt;/em&gt;
directly.&lt;/p&gt;


	&lt;p&gt;What we need are refactoring tools that scale down to this sub-method level, and
that&amp;#8217;s where closures come to the rescue.  Using them, we can corral
the remaining redundancy with a local logging helper &lt;em&gt;llog&lt;/em&gt; that &amp;#8220;closes
over&amp;#8221; the relevant state:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_ruby "&gt;&lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;process&lt;/span&gt;
  &lt;span class="ident"&gt;sn&lt;/span&gt; &lt;span class="punct"&gt;=&lt;/span&gt; &lt;span class="ident"&gt;next_serial&lt;/span&gt;&lt;span class="punct"&gt;()&lt;/span&gt;
  &lt;span class="ident"&gt;llog&lt;/span&gt; &lt;span class="punct"&gt;=&lt;/span&gt; &lt;span class="ident"&gt;lambda&lt;/span&gt; &lt;span class="punct"&gt;{&lt;/span&gt; &lt;span class="punct"&gt;|&lt;/span&gt;&lt;span class="ident"&gt;s&lt;/span&gt;&lt;span class="punct"&gt;|&lt;/span&gt; &lt;span class="ident"&gt;mylog&lt;/span&gt;&lt;span class="punct"&gt;(&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;process&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;,&lt;/span&gt; &lt;span class="ident"&gt;sn&lt;/span&gt;&lt;span class="punct"&gt;,&lt;/span&gt; &lt;span class="ident"&gt;s&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt; &lt;span class="punct"&gt;}&lt;/span&gt;
  &lt;span class="ident"&gt;llog&lt;/span&gt;&lt;span class="punct"&gt;[&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;stage 1&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;]&lt;/span&gt;
  &lt;span class="comment"&gt;# ... do some work&lt;/span&gt;
  &lt;span class="ident"&gt;llog&lt;/span&gt;&lt;span class="punct"&gt;[&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;stage 2&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;]&lt;/span&gt;
  &lt;span class="comment"&gt;# ... do some more work&lt;/span&gt;
  &lt;span class="ident"&gt;llog&lt;/span&gt;&lt;span class="punct"&gt;[&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;finished&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;]&lt;/span&gt;
&lt;span class="keyword"&gt;end&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;Notice how much simpler and less redundant the logging code is?  Each stage can now be logged just by giving its name to &lt;em&gt;llog&lt;/em&gt;.  We don&amp;#8217;t need to pass in the activity name or serial number because &lt;em&gt;llog&lt;/em&gt; already knows them both.  It knows the activity name because we made it part of &lt;em&gt;llog&lt;/em&gt;&amp;#8217;s definition, but it knows the serial number because &lt;em&gt;sn&lt;/em&gt; is captured in &lt;em&gt;llog&lt;/em&gt;&amp;#8217;s closure &amp;#8211; for free.  (Note: If &lt;em&gt;f&lt;/em&gt; is a &lt;tt&gt;Proc&lt;/tt&gt; object, &lt;em&gt;f&lt;/em&gt;[&lt;em&gt;args&lt;/em&gt;] is syntactic sugar for &lt;em&gt;f&lt;/em&gt;&lt;tt&gt;.call&lt;/tt&gt;(&lt;em&gt;args&lt;/em&gt;).)&lt;/p&gt;


	&lt;p&gt;Of course, if we have several methods that require a unique serial
number and a corresponding logger, we could (thanks to closures)
factor things further:&lt;/p&gt;


&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_ruby "&gt;&lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;process&lt;/span&gt;
  &lt;span class="ident"&gt;sn&lt;/span&gt;&lt;span class="punct"&gt;,&lt;/span&gt; &lt;span class="ident"&gt;llog&lt;/span&gt; &lt;span class="punct"&gt;=&lt;/span&gt; &lt;span class="ident"&gt;next_serial_and_logger&lt;/span&gt;&lt;span class="punct"&gt;(&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;process&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;)&lt;/span&gt;
  &lt;span class="ident"&gt;llog&lt;/span&gt;&lt;span class="punct"&gt;[&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;stage 1&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;]&lt;/span&gt;
  &lt;span class="comment"&gt;# ... do some work&lt;/span&gt;
  &lt;span class="ident"&gt;llog&lt;/span&gt;&lt;span class="punct"&gt;[&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;stage 2&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;]&lt;/span&gt;
  &lt;span class="comment"&gt;# ... do some more work&lt;/span&gt;
  &lt;span class="ident"&gt;llog&lt;/span&gt;&lt;span class="punct"&gt;[&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;finished&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;]&lt;/span&gt;
&lt;span class="keyword"&gt;end&lt;/span&gt;

&lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;next_serial_and_logger&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="ident"&gt;activity&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt;
  &lt;span class="ident"&gt;sn&lt;/span&gt; &lt;span class="punct"&gt;=&lt;/span&gt; &lt;span class="ident"&gt;next_serial&lt;/span&gt;&lt;span class="punct"&gt;()&lt;/span&gt;
  &lt;span class="punct"&gt;[&lt;/span&gt;&lt;span class="ident"&gt;sn&lt;/span&gt;&lt;span class="punct"&gt;,&lt;/span&gt; &lt;span class="ident"&gt;lambda&lt;/span&gt; &lt;span class="punct"&gt;{&lt;/span&gt; &lt;span class="punct"&gt;|&lt;/span&gt;&lt;span class="ident"&gt;s&lt;/span&gt;&lt;span class="punct"&gt;|&lt;/span&gt; &lt;span class="ident"&gt;mylog&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="ident"&gt;activity&lt;/span&gt;&lt;span class="punct"&gt;,&lt;/span&gt; &lt;span class="ident"&gt;sn&lt;/span&gt;&lt;span class="punct"&gt;,&lt;/span&gt; &lt;span class="ident"&gt;s&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt; &lt;span class="punct"&gt;}]&lt;/span&gt;
&lt;span class="keyword"&gt;end&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;You get the point: Closures reduce the cost of working with local
state because they capture it implicitly.  There is no need to pass
the state back and forth; it&amp;#8217;s simply there.&lt;/p&gt;


	&lt;p&gt;Because the cra