<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:posterous="http://posterous.com/help/rss/1.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
  <channel>
    <title>musings of a Lispnik</title>
    <link>http://blog.danieljanus.pl</link>
    <description>Daniel Janus's blog</description>
    <generator>posterous.com</generator>
    <link xmlns="http://www.w3.org/2005/Atom" href="http://posterous.com/api/sup_update#2b4d5af58" type="application/json" rel="http://api.friendfeed.com/2008/03#sup" />
    
    
    <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/MusingsOfALispnik" /><feedburner:info uri="musingsofalispnik" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://posterous.superfeedr.com/" /><item>
      <pubDate>Thu, 08 Dec 2011 16:32:30 -0800</pubDate>
      <title>Combining virtual sequences</title>
      <link>http://feedproxy.google.com/~r/MusingsOfALispnik/~3/ABytEGOHDHo/combining-virtual-sequences</link>
      <guid isPermaLink="false">http://blog.danieljanus.pl/combining-virtual-sequences</guid>
      <description>&lt;p&gt;
	&lt;h2&gt;or, Sequential Fun with Macros&lt;/h2&gt;

&lt;h2&gt;or, How to Implement Clojure-Like Pseudo-Sequences with Poor Man&amp;rsquo;s Laziness in a Predominantly Imperative Language&lt;/h2&gt;

&lt;h3&gt;Sequences and iteration&lt;/h3&gt;

&lt;p&gt;There are a number of motivations for this post.  One stems from my
extensive exposure to Clojure over the past few years: this was, and
still is, my primary programming language for everyday work.  Soon, I
realized that much of the power of Clojure comes from a &lt;em&gt;sequence&lt;/em&gt;
abstraction being one of its central concepts, and a standard library
that contains many sequence-manipulating functions.  It turns out that
by combining them it is possible to solve a wide range of problems in
a concise, high-level way. In contrast, it pays to think in terms of
whole sequences, rather than individual elements.&lt;/p&gt;

&lt;p&gt;Another motivation comes from a classical piece of functional
programming humour, &lt;a href="http://www.willamette.edu/~fruehr/haskell/evolution.html"&gt;The Evolution of a Haskell Programmer&lt;/a&gt;. If you
don&amp;rsquo;t know it, go check it out: it consists of several Haskell
implementations of factorial, starting out from a straightforward
recursive definition, passing through absolutely hilarious versions
involving category-theoretical concepts, and finally arriving at this
simple version that is considered most idiomatic:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;fac n = product [1..n]&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;This is very Clojure-like in that it involves a sequence (a list
comprehension). In Clojure, this could be implemented as&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(&lt;span class="keyword"&gt;defn&lt;/span&gt; &lt;span class="function"&gt;fac&lt;/span&gt; [n]
  (&lt;span class="keyword"&gt;reduce&lt;/span&gt; &lt;span class="keyword"&gt;*&lt;/span&gt; &lt;span class="integer"&gt;1&lt;/span&gt; (&lt;span class="keyword"&gt;range&lt;/span&gt; &lt;span class="integer"&gt;1&lt;/span&gt; (&lt;span class="keyword"&gt;inc&lt;/span&gt; n))))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Now, I thought to myself, how would I write factorial in an imperative
language? Say, Pascal?&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="keyword"&gt;function&lt;/span&gt; fac(n : integer) : integer;
&lt;span class="keyword"&gt;var&lt;/span&gt;
  i, res : integer;
&lt;span class="keyword"&gt;begin&lt;/span&gt;
  res := &lt;span class="integer"&gt;1&lt;/span&gt;;
  &lt;span class="keyword"&gt;for&lt;/span&gt; i := &lt;span class="integer"&gt;1&lt;/span&gt; &lt;span class="keyword"&gt;to&lt;/span&gt; n &lt;span class="keyword"&gt;do&lt;/span&gt;
    res := res * i;
  fac := res;
&lt;span class="keyword"&gt;end&lt;/span&gt;;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;This is very different from the functional version that works with
sequences.  It is much more elaborate, introducing an explicit loop.
On the other hand, it&amp;rsquo;s memory efficient: it&amp;rsquo;s clear that its memory
requirements are O(1), whereas a naïve implementation of a sequence
would need O(n) to construct it all in memory and then reduce it down
to a single value.&lt;/p&gt;

&lt;p&gt;Or is it really that different? Think of the changing values of &lt;code&gt;i&lt;/code&gt; in
that loop. On first iteration it is 1, on second iteration it&amp;rsquo;s 2, and
so on up to n. Therefore, one can really think of a &lt;code&gt;for&lt;/code&gt; loop as a
sequence! I call it a &amp;ldquo;virtual&amp;rdquo; sequence, since it is not an actual
data structure; it&amp;rsquo;s just a snippet of code.&lt;/p&gt;

&lt;p&gt;To rephrase it as a definition: a virtual sequence is a snippet of
code that (presumably repeatedly) &lt;em&gt;yields&lt;/em&gt; the member values.&lt;/p&gt;

&lt;h3&gt;Let&amp;rsquo;s write some code!&lt;/h3&gt;

&lt;p&gt;To illustrate it, throughout the remainder of this article I will be
using Common Lisp, for the following reasons:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It allows for imperative style, including GOTO-like statements.
This will enable us to generate very low-level code.&lt;/li&gt;
&lt;li&gt;Thanks to macros, we will be able to obtain interesting
transformations.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;Okay, so let&amp;rsquo;s have a look at how to generate a one-element
sequence. Simple enough:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(defmacro vsingle (x)
 `(yield ,x))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;The name &lt;code&gt;VSINGLE&lt;/code&gt; stands for &amp;ldquo;Virtual sequence that just yields a
SINGLE element&amp;rdquo;. (In general, I will try to define virtual sequences
named and performing similarly to their Clojure counterparts here;
whenever there is a name clash with an already existing CL function,
the name will be prefixed with &lt;code&gt;V&lt;/code&gt;.)  We will not concern ourselves
with the actual definition of &lt;code&gt;YIELD&lt;/code&gt; at the moment; for debugging, we
can define it just as printing the value to the standard output.&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(defun yield (x)
  (format t &amp;quot;~A~%&amp;quot; x))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;We can also convert a Lisp list to a virtual sequence which just
yields each element of the list in turn:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(defmacro vseq (list)
  `(loop for x in ,list do (yield x)))

(defmacro vlist (&amp;amp;rest elems)
  `(vseq (list ,@elems)))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Now let&amp;rsquo;s try to define &lt;code&gt;RANGE&lt;/code&gt;. We could use &lt;code&gt;loop&lt;/code&gt;, but for the sake
of example, let&amp;rsquo;s pretend that it doesn&amp;rsquo;t exist and write a macro that
expands to low-level GOTO-ridden code. For those of you who are not
familiar with Common Lisp, &lt;code&gt;GO&lt;/code&gt; is like GOTO, except it takes a label
that should be established within a &lt;code&gt;TAGBODY&lt;/code&gt; container.&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(defmacro range (start &amp;amp;optional end (step 1))
  (unless end
    (setf end start start 0))
  (let ((fv (gensym)))
    `(let ((,fv ,start))
       (tagbody
        loop
          (when (&amp;gt;= ,fv ,end)
            (go out))
          (yield ,fv)
          (incf ,fv ,step)
          (go loop)
       out))))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;&lt;em&gt;Infinite&lt;/em&gt; virtual sequences are also possible. After all, there&amp;rsquo;s
nothing preventing us from considering a snippet of code that loops
infinitely, executing &lt;code&gt;YIELD&lt;/code&gt;, as a virtual sequence!  We will define
the equivalent of Clojure&amp;rsquo;s &lt;code&gt;iterate&lt;/code&gt;: given a function &lt;code&gt;fun&lt;/code&gt; and
initial value &lt;code&gt;val&lt;/code&gt;, it will repeatedly generate &lt;code&gt;val&lt;/code&gt;, &lt;code&gt;(fun val)&lt;/code&gt;,
&lt;code&gt;(fun (fun val))&lt;/code&gt;, etc.&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(defmacro iterate (fun val)
  (let ((fv (gensym)))
    `(let ((,fv ,val))
       (tagbody loop
          (yield ,fv)
          (setf ,fv (funcall ,fun ,fv))
          (go loop)))))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;So far, we have defined a number of ways to create virtual sequences.
Now let&amp;rsquo;s ask ourselves: is there a way, given code for a virtual
sequence, to yield only the elements from the original that satisfy a
certain predicate? In other words, can we define a &lt;code&gt;filter&lt;/code&gt; for
virtual sequences? Sure enough. Just replace every occurrence of
&lt;code&gt;yield&lt;/code&gt; with code that checks whether the yielded value satisfies the
predicate, and only if it does invokes &lt;code&gt;yield&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;First we write a simple code walker that applies some
transformation to every &lt;code&gt;yield&lt;/code&gt; occurrence in a given snippet:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(defun replace-yield (tree replace)
  (if (consp tree)
      (if (eql (car tree) 'yield)
          (funcall replace (cadr tree))
          (loop for x in tree collect (replace-yield x replace)))
      tree))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;We can now write &lt;code&gt;filter&lt;/code&gt; like this:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(defmacro filter (pred vseq &amp;amp;environment env)
  (replace-yield (macroexpand vseq env)
                 (lambda (x) `(when (funcall ,pred ,x) (yield ,x)))))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;It is important to point out that since &lt;code&gt;filter&lt;/code&gt; is a macro, the
arguments are passed to it unevaluated, so if &lt;code&gt;vseq&lt;/code&gt; is a virtual
sequence definition like &lt;code&gt;(range 10)&lt;/code&gt;, we need to macroexpand it
before replacing &lt;code&gt;yield&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We can now verify that &lt;code&gt;(filter #'evenp (range 10))&lt;/code&gt; works. It
macroexpands to something similar to&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(LET ((#:G70192 0))
  (TAGBODY
    LOOP (IF (&amp;gt;= #:G70192 10)
           (PROGN (GO OUT)))
         (IF (FUNCALL #'EVENP #:G70192)
           (PROGN (YIELD #:G70192)))
         (SETQ #:G70192 (+ #:G70192 1))
         (GO LOOP)
    OUT))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;&lt;code&gt;concat&lt;/code&gt; is extremely simple. To produce all elements of &lt;code&gt;vseq1&lt;/code&gt;
followed by all elements of &lt;code&gt;vseq2&lt;/code&gt;, just execute code corresponding
to &lt;code&gt;vseq1&lt;/code&gt; and then code corresponding to &lt;code&gt;vseq2&lt;/code&gt;. Or, for multiple
sequences:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(defmacro concat (&amp;amp;rest vseqs)
  `(progn ,@vseqs))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;To define &lt;code&gt;take&lt;/code&gt;, we&amp;rsquo;ll need to wrap the original code in a block
that can be escaped from by means of &lt;code&gt;return-from&lt;/code&gt; (which is just
another form of &lt;code&gt;goto&lt;/code&gt;). We&amp;rsquo;ll add a counter that will start from
&lt;code&gt;n&lt;/code&gt; and keep decreasing on each &lt;code&gt;yield&lt;/code&gt;; once it reaches zero, we
escape the block:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(defmacro take (n vseq &amp;amp;environment env)
  (let ((x (gensym))
        (b (gensym)))
    `(let ((,x ,n))
       (block ,b
         ,(replace-yield (macroexpand vseq env)
                         (lambda (y) `(progn (yield ,y)
                                             (decf ,x)
                                             (when (zerop ,x)
                                               (return-from ,b)))))))))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;&lt;code&gt;rest&lt;/code&gt; (or, rather, &lt;code&gt;vrest&lt;/code&gt;, as that name is taken) can be defined
similarly:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(defmacro vrest (vseq &amp;amp;environment env)
  (let ((skipped (gensym)))
    (replace-yield
     `(let ((,skipped nil)) ,(macroexpand vseq env))
     (lambda (x) `(if ,skipped (yield ,x) (setf ,skipped t))))))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;&lt;code&gt;vfirst&lt;/code&gt; is another matter. It should return a value instead of
producing a virtual sequence, so we need to actually execute the code
&amp;mdash; but with &lt;code&gt;yield&lt;/code&gt; bound to something else. We want to establish a
block as with &lt;code&gt;take&lt;/code&gt;, but our &lt;code&gt;yield&lt;/code&gt; will immediately return from the
block once the first value is yielded:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(defmacro vfirst (vseq)
  (let ((block-name (gensym)))
   `(block ,block-name
      (flet ((yield (x) (return-from ,block-name x)))
        ,vseq))))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Note that so far we&amp;rsquo;ve seen three classes of macros:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;macros that create virtual sequences;&lt;/li&gt;
&lt;li&gt;macros that transform virtual sequences to another virtual
sequences;&lt;/li&gt;
&lt;li&gt;and finally, &lt;code&gt;vfirst&lt;/code&gt; is our first example of a macro that
produces a result out of a virtual sequence.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;Our next logical step is &lt;code&gt;vreduce&lt;/code&gt;. Again, we&amp;rsquo;ll produce code
that rebinds &lt;code&gt;yield&lt;/code&gt;: this time to a function that replaces
the value of a variable (the accumulator) by result of calling
a function on the accumulator&amp;rsquo;s old value and the value being yielded.&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(defmacro vreduce (f val vseq)
  `(let ((accu ,val))
     (flet ((yield (x) (setf accu (funcall ,f accu x))))
       ,vseq
       accu)))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;We can now build a constructs that executes a virtual sequence and
wraps the results up as a Lisp list, in terms of &lt;code&gt;vreduce&lt;/code&gt;.&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(defun conj (x y)
  (cons y x))

(defmacro realize (vseq)
 `(nreverse (vreduce #'conj nil ,vseq)))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Let&amp;rsquo;s verify that it works:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;CL-USER&amp;gt; (realize (range 10))
(0 1 2 3 4 5 6 7 8 9)

CL-USER&amp;gt; (realize (take 5 (filter #'oddp (iterate #'1+ 0))))
(1 3 5 7 9)&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Hey! Did we just manipulate an &lt;em&gt;infinite&lt;/em&gt; sequence and got the result
in a &lt;em&gt;finite&lt;/em&gt; amount of time? And that without explicit support for
laziness in our language? How cool is that?!&lt;/p&gt;

&lt;p&gt;Anyway, let&amp;rsquo;s finally define our factorial:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(defun fac (n)
   (vreduce #'* 1 (range 1 (1+ n))))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;h3&gt;Benchmarking&lt;/h3&gt;

&lt;p&gt;Factorials grow too fast, so for the purpose of benchmarking let&amp;rsquo;s
write a function that adds numbers from 0 below n, in sequence-y
style. First using Common Lisp builtins:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(defun sum-below (n)
  (reduce #'+ (loop for i from 0 below n collect i) :initial-value 0))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;And now with our virtual sequences:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;(defun sum-below-2 (n)
  (vreduce #'+ 0 (range n)))&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Let&amp;rsquo;s try to time the two versions. On my Mac running Clozure CL 1.7,
this gives:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;CL-USER&amp;gt; (time (sum-below 10000000))
 (SUM-BELOW 10000000) took 8,545,512 microseconds (8.545512 seconds) to run
                     with 2 available CPU cores.
 During that period, 2,367,207 microseconds (2.367207 seconds) were spent in user mode
                     270,481 microseconds (0.270481 seconds) were spent in system mode
 5,906,274 microseconds (5.906274 seconds) was spent in GC.
  160,000,016 bytes of memory allocated.
  39,479 minor page faults, 1,359 major page faults, 0 swaps.
 49999995000000

 CL-USER&amp;gt; (time (sum-below-2 10000000))
 (SUM-BELOW-2 10000000) took 123,081 microseconds (0.123081 seconds) to run
                     with 2 available CPU cores.
 During that period, 127,632 microseconds (0.127632 seconds) were spent in user mode
                     666 microseconds (0.000666 seconds) were spent in system mode
  4 minor page faults, 0 major page faults, 0 swaps.
 49999995000000&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;As expected, &lt;code&gt;SUM-BELOW-2&lt;/code&gt; is much faster, causes less page faults and
presumably conses less.  (Critics will be quick to point out that we
could idiomatically write it using &lt;code&gt;LOOP&lt;/code&gt;&amp;rsquo;s &lt;code&gt;SUM/SUMMING&lt;/code&gt; clause,
which would probably be yet faster, and I agree; yet if we were
reducing by something other than &lt;code&gt;+&lt;/code&gt; &amp;mdash; something that &lt;code&gt;LOOP&lt;/code&gt; has not
built in as a clause &amp;mdash; this would not be an option.)&lt;/p&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;We have seen how snippets of code can be viewed as sequences and how
to combine them to produce other virtual sequences. As we are nearing
the end of this article, it is perhaps fitting to ask: what are the
limitations and drawbacks of this approach?&lt;/p&gt;

&lt;p&gt;Clearly, this kind of sequences is less powerful than &amp;ldquo;ordinary&amp;rdquo;
sequences such as Clojure&amp;rsquo;s. The fact that we&amp;rsquo;ve built them on macros
means that once we escape the world of code transformation by invoking
some macro of the third class, we can&amp;rsquo;t manipulate them anymore. In
Clojure world, &lt;code&gt;first&lt;/code&gt; and &lt;code&gt;rest&lt;/code&gt; are very similar; in virtual
sequences, they are altogether different: they belong to different
world. The same goes for &lt;code&gt;map&lt;/code&gt; (had we defined one) and &lt;code&gt;reduce&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;But imagine that instead of having just one programming language, we
have a high-level language A in which we are writing macros that
expand to code in a low-level language B. It is important to point out
that the generated code is very low-level. It could almost be
assembly: in fact, most of the macros we&amp;rsquo;ve written don&amp;rsquo;t even require
language B to have composite data-types beyond the type of elements of
collections (which could be simple integers)!&lt;/p&gt;

&lt;p&gt;Is there a practical side to this? I don&amp;rsquo;t know: to me it just seems
to be something with hack value. Time will tell if I can put it to
good use.&lt;/p&gt;
	
&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.danieljanus.pl/combining-virtual-sequences"&gt;Permalink&lt;/a&gt; 

	| &lt;a href="http://blog.danieljanus.pl/combining-virtual-sequences#comment"&gt;Leave a comment&amp;nbsp;&amp;nbsp;&amp;raquo;&lt;/a&gt;

&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MusingsOfALispnik/~4/ABytEGOHDHo" height="1" width="1"/&gt;</description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/1334473/nat-face-square.jpeg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/YXpC5IC5SCt</posterous:profileUrl>
        <posterous:firstName>Daniel</posterous:firstName>
        <posterous:lastName>Janus</posterous:lastName>
        <posterous:nickName>danieljanus</posterous:nickName>
        <posterous:displayName>Daniel Janus</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.danieljanus.pl/combining-virtual-sequences</feedburner:origLink></item>
    <item>
      <pubDate>Sun, 10 Jul 2011 16:07:00 -0700</pubDate>
      <title>Color your own Europe with Clojure!</title>
      <link>http://feedproxy.google.com/~r/MusingsOfALispnik/~3/3N_3CqU6k-Q/color-your-own-europe-with-clojure</link>
      <guid isPermaLink="false">http://blog.danieljanus.pl/color-your-own-europe-with-clojure</guid>
      <description>&lt;p&gt;
	&lt;p&gt;This is a slightly edited translation of &lt;a href="http://plblog.danieljanus.pl/pokoloruj-sobie-europe"&gt;an article&lt;/a&gt; I first published
on my Polish blog on January 19, 2011. It is meant to target newcomers to Clojure
and show how to use Clojure to solve a simple real-life problems.&lt;/p&gt;

&lt;h2&gt;The problem&lt;/h2&gt;

&lt;p&gt;Some time ago I was asked to prepare a couple of differently-colored
maps of Europe. I got some datasets which mapped countries of Europe
to numerical values: the greater the value, the darker the corresponding
color should be. A sample colored map looked like this:&lt;/p&gt;

&lt;p&gt;&lt;img src="http://danieljanus.pl/slides/2010/wjug-clojure/m2.png" alt="A color map of Europe" /&gt;&lt;/p&gt;

&lt;p&gt;I began by downloading an easily editable &lt;a href="http://commons.wikimedia.org/wiki/File:Blank_map_of_Europe.svg"&gt;map&lt;/a&gt; from Wikipedia Commons,
calculated the required color intensities for the first dataset, launched
&lt;a href="http://www.inkscape.org"&gt;Inkscape&lt;/a&gt; and started coloring. After half an hour of tedious clicking,
I realized that I would be better off writing a simple program in Clojure
that would generate the map for me. It turned out to be an easy task: the
remainder of this article will be an attempt to reconstruct my steps.&lt;/p&gt;

&lt;h2&gt;SVG&lt;/h2&gt;

&lt;p&gt;The format of the source image is SVG. I knew it was an XML-based vector
graphics format, I&amp;rsquo;d often encountered images in this format on Wikipedia &amp;mdash;
but editing it by hand was new to me. Luckily, it turned out that the
image has a simple structure. Each country&amp;rsquo;s envelope curve is described
with a &lt;code&gt;path&lt;/code&gt; element that looks like this:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="ta"&gt;&amp;lt;path&lt;/span&gt;
   &lt;span class="an"&gt;id&lt;/span&gt;=&lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;pl&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;
   &lt;span class="an"&gt;class&lt;/span&gt;=&lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;eu europe&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;
   &lt;span class="an"&gt;d&lt;/span&gt;=&lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;a long list of curve node coordinates&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt; &lt;span class="ta"&gt;/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;An important thing to note here is the &lt;code&gt;id&lt;/code&gt; attribute &amp;mdash; this is the two-letter
ISO-3166-1-ALPHA2 country code. In fact, there is an informative comment
right at the beginning of the image that explains the naming conventions
used. Having such a splendid input was of great help.&lt;/p&gt;

&lt;p&gt;Just like HTML, SVG &lt;a href="http://www.w3.org/TR/SVG/styling.html"&gt;uses CSS stylesheets&lt;/a&gt; to define the look of an
element. All that is needed to color Poland red is to style the element
with a &lt;code&gt;fill&lt;/code&gt; attribute:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="ta"&gt;&amp;lt;path&lt;/span&gt;
   &lt;span class="an"&gt;id&lt;/span&gt;=&lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;pl&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;
   &lt;span class="an"&gt;style&lt;/span&gt;=&lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;fill: #ff0000;&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;
   &lt;span class="an"&gt;class&lt;/span&gt;=&lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;eu europe&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;
   &lt;span class="an"&gt;d&lt;/span&gt;=&lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;a long list of curve node coordinates&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt; &lt;span class="ta"&gt;/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Now that we know all this, let&amp;rsquo;s start coding!&lt;/p&gt;

&lt;h2&gt;XML in Clojure&lt;/h2&gt;

&lt;p&gt;The basic way to handle XML in Clojure is to use the &lt;code&gt;clojure.xml&lt;/code&gt;
namespace, which contains functions that parse XML (on a DOM basis,
i.e., into an in-memory tree structure) and serialize such
structures back into XML. Let us launch a REPL and start by
reading our map and parsing it:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;use&lt;/span&gt; &lt;span class="of"&gt;'&lt;/span&gt;clojure.xml&lt;span class="of"&gt;)&lt;/span&gt;
nil
&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;def&lt;/span&gt; m &lt;span class="of"&gt;(&lt;/span&gt;parse &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;/home/nathell/eur/Blank_map_of_Europe.svg&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
&lt;span class="of"&gt;[&lt;/span&gt;&lt;span class="r"&gt;..&lt;/span&gt;&lt;span class="r"&gt;.&lt;/span&gt;a &lt;span class="r"&gt;long&lt;/span&gt; while.&lt;span class="r"&gt;..&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt;
Unexpected end of file from server
  &lt;span class="of"&gt;[&lt;/span&gt;Thrown &lt;span class="r"&gt;class&lt;/span&gt; java.net.SocketException&lt;span class="of"&gt;]&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Hold on in there! What&amp;rsquo;s that &lt;code&gt;SocketException&lt;/code&gt; doing here? Firefox
displays this map properly, so does Chrome, WTF?! Shouldn&amp;rsquo;t everything
work fine in such a great language as Clojure?&lt;/p&gt;

&lt;p&gt;Well, the language is as good as its libraries &amp;mdash; and when it comes
to Clojure, one can stretch that thought further: Clojure libraries
are as good as the Java libraries they use under the hood. In this
case, we&amp;rsquo;ve encountered a feature of the standard Java XML parser
(from &lt;code&gt;javax.xml&lt;/code&gt; package). It is restrictive and tries to reject
invalid documents (even if they are well-formed). If the file
being parsed contains a &lt;code&gt;DOCTYPE&lt;/code&gt; declaration, the Java parser, and hence
&lt;code&gt;clojure.xml/parse&lt;/code&gt;, tries to download the DTD schema from the given
address and validate the document against that schema. This is unfortunate
in many aspects, especially from the point of view of the &lt;a href="http://www.w3.org"&gt;World Wide
Web Consortium&lt;/a&gt;, since their servers hold the Web standards. One
can easily imagine the volume of network traffic this generates:
W3C has a &lt;a href="http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic/"&gt;blog post&lt;/a&gt; about it. Many Java programmers have encountered
this problem at some time. There are a few solutions; we will go
the simplest way and just manually remove the offending &lt;code&gt;DOCTYPE&lt;/code&gt; declaration.&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;def&lt;/span&gt; m &lt;span class="of"&gt;(&lt;/span&gt;parse &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;/home/nathell/eur/bm.svg&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
&lt;span class="er"&gt;#&lt;/span&gt;&lt;span class="of"&gt;'&lt;/span&gt;user/m
&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; m
&lt;span class="of"&gt;[&lt;/span&gt;&lt;span class="r"&gt;..&lt;/span&gt;&lt;span class="r"&gt;.&lt;/span&gt;many screenfuls of numbers.&lt;span class="r"&gt;..&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;This time we managed to parse the image. Viewing the structure is
not easy because of its sheer size (as expected: the file weighs in
at over 0,5 MB!), but from the very first characters of the REPL&amp;rsquo;s
output we can make out that&amp;rsquo;s it a Clojure map (no pun intended).
Let&amp;rsquo;s examine its keys:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;keys&lt;/span&gt; m&lt;span class="of"&gt;)&lt;/span&gt;
&lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:tag&lt;/span&gt; &lt;span class="sy"&gt;:attrs&lt;/span&gt; &lt;span class="sy"&gt;:content&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;So the map contains three entries with descriptive names.
&lt;code&gt;:tag&lt;/code&gt; contains the name of the XML elements, &lt;code&gt;:attrs&lt;/code&gt; is
a map of attributes for this element, and &lt;code&gt;content&lt;/code&gt; is
a vector of its subelements, each in turn being represented
by similarly structured map (or a string if it&amp;rsquo;s a text node):&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:tag&lt;/span&gt; m&lt;span class="of"&gt;)&lt;/span&gt;
&lt;span class="sy"&gt;:svg&lt;/span&gt;
&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:attrs&lt;/span&gt; m&lt;span class="of"&gt;)&lt;/span&gt;
&lt;span class="of"&gt;{&lt;/span&gt;&lt;span class="sy"&gt;:xmlns&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;http://www.w3.org/2000/svg&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;, &lt;span class="sy"&gt;:width&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;680&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;, &lt;span class="sy"&gt;:height&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;520&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;, &lt;span class="sy"&gt;:viewBox&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;1754 161 9938 7945&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;, &lt;span class="sy"&gt;:version&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;1.0&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;, &lt;span class="sy"&gt;:id&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;svg2&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;&lt;span class="of"&gt;}&lt;/span&gt;
&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;count&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:content&lt;/span&gt; m&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
&lt;span class="i"&gt;68&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Just for the sake of practice, let&amp;rsquo;s try to write the serialized
representation of the parsed back as XML. The function &lt;code&gt;emit&lt;/code&gt; should
be able to do it, but it prints XML to standard output. We can use
the &lt;code&gt;with-out-writer&lt;/code&gt; macro from the namespace &lt;code&gt;clojure.contrib.io&lt;/code&gt;
to dump the XML to a file:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;use&lt;/span&gt; &lt;span class="of"&gt;'&lt;/span&gt;clojure.contrib.io&lt;span class="of"&gt;)&lt;/span&gt;
nil
&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;with-out-writer &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;/tmp/a.svg&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;emit m&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
nil&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;We try to view &lt;code&gt;a.svg&lt;/code&gt; in Firefox and&amp;hellip;&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;Error parsing XML: not well-formed
Area: file:///tmp/a.xml
Row 15, column 44: Updated to reflect dissolution of Serbia &amp;amp; Montenegro: http://commons.wikimedia.org/wiki/User:Zirland
-------------------------------------------^&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;It turns out that using &lt;code&gt;clojure.xml/emit&lt;/code&gt; is not recommended, because
it does not handle XML entities in comments correctly; we should
use &lt;code&gt;clojure.contrib.lazy-xml&lt;/code&gt; instead. For the sake of example, though,
let&amp;rsquo;s stay with &lt;code&gt;emit&lt;/code&gt; and manually remove the offending line once
again (we can safely do it, since that&amp;rsquo;s just a comment).&lt;/p&gt;

&lt;h2&gt;Coloring Poland&lt;/h2&gt;

&lt;p&gt;We saw earlier that our main XML node contains 68 subnodes. Let&amp;rsquo;s see
what they are &amp;mdash; tag names will suffice:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;map&lt;/span&gt; &lt;span class="sy"&gt;:tag&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:content&lt;/span&gt; m&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt; 
&lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:title&lt;/span&gt; &lt;span class="sy"&gt;:desc&lt;/span&gt; &lt;span class="sy"&gt;:defs&lt;/span&gt; &lt;span class="sy"&gt;:rect&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:g&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:g&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;So far, so good. Seems that all country descriptions are contained directly
in the main node. Let us try to find Poland:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;count&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;filter&lt;/span&gt; &lt;span class="of"&gt;#(&lt;/span&gt;&lt;span class="r"&gt;and&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="er"&gt;=&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:tag&lt;/span&gt; %&lt;span class="of"&gt;)&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt; 
                       &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="er"&gt;=&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:attrs&lt;/span&gt; %&lt;span class="of"&gt;)&lt;/span&gt; &lt;span class="sy"&gt;:id&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;pl&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt; 
                 &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:content&lt;/span&gt; m&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
&lt;span class="i"&gt;1&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;(This snippet of code filters the list of subnodes of &lt;code&gt;m&lt;/code&gt; to pick only
those elements whose tag name is &lt;code&gt;path&lt;/code&gt; and value of attribute &lt;code&gt;id&lt;/code&gt; is
&lt;code&gt;pl&lt;/code&gt;, and returns the length of such list.)  Let&amp;rsquo;s try to add a &lt;code&gt;style&lt;/code&gt;
attribute to that element, according to what we said earlier. Because
Clojure data structures are immutable, we have to define a new top-level
element which will be the same as &lt;code&gt;m&lt;/code&gt;, except that we will set the style
of the appropriate subnode:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;def&lt;/span&gt; m2 &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;assoc&lt;/span&gt; m
                &lt;span class="sy"&gt;:content&lt;/span&gt;
                &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;map&lt;/span&gt; &lt;span class="of"&gt;#(&lt;/span&gt;&lt;span class="r"&gt;if&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;and&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="er"&gt;=&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:tag&lt;/span&gt; %&lt;span class="of"&gt;)&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
                               &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="er"&gt;=&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:attrs&lt;/span&gt; %&lt;span class="of"&gt;)&lt;/span&gt; &lt;span class="sy"&gt;:id&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;pl&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
                        &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;assoc&lt;/span&gt; % &lt;span class="sy"&gt;:attrs&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;assoc&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:attrs&lt;/span&gt; %&lt;span class="of"&gt;)&lt;/span&gt; &lt;span class="sy"&gt;:style&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;fill: #ff0000;&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
                        %&lt;span class="of"&gt;)&lt;/span&gt;
                     &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:content&lt;/span&gt; m&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
&lt;span class="er"&gt;#&lt;/span&gt;&lt;span class="of"&gt;'&lt;/span&gt;user/m2
&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;with-out-writer &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;/tmp/a.svg&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;emit m2&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
nil&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;We open the created file and see a map with Poland colored red. Yay!&lt;/p&gt;

&lt;h2&gt;Generalization&lt;/h2&gt;

&lt;p&gt;We will generalize our code a bit. Let us write a function that
colors a single state, taking a &lt;code&gt;path&lt;/code&gt; element (subnode of &lt;code&gt;svg&lt;/code&gt;)
as an argument:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;defn&lt;/span&gt; color-state
  &lt;span class="of"&gt;[&lt;/span&gt;&lt;span class="of"&gt;{&lt;/span&gt;&lt;span class="sy"&gt;:keys&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;tag attrs&lt;span class="of"&gt;]&lt;/span&gt; &lt;span class="sy"&gt;:as&lt;/span&gt; element&lt;span class="of"&gt;}&lt;/span&gt; colorize-fn&lt;span class="of"&gt;]&lt;/span&gt;
  &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;let&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;state &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:id&lt;/span&gt; attrs&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt;
    &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;if-let&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;color &lt;span class="of"&gt;(&lt;/span&gt;colorize-fn state&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt;
      &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;assoc&lt;/span&gt; element &lt;span class="sy"&gt;:attrs&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;assoc&lt;/span&gt; attrs &lt;span class="sy"&gt;:style&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;str&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;fill:&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt; color&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
      element&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;This function is similar to the anonymous one we used above in the
&lt;code&gt;map&lt;/code&gt; call, but differs in some respects. It takes two arguments.
As mentioned, the first one is the XML element (destructured
into &lt;code&gt;tag&lt;/code&gt; and &lt;code&gt;attrs&lt;/code&gt;: you can read more about destructuring in
&lt;a href="http://clojure.org/special_forms"&gt;the appropriate part of Clojure docs&lt;/a&gt;), and the second argument
is&amp;hellip; a function that should take a two-letter country code and return
a HTML color description (or &lt;code&gt;nil&lt;/code&gt;, if that country&amp;rsquo;s color is not
specified &amp;mdash; &lt;code&gt;color-state&lt;/code&gt; will cope with this and return the element
unchanged).&lt;/p&gt;

&lt;p&gt;Now that we have &lt;code&gt;color-state&lt;/code&gt;, we can easily write a higher-level function
that processes and writes XML in one step:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;defn&lt;/span&gt; save-color-map
  &lt;span class="of"&gt;[&lt;/span&gt;svg colorize-fn outfile&lt;span class="of"&gt;]&lt;/span&gt;
  &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;let&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;colored-map &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;assoc&lt;/span&gt; svg &lt;span class="sy"&gt;:content&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;map&lt;/span&gt; &lt;span class="of"&gt;#(&lt;/span&gt;color-state % colorize-fn&lt;span class="of"&gt;)&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:content&lt;/span&gt; svg&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt;
    &lt;span class="of"&gt;(&lt;/span&gt;with-out-writer out
      &lt;span class="of"&gt;(&lt;/span&gt;emit colored-map&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Let&amp;rsquo;s test it:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;save-color-map m &lt;span class="of"&gt;{&lt;/span&gt;&lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;pl&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;#00ff00&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;&lt;span class="of"&gt;}&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;/tmp/a.svg&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
nil&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;This time Poland is green (we used a country→color map as an argument
to &lt;code&gt;color-state&lt;/code&gt;, since Clojure maps are callable like functions). Let&amp;rsquo;s try
to add blue Germany:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;save-color-map m &lt;span class="of"&gt;{&lt;/span&gt;&lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;pl&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;#00ff00&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;, &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;de&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;#0000ff&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;&lt;span class="of"&gt;}&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;/tmp/a.svg&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
nil&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;It works!&lt;/p&gt;

&lt;h2&gt;Problem with the UK&lt;/h2&gt;

&lt;p&gt;Inspired by our success, we try to color different countries.
It mostly works, but the United Kingdom remains gray, regardless
of whether we specify its code as &amp;ldquo;uk&amp;rdquo; or &amp;ldquo;gb&amp;rdquo;. We resort to the
source of our image, and the beginning comment once again proves
helpful:&lt;/p&gt;

&lt;blockquote class="posterous_medium_quote"&gt;&lt;p&gt;Certain countries are further subdivided the United Kingdom has
gb-gbn for Great Britain and gb-nir for Northern Ireland. Russia is
divided into ru-kgd for the Kaliningrad Oblast and ru-main for the
Main body of Russia. There is the additional grouping #xb for the
&amp;ldquo;British Islands&amp;rdquo; (the UK with its Crown Dependencies &amp;ndash;
Jersey, Guernsey and the Isle of Man)&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;Perhaps we have to specify &amp;ldquo;gb-gbn&amp;rdquo; and &amp;ldquo;gb-nir&amp;rdquo;, instead of just &amp;ldquo;gb&amp;rdquo;?
We try that, but still no luck. After a while of thought: oh yes! Our
initial assumption that &lt;em&gt;all&lt;/em&gt; the country definitions are &lt;code&gt;path&lt;/code&gt; subnodes
of the toplevel &lt;code&gt;svg&lt;/code&gt; node is false. We have to fix that.&lt;/p&gt;

&lt;p&gt;So far we have been doing a &amp;ldquo;flat&amp;rdquo; transform of the SVG tree: we
only changed the subnodes of the toplevel node, but no deeper.
We should change all the &lt;code&gt;path&lt;/code&gt; elements (and &lt;code&gt;g&lt;/code&gt;, if we want to
color groups of paths like the UK), regardless of how deep they
occur in the tree.&lt;/p&gt;

&lt;p&gt;We can use a &lt;a href="http://clojure.org/other_libraries"&gt;zipper&lt;/a&gt; to do a depth-first walk of the SVG tree.
Let us define a function that takes a zipper, a predicate that tells
whether to edit the node in question, and the transformation function
to apply to the node if the predicate returns &lt;code&gt;true&lt;/code&gt;:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;defn&lt;/span&gt; map-zipper &lt;span class="of"&gt;[&lt;/span&gt;f pred z&lt;span class="of"&gt;]&lt;/span&gt;
  &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;if&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;zip/end? z&lt;span class="of"&gt;)&lt;/span&gt;
    &lt;span class="of"&gt;(&lt;/span&gt;zip/root z&lt;span class="of"&gt;)&lt;/span&gt;
    &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;recur&lt;/span&gt; f pred &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;-&amp;gt;&lt;/span&gt; z &lt;span class="of"&gt;(&lt;/span&gt;zip/edit &lt;span class="of"&gt;#(&lt;/span&gt;&lt;span class="r"&gt;if&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;pred %&lt;span class="of"&gt;)&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;f %&lt;span class="of"&gt;)&lt;/span&gt; %&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt; zip/next&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Now we rewrite &lt;code&gt;save-color-map&lt;/code&gt; as:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;defn&lt;/span&gt; save-color-map
  &lt;span class="of"&gt;[&lt;/span&gt;svg colorize-fn outfile&lt;span class="of"&gt;]&lt;/span&gt;
  &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;let&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;colored-map &lt;span class="of"&gt;(&lt;/span&gt;map-zipper &lt;span class="of"&gt;#(&lt;/span&gt;color-state % colorize-fn&lt;span class="of"&gt;)&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;fn&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;x&lt;span class="of"&gt;]&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="er"&gt;#&lt;/span&gt;&lt;span class="of"&gt;{&lt;/span&gt;&lt;span class="sy"&gt;:g&lt;/span&gt; &lt;span class="sy"&gt;:path&lt;/span&gt;&lt;span class="of"&gt;}&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:tag&lt;/span&gt; x&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;zip/xml-zip svg&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt;
    &lt;span class="of"&gt;(&lt;/span&gt;with-out-writer out
      &lt;span class="of"&gt;(&lt;/span&gt;emit colored-map&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;This time the UK can be colored.&lt;/p&gt;

&lt;h2&gt;Colorizers&lt;/h2&gt;

&lt;p&gt;We have automated the process of styling countries to make them
appear in color, but translating particular numbers to RGB is tedious.
In the last part of this article we will see how to ease this:
we are going to write a &lt;em&gt;colorizer&lt;/em&gt;, i.e., a function suitable for
passing to &lt;code&gt;color-state&lt;/code&gt; and &lt;code&gt;save-color-map&lt;/code&gt; (so far we&amp;rsquo;ve been
using maps for this).&lt;/p&gt;

&lt;p&gt;Let&amp;rsquo;s start by writing a functions that translates a triplet of numbers
into a HTML RGB notation, because it will be easier for us to work
with integers than with strings:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;defn&lt;/span&gt; htmlize-color
  &lt;span class="of"&gt;[&lt;/span&gt;&lt;span class="of"&gt;[&lt;/span&gt;r g b&lt;span class="of"&gt;]&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt;
  &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;format&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;#%02x%02x%02x&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt; r g b&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Now we insert a call to &lt;code&gt;htmlize-color&lt;/code&gt; into the appropriate pace
in &lt;code&gt;color-state&lt;/code&gt;:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;defn&lt;/span&gt; color-state
  &lt;span class="of"&gt;[&lt;/span&gt;&lt;span class="of"&gt;{&lt;/span&gt;&lt;span class="sy"&gt;:keys&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;tag attrs&lt;span class="of"&gt;]&lt;/span&gt; &lt;span class="sy"&gt;:as&lt;/span&gt; element&lt;span class="of"&gt;}&lt;/span&gt; colorize-fn&lt;span class="of"&gt;]&lt;/span&gt;
  &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;let&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;state &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="sy"&gt;:id&lt;/span&gt; attrs&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt;
    &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;if-let&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;color &lt;span class="of"&gt;(&lt;/span&gt;colorize-fn state&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt;
      &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;assoc&lt;/span&gt; element &lt;span class="sy"&gt;:attrs&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;assoc&lt;/span&gt; attrs &lt;span class="sy"&gt;:style&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;str&lt;/span&gt; &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;fill:&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;htmlize-color color&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
      element&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Now imagine we have a table with numeric values for states, like this:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;State       Value
------------------
Poland       20
Germany      15
Netherlands  30&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;We want to have a function that assigns colors to states, such that
the intensity of a color should be proportional to the value assigned
to a given state. To be more general, assume we have two colors,
c1 and c2, and for a given state, for each of the R, G, B components
we assign a value proportional to the difference between the state&amp;rsquo;s value
and the smallest value in the dataset, normalized to lie between c1 and c2.&lt;/p&gt;

&lt;p&gt;This sounds complex, but I hope an example will clear things up.
This is the Clojure implementation of the described algorithm:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;defn&lt;/span&gt; make-colorizer
  &lt;span class="of"&gt;[&lt;/span&gt;dataset ranges&lt;span class="of"&gt;]&lt;/span&gt;
  &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;let&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;minv &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;apply&lt;/span&gt; &lt;span class="r"&gt;min&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;vals&lt;/span&gt; dataset&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
        maxv &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;apply&lt;/span&gt; &lt;span class="r"&gt;max&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;vals&lt;/span&gt; dataset&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
        progress &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;map&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;fn&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;&lt;span class="of"&gt;[&lt;/span&gt;min-col max-col&lt;span class="of"&gt;]&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="er"&gt;/&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;-&lt;/span&gt; max-col min-col&lt;span class="of"&gt;)&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;-&lt;/span&gt; maxv minv&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt; ranges&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt;
    &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;into&lt;/span&gt; &lt;span class="of"&gt;{&lt;/span&gt;&lt;span class="of"&gt;}&lt;/span&gt;
          &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;map&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;fn&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;&lt;span class="of"&gt;[&lt;/span&gt;k v&lt;span class="of"&gt;]&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;&lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;.&lt;/span&gt;toLowerCase k&lt;span class="of"&gt;)&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;map&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;fn&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;progress &lt;span class="of"&gt;[&lt;/span&gt;min-color _&lt;span class="of"&gt;]&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;int&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;+&lt;/span&gt; min-color &lt;span class="of"&gt;(&lt;/span&gt;* &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="r"&gt;-&lt;/span&gt; v minv&lt;span class="of"&gt;)&lt;/span&gt; progress&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt; progress ranges&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;
               dataset&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Let us see how it works on our sample data:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="r"&gt;&amp;gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;make-colorizer &lt;span class="of"&gt;{&lt;/span&gt;&lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;pl&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt; &lt;span class="i"&gt;20&lt;/span&gt;, &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;de&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt; &lt;span class="i"&gt;15&lt;/span&gt;, &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;nl&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt; &lt;span class="i"&gt;30&lt;/span&gt;&lt;span class="of"&gt;}&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;&lt;span class="of"&gt;[&lt;/span&gt;&lt;span class="i"&gt;0&lt;/span&gt; &lt;span class="i"&gt;255&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;&lt;span class="i"&gt;0&lt;/span&gt; &lt;span class="i"&gt;0&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt; &lt;span class="of"&gt;[&lt;/span&gt;&lt;span class="i"&gt;0&lt;/span&gt; &lt;span class="i"&gt;0&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt;&lt;span class="of"&gt;]&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt; 
&lt;span class="of"&gt;{&lt;/span&gt;&lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;pl&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="i"&gt;85&lt;/span&gt; &lt;span class="i"&gt;0&lt;/span&gt; &lt;span class="i"&gt;0&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;, &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;de&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="i"&gt;0&lt;/span&gt; &lt;span class="i"&gt;0&lt;/span&gt; &lt;span class="i"&gt;0&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;, &lt;span class="s"&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;span class="k"&gt;nl&lt;/span&gt;&lt;span class="dl"&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt; &lt;span class="of"&gt;(&lt;/span&gt;&lt;span class="i"&gt;255&lt;/span&gt; &lt;span class="i"&gt;0&lt;/span&gt; &lt;span class="i"&gt;0&lt;/span&gt;&lt;span class="of"&gt;)&lt;/span&gt;&lt;span class="of"&gt;}&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;The second argument means that the red component is to range between
0 and 255, and the green and blue components are to be fixed at 0.&lt;/p&gt;

&lt;p&gt;Like we wanted, Germany ends up darkest (because it has the least value),
the Netherlands is lightest (because it has the greatest value), and Poland&amp;rsquo;s
intensity is one third that of the Netherlands (because 20 is in one third of
the way between 15 and 30).&lt;/p&gt;

&lt;h2&gt;Wrapping up&lt;/h2&gt;

&lt;p&gt;The application we created can be further developed in many ways.
One can, for instance, add a Web interface for it, or write
many different colorizers (e.g., discrete colorizer: fixed colours
for ranges of input values, or a temperature colorizer transitioning
smoothly from blue through white to red &amp;mdash; to do this we would have to
pass through the HSV color space).&lt;/p&gt;

&lt;p&gt;What is your idea to improve on it? For those of you who are tired
of pasting snippets of code into the REPL, I&amp;rsquo;m putting the complete
source code with a Leiningen project on &lt;a href="https://github.com/nathell/color-europe"&gt;GitHub&lt;/a&gt;. Forks are
welcome.&lt;/p&gt;
	
&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.danieljanus.pl/color-your-own-europe-with-clojure"&gt;Permalink&lt;/a&gt; 

	| &lt;a href="http://blog.danieljanus.pl/color-your-own-europe-with-clojure#comment"&gt;Leave a comment&amp;nbsp;&amp;nbsp;&amp;raquo;&lt;/a&gt;

&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MusingsOfALispnik/~4/3N_3CqU6k-Q" height="1" width="1"/&gt;</description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/1334473/nat-face-square.jpeg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/YXpC5IC5SCt</posterous:profileUrl>
        <posterous:firstName>Daniel</posterous:firstName>
        <posterous:lastName>Janus</posterous:lastName>
        <posterous:nickName>danieljanus</posterous:nickName>
        <posterous:displayName>Daniel Janus</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.danieljanus.pl/color-your-own-europe-with-clojure</feedburner:origLink></item>
    <item>
      <pubDate>Fri, 08 Jul 2011 12:39:44 -0700</pubDate>
      <title>Meet my little friend createTree</title>
      <link>http://feedproxy.google.com/~r/MusingsOfALispnik/~3/0Pw8__X8rw0/meet-my-little-friend-createtree</link>
      <guid isPermaLink="false">http://blog.danieljanus.pl/meet-my-little-friend-createtree</guid>
      <description>&lt;p&gt;
	&lt;p&gt;I&amp;rsquo;ve recently been developing an iPhone application in my spare time.
I&amp;rsquo;m not going to tell you what it is just yet (I will post a separate
entry once I manage to get it into the App Store); for now, let me just
say that I&amp;rsquo;m writing it in JavaScript and HTML5, using &lt;a href="http://www.phonegap.com/"&gt;PhoneGap&lt;/a&gt; and
&lt;a href="http://jqtouch.com/"&gt;jQTouch&lt;/a&gt; to give it a native touch.&lt;/p&gt;

&lt;p&gt;After having written some of code, I began testing it on a real device
and encountered a nasty issue. It turned out that some of the screens of
my app, containing a dynamically-generated content, sometimes would not
show up. I tried to chase the problem down, but it seemed totally
random. Finally, I googled up &lt;a href="http://martinkou.blogspot.com/2011/05/alternative-workaround-for-mobile.html"&gt;this blog post&lt;/a&gt; that gave me a clue.&lt;/p&gt;

&lt;p&gt;My code was using jQuery&amp;rsquo;s &lt;code&gt;.html()&lt;/code&gt; method (and hence &lt;code&gt;innerHTML&lt;/code&gt; under
the hood) to display the dynamic content. It turns out that, on Mobile
Safari, using &lt;code&gt;innerHTML&lt;/code&gt; is highly unreliable (at least on iOS 4.3, but
this seems to be a long-standing bug). Sometimes, the change just does
not happen. I changed one of my screens, to build and insert DOM objects
explicitly, and sure enough, it started to work predictably well.&lt;/p&gt;

&lt;p&gt;So I had to remove all usages of &lt;code&gt;.html()&lt;/code&gt; from my app. The downside to
it was that explicit DOM-building code is much more verbose than the
version that constructs HTML and then sets it up. It&amp;rsquo;s tedious to write
and contains much boilerplate.&lt;/p&gt;

&lt;p&gt;To not be forced to change code, the above-quoted article advocates
using a pure-JavaScript HTML parser outputting DOM to replace jQuery&amp;rsquo;s
&lt;code&gt;.html()&lt;/code&gt; method. I considered this for a while, but finally decided
against it &amp;mdash; I didn&amp;rsquo;t want to include another big, complex dependency
that potentially could misbehave at times (writing HTML parsers is
&lt;em&gt;hard&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Instead, I came up with this:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="kw"&gt;function&lt;/span&gt; &lt;span class="fu"&gt;createTree&lt;/span&gt;(tree) {
    &lt;span class="kw"&gt;if&lt;/span&gt; (&lt;span class="kw"&gt;typeof&lt;/span&gt; tree === &lt;span class="s"&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="k"&gt;string&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;/span&gt; || &lt;span class="kw"&gt;typeof&lt;/span&gt; tree === &lt;span class="s"&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="k"&gt;number&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;/span&gt;)
        &lt;span class="kw"&gt;return&lt;/span&gt; document.createTextNode(tree);
    &lt;span class="kw"&gt;var&lt;/span&gt; tag = tree[&lt;span class="i"&gt;0&lt;/span&gt;], attrs = tree[&lt;span class="i"&gt;1&lt;/span&gt;], res = document.createElement(tag);
    &lt;span class="kw"&gt;for&lt;/span&gt; (&lt;span class="kw"&gt;var&lt;/span&gt; attr &lt;span class="kw"&gt;in&lt;/span&gt; attrs) {
        val = attrs[attr];
        &lt;span class="kw"&gt;if&lt;/span&gt; (attr === &lt;span class="s"&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;/span&gt;)
            res.className = val;
        &lt;span class="kw"&gt;else&lt;/span&gt;
            &lt;span class="pd"&gt;$&lt;/span&gt;(res).attr(attr, val);
    }
    &lt;span class="kw"&gt;for&lt;/span&gt; (&lt;span class="kw"&gt;var&lt;/span&gt; i = &lt;span class="i"&gt;2&lt;/span&gt;; i &amp;lt; tree.length; i++)
        res.appendChild(createTree(tree[i]));
    &lt;span class="kw"&gt;return&lt;/span&gt; res;
}&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;This is very similar in spirit to &lt;code&gt;.html()&lt;/code&gt;, except that instead of
passing HTML, you give it a data structure representing the DOM tree to
construct. It can either be a string (which yields a text node), or a
list consisting of the HTML tag name, an object mapping attributes to
their values, and zero or more subtrees of the same form. Compare:&lt;/p&gt;

&lt;p&gt;Using &lt;code&gt;.html()&lt;/code&gt;:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="kw"&gt;var&lt;/span&gt; html = &lt;span class="s"&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="k"&gt;&amp;lt;p&amp;gt;This is an &amp;lt;span class=&amp;quot;red&amp;quot;&amp;gt;example.&amp;lt;/span&amp;gt;&amp;lt;/p&amp;gt;&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;/span&gt;;
&lt;span class="pd"&gt;$&lt;/span&gt;(&lt;span class="s"&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="k"&gt;#myDiv&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;/span&gt;).html(html);&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Using &lt;code&gt;createTree&lt;/code&gt;:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="kw"&gt;var&lt;/span&gt; tree = [&lt;span class="s"&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="k"&gt;p&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;/span&gt;, {}, 
            &lt;span class="s"&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="k"&gt;This is an &lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;/span&gt;, 
            [&lt;span class="s"&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="k"&gt;span&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;/span&gt;, {&lt;span class="ke"&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;/span&gt;: &lt;span class="s"&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="k"&gt;red&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;/span&gt;}, &lt;span class="s"&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="k"&gt;example.&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;/span&gt;]];
&lt;span class="pd"&gt;$&lt;/span&gt;(&lt;span class="s"&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="k"&gt;#myDiv&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;/span&gt;).empty().append(createTree(tree));&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;A side benefit is that it is just as easy to build up a tree dynamically
as it is to create HTML, and the code often gets clearer. Note how the
&lt;code&gt;createTree&lt;/code&gt; version above does not mix single and double quotes which
is easy to mess up in the &lt;code&gt;.html()&lt;/code&gt; version.&lt;/p&gt;
	
&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.danieljanus.pl/meet-my-little-friend-createtree"&gt;Permalink&lt;/a&gt; 

	| &lt;a href="http://blog.danieljanus.pl/meet-my-little-friend-createtree#comment"&gt;Leave a comment&amp;nbsp;&amp;nbsp;&amp;raquo;&lt;/a&gt;

&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MusingsOfALispnik/~4/0Pw8__X8rw0" height="1" width="1"/&gt;</description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/1334473/nat-face-square.jpeg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/YXpC5IC5SCt</posterous:profileUrl>
        <posterous:firstName>Daniel</posterous:firstName>
        <posterous:lastName>Janus</posterous:lastName>
        <posterous:nickName>danieljanus</posterous:nickName>
        <posterous:displayName>Daniel Janus</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.danieljanus.pl/meet-my-little-friend-createtree</feedburner:origLink></item>
    <item>
      <pubDate>Wed, 25 May 2011 11:47:38 -0700</pubDate>
      <title>A quirk with JavaScript closures</title>
      <link>http://feedproxy.google.com/~r/MusingsOfALispnik/~3/MNKuHaBPyb8/a-quirk-with-javascript-closures</link>
      <guid isPermaLink="false">http://blog.danieljanus.pl/a-quirk-with-javascript-closures</guid>
      <description>&lt;p&gt;
	&lt;p&gt;I keep running into this obstacle every now and then. Consider
this example:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&amp;gt; q = []
[]
&amp;gt; &lt;span class="kw"&gt;for&lt;/span&gt; (&lt;span class="kw"&gt;var&lt;/span&gt; i = &lt;span class="i"&gt;0&lt;/span&gt;; i &amp;lt; &lt;span class="i"&gt;3&lt;/span&gt;; i++) 
    q.push(&lt;span class="kw"&gt;function&lt;/span&gt;() { console.log(i); });
&amp;gt; q[&lt;span class="i"&gt;0&lt;/span&gt;]()
&lt;span class="i"&gt;3&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;I wanted an array of three closures, each printing a different
number to the console when called. Instead, each prints 3
(or, rather, whatever the value of the variable &lt;code&gt;i&lt;/code&gt; happens to be).&lt;/p&gt;

&lt;p&gt;I am not exactly sure about the reason, but presumably this happens
because the &lt;code&gt;i&lt;/code&gt; in each lambda refers to the &lt;em&gt;variable&lt;/em&gt; i itself,
not to its binding from the creation time of the function.&lt;/p&gt;

&lt;p&gt;One solution is to enforce the bindings explicitly on each iteration,
like this:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;&lt;span class="kw"&gt;for&lt;/span&gt; (&lt;span class="kw"&gt;var&lt;/span&gt; i = &lt;span class="i"&gt;0&lt;/span&gt;; i &amp;lt; &lt;span class="i"&gt;3&lt;/span&gt;; i++) 
  (&lt;span class="kw"&gt;function&lt;/span&gt;(v) {
     q.push(&lt;span class="kw"&gt;function&lt;/span&gt;() { console.log(v); });
   })(i);&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Or use &lt;a href="http://documentcloud.github.com/underscore/"&gt;Underscore.js&lt;/a&gt;, which is what I actually do:&lt;/p&gt;

&lt;div class="CodeRay"&gt;
  &lt;div class="code"&gt;&lt;pre&gt;_([&lt;span class="i"&gt;1&lt;/span&gt;,&lt;span class="i"&gt;2&lt;/span&gt;,&lt;span class="i"&gt;3&lt;/span&gt;]).each(&lt;span class="kw"&gt;function&lt;/span&gt;(i) {
  q.push(&lt;span class="kw"&gt;function&lt;/span&gt;() { console.log(i); });
});&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
	
&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.danieljanus.pl/a-quirk-with-javascript-closures"&gt;Permalink&lt;/a&gt; 

	| &lt;a href="http://blog.danieljanus.pl/a-quirk-with-javascript-closures#comment"&gt;Leave a comment&amp;nbsp;&amp;nbsp;&amp;raquo;&lt;/a&gt;

&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MusingsOfALispnik/~4/MNKuHaBPyb8" height="1" width="1"/&gt;</description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/1334473/nat-face-square.jpeg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/YXpC5IC5SCt</posterous:profileUrl>
        <posterous:firstName>Daniel</posterous:firstName>
        <posterous:lastName>Janus</posterous:lastName>
        <posterous:nickName>danieljanus</posterous:nickName>
        <posterous:displayName>Daniel Janus</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.danieljanus.pl/a-quirk-with-javascript-closures</feedburner:origLink></item>
    <item>
      <pubDate>Mon, 28 Mar 2011 04:20:24 -0700</pubDate>
      <title>The Dijkstran wheel of fortune: SPSS, Excel, VBA</title>
      <link>http://feedproxy.google.com/~r/MusingsOfALispnik/~3/HQDMaLkoRDU/the-dijkstran-wheel-of-fortune-spss-excel-vba</link>
      <guid isPermaLink="false">http://blog.danieljanus.pl/the-dijkstran-wheel-of-fortune-spss-excel-vba</guid>
      <description>&lt;p&gt;
	&lt;blockquote class="posterous_medium_quote"&gt;&lt;p&gt;It is practically impossible to teach good programming to students
that have had a prior exposure to BASIC: as potential programmers
they are mentally mutilated beyond hope of regeneration.&lt;/p&gt;

&lt;p&gt;       &amp;mdash; Edsger W. Dijkstra, EWD 498&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;I like to think of myself somewhat egotistically as a counterexample
to the above Dijkstra&amp;rsquo;s statement. Granted, some of my code is
definitely of poor quality, and I dare not call myself a good
programmer. But, having started with BASIC on a Commodore 64, then
proceeding to learn Pascal (of the Turbo/Borland flavour), then C, x86
assembly, OCaml, Smalltalk, Java, C++, Haskell, Common Lisp, Clojure,
and a couple of other languages, with a few enlightenments achieved
along the way, I do think I managed to regenerate from the mental
wounds that BASIC had inflicted upon me. And now I feel a strange
sensation, now that the Dijkstran wheel of fortune has made a full
spin: I&amp;rsquo;ve spend the last few days writing BASIC code. I&amp;rsquo;ve written
several Excel macros in Visual Basic for Applications.&lt;/p&gt;

&lt;p&gt;Why the strange selection of a language? Well, this was simply the
best tool for the job. What I needed to do was postprocess the output
of some statistical analyses performed in &lt;a href="http://www.spss.com"&gt;SPSS&lt;/a&gt; running under
Windows, altering the way the results were presented. SPSS can export
data to HTML, Word, and Excel; of these three, the latter is most
convenient, because it preserves the structure of the output tables
most thoroughly. (In principle, HTML does too, and in fact my first
stab was with Clojure, but I stopped after realizing just how much
ad-hoc, throwaway code that parses the SPSS-generated HTML, munges it
several times to and fro, and then outputs back HTML I&amp;rsquo;d have to
write). So I went the Excel way, and in this post I&amp;rsquo;d like to share my
mixed feelings from that encounter.&lt;/p&gt;

&lt;p&gt;Visual Basic the language is icky. It is certainly a step forward
from the BASIC I remember from decades ago, in that I didn&amp;rsquo;t have to
number my lines, and it is possible to structure the code nicely so
that it doesn&amp;rsquo;t contain any GOTOs, GOSUBs or RETURNs. And it has this
object-oriented feel to it. But compared to modern languages,
programming in it resembles voluntarily putting on handcuffs, and then
jumping around to avoid stumbling over the logs it throws under your
legs. Not quite so big and scary logs as C++ does, but still. I mean,
why on earth does VB have to distinguish between expressions and
statements? Many languages do, but in most of them an expression is
at least a valid statement. Not so in VB. Also, VB is still
line-oriented: whether or not you require an &lt;code&gt;End If&lt;/code&gt; in the
conditional statement depends on whether it fits in one line or not.
But my biggest pain was with the assignments. VB makes a distinction
between reference assignments and other assignments, requiring a &lt;code&gt;Set&lt;/code&gt;
statement in the first case, and disallowing it in the second. So,
&lt;code&gt;Set myCell = thatOtherCell&lt;/code&gt; but &lt;code&gt;foo = 42&lt;/code&gt;. Worse, forgetting the
&lt;code&gt;Set&lt;/code&gt; in the first case does not result in an error, which makes such
bugs very hard to debug. Yurgh.&lt;/p&gt;

&lt;p&gt;Also, the IDE built into Excel for developing VB macros is mediocre.
There is an editor, which highlights the syntax and automatically
reformats the code, inserting spaces as appropriate, which is nice.
It slaps me in face with a modal dialog whenever I make a syntax error
and move off the line, which is not so nice. There is a REPL of sorts,
taking the form of an &amp;ldquo;Immediate&amp;rdquo; window, into which you can type
statements (not expressions, remember?) and tap Enter to execute them.
You can also &lt;code&gt;Debug.Print&lt;/code&gt; to them, like to a JavaScript console. It
is not reachable by Ctrl-Tab from the editor, so I ended up using
mouse much more often than normally. I want my Emacs back!&lt;/p&gt;

&lt;p&gt;On the other hand, I find the object-oriented API for actually
accessing the spreadsheets quite well-designed and pleasant to
use. You just grab the object representing your worksheets from the
global &lt;code&gt;Worksheets&lt;/code&gt; object (indexable by number or by name), and from
there you access your cells. The basic object you work with is the
&lt;code&gt;Range&lt;/code&gt; object, representing either a single cell or a bunch of them;
you can get or set cell values, change the formatting, call &lt;code&gt;Offset&lt;/code&gt;
to navigate around as if with cursor keys. You also can search for
specific content in the sheet. Simple enough, easy to use and pick up;
and above all, allows to get the job done without getting in the way
much.&lt;/p&gt;

&lt;p&gt;As for SPSS itself: it sucks. In fact, it sucks so great and in so
many different ways that it merits its own blog entry (which will
follow someday). For now, I&amp;rsquo;ll only note down the things pertaining to
Excel interop; hopefully it will save somebody&amp;rsquo;s time.&lt;/p&gt;

&lt;p&gt;Problem is, SPSS 19&amp;rsquo;s Excel export is buggy. In fact, it&amp;rsquo;s so
unreliable that I&amp;rsquo;ve wasted more hours struggling with it than
actually writing my macros. (We&amp;rsquo;re talking SPSS 19 here; I&amp;rsquo;ve also
tried version 17, with the same results.) It exports small data chunks
fine, but the larger your output, the more likely it is that Excel
alerts about unreadable content in your file. Excel then offers to
repair the data, which mostly succeeds, but inevitably loses the
formatting &amp;mdash; which for me was a no-no.&lt;/p&gt;

&lt;p&gt;So, after long hours of experimentation and attempting different
workarounds, I found that it is much, much more reliable to just copy
your data and paste it into Excel directly, without exporting to a
temporary file. Just do &lt;code&gt;Edit -&amp;gt; Copy special&lt;/code&gt; and select Excel BIFF
format, to make sure you&amp;rsquo;re copying the right data. If Excel complains
about not being able to understand the copied content (turn on the
Clipboard preview to find out), save your output to .spv, restart
SPSS, re-run your syntax and try again. With luck, it will eventually
work. At least for me it did.&lt;/p&gt;
	
&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.danieljanus.pl/the-dijkstran-wheel-of-fortune-spss-excel-vba"&gt;Permalink&lt;/a&gt; 

	| &lt;a href="http://blog.danieljanus.pl/the-dijkstran-wheel-of-fortune-spss-excel-vba#comment"&gt;Leave a comment&amp;nbsp;&amp;nbsp;&amp;raquo;&lt;/a&gt;

&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MusingsOfALispnik/~4/HQDMaLkoRDU" height="1" width="1"/&gt;</description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/1334473/nat-face-square.jpeg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/YXpC5IC5SCt</posterous:profileUrl>
        <posterous:firstName>Daniel</posterous:firstName>
        <posterous:lastName>Janus</posterous:lastName>
        <posterous:nickName>danieljanus</posterous:nickName>
        <posterous:displayName>Daniel Janus</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.danieljanus.pl/the-dijkstran-wheel-of-fortune-spss-excel-vba</feedburner:origLink></item>
    <item>
      <pubDate>Fri, 11 Mar 2011 08:07:36 -0800</pubDate>
      <title>Hello world, again</title>
      <link>http://feedproxy.google.com/~r/MusingsOfALispnik/~3/aa40VYj49YM/hello-world-again</link>
      <guid isPermaLink="false">http://blog.danieljanus.pl/hello-world-again</guid>
      <description>&lt;p&gt;
	&lt;p&gt;I&amp;rsquo;ve been quiet on the front of blogging in English recently. But that
doesn&amp;rsquo;t mean I&amp;rsquo;ve given up.&lt;/p&gt;

&lt;p&gt;After more than a year, I had become tired of maintaining a &lt;a href="http://blosxom.com"&gt;Blosxom&lt;/a&gt;
installation. I greatly admire Blosxom, its minimalism and
extensibility, but the default installation is just too minimal for my
needs. And the plugins tend to have rough edges. Like the Disqus
comments that I&amp;rsquo;ve enabled at one time on the otherwise static blog
pages: the correct number of comments appears in some places but not
all; besides, they just don&amp;rsquo;t feel right.&lt;/p&gt;

&lt;p&gt;So I&amp;rsquo;ve embarked on an experiment with a blogging platform, namely
Posterous. I&amp;rsquo;ve started a &lt;a href="http://plblog.danieljanus.pl"&gt;blog in Polish&lt;/a&gt; there to comment on
local affairs in my mother tongue and to popularize Clojure among
Polish programmers. And after a few months, I consider this experiment
successful. Posterous supports Markdown, which I grew accustomed to
while using Blosxom. It automatically syntax-highlights snippets of
Clojure code that I post, which is a big win. It is highly
customizable, easy to use (blogging via email FTW!), and lets me
control my data. It does have its deficiencies, but on the whole it
gets in the way less. So I&amp;rsquo;m switching to Posterous for &amp;ldquo;Musings of a
Lispnik&amp;rdquo; too.&lt;/p&gt;

&lt;p&gt;It is unclear for me how to migrate the old content to new platform, so
for now I&amp;rsquo;ll leave it as is under &lt;a href="http://danieljanus.pl/oldblog"&gt;a temporary address&lt;/a&gt;, while
posting new things exclusively here.&lt;/p&gt;

&lt;p&gt;In the near future, I plan to translate a few articles about Clojure
I&amp;rsquo;d written in Polish and post their English versions here. Stay
tuned!&lt;/p&gt;
	
&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.danieljanus.pl/hello-world-again"&gt;Permalink&lt;/a&gt; 

	| &lt;a href="http://blog.danieljanus.pl/hello-world-again#comment"&gt;Leave a comment&amp;nbsp;&amp;nbsp;&amp;raquo;&lt;/a&gt;

&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MusingsOfALispnik/~4/aa40VYj49YM" height="1" width="1"/&gt;</description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/1334473/nat-face-square.jpeg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/YXpC5IC5SCt</posterous:profileUrl>
        <posterous:firstName>Daniel</posterous:firstName>
        <posterous:lastName>Janus</posterous:lastName>
        <posterous:nickName>danieljanus</posterous:nickName>
        <posterous:displayName>Daniel Janus</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.danieljanus.pl/hello-world-again</feedburner:origLink></item>
  </channel>
</rss>

