<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <id>tag:blog.danieljanus.pl,2019:category:programming</id>
  <title>Daniel Janus – programming</title>
  <link href="http://blog.danieljanus.pl/category/programming/"/>
  <updated>2025-12-27T00:00:00Z</updated>
  <author>
    <name>Daniel Janus</name>
    <uri>http://danieljanus.pl</uri>
    <email>dj@danieljanus.pl</email>
  </author>
  <entry>
    <id>tag:blog.danieljanus.pl,2025-12-27:post:llms</id>
    <title>On LLMs in programming</title>
    <link href="http://blog.danieljanus.pl/llms/"/>
    <updated>2025-12-27T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;&lt;a href="https://www.poetryfoundation.org/poems/44122/a-nocturnal-upon-st-lucys-day"&gt;&lt;em&gt;’Tis the year’s midnight, and it is the day’s&lt;/em&gt;.&lt;/a&gt;&lt;/p&gt;&lt;p&gt;Well, it’s two weeks past Lucy’s as I write this, but it is still that time of the year: the time of slowing down, taking a step back from the hustle and bustle of everyday, reflecting on what has happened and what is yet to come. Perhaps no better time to put together my thoughts on LLMs, and more specifically on their use in programming.&lt;/p&gt;&lt;p&gt;This post is not meant to take a stance in the ongoing discussion about the merits and risks of using LLMs. A lot has been said already about things like their moral and legal aspects, their energy footprint, how they impact society at large — I will skip all of this stuff, as I don’t have anything of value to add here. I do have opinions, but I don’t want to convince anyone. Rather, I hope to find some words to express and let out the &lt;em&gt;anxiety&lt;/em&gt; that has been brewing in me for the last couple of months.&lt;/p&gt;&lt;h2 id="where-i-stand"&gt;Where I stand&lt;/h2&gt;&lt;p&gt;I might call myself a “conscious LLM-skeptic”. That is, while my attitude towards LLMs is far from enthusiastic, I do use them and have found them genuinely useful on multiple occasions in day-to-day programming. I used to have a Claude Pro subscription (I’ve cancelled it for the moment but it’s not unlikely I’ll renew at some point). I have no doubt that they’re here to stay, they’ve significantly changed the landscape of software development and will continue to do so.&lt;/p&gt;&lt;p&gt;So why the anxiety, instead of, say, enthusiasm?&lt;/p&gt;&lt;p&gt;I guess a large part of it is due to the change itself. Especially given the pace of it. A lot of things that I have grown accustomed to are now different than what they used to be; things that I had taken for granted no longer are. Change naturally breeds anxiety.&lt;/p&gt;&lt;p&gt;But I think there’s more to it.&lt;/p&gt;&lt;h2 id="conscious-excitement"&gt;Conscious excitement&lt;/h2&gt;&lt;p&gt;Let me quote first a passage from “A Study in Scarlet”, where Dr. Watson discovers the extent of Sherlock Holmes’ knowledge of the world:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;His ignorance was as remarkable as his knowledge. Of contemporary literature, philosophy and politics he appeared to know next to nothing. Upon my quoting Thomas Carlyle, he inquired in the naivest way who he might be and what he had done. My surprise reached a climax, however, when I found incidentally that he was ignorant of the Copernican Theory and of the composition of the Solar System. That any civilized human being in this nineteenth century should not be aware that the earth travelled round the sun appeared to be to me such an extraordinary fact that I could hardly realize it.&lt;/p&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;p&gt;“You appear to be astonished,” he said, smiling at my expression of surprise. “Now that I do know it I shall do my best to forget it.”&lt;/p&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;p&gt;“To forget it!”&lt;/p&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;p&gt;“You see,” he explained, “I consider that a man’s brain originally is like a little empty attic, and you have to stock it with such furniture as you choose. A fool takes in all the lumber of every sort that he comes across, so that the knowledge which might be useful to him gets crowded out, or at best is jumbled up with a lot of other things so that he has a difficulty in laying his hands upon it. Now the skilful workman is very careful indeed as to what he takes into his brain-attic. He will have nothing but the tools which may help him in doing his work, but of these he has a large assortment, and all in the most perfect order. It is a mistake to think that that little room has elastic walls and can distend to any extent. Depend upon it there comes a time when for every addition of knowledge you forget something that you knew before. It is of the highest importance, therefore, not to have useless facts elbowing out the useful ones.”&lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;I remember my astonishment at this thought process when I first read this. I might have been 11 or so at the time. Surely, I thought, the mind isn’t quite as rigid as Holmes paints it here? Surely you can keep throwing new information at it – the more, the better – and it will adapt, processing it, improving the mental model and discarding unuseful things?&lt;/p&gt;&lt;p&gt;But the older I get, the more I keep coming back to this attic analogy. Especially since I’ve learned about my ADHD a few years ago. I now believe that Holmes has a point here: that one needs to be careful and conscious when deciding what to furnish their brain with. Not necessarily with respect to &lt;em&gt;facts&lt;/em&gt;, as per Holmes, but certainly with &lt;em&gt;attention&lt;/em&gt;.&lt;/p&gt;&lt;p&gt;Because it’s attention that’s the scarcest, most precious resource that my brain has to offer. Even more precious than time (which, too, is &lt;a href="https://leebyron.com/4000/"&gt;scarce&lt;/a&gt;). Corollary: I need to choose very consciously what I devote my attention to.&lt;/p&gt;&lt;p&gt;Another thing I discovered is that attention and excitement are very much intertwined. Excitement arises when thinking about something deeply, and it is possible, to a certain extent, to &lt;em&gt;induce&lt;/em&gt; excitement. It’s conscious, too. Corollary #2: I need to choose very consciously what to be excited about. &lt;a href="https://www.reddit.com/r/funny/comments/2me726/basic_fuckonomics/"&gt;It’s just basic fuckonomics.&lt;/a&gt;&lt;/p&gt;&lt;p&gt;And I’ve made a choice for those areas not to include LLMs – lest they divert my attention from things I care about.&lt;/p&gt;&lt;p&gt;I care about the fundamentals of my craft. I care about programming languages and their theory. I care about the trade-offs of static vs dynamic typing; of manual vs automatic memory management. I care about algorithms and data structures. I care about clarity when expressing ideas with code. I care about abstractions.&lt;/p&gt;&lt;p&gt;Most importantly, I care about the &lt;em&gt;fun&lt;/em&gt; I’ve had from learning, exploring, and applying all these things. I choose to continue to derive the fun from them.&lt;/p&gt;&lt;p&gt;(Incidentally, some of the most productive uses of LLMs I’ve had were when I used them as a glorified rubber duck – having casual conversations that sought to increase my understanding of the problem at hand – rather than asking them to write code.)&lt;/p&gt;&lt;h2 id="are-we-all-10x-programmers-now?"&gt;Are we all 10x programmers now?&lt;/h2&gt;&lt;p&gt;In the paper &lt;a href="https://econweb.ucsd.edu/~vramey/research/Century_Published.pdf"&gt;“A Century of Work and Leisure”&lt;/a&gt;, Valerie A. Ramey and Neville Francis look at how people have been using their time throughout the 20th century – in particular, how much time they’ve been spending on domestic chores (or activities that they dub “home production”: planning, buying things, cleaning, housecare, preparing food, laundries, etc). They find that per-household amount of time spent on this has largely remained the same over time: women now spend significantly less time than they used to, but this is largely offset by the increase of time invested into home chores by men.&lt;/p&gt;&lt;p&gt;Why, given the revolutionary advances in technology over that time and the proliferation of washing machines, microwave ovens and other appliances?&lt;/p&gt;&lt;p&gt;Ulrich Schnabel in &lt;a href="https://www.google.com/books/edition/Mu%C3%9Fe/sU-JKnhsNJoC"&gt;“Leisure: The Happiness of Doing Nothing”&lt;/a&gt; (a great book that, sadly, has not been translated to English as far as I know) cites Ramey and Francis’ work and argues the answer to be &lt;a href="https://en.wikipedia.org/wiki/Parkinson%27s_law"&gt;Parkinson's law&lt;/a&gt;:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;Parkinson’s law provides the first answer: “A job expands to exactly the extent that time is available for its completion—regardless of the actual amount of work.” […]&lt;/p&gt;&lt;p&gt;Put more kindly, Parkinson’s law can also be interpreted as follows: As technology saves us time, our expectations and demands increase. A hundred years ago, well-groomed clothes, a clean house, and a multi-course meal were still considered luxuries; today, these things have largely become the norm.&lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;Now, with the advent of LLMs, I can’t help feeling that we’re going through this all over again. New technology appears that purports to save us all precious time; and then, some time later, we discover that we have just as little free time as we used to. Parkinson’s law at work again. But unlike with home management, in this case it’s not due to &lt;em&gt;our&lt;/em&gt; increased expectations about what is or is not luxurious – it’s that expectations &lt;em&gt;towards us&lt;/em&gt; have increased. Deliver more features! Write more code! Review more PRs! More, more, more!&lt;/p&gt;&lt;p&gt;We may have all become 10x programmers, but the reference point has shifted, too, so the 10x doesn’t apply anymore: the factors have to be recomputed. Where is my peace of mind?&lt;/p&gt;&lt;p&gt;(Yes, this is tongue-in-cheek and I can’t quantify it in any way. Remember, this is ventilation, not a meritorical argument.)&lt;/p&gt;&lt;h2 id="adapt-or-perish"&gt;Adapt or perish&lt;/h2&gt;&lt;p&gt;I keep having these doubts and fears. Will I still have a job in a few years? Is my ability to think deeply about problems still a valuable asset? Will I be forced to use LLMs if I want to continue working as a software engineer?&lt;/p&gt;&lt;p&gt;At the end of the day, I am a human. I know what it’s like to experience beauty – through my senses, in my mind, with all my flesh – and I know that &lt;a href="https://archive.org/details/machinebeautyele00gele"&gt;code can be beautiful&lt;/a&gt;. At least nothing will strip me of that.&lt;/p&gt;&lt;h2 id="final-words"&gt;Final words&lt;/h2&gt;&lt;p&gt;I don’t have a good conclusion. So, instead, I’ll make a statement: this blog (by which I mean the whole site, not just this article) is mine, a human’s, and does not nor will it ever contain any LLM-written content (except for purposes of commentary when clearly marked as such). I’m not saying that I won’t write here about LLMs ever again, but I don’t think it’s likely to happen anytime soon: I prefer to write about things that I’m excited about.&lt;/p&gt;&lt;p&gt;Here are some links to texts by other people that resonate with me. That’s not to say that I necessarily agree with every single word they say; I just found myself nodding along as I read them.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;&lt;a href="https://paddy.carvers.com/posts/2025/07/ai/"&gt;I’m Tired of Talking About AI&lt;/a&gt;&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;&lt;a href="https://hojberg.xyz/the-programmer-identity-crisis/"&gt;The Programmer Identity Crisis&lt;/a&gt;&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;&lt;a href="https://alexn.org/blog/2025/10/27/ai-sucks-the-joy-out-of-programming/"&gt;‘AI’ Sucks the Joy Out of Programming&lt;/a&gt;&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2025-04-22:post:datomic-forking-the-past</id>
    <title>No, really, you can’t branch Datomic from the past (and what you can do instead)</title>
    <link href="http://blog.danieljanus.pl/datomic-forking-the-past/"/>
    <updated>2025-04-22T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;I have a love-hate relationship with &lt;a href="https://www.datomic.com/"&gt;Datomic&lt;/a&gt;. Datomic is a Clojure-based database based on a record of immutable facts; this post assumes a passing familiarity with it – if you haven’t yet, I highly recommend checking it out, it’s enlightening even if you end up not using it.&lt;/p&gt;&lt;p&gt;I’ll leave ranting on the “hate” part for some other time; here, I’d like to focus on some of the love – and its limits.&lt;/p&gt;&lt;p&gt;Datomic has this feature called “speculative writes”. It allows you to take an immutable database value, apply some new facts to it (speculatively, i.e., without sending them over to the transactor – this is self-contained within the JVM), and query the resulting database value &lt;em&gt;as if&lt;/em&gt; those facts had been transacted for real.&lt;/p&gt;&lt;p&gt;This is incredibly powerful. It lets you “fork” a Datomic connection (with the help of an ingenious library called &lt;a href="https://github.com/vvvvalvalval/datomock/"&gt;Datomock&lt;/a&gt;), so that you can see all of the data in the source database up to the point of forking, but any new writes happen only in memory. You can develop on top of production data, but without any risk of damaging them! I remember how aghast I was upon first hearing about the concept, but now can’t imagine my life without it. Datomock’s author offers an analogy to Git: it’s like database values being commits, and connections being branches.&lt;/p&gt;&lt;p&gt;Another awesome feature of Datomic is that it lets you travel back in time. You can call &lt;a href="https://docs.datomic.com/reference/filters.html#as-of"&gt;&lt;code&gt;as-of&lt;/code&gt;&lt;/a&gt; on a database value, passing a timestamp, and you get back a db &lt;em&gt;as it was at that point in time&lt;/em&gt; – which you can query to your heart’s content. This aids immensely in forensic debugging, and helps answer questions which would have been outright impossible to answer with classical DBMSs.&lt;/p&gt;&lt;p&gt;Now, we’re getting to the crux of this post: &lt;code&gt;as-of&lt;/code&gt; and speculative writes don’t compose together. If you try to create a Datomocked connection off of a database value obtained from &lt;code&gt;as-of&lt;/code&gt;, you’ll get back a connection to which you can transact new facts, but you’ll never be able to see them. The analogy to Git falls down here: it’s as if Git only let you branch &lt;code&gt;HEAD&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;This is a well-known gotcha among Datomic users. From &lt;a href="https://docs.datomic.com/reference/filters.html#as-of-not-branch"&gt;Datomic’s documentation&lt;/a&gt;:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;&lt;strong&gt;as-of Is Not a Branch&lt;/strong&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;p&gt;Filters are applied to an unfiltered database value obtained from &lt;code&gt;db&lt;/code&gt; or &lt;code&gt;with&lt;/code&gt;. In particular, the combination of &lt;code&gt;with&lt;/code&gt; and &lt;code&gt;as-of&lt;/code&gt; means "&lt;code&gt;with&lt;/code&gt; followed by &lt;code&gt;as-of&lt;/code&gt;", regardless of which API call you make first. &lt;code&gt;with&lt;/code&gt; plus &lt;code&gt;as-of&lt;/code&gt; lets you see a speculative db with recent datoms filtered out, but it does not let you branch the past.&lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;So it appears that this is an insurmountable obstacle: you can’t fork the past with Datomic.&lt;/p&gt;&lt;p&gt;Or can you?&lt;/p&gt;&lt;p&gt;Reddit user NamelessMason has tried to &lt;a href="https://www.reddit.com/r/Clojure/comments/yemxzi/datomic_with_asof_or_the_elusive_branching_off_a/"&gt;reimplement &lt;code&gt;as-of&lt;/code&gt; on top of &lt;code&gt;d/filter&lt;/code&gt;&lt;/a&gt;, yielding what seems to be a working approach to “datofork”! Quoting his post:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;Datomic supports 4 kinds of filters: &lt;code&gt;as-of&lt;/code&gt;, &lt;code&gt;since&lt;/code&gt;, &lt;code&gt;history&lt;/code&gt; and custom &lt;code&gt;d/filter&lt;/code&gt;, where you can filter by arbitrary datom predicate. […]&lt;/p&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;p&gt;&lt;code&gt;d/as-of&lt;/code&gt; sets a effective upper limit on the T values visible through the Database object. This applies both to existing datoms as well as any datoms you try to add later. But since the &lt;code&gt;tx&lt;/code&gt; value for the next transaction is predictable, and custom filters compose just fine, perhaps we could just white-list future transactions?&lt;/p&gt;&lt;/blockquote&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;defn&lt;/span&gt; &lt;span class="hljs-title"&gt;as-of&amp;#x27;&amp;#x27;&lt;/span&gt; [db t]
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [tx-limit (&lt;span class="hljs-name"&gt;d/t-&amp;gt;tx&lt;/span&gt; t)
        tx-allow (&lt;span class="hljs-name"&gt;d/t-&amp;gt;tx&lt;/span&gt; (&lt;span class="hljs-name"&gt;d/basis-t&lt;/span&gt; db))]
    (&lt;span class="hljs-name"&gt;d/filter&lt;/span&gt; db (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;fn&lt;/span&gt;&lt;/span&gt; [_ [e a v tx]] (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;or&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;&amp;lt;=&lt;/span&gt;&lt;/span&gt; tx tx-limit) (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;&amp;gt;&lt;/span&gt;&lt;/span&gt; tx tx-allow))))))
&lt;/code&gt;&lt;/pre&gt;&lt;blockquote&gt;&lt;p&gt;[…] Seems to work fine!&lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;Sadly, it doesn’t actually work fine. Here’s a counterexample:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;def&lt;/span&gt; &lt;span class="hljs-title"&gt;conn&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [u &lt;span class="hljs-string"&gt;&amp;quot;datomic:mem:test&amp;quot;&lt;/span&gt;] (&lt;span class="hljs-name"&gt;d/create-database&lt;/span&gt; u) (&lt;span class="hljs-name"&gt;d/connect&lt;/span&gt; u)))

&lt;span class="hljs-comment"&gt;;; Let&amp;#x27;s add some basic schema&lt;/span&gt;
@(&lt;span class="hljs-name"&gt;d/transact&lt;/span&gt; conn [{&lt;span class="hljs-symbol"&gt;:db/ident&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:test/id&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:db/valueType&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:db.type/string&lt;/span&gt;
                    &lt;span class="hljs-symbol"&gt;:db/cardinality&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:db.cardinality/one&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:db/unique&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:db.unique/identity&lt;/span&gt;}])
(&lt;span class="hljs-name"&gt;d/basis-t&lt;/span&gt; (&lt;span class="hljs-name"&gt;d/db&lt;/span&gt; conn)) &lt;span class="hljs-comment"&gt;;=&amp;gt; 1000&lt;/span&gt;

&lt;span class="hljs-comment"&gt;;; Now let&amp;#x27;s transact an entity&lt;/span&gt;
@(&lt;span class="hljs-name"&gt;d/transact&lt;/span&gt; conn [{&lt;span class="hljs-symbol"&gt;:test/id&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;test&amp;quot;&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:db/ident&lt;/span&gt; &lt;span class="hljs-symbol"&gt;::the-entity&lt;/span&gt;}])
(&lt;span class="hljs-name"&gt;d/basis-t&lt;/span&gt; (&lt;span class="hljs-name"&gt;d/db&lt;/span&gt; conn)) &lt;span class="hljs-comment"&gt;;=&amp;gt; 1001&lt;/span&gt;

&lt;span class="hljs-comment"&gt;;; And in another transaction let&amp;#x27;s change the :test/id of that entity&lt;/span&gt;
@(&lt;span class="hljs-name"&gt;d/transact&lt;/span&gt; conn [[&lt;span class="hljs-symbol"&gt;:db/add&lt;/span&gt; &lt;span class="hljs-symbol"&gt;::the-entity&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:test/id&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;test2&amp;quot;&lt;/span&gt;]])
(&lt;span class="hljs-name"&gt;d/basis-t&lt;/span&gt; (&lt;span class="hljs-name"&gt;d/db&lt;/span&gt; conn)) &lt;span class="hljs-comment"&gt;;=&amp;gt; 1003&lt;/span&gt;

&lt;span class="hljs-comment"&gt;;; Trying a speculative write, forking from 1001&lt;/span&gt;
(&lt;span class="hljs-keyword"&gt;def&lt;/span&gt; &lt;span class="hljs-title"&gt;db&amp;#x27;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;-&amp;gt;&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;d/db&lt;/span&gt; conn)
             (&lt;span class="hljs-name"&gt;as-of&amp;#x27;&amp;#x27;&lt;/span&gt; &lt;span class="hljs-number"&gt;1001&lt;/span&gt;)
             (&lt;span class="hljs-name"&gt;d/with&lt;/span&gt; [[&lt;span class="hljs-symbol"&gt;:db/add&lt;/span&gt; &lt;span class="hljs-symbol"&gt;::the-entity&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:test/id&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;test3&amp;quot;&lt;/span&gt;]])
             &lt;span class="hljs-symbol"&gt;:db-after&lt;/span&gt;))
(&lt;span class="hljs-symbol"&gt;:test/id&lt;/span&gt; (&lt;span class="hljs-name"&gt;d/entity&lt;/span&gt; db&amp;#x27; &lt;span class="hljs-symbol"&gt;::the-entity&lt;/span&gt;)) &lt;span class="hljs-comment"&gt;;=&amp;gt; &amp;quot;test&amp;quot; (WRONG! it should be &amp;quot;test3&amp;quot;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;To recap what we just did: we transacted version A of an entity, then an updated version B, then tried to fork C off of A, but we’re still seeing A’s version of the data. Can we somehow save the day?&lt;/p&gt;&lt;p&gt;To see what &lt;code&gt;d/filter&lt;/code&gt; is doing, we can add a debug &lt;code&gt;println&lt;/code&gt; to the filtering function, following NamelessMason’s example (I’m translating &lt;code&gt;tx&lt;/code&gt; values to &lt;code&gt;t&lt;/code&gt; for easier understanding):&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;defn&lt;/span&gt; &lt;span class="hljs-title"&gt;as-of&amp;#x27;&amp;#x27;&lt;/span&gt; [db t]
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [tx-limit (&lt;span class="hljs-name"&gt;d/t-&amp;gt;tx&lt;/span&gt; t)
        tx-allow (&lt;span class="hljs-name"&gt;d/t-&amp;gt;tx&lt;/span&gt; (&lt;span class="hljs-name"&gt;d/basis-t&lt;/span&gt; db))]
    (&lt;span class="hljs-name"&gt;d/filter&lt;/span&gt; db (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;fn&lt;/span&gt;&lt;/span&gt; [_ [e a v tx &lt;span class="hljs-symbol"&gt;:as&lt;/span&gt; datom]]
                   (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [result (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;or&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;&amp;lt;=&lt;/span&gt;&lt;/span&gt; tx tx-limit) (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;&amp;gt;&lt;/span&gt;&lt;/span&gt; tx tx-allow))]
                     (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;printf&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;%s -&amp;gt; %s\n&amp;quot;&lt;/span&gt; (&lt;span class="hljs-name"&gt;pr-str&lt;/span&gt; [e a v (&lt;span class="hljs-name"&gt;d/tx-&amp;gt;t&lt;/span&gt; tx)]) result)
                     result)))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Re-running the above speculative write snippet now yields:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;[&lt;span class="hljs-number"&gt;17592186045418&lt;/span&gt; &lt;span class="hljs-number"&gt;72&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;test&amp;quot;&lt;/span&gt; &lt;span class="hljs-number"&gt;1003&lt;/span&gt;] -&amp;gt; &lt;span class="hljs-literal"&gt;false&lt;/span&gt;
[&lt;span class="hljs-number"&gt;17592186045418&lt;/span&gt; &lt;span class="hljs-number"&gt;72&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;test&amp;quot;&lt;/span&gt; &lt;span class="hljs-number"&gt;1001&lt;/span&gt;] -&amp;gt; &lt;span class="hljs-literal"&gt;true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;So &lt;code&gt;d/filter&lt;/code&gt; saw that tx 1003 retracts the &lt;code&gt;"test"&lt;/code&gt; value for our datom, but it’s rejected because it doesn’t meet the condition &lt;code&gt;(or (&lt;= tx tx-limit) (&gt; tx tx-allow))&lt;/code&gt;. And at this point, it never even looks at datoms in the speculative transaction 1004, the one that asserted our &lt;code&gt;"test3"&lt;/code&gt;. It looks like Datomic’s &lt;code&gt;d/filter&lt;/code&gt; does some optimizations where it skips datoms if it determines they cannot apply based on previous ones.&lt;/p&gt;&lt;p&gt;But even if it &lt;em&gt;did&lt;/em&gt; do what we want (i.e., include datoms from tx 1001 and 1004 but not 1003), it would have been impossible. Let’s see what datoms our speculative transaction introduces:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;-&amp;gt;&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;d/db&lt;/span&gt; conn)
    (&lt;span class="hljs-name"&gt;as-of&amp;#x27;&amp;#x27;&lt;/span&gt; &lt;span class="hljs-number"&gt;1001&lt;/span&gt;)
    (&lt;span class="hljs-name"&gt;d/with&lt;/span&gt; [[&lt;span class="hljs-symbol"&gt;:db/add&lt;/span&gt; &lt;span class="hljs-symbol"&gt;::the-entity&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:test/id&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;test3&amp;quot;&lt;/span&gt;]])
    &lt;span class="hljs-symbol"&gt;:tx-data&lt;/span&gt;
    (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;-&amp;gt;&amp;gt;&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;mapv&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;juxt&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:e&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:a&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:v&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;comp&lt;/span&gt;&lt;/span&gt; d/tx-&amp;gt;t &lt;span class="hljs-symbol"&gt;:tx&lt;/span&gt;) &lt;span class="hljs-symbol"&gt;:added&lt;/span&gt;))))
&lt;span class="hljs-comment"&gt;;=&amp;gt; [[13194139534316 50 #inst &amp;quot;2025-04-22T12:48:40.875-00:00&amp;quot; 1004 true]&lt;/span&gt;
&lt;span class="hljs-comment"&gt;;=&amp;gt;  [17592186045418 72 &amp;quot;test3&amp;quot; 1004 true]&lt;/span&gt;
&lt;span class="hljs-comment"&gt;;=&amp;gt;  [17592186045418 72 &amp;quot;test2&amp;quot; 1004 false]]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;It adds the value of &lt;code&gt;"test3"&lt;/code&gt; but retracts &lt;code&gt;"test2"&lt;/code&gt;! Not &lt;code&gt;"test"&lt;/code&gt;! It appears that &lt;code&gt;d/with&lt;/code&gt; looks at the unfiltered database value to produce new datoms for the speculative db value (corroborated by the fact that we don’t get any output from the filtering fn at this point; we only do when we actually query &lt;code&gt;db'&lt;/code&gt;). Our filter cannot work: transactions 1001 plus 1004 would be “add &lt;code&gt;"test"&lt;/code&gt;, retract &lt;code&gt;"test2"&lt;/code&gt;, add &lt;code&gt;"test3"&lt;/code&gt;”, which is not internally consistent.&lt;/p&gt;&lt;p&gt;So, no, really, you can’t branch Datomic from the past.&lt;/p&gt;&lt;p&gt;Which brings us back to square one: what can we do? What is our usecase for branching the past, anyway?&lt;/p&gt;&lt;p&gt;Dunno about you, but to me the allure is integration testing. Rather than having to maintain an elaborate set of fixtures, with artificial entity names peppered with the word “example”, I want to test on data that’s &lt;em&gt;close&lt;/em&gt; to production; that &lt;em&gt;feels&lt;/em&gt; like production. Ideally, it &lt;em&gt;is&lt;/em&gt; production data, isolated and made invincible by forking. At the same time, tests have to behave predictably: I don’t want a test to fail just because someone deleted yesterday an entity from production that the test depends on. Being able to fork the past would have been a wonderful solution if it worked, but… it’s what it is.&lt;/p&gt;&lt;p&gt;So now I’m experimenting with a different approach. My observation here is that my app’s Datomic database is (and I’d wager a guess that most real-world DBs are as well) “mostly hierarchical”. That is, while its graph of entities might be a giant strongly-connected blob, it can be subdivided into many small subgraphs by judiciously removing edges.&lt;/p&gt;&lt;p&gt;This makes sense for testing. A test typically focuses on a handful of “top-level entities” that I need to be present in my testing database like they are in production, along with all their dependencies – sub-entities that they point to. Say, if I were developing a UI for the &lt;a href="https://github.com/Datomic/mbrainz-sample"&gt;MusicBrainz database&lt;/a&gt; and testing the release page, I’d need a release entity, along with its tracks, label, medium, artist, country etc to be present in my testing DB. But just one release is enough; I don’t need all 10K of them.&lt;/p&gt;&lt;p&gt;My workflow is thus:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;create an empty in-memory DB&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;feed it with the same schema that production has&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;get hold of a production db with a fixed as-of&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;given a “seed entity”, perform a graph traversal (via EAVT and VAET indexes) starting from that entity to determine reachable entities, judiciously blacklisting attributes (and whitelisting “backward-pointing” ones) to avoid importing too much&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;copy those entities to my fresh DB&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;run the test!&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;This can be done generically. I’ve written &lt;a href="https://gist.github.com/nathell/d3b6f9509a00857cd1843e366797f884"&gt;some proof-of-concept code&lt;/a&gt; that wraps a Datomic db to implement the &lt;a href="https://github.com/aysylu/loom"&gt;Loom&lt;/a&gt; graph protocol, so that one can use Loom’s graph algorithms to perform a breadth-first entity scan, and a function to walk over those entities and convert them to a transaction applicable on top of a pristine DB. So far I’ve been able to extract meaningful small sub-dbs (on the order of ~10K datoms) from my huge production DB of 17+ billion datoms.&lt;/p&gt;&lt;p&gt;This is a gist for now, but let me know if there’s interest and I can convert it into a proper library.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2025-03-02:post:cleaner-codebase</id>
    <title>Cleaner codebase, happier mind</title>
    <link href="http://blog.danieljanus.pl/cleaner-codebase/"/>
    <updated>2025-03-02T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;This is my home-office desk on a typical day. Yuck – look at those mugs, cables and rubbish!&lt;/p&gt;&lt;img src="/img/blog/my-desk.webp"&gt;
&lt;p&gt;As a person with ADHD, I have a hard time maintaining cleanliness – and a high tolerance to mess around me. However, being in a cluttered environment does take its toll. Often I find myself frustrated by it, but also overwhelmed by tasks at hand, to the point of cleaning up feeling almost an insurmountable chore; often, when I start my workday by physically cleaning things up, I find it giving me a dopamine boost that impacts my productivity for the rest of the day.&lt;/p&gt;&lt;p&gt;I’m not alone. There is a &lt;a href="https://psycnet.apa.org/record/2020-73700-008"&gt;known link between office cleanliness and wellbeing&lt;/a&gt;; some companies have clean desk policies. If nothing else, keeping the work environment clean has a positive psychological effect on people.&lt;/p&gt;&lt;p&gt;Increasingly often, I find myself wondering: why don’t we apply the same thinking to codebases?&lt;/p&gt;&lt;p&gt;Let me stress that I’m not talking about “clean code” in the &lt;a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882"&gt;Uncle Bob sense&lt;/a&gt;; I mean the chores that everyone would like to see done, but nobody apparently has time for doing — the cruft that has accumulated as tech debt. Every codebase has something like this, and you know it when you see it. That flaky test that’s been failing once in 20 times or so, for no apparent reason. That legacy component that could plausibly be implemented with more modern infrastructure. That Jenkins instance you keep around just for CI-ing it. Those three in-house libraries that all do the same thing, but in slightly different ways. Those modules that are only there because you ran an A/B test involving them a year ago, which has since been rolled back. And so on.&lt;/p&gt;&lt;p&gt;Yes, this is tech debt, and has to be managed economically. Sometimes it makes sense to bear with things as they are, because your time is needed elsewhere. Or there’s no clear financial gain to be had from investing effort in cleaning up that stuff.&lt;/p&gt;&lt;p&gt;But I believe there are &lt;em&gt;psychological&lt;/em&gt; gains. It can give a sense of accomplishment; it can make the codebase more pleasant to work with; it can reduce frustration. It can make people happier in the long run.&lt;/p&gt;&lt;p&gt;One of the strategies I’ve found useful for home cleaning is allocating regular but short time slots in the calendar. I call them “a quarter for home.” While 15 minutes is not enough for a thorough cleanup of a room, it can still make a night-and-day difference in how it feels to be in that room.&lt;/p&gt;&lt;p&gt;And so, going forward, I’m instituting the same policy for myself, for codebases I work with. A daily quarter for code. Or half an hour every second morning. I might be busy, but it happens very rarely that I don’t have a half an hour to spare. Sure, some cleanups might require multi-day refactoring to complete, but so what? There are smaller ones, requiring just one or a few sessions. The fact that I have a limited, dedicated time slot means that I’ll ask myself “how can I use it effectively?” And even larger undertakings can be done in multiple half-an-hour-long sittings: there are no deadlines.&lt;/p&gt;&lt;p&gt;Whether or not this works out remains to be seen (forming habits is another thing that ADHD makes harder). I plan to follow up with a retrospective post in a few months. In the meantime, if you have done or plan to do something similar, I’m keen to hear from you!&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2025-02-21:post:double-double-toil-and-trouble</id>
    <title>Double, double toil and trouble or, Corner-Cases of Comparing Clojure Numbers</title>
    <link href="http://blog.danieljanus.pl/double-double-toil-and-trouble/"/>
    <updated>2025-02-21T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;&lt;a href="https://www.destroyallsoftware.com/talks/wat"&gt;Let’s talk about&lt;/a&gt; Clojure.&lt;/p&gt;&lt;p&gt;In Clojure, comparing two numbers can throw an exception.&lt;/p&gt;&lt;img src="/img/blog/wat-shark.jpg" alt="Wat"&gt;
&lt;p&gt;Check this out:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;&amp;lt;&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;1/4&lt;/span&gt; &lt;span class="hljs-number"&gt;0.5M&lt;/span&gt;)
&lt;span class="hljs-comment"&gt;;=&amp;gt; true        ; as expected&lt;/span&gt;

(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;&amp;lt;&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;1/3&lt;/span&gt; &lt;span class="hljs-number"&gt;0.5M&lt;/span&gt;)
&lt;span class="hljs-comment"&gt;; Execution error (ArithmeticException) at java.math.BigDecimal/divide (BigDecimal.java:1783).&lt;/span&gt;
&lt;span class="hljs-comment"&gt;; Non-terminating decimal expansion; no exact representable decimal result.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;But why? Why would comparing two perfectly cromulent numbers throw an &lt;code&gt;ArithmeticException&lt;/code&gt;?! Everybody knows that ⅓ &lt; 0.5 – we aren’t dividing by zero or anything like that, are we?&lt;/p&gt;&lt;p&gt;Well, the problem is that we’re comparing a ratio to a &lt;code&gt;BigDecimal&lt;/code&gt; (a decimal number of arbitrary precision). Java doesn’t offer a built-in way of comparing these (Clojure’s ratios aren’t part of the Java standard library), so it has to coerce one into the other. It chooses to coerce the ratio into a BigDecimal, so divides &lt;code&gt;(bigdec 1)&lt;/code&gt; by &lt;code&gt;(bigdec 3)&lt;/code&gt;…&lt;/p&gt;&lt;p&gt;…and that &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html#divide-java.math.BigDecimal-"&gt;throws!&lt;/a&gt; The decimal representation of ⅓ is infinite, so you can’t keep all the digits in finite memory.&lt;/p&gt;&lt;p&gt;You may ask: how exactly does Clojure know what coercions to apply and how to produce the result? Let’s look at the code.&lt;/p&gt;&lt;p&gt;The implementation of &lt;code&gt;clojure.core/&lt;&lt;/code&gt; calls the Java method &lt;code&gt;clojure.lang.Numbers.lt&lt;/code&gt;, which is implemented &lt;a href="https://github.com/clojure/clojure/blob/clojure-1.12.0/src/jvm/clojure/lang/Numbers.java#L252-L254"&gt;like this&lt;/a&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs java"&gt;&lt;span class="hljs-keyword"&gt;static&lt;/span&gt; &lt;span class="hljs-keyword"&gt;public&lt;/span&gt; &lt;span class="hljs-type"&gt;boolean&lt;/span&gt; &lt;span class="hljs-title function_"&gt;lt&lt;/span&gt;&lt;span class="hljs-params"&gt;(Object x, Object y)&lt;/span&gt;{
	&lt;span class="hljs-keyword"&gt;return&lt;/span&gt; ops(x).combine(ops(y)).lt((Number)x, (Number)y);
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;What’s &lt;code&gt;ops&lt;/code&gt;? It’s an implementation of the &lt;code&gt;Ops&lt;/code&gt; interface, which has methods for addition, subtraction, etc.; each number class has its own implementation: there is a &lt;code&gt;LongOps&lt;/code&gt;, &lt;code&gt;RatioOps&lt;/code&gt;, &lt;code&gt;BigDecimalOps&lt;/code&gt; etc.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;combine&lt;/code&gt; method can alter the behaviour of an &lt;code&gt;Ops&lt;/code&gt; depending on the type of the other argument – for example, &lt;code&gt;RatioOps&lt;/code&gt; switches to &lt;code&gt;BigDecimalOps&lt;/code&gt; if the other argument is a &lt;code&gt;BigDecimal&lt;/code&gt;. It’s like a poor man’s implementation of multiple dispatch, which Java doesn’t have.&lt;/p&gt;&lt;p&gt;&lt;code&gt;BigDecimalOps.lt&lt;/code&gt; calls &lt;code&gt;toBigDecimal&lt;/code&gt; on both arguments, and it’s &lt;a href="https://github.com/clojure/clojure/blob/clojure-1.12.0/src/jvm/clojure/lang/Numbers.java#L297-L322"&gt;that method&lt;/a&gt; that performs the failing division:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs java"&gt;&lt;span class="hljs-keyword"&gt;static&lt;/span&gt; BigDecimal &lt;span class="hljs-title function_"&gt;toBigDecimal&lt;/span&gt;&lt;span class="hljs-params"&gt;(Object x)&lt;/span&gt; {
    &lt;span class="hljs-comment"&gt;// ... other cases ...&lt;/span&gt;
    &lt;span class="hljs-keyword"&gt;if&lt;/span&gt; (x &lt;span class="hljs-keyword"&gt;instanceof&lt;/span&gt; Ratio) {
        &lt;span class="hljs-type"&gt;Ratio&lt;/span&gt; &lt;span class="hljs-variable"&gt;r&lt;/span&gt; &lt;span class="hljs-operator"&gt;=&lt;/span&gt; (Ratio)x;
        &lt;span class="hljs-keyword"&gt;return&lt;/span&gt; (BigDecimal)divide(&lt;span class="hljs-keyword"&gt;new&lt;/span&gt; &lt;span class="hljs-title class_"&gt;BigDecimal&lt;/span&gt;(r.numerator), r.denominator);
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Incidentally, this used to produce the expected result in Clojure up to 1.2.1. At that version, Clojure already used the &lt;code&gt;Ops&lt;/code&gt;-based multiple dispatch, but combining &lt;code&gt;RatioOps&lt;/code&gt; with &lt;code&gt;BigDecimalOps&lt;/code&gt; would yield the former, not the latter.&lt;/p&gt;&lt;p&gt;Is the current behaviour a bug? I’m not sure. It seems so, but maybe 1.3.0’s optimizations warrant this behaviour in the admitedly rare case. There’s an &lt;a href="https://ask.clojure.org/index.php/14411/comparing-ratios-with-bigdecimals-can-throw"&gt;ongoing discussion&lt;/a&gt; on the Ask Clojure Q&amp;A.&lt;/p&gt;&lt;p&gt;So, in current Clojure, how do you compare ratios to bigdecs? Simple, you think: just coerce the bigdec to a double!&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;&amp;lt;&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;1/3&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;double&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;0.5M&lt;/span&gt;))
&lt;span class="hljs-comment"&gt;;=&amp;gt; true&lt;/span&gt;

(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;&amp;gt;&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;2/3&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;double&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;0.5M&lt;/span&gt;))
&lt;span class="hljs-comment"&gt;;=&amp;gt; true&lt;/span&gt;

(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;=&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;1/2&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;double&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;0.5M&lt;/span&gt;))
&lt;span class="hljs-comment"&gt;;=&amp;gt; false&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Wait, WHAT?&lt;/p&gt;&lt;img src="/img/blog/wat-cat.jpg" alt="Wat"&gt;
&lt;p&gt;Yep. Comparing ratios to doubles for &lt;em&gt;inequality&lt;/em&gt; works fine, but a ratio is never &lt;em&gt;equal&lt;/em&gt; to a double (nor a bigdec), even if said double is an exact representation of the ratio.&lt;/p&gt;&lt;p&gt;This one is documented, but often forgotten about (and not hinted at by the docstring). From Clojure’s &lt;a href="https://clojure.org/guides/equality"&gt;equality guide&lt;/a&gt;:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;Clojure’s &lt;code&gt;=&lt;/code&gt; is true when called with two immutable scalar values, if:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;Both arguments are nil, true, false, the same character, or the same string (i.e. the same sequence of characters).&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;Both arguments are symbols, or both keywords, with equal namespaces and names.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;Both arguments are numbers in the same 'category', and numerically the same, where category is one of:&lt;/span&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;integer or ratio&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;floating point (float or double)&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;BigDecimal.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/blockquote&gt;&lt;p&gt;And indeed, the code for &lt;code&gt;Numbers.equal&lt;/code&gt; has &lt;a href="https://github.com/clojure/clojure/blob/clojure-1.12.0/src/jvm/clojure/lang/Numbers.java#L247-L250"&gt;a check for both operands’ categories&lt;/a&gt; before it delves to the &lt;code&gt;Ops&lt;/code&gt; business that we’ve seen. Remember also that Clojure has a numbers-only &lt;code&gt;==&lt;/code&gt; which doesn’t trigger that category check:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;==&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;1/2&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;double&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;0.5M&lt;/span&gt;))
&lt;span class="hljs-comment"&gt;;=&amp;gt; true ; yay&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Corollary: if you want to compare a ratio to a &lt;code&gt;BigDecimal&lt;/code&gt;, you &lt;em&gt;could&lt;/em&gt; coerce the bigdec to a double. That can return an incorrect result only in a very narrow range of cases: when the BigDecimal’s value is close enough to the ratio that it would be lost in the double conversion.&lt;/p&gt;&lt;p&gt;For 100% certainty, the only way I’m aware of is to remember to always use &lt;code&gt;==&lt;/code&gt; when comparing for equality, and explicitly coerce the bigdec to ratio:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;defn&lt;/span&gt; &lt;span class="hljs-title"&gt;exactly-equals?&lt;/span&gt; [ratio bigdec]
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;==&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;*&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;1&lt;/span&gt; (&lt;span class="hljs-name"&gt;clojure.lang.Numbers/toRatio&lt;/span&gt; bigdec)) ratio))

(&lt;span class="hljs-name"&gt;exactly-equals?&lt;/span&gt; &lt;span class="hljs-number"&gt;1/18446744073709551616&lt;/span&gt; &lt;span class="hljs-number"&gt;5.42101086242752217003726400434970855712890625E-20M&lt;/span&gt;)
&lt;span class="hljs-comment"&gt;;=&amp;gt; true ; correct even in this pathological case!&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;(Multiplying by 1 forces Clojure to normalize the ratio. Otherwise, converting &lt;code&gt;0.5M&lt;/code&gt; would have yielded &lt;code&gt;5/10&lt;/code&gt; which doesn’t test &lt;code&gt;==&lt;/code&gt; to &lt;code&gt;1/2&lt;/code&gt;. Go figure.)&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2024-01-26:post:lossy-css-compression</id>
    <title>Lossy CSS compression for fun and loss (or profit)</title>
    <link href="http://blog.danieljanus.pl/lossy-css-compression/"/>
    <updated>2024-01-26T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;h2 id="what"&gt;What&lt;/h2&gt;&lt;p&gt;Late last year, I had an idea that’s been steadily brewing in my head. I’ve found myself with some free time recently (it coincided with vacation, go figure), and I’ve hacked together some proof-of-concept code. Whether or not it is actually proving the concept I’m not sure, but the results are somewhat interesting, and I believe the idea is novel (I haven’t found any other implementation in the wild). So it’s at least worthy of a blog post.&lt;/p&gt;&lt;p&gt;I wrote &lt;code&gt;cssfact&lt;/code&gt;, a lossy CSS compressor. That is, a program that takes some CSS and outputs back some other CSS that hopefully retains some (most) of the information in the input, but contains fewer rules than the original. Exactly how many rules it produces is configurable, and the loss depends on that number.&lt;/p&gt;&lt;p&gt;The program only works on style rules (which make up the majority of a typical CSS). It leaves the non-style rules unchanged.&lt;/p&gt;&lt;p&gt;&lt;a href="https://github.com/nathell/cssfact"&gt;Here’s the source&lt;/a&gt;. It’s not exactly straightforward to get it running, but it shouldn’t be very hard, either. It’s very simple – the program itself doesn’t contain any fancy logic; the actual decisions on what the output will contain are made by an external program.&lt;/p&gt;&lt;p&gt;If you just want to see some results, here is a sample with &lt;a href="https://danieljanus.pl"&gt;my homepage&lt;/a&gt; serving as a patient etherized upon a table. Its CSS is quite small – 55 style rules that cssfact can work on – and here’s how the page looks with various settings:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;Original: &lt;a href="https://danieljanus.pl"&gt;page&lt;/a&gt;, &lt;a href="https://danieljanus.pl/css/nhp.css"&gt;CSS&lt;/a&gt;, &lt;a href="https://github.com/nathell/nhp/blob/master/src/sass/nhp.sass"&gt;source SASS&lt;/a&gt;&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;1 style rule: &lt;a href="https://danieljanus.pl/index1.html"&gt;page&lt;/a&gt;, &lt;a href="https://danieljanus.pl/css/nhp1.css"&gt;CSS&lt;/a&gt; (93% information loss)&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;5 style rules: &lt;a href="https://danieljanus.pl/index5.html"&gt;page&lt;/a&gt;, &lt;a href="https://danieljanus.pl/css/nhp5.css"&gt;CSS&lt;/a&gt; (74% information loss)&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;10 style rules: &lt;a href="https://danieljanus.pl/index10.html"&gt;page&lt;/a&gt;, &lt;a href="https://danieljanus.pl/css/nhp10.css"&gt;CSS&lt;/a&gt; (55% information loss)&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;20 style rules: &lt;a href="https://danieljanus.pl/index20.html"&gt;page&lt;/a&gt;, &lt;a href="https://danieljanus.pl/css/nhp20.css"&gt;CSS&lt;/a&gt; (31% information loss)&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;30 style rules: &lt;a href="https://danieljanus.pl/index30.html"&gt;page&lt;/a&gt;, &lt;a href="https://danieljanus.pl/css/nhp30.css"&gt;CSS&lt;/a&gt; (17% information loss)&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;My homepage and both of my blogs all use the same CSS, so you can try to replace the CSS in your browser’s devtools elsewhere on the site and see how it looks.&lt;/p&gt;&lt;h2 id="how"&gt;How&lt;/h2&gt;&lt;p&gt;Three words: &lt;a href="https://cs.uef.fi/~pauli/bmf_tutorial/material.html"&gt;binary matrix factorization&lt;/a&gt; (BMF, in the Boolean algebra).&lt;/p&gt;&lt;p&gt;I guess I could just stop here, but I’ll elaborate just in case it isn’t clear.&lt;/p&gt;&lt;p&gt;Consider a simple CSS snippet:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs css"&gt;&lt;span class="hljs-selector-tag"&gt;h1&lt;/span&gt;, &lt;span class="hljs-selector-tag"&gt;h2&lt;/span&gt; {
   &lt;span class="hljs-attribute"&gt;padding&lt;/span&gt;: &lt;span class="hljs-number"&gt;0&lt;/span&gt;;
   &lt;span class="hljs-attribute"&gt;margin-bottom&lt;/span&gt;: &lt;span class="hljs-number"&gt;0.5em&lt;/span&gt;;
}

&lt;span class="hljs-selector-tag"&gt;h1&lt;/span&gt; {
   &lt;span class="hljs-attribute"&gt;font-size&lt;/span&gt;: &lt;span class="hljs-number"&gt;32px&lt;/span&gt;;
   &lt;span class="hljs-attribute"&gt;font-weight&lt;/span&gt;: bold;
}

&lt;span class="hljs-selector-tag"&gt;h2&lt;/span&gt; {
   &lt;span class="hljs-attribute"&gt;font-size&lt;/span&gt;: &lt;span class="hljs-number"&gt;24px&lt;/span&gt;;
   &lt;span class="hljs-attribute"&gt;font-weight&lt;/span&gt;: bold;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The first rule tells you that for all elements that match either the &lt;code&gt;h1&lt;/code&gt; or &lt;code&gt;h2&lt;/code&gt; selectors, the two declarations should apply.&lt;/p&gt;&lt;p&gt;You could visualize this CSS as a 5x2 binary matrix &lt;i&gt;A&lt;sup&gt;T&lt;/sup&gt;&lt;/i&gt; where the &lt;em&gt;n&lt;/em&gt; columns correspond to simple selectors (i.e., without commas in them) and the &lt;em&gt;m&lt;/em&gt; rows correspond to declarations:&lt;/p&gt;&lt;style&gt;
.css-table th { text-align: right; }
.css-table td { text-align: center; }
&lt;/style&gt;
&lt;table class="css-table"&gt;
        &lt;tr&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;&lt;code&gt;h1&lt;/code&gt;&lt;/th&gt;&lt;th&gt;&lt;code&gt;h2&lt;/code&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;&lt;th&gt;&lt;code&gt;padding: 0&lt;/code&gt;&lt;/th&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;/tr&gt;
        &lt;tr&gt;&lt;th&gt;&lt;code&gt;margin-bottom: 0.5em&lt;/code&gt;&lt;/th&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;/tr&gt;
        &lt;tr&gt;&lt;th&gt;&lt;code&gt;font-size: 32px&lt;/code&gt;&lt;/th&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;/tr&gt;
        &lt;tr&gt;&lt;th&gt;&lt;code&gt;font-size: 24px&lt;/code&gt;&lt;/th&gt;&lt;td&gt;0&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;/tr&gt;
        &lt;tr&gt;&lt;th&gt;&lt;code&gt;font-weight: bold&lt;/code&gt;&lt;/th&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;/tr&gt;
    &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;You could also transpose the matrix, yielding &lt;em&gt;A&lt;/em&gt; with &lt;em&gt;m&lt;/em&gt; rows denoting selectors and &lt;em&gt;n&lt;/em&gt; columns denoting declarations. For my homepage’s CSS, &lt;em&gt;m&lt;/em&gt; = 60 and &lt;em&gt;n&lt;/em&gt; = 81; for bigger stylesheets, several thousand in either direction is not uncommon.&lt;/p&gt;&lt;p&gt;Now, linear algebra gives us algorithms to find a matrix &lt;em&gt;A′ ≈ A&lt;/em&gt; such that there exists a decomposition &lt;em&gt;A′ = B × C&lt;/em&gt;, where &lt;em&gt;B&lt;/em&gt; has dimensions &lt;em&gt;m × r&lt;/em&gt;, &lt;em&gt;C&lt;/em&gt; has dimensions &lt;em&gt;r × n&lt;/em&gt;, and &lt;em&gt;r&lt;/em&gt; is small – typically much smaller than &lt;em&gt;m&lt;/em&gt; or &lt;em&gt;n&lt;/em&gt;. So this is a way of dimensionality reduction.&lt;/p&gt;&lt;p&gt;In the usual algebra of real numbers, there’s no guarantee that &lt;em&gt;B&lt;/em&gt; or &lt;em&gt;C&lt;/em&gt; will themselves be binary matrices – in fact, most likely they won’t. But if we operate in Boolean algebra instead (i.e. one where 1 + 1 = 1), then both &lt;em&gt;B&lt;/em&gt; and &lt;em&gt;C&lt;/em&gt; will be binary. The flip side is that the Boolean BMF problem is NP-hard, so the algorithms found in the wild perform approximate decompositions, not guaranteed to be optimal.&lt;/p&gt;&lt;p&gt;But that’s okay, because lossiness is inherent in what we’re doing anyway, and it turns the binary matrices &lt;em&gt;B&lt;/em&gt; and &lt;em&gt;C&lt;/em&gt; are readily interpretable. Look again at the CSS matrix above: why is there a 1 in the top-left cell? Because at least one of the CSS rules stipulates the declaration &lt;code&gt;padding: 0&lt;/code&gt; for the selector &lt;code&gt;h1&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;This is exactly the definition of matrix multiplication in the Boolean algebra. The matrix &lt;em&gt;A′&lt;/em&gt; will have a 1 at coordinates [&lt;em&gt;i, j&lt;/em&gt;] iff there is at least one &lt;em&gt;k&lt;/em&gt; ∈ {1, …, &lt;em&gt;r&lt;/em&gt;} such that &lt;em&gt;B&lt;/em&gt;[&lt;em&gt;i&lt;/em&gt;, &lt;em&gt;k&lt;/em&gt;] = 1 and &lt;em&gt;C&lt;/em&gt;[&lt;em&gt;k&lt;/em&gt;, &lt;em&gt;j&lt;/em&gt;] = 1. So the columns of &lt;em&gt;B&lt;/em&gt; and rows of &lt;em&gt;C&lt;/em&gt; actually correspond to CSS rules! Every time you write CSS, you’re actually writing out binary matrices – and the browser is multiplying them to get at the actual behaviour.&lt;/p&gt;&lt;p&gt;Well, not really, but it’s one way to think about it. It’s not perfect – it completely glosses over rules overlapping each other and having precedence, and treats them as equally important – but it somewhat works!&lt;/p&gt;&lt;p&gt;You could plug in any BMF algorithm to this approach. For cssfact, I’ve picked the code by &lt;a href="https://github.com/IBM/binary-matrix-factorization/"&gt;Barahona and Goncalves 2019&lt;/a&gt; – sadly, I wasn’t able to find the actual paper – not because it performs spectacularly well (it’s actually dog-slow on larger stylesheets), but because I was easily able to make it work and interface with it.&lt;/p&gt;&lt;h2 id="why"&gt;Why&lt;/h2&gt;&lt;p&gt;Why not?&lt;/p&gt;&lt;p&gt;The sheer joy of exploration is reason enough, but I believe there are potential practical applications. CSS codebases have the tendency to grow organically and eventually start collapsing under their own weight, and they have to be maintained very thoughtfully to prevent that. In many CSS monstrosities found in the wild, there are much cleaner, leaner, essence-capturing cores struggling to get out.&lt;/p&gt;&lt;p&gt;This tool probably won’t automatically extract them for you – so don’t put it in your CI pipeline – but by perusing the CSS that it produces and cross-checking it with the input, you could encounter hints on what redundancy there is in your styles. Things like “these components are actually very similar, so maybe should be united” may become more apparent.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2023-09-09:post:transducers</id>
    <title>My mental model of transducers</title>
    <link href="http://blog.danieljanus.pl/transducers/"/>
    <updated>2023-09-09T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;h2 id="intro"&gt;Intro&lt;/h2&gt;&lt;p&gt;I’ve been programming in Clojure for a long time, but I haven’t been using transducers much. I learned to mechanically transform &lt;code&gt;(into [] (map f coll))&lt;/code&gt; to &lt;code&gt;(into [] (map f) coll)&lt;/code&gt; for a slight performance gain, but not much beyond that. Recently, however, I’ve found myself refactoring transducers-based code at work, which prompted me to get back to speed.&lt;/p&gt;&lt;p&gt;I found Eero Helenius’ article &lt;a href="https://dev.solita.fi/2021/10/14/grokking-clojure-transducers.html"&gt;“Grokking Clojure transducers”&lt;/a&gt; a great help in that. To me, it’s much more approachable than the &lt;a href="https://clojure.org/reference/transducers"&gt;official documentation&lt;/a&gt; – in a large part because it shows you how to build transducers from the ground up, and this method of learning profoundly resonates with me. I highly recommend it. However, it’s also useful to have a visual intuition of how transducers work, a mental model that hints at the big picture without zooming into the details too much. In this post, I’d like to share mine and illustrate it with a REPL session. (Spoiler alert: there’s &lt;a href="https://github.com/clojure/core.async"&gt;core.async&lt;/a&gt; ahead, but in low quantities.)&lt;/p&gt;&lt;h2 id="pictures"&gt;Pictures&lt;/h2&gt;&lt;p&gt;Imagine data flowing through a conveyor belt. Say, infinitely repeating integers from 1 to 5:&lt;/p&gt;&lt;img src="/img/blog/conveyor-belt.svg" alt="Conveyor belt"&gt;
&lt;p&gt;I’m using the abstract term “conveyor belt”, rather than “sequence” or something like this, to avoid associations with any implementation details. Just pieces of data, one after another. These data may be anything; they may flow infinitely or stop at some point; may or may not all exist in memory at the same time. Doesn’t matter. That’s the beauty of transducers: they completely abstract away the implementation of sequentiality.&lt;/p&gt;&lt;p&gt;So, what is a transducer, intuitively? It’s a mechanism for &lt;em&gt;transforming conveyor belts into other conveyor belts&lt;/em&gt;.&lt;/p&gt;&lt;p&gt;For example, &lt;code&gt;(map inc)&lt;/code&gt; is a transducer that says: “take this conveyor belt and produce one where every number is incremented”. Applying it to the above belt yields this one:&lt;/p&gt;&lt;img src="/img/blog/conveyor-belt-2.svg" alt="Conveyor belt, transformed"&gt;
&lt;p&gt;An important thing about transducers is that they’re &lt;em&gt;composable&lt;/em&gt;. To understand that, imagine further transforming the above belt by removing all the odd numbers. Intuitively, that’s what &lt;code&gt;(remove odd?)&lt;/code&gt; does:&lt;/p&gt;&lt;img src="/img/blog/conveyor-belt-3.svg" alt="Conveyor belt, transformed again"&gt;
&lt;p&gt;(I’ve left the spacing between boxes the same as before, because it helps me visualise &lt;code&gt;(remove odd?)&lt;/code&gt; better. I imagine an invisible gnome sitting above the belt, watching carefully all the boxes that pass below it, and snatching greedily every one that happens to contain an odd number.)&lt;/p&gt;&lt;p&gt;Composability means that Clojure lets you say &lt;code&gt;(comp (map inc) (remove odd?))&lt;/code&gt; to mean the transducer that transforms the first belt to the third one. By putting together two simple building blocks, we produced a more complex one – that it itself reusable and can be used as another building block in an ever more complex data pipeline.&lt;/p&gt;&lt;p&gt;Notice we &lt;em&gt;still&lt;/em&gt; haven’t said anything about the actual representation of the data, but are already able to model complex processes. We can then apply them to actual data, whether it’s a simple vector-to-vector transformation within the same JVM, or listening to a topic on a Kafka cluster, summarizing the incoming data and sending them to a data warehouse.&lt;/p&gt;&lt;h2 id="code"&gt;Code&lt;/h2&gt;&lt;p&gt;OK, enough handwaving, time for a demo. Let’s fire up a REPL and load core.async (I’m assuming you’ve added it to your dependencies already). I won’t reproduce here the resulting values of expressions we evaluate (they’re mostly &lt;code&gt;nil&lt;/code&gt;s anyway), but I will reproduce output from the REPL (as comments).&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;require&lt;/span&gt; &amp;#x27;[clojure.core.async &lt;span class="hljs-symbol"&gt;:refer&lt;/span&gt; [chan &amp;lt;!! &amp;gt;!! thread close!]])
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Why core.async? Because I find it a great way to implement a conveyor belt that you can play with interactively. This can help you understand how the various Clojure-provided transducers work. For the noncognoscenti: core.async is a Clojure library that allows you to implement concurrent processes that communicate over &lt;em&gt;channels&lt;/em&gt;. By default, that communication is synchronous, meaning that if a process tries to read from a channel, it blocks until another process writes something to that channel.&lt;/p&gt;&lt;p&gt;As it happens, we can pass a transducer to the function that creates channels, &lt;code&gt;chan&lt;/code&gt;. It will put the invisible gnomes to work on values that pass through the channel. So you can view that channel as a conveyor belt!&lt;/p&gt;&lt;p&gt;For easy tinkering, we can do this:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;defn&lt;/span&gt; &lt;span class="hljs-title"&gt;transformed-belt&lt;/span&gt; [xf]
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [ch (&lt;span class="hljs-name"&gt;chan&lt;/span&gt; &lt;span class="hljs-number"&gt;1&lt;/span&gt; xf)]
    (&lt;span class="hljs-name"&gt;thread&lt;/span&gt;
      (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;loop&lt;/span&gt;&lt;/span&gt; []
        (&lt;span class="hljs-name"&gt;when-some&lt;/span&gt; [value (&lt;span class="hljs-name"&gt;&amp;lt;!!&lt;/span&gt; ch)]
          (&lt;span class="hljs-name"&gt;println&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;Value:&amp;quot;&lt;/span&gt; (&lt;span class="hljs-name"&gt;pr-str&lt;/span&gt; value)))
          (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;recur&lt;/span&gt;&lt;/span&gt;)))
    ch))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This fires up a process working at the receiving end of the conveyor belt. It will print out any transformed values as soon as they become available. Typing at the REPL, we will assume the role of producer, putting data on the belt.&lt;/p&gt;&lt;p&gt;Like this:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;def&lt;/span&gt; &lt;span class="hljs-title"&gt;b&lt;/span&gt; (&lt;span class="hljs-name"&gt;transformed-belt&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;map&lt;/span&gt;&lt;/span&gt; inc)))
(&lt;span class="hljs-name"&gt;&amp;gt;!!&lt;/span&gt; b &lt;span class="hljs-number"&gt;2&lt;/span&gt;)
&lt;span class="hljs-comment"&gt;; Value: 3&lt;/span&gt;
(&lt;span class="hljs-name"&gt;&amp;gt;!!&lt;/span&gt; b &lt;span class="hljs-number"&gt;42&lt;/span&gt;)
&lt;span class="hljs-comment"&gt;; Value: 43&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;It works! We’re putting in numbers, and out come the incremented ones.&lt;/p&gt;&lt;p&gt;When we’re done experimenting with the belt, we need to &lt;code&gt;close!&lt;/code&gt; it. This will cause the worker thread to shutdown.&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;close!&lt;/span&gt; b)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now experiment with something more complex, like that combined transducer we’ve talked about before:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;def&lt;/span&gt; &lt;span class="hljs-title"&gt;b&lt;/span&gt; (&lt;span class="hljs-name"&gt;transformed-belt&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;comp&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;map&lt;/span&gt;&lt;/span&gt; inc) (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;remove&lt;/span&gt;&lt;/span&gt; odd?))))
(&lt;span class="hljs-name"&gt;&amp;gt;!!&lt;/span&gt; b &lt;span class="hljs-number"&gt;1&lt;/span&gt;)
&lt;span class="hljs-comment"&gt;; Value: 2&lt;/span&gt;
(&lt;span class="hljs-name"&gt;&amp;gt;!!&lt;/span&gt; b &lt;span class="hljs-number"&gt;2&lt;/span&gt;)
(&lt;span class="hljs-name"&gt;&amp;gt;!!&lt;/span&gt; b &lt;span class="hljs-number"&gt;3&lt;/span&gt;)
&lt;span class="hljs-comment"&gt;; Value: 4&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We got the transformed 1 and 3, but the intermediate value for 2 was odd, so it was snatched by the gnome and we never saw it.&lt;/p&gt;&lt;p&gt;There’s even more fun to be had! Let’s try &lt;code&gt;(partition-all 3)&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;close!&lt;/span&gt; b)
(&lt;span class="hljs-keyword"&gt;def&lt;/span&gt; &lt;span class="hljs-title"&gt;b&lt;/span&gt; (&lt;span class="hljs-name"&gt;transformed-belt&lt;/span&gt; (&lt;span class="hljs-name"&gt;partition-all&lt;/span&gt; &lt;span class="hljs-number"&gt;3&lt;/span&gt;)))
(&lt;span class="hljs-name"&gt;&amp;gt;!!&lt;/span&gt; b &lt;span class="hljs-number"&gt;1&lt;/span&gt;)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Nothing…&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&amp;gt;!!&lt;/span&gt; b &lt;span class="hljs-number"&gt;2&lt;/span&gt;)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Still nothing…&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&amp;gt;!!&lt;/span&gt; b &lt;span class="hljs-number"&gt;3&lt;/span&gt;)
&lt;span class="hljs-comment"&gt;; Value: [1 2 3]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Blammo! Our gnome is now packaging together incoming items into bundles of three, caching them in the interim while the bundle is not complete yet. But if we close the input prematurely, it will acknowledge and produce the incomplete bundle:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&amp;gt;!!&lt;/span&gt; b &lt;span class="hljs-number"&gt;4&lt;/span&gt;)
(&lt;span class="hljs-name"&gt;&amp;gt;!!&lt;/span&gt; b &lt;span class="hljs-number"&gt;5&lt;/span&gt;)
(&lt;span class="hljs-name"&gt;close!&lt;/span&gt; b)
&lt;span class="hljs-comment"&gt;; Value: [4 5]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In fact, &lt;code&gt;partition-all&lt;/code&gt; is what prompted me to write this post. That code at work I mentioned actually included a transducer composition that had a &lt;code&gt;(net.cgrand.xforms/into [])&lt;/code&gt; in it. That transducer (from Christophe Grand’s &lt;a href="https://github.com/cgrand/xforms/"&gt;xforms&lt;/a&gt; library) accumulates data until there’s nothing more to accumulate, and then emits all of it as one large vector. By replacing it with &lt;code&gt;partition-all&lt;/code&gt;, I altered the downstream processing to handle multiple smaller batches rather than one huge batch, improving the system’s latency.&lt;/p&gt;&lt;p&gt;A small change for a huge win. Clojure continues to amaze me.&lt;/p&gt;&lt;p&gt;Plus, it’s fun to make JS-less animations in SVG. :)&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2023-07-20:post:iterating-trees</id>
    <title>A visual tree iterator in Rust</title>
    <link href="http://blog.danieljanus.pl/iterating-trees/"/>
    <updated>2023-07-20T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;My &lt;a href="/2023/07/06/learning-to-learn-rust/"&gt;adventure with learning Rust&lt;/a&gt; continues. As a quick recap from the previous post, I’m writing a &lt;a href="https://github.com/nathell/treeviewer"&gt;tree viewer&lt;/a&gt;. I have now completed another major milestone, which is to rewrite the tree-printing function to use an iterator. (Rationale: it makes the code more reusable – I can, for instance, easily implement a tree-drawing view for &lt;a href="https://github.com/gyscos/cursive"&gt;Cursive&lt;/a&gt; with it.)&lt;/p&gt;&lt;p&gt;And, as usual, I’ve fallen into many traps before arriving at a working version. In this post, I’ll reflect on the mistakes I’ve made.&lt;/p&gt;&lt;h2 id="the-problem"&gt;The problem&lt;/h2&gt;&lt;p&gt;Let’s start with establishing the problem. Given a &lt;code&gt;Tree&lt;/code&gt; struct defined as:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;&lt;span class="hljs-keyword"&gt;pub&lt;/span&gt; &lt;span class="hljs-keyword"&gt;struct&lt;/span&gt; &lt;span class="hljs-title class_"&gt;Tree&lt;/span&gt;&amp;lt;T&amp;gt; {
    value: T,
    children: &lt;span class="hljs-type"&gt;Vec&lt;/span&gt;&amp;lt;Tree&amp;lt;T&amp;gt;&amp;gt;,
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;I want it to have a &lt;code&gt;lines()&lt;/code&gt; method returning an iterator, so that I can implement &lt;code&gt;print_tree&lt;/code&gt; as:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;&lt;span class="hljs-keyword"&gt;fn&lt;/span&gt; &lt;span class="hljs-title function_"&gt;print_tree&lt;/span&gt;&amp;lt;T: Display&amp;gt;(t: &amp;amp;Tree&amp;lt;T&amp;gt;) {
    &lt;span class="hljs-keyword"&gt;for&lt;/span&gt; &lt;span class="hljs-variable"&gt;line&lt;/span&gt; &lt;span class="hljs-keyword"&gt;in&lt;/span&gt; t.&lt;span class="hljs-title function_ invoke__"&gt;lines&lt;/span&gt;() {
        &lt;span class="hljs-built_in"&gt;println!&lt;/span&gt;(&lt;span class="hljs-string"&gt;&amp;quot;{}&amp;quot;&lt;/span&gt;, line);
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;and have the output identical to the previous version.&lt;/p&gt;&lt;h2 id="the-algorithm"&gt;The algorithm&lt;/h2&gt;&lt;p&gt;Before we dive into the iterator sea, let’s have a look at the algorithm. Imagine that we’re printing the tree (in sexp-notation) &lt;code&gt;(root (one (two) (three (four))) (five (six)))&lt;/code&gt;. This is its dissected visual representation:&lt;/p&gt;&lt;img src="/img/blog/tree-anatomy.png" alt="Anatomy of a tree"&gt;
&lt;p&gt;Each line consists of three concatenated elements, which I call “parent prefix”, “immediate prefix”, and “node value”. The immediate prefix is always (except for the root node) &lt;code&gt;"└─ "&lt;/code&gt; or &lt;code&gt;"├─ "&lt;/code&gt;, depending on whether the node in question is the last child of its parent or not. The parent prefix has variable length that depends on the node’s depth, and has the following properties:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;For any node, all its subnodes’ parent prefixes start with its parent prefix.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;For any node, the parent prefixes of its direct children are obtained by appending &lt;code&gt;"   "&lt;/code&gt; or &lt;code&gt;"│  "&lt;/code&gt; to its own parent prefix, again depending on whether the node is its parent’s last child or not.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;This gives rise to the following algorithm that calls itself recursively:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;&lt;span class="hljs-keyword"&gt;fn&lt;/span&gt; &lt;span class="hljs-title function_"&gt;print_tree&lt;/span&gt;&amp;lt;T&amp;gt;(t: &amp;amp;Tree&amp;lt;T&amp;gt;,
                 parent_prefix: &amp;amp;&lt;span class="hljs-type"&gt;str&lt;/span&gt;,
                 immediate_prefix: &amp;amp;&lt;span class="hljs-type"&gt;str&lt;/span&gt;,
                 parent_suffix: &amp;amp;&lt;span class="hljs-type"&gt;str&lt;/span&gt;)
    &lt;span class="hljs-keyword"&gt;where&lt;/span&gt; T: Display
{
    &lt;span class="hljs-comment"&gt;// print the line for node t&lt;/span&gt;
    &lt;span class="hljs-built_in"&gt;println!&lt;/span&gt;(&lt;span class="hljs-string"&gt;&amp;quot;{0}{1}{2}&amp;quot;&lt;/span&gt;, parent_prefix, immediate_prefix, t.value);

    &lt;span class="hljs-comment"&gt;// print all children of t recursively&lt;/span&gt;
    &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-keyword"&gt;mut &lt;/span&gt;&lt;span class="hljs-variable"&gt;it&lt;/span&gt; = t.children.&lt;span class="hljs-title function_ invoke__"&gt;iter&lt;/span&gt;().&lt;span class="hljs-title function_ invoke__"&gt;peekable&lt;/span&gt;();
    &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;child_prefix&lt;/span&gt; = &lt;span class="hljs-built_in"&gt;format!&lt;/span&gt;(&lt;span class="hljs-string"&gt;&amp;quot;{0}{1}&amp;quot;&lt;/span&gt;, parent_prefix, parent_suffix);

    &lt;span class="hljs-keyword"&gt;while&lt;/span&gt; &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;Some&lt;/span&gt;(child) = it.&lt;span class="hljs-title function_ invoke__"&gt;next&lt;/span&gt;() {
        &lt;span class="hljs-keyword"&gt;match&lt;/span&gt; it.&lt;span class="hljs-title function_ invoke__"&gt;peek&lt;/span&gt;() {
            &lt;span class="hljs-literal"&gt;None&lt;/span&gt;    =&amp;gt; &lt;span class="hljs-title function_ invoke__"&gt;print_tree&lt;/span&gt;(child, &amp;amp;child_prefix, &lt;span class="hljs-string"&gt;&amp;quot;└─ &amp;quot;&lt;/span&gt;, &lt;span class="hljs-string"&gt;&amp;quot;   &amp;quot;&lt;/span&gt;),
            &lt;span class="hljs-title function_ invoke__"&gt;Some&lt;/span&gt;(_) =&amp;gt; &lt;span class="hljs-title function_ invoke__"&gt;print_tree&lt;/span&gt;(child, &amp;amp;child_prefix, &lt;span class="hljs-string"&gt;&amp;quot;├─ &amp;quot;&lt;/span&gt;, &lt;span class="hljs-string"&gt;&amp;quot;│  &amp;quot;&lt;/span&gt;),
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The three extra string arguments start out as empty strings and become populated as the algorithm descends into the tree. The implementation uses a &lt;a href="https://doc.rust-lang.org/stable/std/iter/struct.Peekable.html"&gt;peekable&lt;/a&gt; iterator over the &lt;code&gt;children&lt;/code&gt; vector to construct the prefixes appropriately.&lt;/p&gt;&lt;h2 id="building-an-iterator,-take-1"&gt;Building an iterator, take 1&lt;/h2&gt;&lt;p&gt;So the printing implementation is recursive. How do we write a recursive iterator in Rust? Is it even possible? I initially thought I would have to replace the recursion with an explicit stack stored in the iterator’s mutable state, started to write some code, and promptly got lost.&lt;/p&gt;&lt;p&gt;I then searched for the state-of-the-art on iterating through trees, and found &lt;a href="https://fasterthanli.me/articles/recursive-iterators-rust"&gt;this post&lt;/a&gt; by Amos Wenger. You might want to read it first before continuing; my final implementation ended up being an adaptation of one of the techniques described there.&lt;/p&gt;&lt;p&gt;My definition of tree is slightly different than Amos’s (mine has only one value in a node), but it’s easy enough to adapt his final solution to iterate over its values:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;&lt;span class="hljs-keyword"&gt;impl&lt;/span&gt;&amp;lt;T&amp;gt; Tree&amp;lt;T&amp;gt; &lt;span class="hljs-keyword"&gt;where&lt;/span&gt; T: Display {
    &lt;span class="hljs-keyword"&gt;pub&lt;/span&gt; &lt;span class="hljs-keyword"&gt;fn&lt;/span&gt; &lt;span class="hljs-title function_"&gt;lines&lt;/span&gt;&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;&amp;gt;(&amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt; &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;) &lt;span class="hljs-punctuation"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="hljs-type"&gt;Box&lt;/span&gt;&amp;lt;&lt;span class="hljs-keyword"&gt;dyn&lt;/span&gt; &lt;span class="hljs-built_in"&gt;Iterator&lt;/span&gt;&amp;lt;Item = &lt;span class="hljs-type"&gt;String&lt;/span&gt;&amp;gt; + &lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;&amp;gt; {
        &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;child_iter&lt;/span&gt; = &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.children.&lt;span class="hljs-title function_ invoke__"&gt;iter&lt;/span&gt;().&lt;span class="hljs-title function_ invoke__"&gt;map&lt;/span&gt;(|n| n.&lt;span class="hljs-title function_ invoke__"&gt;lines&lt;/span&gt;()).&lt;span class="hljs-title function_ invoke__"&gt;flatten&lt;/span&gt;();

        &lt;span class="hljs-type"&gt;Box&lt;/span&gt;::&lt;span class="hljs-title function_ invoke__"&gt;new&lt;/span&gt;(
            &lt;span class="hljs-title function_ invoke__"&gt;once&lt;/span&gt;(&lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.value.&lt;span class="hljs-title function_ invoke__"&gt;to_string&lt;/span&gt;()).&lt;span class="hljs-title function_ invoke__"&gt;chain&lt;/span&gt;(child_iter)
        )
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;(Note the &lt;code&gt;dyn&lt;/code&gt; keyword; Rust started requiring it in this context sometime after Amos’s article was published.)&lt;/p&gt;&lt;p&gt;Clever! This sidesteps the issue of writing a custom iterator altogether, by chaining some standard ones, wrapping them in a box and sprinkling some lifetime annotation magic powder to appease the borrow checker. We also make it explicit that the iterator is returning strings, no matter what the type of tree nodes is.&lt;/p&gt;&lt;p&gt;&lt;em&gt;But…&lt;/em&gt; while it compiles and produces a sequence of strings, they don’t reflect the structure of the tree: there’s no pretty prefixing going on.&lt;/p&gt;&lt;p&gt;Let’s try to fix that. Clearly, the iterator-returning function will now need to take three additional arguments, just like &lt;code&gt;print_tree&lt;/code&gt; – the first one will now be a &lt;code&gt;String&lt;/code&gt; because we’ll be building it at runtime, and the other two are string literals so can just be &lt;code&gt;&amp;'static str&lt;/code&gt;s. Let’s try:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;&lt;span class="hljs-comment"&gt;// changing the name because we now accept extra params&lt;/span&gt;
&lt;span class="hljs-comment"&gt;// I want the original lines() to keep its signature&lt;/span&gt;
&lt;span class="hljs-keyword"&gt;pub&lt;/span&gt; &lt;span class="hljs-keyword"&gt;fn&lt;/span&gt; &lt;span class="hljs-title function_"&gt;prefixed_lines&lt;/span&gt;&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;&amp;gt;(&amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt; &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;,
                          parent_prefix: &lt;span class="hljs-type"&gt;String&lt;/span&gt;,
                          immediate_prefix: &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;static&lt;/span&gt; &lt;span class="hljs-type"&gt;str&lt;/span&gt;,
                          parent_suffix: &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;static&lt;/span&gt; &lt;span class="hljs-type"&gt;str&lt;/span&gt;)
                         &lt;span class="hljs-punctuation"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="hljs-type"&gt;Box&lt;/span&gt;&amp;lt;&lt;span class="hljs-keyword"&gt;dyn&lt;/span&gt; &lt;span class="hljs-built_in"&gt;Iterator&lt;/span&gt;&amp;lt;Item = &lt;span class="hljs-type"&gt;String&lt;/span&gt;&amp;gt; + &lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;&amp;gt;
{
    &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;value&lt;/span&gt; = &lt;span class="hljs-built_in"&gt;format!&lt;/span&gt;(&lt;span class="hljs-string"&gt;&amp;quot;{0}{1}{2}&amp;quot;&lt;/span&gt;, parent_prefix, immediate_prefix, &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.value);
    &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-keyword"&gt;mut &lt;/span&gt;&lt;span class="hljs-variable"&gt;peekable&lt;/span&gt; = &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.children.&lt;span class="hljs-title function_ invoke__"&gt;iter&lt;/span&gt;().&lt;span class="hljs-title function_ invoke__"&gt;peekable&lt;/span&gt;();
    &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;child_iter&lt;/span&gt; = peekable
        .&lt;span class="hljs-title function_ invoke__"&gt;map&lt;/span&gt;(|n| {
            &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;child_prefix&lt;/span&gt; = &lt;span class="hljs-built_in"&gt;format!&lt;/span&gt;(&lt;span class="hljs-string"&gt;&amp;quot;{0}{1}&amp;quot;&lt;/span&gt;, parent_prefix, parent_suffix);
            &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;last&lt;/span&gt; = !peekable.&lt;span class="hljs-title function_ invoke__"&gt;peek&lt;/span&gt;().&lt;span class="hljs-title function_ invoke__"&gt;is_some&lt;/span&gt;();
            &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;immediate_prefix&lt;/span&gt; = &lt;span class="hljs-keyword"&gt;if&lt;/span&gt; last { &lt;span class="hljs-string"&gt;&amp;quot;└─ &amp;quot;&lt;/span&gt; } &lt;span class="hljs-keyword"&gt;else&lt;/span&gt; { &lt;span class="hljs-string"&gt;&amp;quot;├─ &amp;quot;&lt;/span&gt; };
            &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;parent_suffix&lt;/span&gt; = &lt;span class="hljs-keyword"&gt;if&lt;/span&gt; last { &lt;span class="hljs-string"&gt;&amp;quot;   &amp;quot;&lt;/span&gt; } &lt;span class="hljs-keyword"&gt;else&lt;/span&gt; { &lt;span class="hljs-string"&gt;&amp;quot;│  &amp;quot;&lt;/span&gt; };
            n.&lt;span class="hljs-title function_ invoke__"&gt;prefixed_lines&lt;/span&gt;(child_prefix, immediate_prefix, parent_suffix)
        })
        .&lt;span class="hljs-title function_ invoke__"&gt;flatten&lt;/span&gt;();

    &lt;span class="hljs-type"&gt;Box&lt;/span&gt;::&lt;span class="hljs-title function_ invoke__"&gt;new&lt;/span&gt;(
        &lt;span class="hljs-title function_ invoke__"&gt;once&lt;/span&gt;(value).&lt;span class="hljs-title function_ invoke__"&gt;chain&lt;/span&gt;(child_iter)
    )
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And, sure enough, it doesn’t compile. One of the things that Rust complains about is:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;error[E0373]: closure may outlive the current function,
    but it borrows `peekable`, which is owned by the current function
  --&gt; src/main.rs:55:18
   |
55 |     .map(|n| {
   |          ^^^ may outlive borrowed value `peekable`
56 |         let child_prefix = format!("{0}{1}"...
57 |         let last = !peekable.peek().is_some();
   |                     -------- `peekable` is borrowed here
   |
note: closure is returned here
  --&gt; src/main.rs:64:9
   |
64 | Box::new(once(value).chain(child_iter))
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: to force the closure to take ownership of `peekable`
      (and any other referenced variables), use the `move` keyword
   |
55 |     .map(move |n| {
   |          ++++
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;So trying to borrow the iterator from within the closure passed to &lt;code&gt;map()&lt;/code&gt; is non-kosher. I’m not sure where the “may outlive the current function” comes from, but I think this is because &lt;a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map"&gt;the iterator returned by &lt;code&gt;map&lt;/code&gt; is lazy&lt;/a&gt;, and so the closure needs to be able to live for at least as long as the resulting iterator does. The suggestion of using &lt;code&gt;move&lt;/code&gt; doesn’t work, because it then invalidates the &lt;code&gt;map&lt;/code&gt; call. (Rust complained about borrowing &lt;code&gt;parent_prefix&lt;/code&gt; and &lt;code&gt;parent_suffix&lt;/code&gt; as well, and &lt;code&gt;move&lt;/code&gt; does work for those.)&lt;/p&gt;&lt;h2 id="taking-a-step-back"&gt;Taking a step back&lt;/h2&gt;&lt;p&gt;I was not able to find a way out of this conundrum. But after re-reading Amos’s post, I’ve decided to revisit his “bad” approach, with a custom iterator (which I now think is actually not bad at all). It made all the more sense to me when I considered future extensibility: eventually I want to be able to render certain subtrees collapsed, and I want the iterator to know about that.&lt;/p&gt;&lt;p&gt;It took me a while to understand how that &lt;a href="https://play.rust-lang.org/?version=stable&amp;amp;mode=debug&amp;amp;edition=2018&amp;amp;gist=c2cf6a965c3637553edd95eecc1993cd"&gt;custom iterator&lt;/a&gt; works. It doesn’t have an explicit stack and doesn’t try to “de-recursivize” the process! Instead, it holds two sub-iterators, one initially iterating over the node values (&lt;code&gt;viter&lt;/code&gt;) and the other over children (&lt;code&gt;citer&lt;/code&gt;). The &lt;code&gt;next()&lt;/code&gt; method just tries &lt;code&gt;viter&lt;/code&gt; first; if it returns nothing, then a next subtree is picked from &lt;code&gt;citer&lt;/code&gt;, and &lt;code&gt;viter&lt;/code&gt; (by now already consumed) &lt;em&gt;is replaced by another instance of the same iterator, but for that subtree&lt;/em&gt;.&lt;/p&gt;&lt;p&gt;Meditate on this for a while. There’s a lot going on here.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;&lt;code&gt;viter&lt;/code&gt; starts out as an iterator over a vector (a &lt;code&gt;std::slice::Iter&lt;/code&gt;), and then gets replaced by a tree iterator (Amos’s &lt;code&gt;NodeIter&lt;/code&gt;).&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;This is possible because it’s declared as a &lt;code&gt;Box&amp;lt;Iterator&amp;lt;Item = &amp;'a i32&gt; + 'a&gt;&lt;/code&gt;. TIL: in Rust, you can’t use a trait directly as a type for a struct field (because there’s no telling what its size will be), but you &lt;em&gt;can&lt;/em&gt; put it into a &lt;code&gt;Box&lt;/code&gt; (or, I guess, &lt;code&gt;Rc&lt;/code&gt; or &lt;code&gt;Arc&lt;/code&gt;). Polymorphism, baby!&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;Recursion is achieved by having &lt;code&gt;NodeIter&lt;/code&gt; contain a member that, at times, is itself another &lt;code&gt;NodeIter&lt;/code&gt;; whereas the correct behaviour is obtained by having those &lt;code&gt;NodeIters&lt;/code&gt; instantiated at the right moment.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Whoa. Now &lt;em&gt;that’s&lt;/em&gt; clever. I probably wouldn’t have thought about this. It’s good to be standing on the shoulders of giants. Thanks, Amos.&lt;/p&gt;&lt;p&gt;Anyway, let’s adapt it to our use-case and add the prefixes to the iterator’s state:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;&lt;span class="hljs-keyword"&gt;pub&lt;/span&gt; &lt;span class="hljs-keyword"&gt;struct&lt;/span&gt; &lt;span class="hljs-title class_"&gt;TreeIterator&lt;/span&gt;&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;, T&amp;gt; {
    parent_prefix: &lt;span class="hljs-type"&gt;String&lt;/span&gt;,
    immediate_prefix: &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;static&lt;/span&gt; &lt;span class="hljs-type"&gt;str&lt;/span&gt;,
    parent_suffix: &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;static&lt;/span&gt; &lt;span class="hljs-type"&gt;str&lt;/span&gt;,
    viter: &lt;span class="hljs-type"&gt;Box&lt;/span&gt;&amp;lt;&lt;span class="hljs-keyword"&gt;dyn&lt;/span&gt; &lt;span class="hljs-built_in"&gt;Iterator&lt;/span&gt;&amp;lt;Item = &lt;span class="hljs-type"&gt;String&lt;/span&gt;&amp;gt; + &lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;&amp;gt;,
    citer: &lt;span class="hljs-type"&gt;Box&lt;/span&gt;&amp;lt;&lt;span class="hljs-keyword"&gt;dyn&lt;/span&gt; &lt;span class="hljs-built_in"&gt;Iterator&lt;/span&gt;&amp;lt;Item = &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt; Tree&amp;lt;T&amp;gt;&amp;gt; + &lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;&amp;gt;,
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And our iterator implementation follows Amos’s, except that we handle the prefixes and initialize &lt;code&gt;viter&lt;/code&gt; with a &lt;a href="https://doc.rust-lang.org/std/iter/struct.Once.html"&gt;&lt;code&gt;Once&lt;/code&gt;&lt;/a&gt; iterator:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;&lt;span class="hljs-keyword"&gt;impl&lt;/span&gt;&amp;lt;T&amp;gt; Tree&amp;lt;T&amp;gt; &lt;span class="hljs-keyword"&gt;where&lt;/span&gt; T: Display {
    &lt;span class="hljs-keyword"&gt;pub&lt;/span&gt; &lt;span class="hljs-keyword"&gt;fn&lt;/span&gt; &lt;span class="hljs-title function_"&gt;prefixed_lines&lt;/span&gt;&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;&amp;gt;(&amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt; &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;,
                      parent_prefix: &lt;span class="hljs-type"&gt;String&lt;/span&gt;,
                      immediate_prefix: &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;static&lt;/span&gt; &lt;span class="hljs-type"&gt;str&lt;/span&gt;,
                      parent_suffix: &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;static&lt;/span&gt; &lt;span class="hljs-type"&gt;str&lt;/span&gt;)
                     &lt;span class="hljs-punctuation"&gt;-&amp;gt;&lt;/span&gt; TreeIterator&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;, T&amp;gt;
    {
        TreeIterator {
            parent_prefix: parent_prefix,
            immediate_prefix: immediate_prefix,
            parent_suffix: parent_suffix,
            viter: &lt;span class="hljs-type"&gt;Box&lt;/span&gt;::&lt;span class="hljs-title function_ invoke__"&gt;new&lt;/span&gt;(&lt;span class="hljs-title function_ invoke__"&gt;once&lt;/span&gt;(&lt;span class="hljs-built_in"&gt;format!&lt;/span&gt;(&lt;span class="hljs-string"&gt;&amp;quot;{}&amp;quot;&lt;/span&gt;, &amp;amp;&lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.value))),
            citer: &lt;span class="hljs-type"&gt;Box&lt;/span&gt;::&lt;span class="hljs-title function_ invoke__"&gt;new&lt;/span&gt;(&lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.children.&lt;span class="hljs-title function_ invoke__"&gt;iter&lt;/span&gt;().&lt;span class="hljs-title function_ invoke__"&gt;peekable&lt;/span&gt;()),
        }
    }
}

&lt;span class="hljs-keyword"&gt;impl&lt;/span&gt;&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;, T&amp;gt; &lt;span class="hljs-built_in"&gt;Iterator&lt;/span&gt; &lt;span class="hljs-keyword"&gt;for&lt;/span&gt; &lt;span class="hljs-title class_"&gt;TreeIterator&lt;/span&gt;&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;, T&amp;gt; &lt;span class="hljs-keyword"&gt;where&lt;/span&gt; T: Display {
    &lt;span class="hljs-keyword"&gt;type&lt;/span&gt; &lt;span class="hljs-title class_"&gt;Item&lt;/span&gt; = &lt;span class="hljs-type"&gt;String&lt;/span&gt;;

    &lt;span class="hljs-keyword"&gt;fn&lt;/span&gt; &lt;span class="hljs-title function_"&gt;next&lt;/span&gt;(&amp;amp;&lt;span class="hljs-keyword"&gt;mut&lt;/span&gt; &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;) &lt;span class="hljs-punctuation"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="hljs-type"&gt;Option&lt;/span&gt;&amp;lt;&lt;span class="hljs-keyword"&gt;Self&lt;/span&gt;::Item&amp;gt; {
        &lt;span class="hljs-keyword"&gt;if&lt;/span&gt; &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;Some&lt;/span&gt;(val) = &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.viter.&lt;span class="hljs-title function_ invoke__"&gt;next&lt;/span&gt;() {
            &lt;span class="hljs-title function_ invoke__"&gt;Some&lt;/span&gt;(&lt;span class="hljs-built_in"&gt;format!&lt;/span&gt;(&lt;span class="hljs-string"&gt;&amp;quot;{0}{1}{2}&amp;quot;&lt;/span&gt;, &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.parent_prefix, &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.immediate_prefix, val))
        } &lt;span class="hljs-keyword"&gt;else&lt;/span&gt; &lt;span class="hljs-keyword"&gt;if&lt;/span&gt; &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;Some&lt;/span&gt;(child) = &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.citer.&lt;span class="hljs-title function_ invoke__"&gt;next&lt;/span&gt;() {
            &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;last&lt;/span&gt; = !&lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.citer.&lt;span class="hljs-title function_ invoke__"&gt;peek&lt;/span&gt;().&lt;span class="hljs-title function_ invoke__"&gt;is_some&lt;/span&gt;();
            &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;immediate_prefix&lt;/span&gt; = &lt;span class="hljs-keyword"&gt;if&lt;/span&gt; last { &lt;span class="hljs-string"&gt;&amp;quot;└─ &amp;quot;&lt;/span&gt; } &lt;span class="hljs-keyword"&gt;else&lt;/span&gt; { &lt;span class="hljs-string"&gt;&amp;quot;├─ &amp;quot;&lt;/span&gt; };
            &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;parent_suffix&lt;/span&gt; = &lt;span class="hljs-keyword"&gt;if&lt;/span&gt; last { &lt;span class="hljs-string"&gt;&amp;quot;   &amp;quot;&lt;/span&gt; } &lt;span class="hljs-keyword"&gt;else&lt;/span&gt; { &lt;span class="hljs-string"&gt;&amp;quot;│  &amp;quot;&lt;/span&gt; };
            &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;subprefix&lt;/span&gt; = &lt;span class="hljs-built_in"&gt;format!&lt;/span&gt;(&lt;span class="hljs-string"&gt;&amp;quot;{0}{1}&amp;quot;&lt;/span&gt;, &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.parent_prefix, &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.parent_suffix);
            &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.viter = &lt;span class="hljs-type"&gt;Box&lt;/span&gt;::&lt;span class="hljs-title function_ invoke__"&gt;new&lt;/span&gt;(child.&lt;span class="hljs-title function_ invoke__"&gt;prefixed_lines&lt;/span&gt;(subprefix, immediate_prefix, parent_suffix));
            &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.&lt;span class="hljs-title function_ invoke__"&gt;next&lt;/span&gt;()
        } &lt;span class="hljs-keyword"&gt;else&lt;/span&gt; {
            &lt;span class="hljs-literal"&gt;None&lt;/span&gt;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Looks sensible, right? Except (you guessed it!) it doesn’t compile:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;error[E0599]: no method named `peek` found &lt;span class="hljs-keyword"&gt;for&lt;/span&gt; &lt;span class="hljs-title class_"&gt;struct&lt;/span&gt;
    `&lt;span class="hljs-type"&gt;Box&lt;/span&gt;&amp;lt;(&lt;span class="hljs-keyword"&gt;dyn&lt;/span&gt; &lt;span class="hljs-built_in"&gt;Iterator&lt;/span&gt;&amp;lt;Item = &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt; Tree&amp;lt;T&amp;gt;&amp;gt; + &lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;)&amp;gt;` &lt;span class="hljs-keyword"&gt;in&lt;/span&gt; the current scope
  -&lt;span class="hljs-punctuation"&gt;-&amp;gt;&lt;/span&gt; src/main.rs:&lt;span class="hljs-number"&gt;38&lt;/span&gt;:&lt;span class="hljs-number"&gt;36&lt;/span&gt;
   |
&lt;span class="hljs-number"&gt;38&lt;/span&gt; |     &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;last&lt;/span&gt; = !&lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.citer.&lt;span class="hljs-title function_ invoke__"&gt;peek&lt;/span&gt;().&lt;span class="hljs-title function_ invoke__"&gt;is_some&lt;/span&gt;();
   |                            ^^^^ help: there is a method with a
   |                                 similar name: `peekable`
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Ah, right. We’ve forgotten to tell Rust that &lt;code&gt;citer&lt;/code&gt; contains a &lt;code&gt;Peekable&lt;/code&gt;. Let’s fix that:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;&lt;span class="hljs-keyword"&gt;pub&lt;/span&gt; &lt;span class="hljs-keyword"&gt;struct&lt;/span&gt; &lt;span class="hljs-title class_"&gt;TreeIterator&lt;/span&gt;&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;, T&amp;gt; {
    &lt;span class="hljs-comment"&gt;// … other fields as before&lt;/span&gt;
    citer: &lt;span class="hljs-type"&gt;Box&lt;/span&gt;&amp;lt;Peekable&amp;lt;&lt;span class="hljs-keyword"&gt;dyn&lt;/span&gt; &lt;span class="hljs-built_in"&gt;Iterator&lt;/span&gt;&amp;lt;Item = &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt; Tree&amp;lt;T&amp;gt;&amp;gt; + &lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;&amp;gt;&amp;gt;,
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Nope, that doesn’t compile either:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;error[E0277]: the size &lt;span class="hljs-keyword"&gt;for&lt;/span&gt; &lt;span class="hljs-title class_"&gt;values&lt;/span&gt; of &lt;span class="hljs-keyword"&gt;type&lt;/span&gt; `(&lt;span class="hljs-keyword"&gt;dyn&lt;/span&gt; &lt;span class="hljs-built_in"&gt;Iterator&lt;/span&gt;&amp;lt;Item = &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt; Tree&amp;lt;T&amp;gt;&amp;gt; + &lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;)`
    cannot be known at compilation time
  -&lt;span class="hljs-punctuation"&gt;-&amp;gt;&lt;/span&gt; src/main.rs:&lt;span class="hljs-number"&gt;16&lt;/span&gt;:&lt;span class="hljs-number"&gt;12&lt;/span&gt;
   |
&lt;span class="hljs-number"&gt;16&lt;/span&gt; |     citer: &lt;span class="hljs-type"&gt;Box&lt;/span&gt;&amp;lt;Peekable&amp;lt;&lt;span class="hljs-keyword"&gt;dyn&lt;/span&gt; &lt;span class="hljs-built_in"&gt;Iterator&lt;/span&gt;&amp;lt;Item = &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt; Tree&amp;lt;T&amp;gt;&amp;gt; + &lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;&amp;gt;&amp;gt;,
   |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |            doesn&lt;span class="hljs-symbol"&gt;&amp;#x27;t&lt;/span&gt; have a size known at compile-time
   |
   = help: the &lt;span class="hljs-keyword"&gt;trait&lt;/span&gt; `&lt;span class="hljs-built_in"&gt;Sized&lt;/span&gt;` is not implemented &lt;span class="hljs-keyword"&gt;for&lt;/span&gt;
           `(&lt;span class="hljs-keyword"&gt;dyn&lt;/span&gt; &lt;span class="hljs-built_in"&gt;Iterator&lt;/span&gt;&amp;lt;Item = &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt; Tree&amp;lt;T&amp;gt;&amp;gt; + &lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;)`
note: required by a bound &lt;span class="hljs-keyword"&gt;in&lt;/span&gt; `Peekable`
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Bummer. We can put a trait of unknown size in a &lt;code&gt;Box&lt;/code&gt;, but we can’t put a &lt;code&gt;Peekable&lt;/code&gt; in between! &lt;code&gt;Peekable&lt;/code&gt; needs to know the size of its contents at compile time. Trying to convince it by sprinkling &lt;code&gt;+ Sized&lt;/code&gt; in various places doesn’t work.&lt;/p&gt;&lt;p&gt;Fortunately, we know the &lt;em&gt;actual&lt;/em&gt; type of &lt;code&gt;citer&lt;/code&gt;. It’s an iterator over &lt;code&gt;Vec&amp;lt;Tree&amp;lt;T&gt;&gt;&lt;/code&gt;, so it’s a &lt;code&gt;std::slice::Iter&amp;lt;Tree&amp;lt;T&gt;&gt;&lt;/code&gt;. Let’s put it in the definition of &lt;code&gt;TreeIterator&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;&lt;span class="hljs-keyword"&gt;use&lt;/span&gt; std::slice::Iter;

&lt;span class="hljs-keyword"&gt;pub&lt;/span&gt; &lt;span class="hljs-keyword"&gt;struct&lt;/span&gt; &lt;span class="hljs-title class_"&gt;TreeIterator&lt;/span&gt;&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;, T&amp;gt; {
    &lt;span class="hljs-comment"&gt;// … other fields as before&lt;/span&gt;
    citer: &lt;span class="hljs-type"&gt;Box&lt;/span&gt;&amp;lt;Peekable&amp;lt;Iter&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;, Tree&amp;lt;T&amp;gt;&amp;gt;&amp;gt;&amp;gt;,
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And it compiles!&lt;/p&gt;&lt;h2 id="removing-the-root"&gt;Removing the root&lt;/h2&gt;&lt;p&gt;Here’s what happens when you try to run treeviewer with this implementation on a very simple tree:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs bash"&gt;$ &lt;span class="hljs-built_in"&gt;echo&lt;/span&gt; -e &lt;span class="hljs-string"&gt;&amp;#x27;one\ntwo&amp;#x27;&lt;/span&gt; | ./target/debug/treeviewer

├─ one
└─ two
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Seems good, but that empty line is worrying. That’s because treeviewer takes slash-separated paths as input, and because the paths can begin with anything, it puts everything under a pre-existing root node with an empty &lt;code&gt;value&lt;/code&gt;. We don’t want the output to contain that root node.&lt;/p&gt;&lt;p&gt;Simple, right? We just need to initialize &lt;code&gt;viter&lt;/code&gt; with an empty iterator if one of the prefixes is also empty:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;&lt;span class="hljs-keyword"&gt;pub&lt;/span&gt; &lt;span class="hljs-keyword"&gt;fn&lt;/span&gt; &lt;span class="hljs-title function_"&gt;prefixed_lines&lt;/span&gt;&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;&amp;gt;(&amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt; &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;,
                          parent_prefix: &lt;span class="hljs-type"&gt;String&lt;/span&gt;,
                          immediate_prefix: &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;static&lt;/span&gt; &lt;span class="hljs-type"&gt;str&lt;/span&gt;,
                          parent_suffix: &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;static&lt;/span&gt; &lt;span class="hljs-type"&gt;str&lt;/span&gt;)
                         &lt;span class="hljs-punctuation"&gt;-&amp;gt;&lt;/span&gt; TreeIterator&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;, T&amp;gt;
{
    TreeIterator {
        &lt;span class="hljs-comment"&gt;// … other fields as before&lt;/span&gt;
        viter: &lt;span class="hljs-type"&gt;Box&lt;/span&gt;::&lt;span class="hljs-title function_ invoke__"&gt;new&lt;/span&gt;(&lt;span class="hljs-keyword"&gt;if&lt;/span&gt; immediate_prefix.&lt;span class="hljs-title function_ invoke__"&gt;is_empty&lt;/span&gt;() {
                           &lt;span class="hljs-title function_ invoke__"&gt;empty&lt;/span&gt;()
                        } &lt;span class="hljs-keyword"&gt;else&lt;/span&gt; {
                           &lt;span class="hljs-title function_ invoke__"&gt;once&lt;/span&gt;(&lt;span class="hljs-built_in"&gt;format!&lt;/span&gt;(&lt;span class="hljs-string"&gt;&amp;quot;{}&amp;quot;&lt;/span&gt;, &amp;amp;&lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.value))
                        }),
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And (this is becoming obvious by now) we’re rewarded by yet another interesting error message:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;error[E0308]: `&lt;span class="hljs-keyword"&gt;if&lt;/span&gt;` and `&lt;span class="hljs-keyword"&gt;else&lt;/span&gt;` have incompatible types
  -&lt;span class="hljs-punctuation"&gt;-&amp;gt;&lt;/span&gt; src/main.rs:&lt;span class="hljs-number"&gt;49&lt;/span&gt;:&lt;span class="hljs-number"&gt;32&lt;/span&gt;
   |
&lt;span class="hljs-number"&gt;46&lt;/span&gt; |   viter: &lt;span class="hljs-type"&gt;Box&lt;/span&gt;::&lt;span class="hljs-title function_ invoke__"&gt;new&lt;/span&gt;(&lt;span class="hljs-keyword"&gt;if&lt;/span&gt; immediate_prefix.&lt;span class="hljs-title function_ invoke__"&gt;is_empty&lt;/span&gt;() {
   |  _________________-
&lt;span class="hljs-number"&gt;47&lt;/span&gt; | |                    &lt;span class="hljs-title function_ invoke__"&gt;empty&lt;/span&gt;()
   | |                    ------- expected because of this
&lt;span class="hljs-number"&gt;48&lt;/span&gt; | |                 } &lt;span class="hljs-keyword"&gt;else&lt;/span&gt; {
&lt;span class="hljs-number"&gt;49&lt;/span&gt; | |                    &lt;span class="hljs-title function_ invoke__"&gt;once&lt;/span&gt;(&lt;span class="hljs-built_in"&gt;format!&lt;/span&gt;(&lt;span class="hljs-string"&gt;&amp;quot;{}&amp;quot;&lt;/span&gt;, &amp;amp;&lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.value))
   | |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   | |                      expected `Empty&amp;lt;_&amp;gt;`, found `Once&amp;lt;&lt;span class="hljs-type"&gt;String&lt;/span&gt;&amp;gt;`
&lt;span class="hljs-number"&gt;50&lt;/span&gt; | |                 }),
   | |_________________- `&lt;span class="hljs-keyword"&gt;if&lt;/span&gt;` and `&lt;span class="hljs-keyword"&gt;else&lt;/span&gt;` have incompatible types
   |
   = note: expected &lt;span class="hljs-keyword"&gt;struct&lt;/span&gt; `std::iter::Empty&amp;lt;_&amp;gt;`
              found &lt;span class="hljs-keyword"&gt;struct&lt;/span&gt; `std::iter::Once&amp;lt;&lt;span class="hljs-type"&gt;String&lt;/span&gt;&amp;gt;`
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Ahhh. Even though both branches of the &lt;code&gt;if&lt;/code&gt; expression have types that meet the trait requirement (&lt;code&gt;Iterator&lt;Item = String&gt;&lt;/code&gt;), these are &lt;em&gt;different types&lt;/em&gt;. Apparently, &lt;code&gt;if&lt;/code&gt; insists on both branches being the same type.&lt;/p&gt;&lt;p&gt;What we can do is lift the &lt;code&gt;if&lt;/code&gt; upwards:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;&lt;span class="hljs-keyword"&gt;pub&lt;/span&gt; &lt;span class="hljs-keyword"&gt;fn&lt;/span&gt; &lt;span class="hljs-title function_"&gt;prefixed_lines&lt;/span&gt;&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;&amp;gt;(&amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt; &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;,
                          parent_prefix: &lt;span class="hljs-type"&gt;String&lt;/span&gt;,
                          immediate_prefix: &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;static&lt;/span&gt; &lt;span class="hljs-type"&gt;str&lt;/span&gt;,
                          parent_suffix: &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;static&lt;/span&gt; &lt;span class="hljs-type"&gt;str&lt;/span&gt;)
                         &lt;span class="hljs-punctuation"&gt;-&amp;gt;&lt;/span&gt; TreeIterator&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;, T&amp;gt;
{
    &lt;span class="hljs-keyword"&gt;if&lt;/span&gt; immediate_prefix.&lt;span class="hljs-title function_ invoke__"&gt;is_empty&lt;/span&gt;() {
        TreeIterator {
            &lt;span class="hljs-comment"&gt;// … other fields as before&lt;/span&gt;
            viter: &lt;span class="hljs-type"&gt;Box&lt;/span&gt;::&lt;span class="hljs-title function_ invoke__"&gt;new&lt;/span&gt;(&lt;span class="hljs-title function_ invoke__"&gt;empty&lt;/span&gt;()),
        }
    } &lt;span class="hljs-keyword"&gt;else&lt;/span&gt; {
        TreeIterator {
            &lt;span class="hljs-comment"&gt;// … other fields as before, repeated&lt;/span&gt;
            viter: &lt;span class="hljs-type"&gt;Box&lt;/span&gt;::&lt;span class="hljs-title function_ invoke__"&gt;new&lt;/span&gt;(&lt;span class="hljs-title function_ invoke__"&gt;once&lt;/span&gt;(&lt;span class="hljs-built_in"&gt;format!&lt;/span&gt;(&lt;span class="hljs-string"&gt;&amp;quot;{}&amp;quot;&lt;/span&gt;, &amp;amp;&lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.value))),
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Yuck. We needed to duplicate most of the instantiation details of &lt;code&gt;TreeIterator&lt;/code&gt;. But at least it compiles and works – the root is gone!&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs bash"&gt;$ &lt;span class="hljs-built_in"&gt;echo&lt;/span&gt; -e &lt;span class="hljs-string"&gt;&amp;#x27;one\ntwo&amp;#x27;&lt;/span&gt; | ./target/debug/treeviewer
├─ one
└─ two
&lt;/code&gt;&lt;/pre&gt;&lt;h2 id="fixing-a-bug"&gt;Fixing a bug&lt;/h2&gt;&lt;p&gt;Or does it? Let’s try the original tree from our illustration:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs bash"&gt;$ &lt;span class="hljs-built_in"&gt;echo&lt;/span&gt; -e &lt;span class="hljs-string"&gt;&amp;#x27;one/two\none/three/four\nfive/six&amp;#x27;&lt;/span&gt; | ./target/debug/treeviewer
├─ one
├─ │  ├─ two
├─ │  └─ three
├─ │  └─ │     └─ four
└─ five
└─    └─ six
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Uh oh. It’s totally garbled. Time to go back to the drawing board.&lt;/p&gt;&lt;p&gt;It took me quite a few &lt;code&gt;println!()&lt;/code&gt; debugging statements to figure out what was going on. Remember, the &lt;code&gt;TreeIterator&lt;/code&gt; for the whole tree will contain a nested &lt;code&gt;TreeIterator&lt;/code&gt; in its &lt;code&gt;viter&lt;/code&gt; field, which in turn may contain another nested &lt;code&gt;TreeIterator&lt;/code&gt;, and so on. Each of these nested iterators eventually passes its value to the “parent” iterator… decorating it with prefixes, again and again!&lt;/p&gt;&lt;p&gt;To fix this, we need to differentiate between two cases:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;&lt;span&gt;We’re producing the value for the node we’re holding (that’s when we need the prefixes);&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;We’re propagating up the value returned by &lt;code&gt;viter&lt;/code&gt; that holds a nested &lt;code&gt;TreeIterator&lt;/code&gt; (in this case we need to return it unchanged).&lt;/span&gt;&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;We’ll add two more fields to &lt;code&gt;TreeIterator&lt;/code&gt;: a boolean indicating whether we’ve already &lt;code&gt;emitted&lt;/code&gt; the value at the node in question, and a reference to that &lt;code&gt;value&lt;/code&gt; itself.&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;&lt;span class="hljs-keyword"&gt;pub&lt;/span&gt; &lt;span class="hljs-keyword"&gt;struct&lt;/span&gt; &lt;span class="hljs-title class_"&gt;TreeIterator&lt;/span&gt;&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;, T&amp;gt; {
    &lt;span class="hljs-comment"&gt;// … other fields as before&lt;/span&gt;
    emitted: &lt;span class="hljs-type"&gt;bool&lt;/span&gt;,
    value: &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt; T,
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And we initialize them as follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;&lt;span class="hljs-keyword"&gt;pub&lt;/span&gt; &lt;span class="hljs-keyword"&gt;fn&lt;/span&gt; &lt;span class="hljs-title function_"&gt;prefixed_lines&lt;/span&gt;&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;&amp;gt;(&amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt; &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;,
                          parent_prefix: &lt;span class="hljs-type"&gt;String&lt;/span&gt;,
                          immediate_prefix: &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;static&lt;/span&gt; &lt;span class="hljs-type"&gt;str&lt;/span&gt;,
                          parent_suffix: &amp;amp;&lt;span class="hljs-symbol"&gt;&amp;#x27;static&lt;/span&gt; &lt;span class="hljs-type"&gt;str&lt;/span&gt;)
                         &lt;span class="hljs-punctuation"&gt;-&amp;gt;&lt;/span&gt; TreeIterator&amp;lt;&lt;span class="hljs-symbol"&gt;&amp;#x27;a&lt;/span&gt;, T&amp;gt;
{
    TreeIterator {
        emitted: immediate_prefix.&lt;span class="hljs-title function_ invoke__"&gt;is_empty&lt;/span&gt;(),
        value: &amp;amp;&lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.value,
        viter: &lt;span class="hljs-type"&gt;Box&lt;/span&gt;::&lt;span class="hljs-title function_ invoke__"&gt;new&lt;/span&gt;(&lt;span class="hljs-title function_ invoke__"&gt;empty&lt;/span&gt;()),
        &lt;span class="hljs-comment"&gt;// … other fields as before&lt;/span&gt;
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Note that the logic of skipping emitting the root has been moved to the initialization of &lt;code&gt;emitted&lt;/code&gt;. This lets us kill the duplication! We now initialize &lt;code&gt;viter&lt;/code&gt; to &lt;code&gt;empty()&lt;/code&gt; – it no longer matters; this initial value will be unused and eventually replaced by child &lt;code&gt;TreeIterator&lt;/code&gt;s.&lt;/p&gt;&lt;p&gt;Finally, we need to amend the implementation of &lt;code&gt;next()&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs rust"&gt;&lt;span class="hljs-keyword"&gt;fn&lt;/span&gt; &lt;span class="hljs-title function_"&gt;next&lt;/span&gt;(&amp;amp;&lt;span class="hljs-keyword"&gt;mut&lt;/span&gt; &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;) &lt;span class="hljs-punctuation"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="hljs-type"&gt;Option&lt;/span&gt;&amp;lt;&lt;span class="hljs-keyword"&gt;Self&lt;/span&gt;::Item&amp;gt; {
    &lt;span class="hljs-keyword"&gt;if&lt;/span&gt; !&lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.emitted {
        &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.emitted = &lt;span class="hljs-literal"&gt;true&lt;/span&gt;;
        &lt;span class="hljs-comment"&gt;// decorate value with prefixes&lt;/span&gt;
        &lt;span class="hljs-title function_ invoke__"&gt;Some&lt;/span&gt;(&lt;span class="hljs-built_in"&gt;format!&lt;/span&gt;(&lt;span class="hljs-string"&gt;&amp;quot;{0}{1}{2}&amp;quot;&lt;/span&gt;, &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.parent_prefix, &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.immediate_prefix, &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.value))
    } &lt;span class="hljs-keyword"&gt;else&lt;/span&gt; &lt;span class="hljs-keyword"&gt;if&lt;/span&gt; &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;Some&lt;/span&gt;(val) = &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.viter.&lt;span class="hljs-title function_ invoke__"&gt;next&lt;/span&gt;() {
        &lt;span class="hljs-title function_ invoke__"&gt;Some&lt;/span&gt;(val) &lt;span class="hljs-comment"&gt;// propagate unchanged&lt;/span&gt;
    } &lt;span class="hljs-keyword"&gt;else&lt;/span&gt; &lt;span class="hljs-keyword"&gt;if&lt;/span&gt; &lt;span class="hljs-keyword"&gt;let&lt;/span&gt; &lt;span class="hljs-variable"&gt;Some&lt;/span&gt;(child) = &lt;span class="hljs-keyword"&gt;self&lt;/span&gt;.citer.&lt;span class="hljs-title function_ invoke__"&gt;next&lt;/span&gt;() {
        &lt;span class="hljs-comment"&gt;// … this part doesn’t change&lt;/span&gt;
    } &lt;span class="hljs-keyword"&gt;else&lt;/span&gt; {
        &lt;span class="hljs-literal"&gt;None&lt;/span&gt;
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And &lt;em&gt;this&lt;/em&gt; version, finally, compiles and works as expected:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs bash"&gt;$ &lt;span class="hljs-built_in"&gt;echo&lt;/span&gt; -e &lt;span class="hljs-string"&gt;&amp;#x27;one/two\none/three/four\nfive/six&amp;#x27;&lt;/span&gt; | ./target/debug/treeviewer
├─ one
│  ├─ two
│  └─ three
│     └─ four
└─ five
   └─ six
&lt;/code&gt;&lt;/pre&gt;&lt;h2 id="takeaways"&gt;Takeaways&lt;/h2&gt;&lt;p&gt;There are quite a few things I learned about Rust in the process, and then there are meta-learnings. Let’s recap the Rust-specific ones first.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;You can’t put a trait in a struct directly, but you can put a &lt;code&gt;Box&lt;/code&gt; of traits.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;But not a &lt;code&gt;Box&lt;/code&gt; of &lt;code&gt;Foo&lt;/code&gt; of traits, where &lt;code&gt;Foo&lt;/code&gt; expect its parameter to be &lt;code&gt;Sized&lt;/code&gt;.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;If you’re &lt;code&gt;map()&lt;/code&gt;ping a closure over an iterator, you can’t access that iterator itself from within the closure.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;Closures by default borrow stuff that they close over, but you can move that stuff to the closure instead with the &lt;code&gt;move&lt;/code&gt; keyword. If I understand correctly, it’s an all-or-nothing move; no mix and match.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;In an &lt;code&gt;if&lt;/code&gt; expression, all branch expressions must be of the same type; conforming to the same trait is not enough.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;And now the general ones.&lt;/p&gt;&lt;p&gt;First off, Rust is &lt;em&gt;hard&lt;/em&gt;. (The least wonder in the world.) Most of the traps I’ve fallen into are accidental complexity, not inherent in the simple problem. I guess that it’s really a matter of the initial steepness of Rust’s learning curve, and that things become easier once you’re past the initial hurdles – you train your instincts to avoid these tarpits and keep the compiler happy.&lt;/p&gt;&lt;p&gt;I’m still very much a newcomer to Rust, so I’m pretty sure I ended up taking a suboptimal approach. A seasoned Rustacean would probably write this code in an altogether different way. If you have suggestions how to improve my code, or how to attack the problem from different angles, tell me!&lt;/p&gt;&lt;p&gt;As an experiment in learning, I’ve decided to reflect on my mistakes more frequently. I elaborate on it in my &lt;a href="/2023/07/06/learning-to-learn-rust/"&gt;previous post&lt;/a&gt;, which also discusses changes I’ve made to my workflow to make learning easier.&lt;/p&gt;&lt;p&gt;Writing the present post showed me how much time it takes. It took me just over an hour to fall into all the traps described in this post and find a way out. A few hours, if you count reading Amos’s post and contemplating the problem. In contrast, this write-up took about two days, plus some &lt;a href="https://mastodon.social/@nathell/110725780205595986"&gt;yak shaving&lt;/a&gt; it led me to. Part of the reason is that the &lt;em&gt;actual&lt;/em&gt; road that I went through was much more bumpy than described here. While writing this, I had to go through no fewer than fifty-six compilation attempts. Here are some of them, with one-line descriptions and a tick or cross to indicate whether the compilation attempt was successful:&lt;/p&gt;&lt;img src="/img/blog/rust-compilation-attempts.png" alt="Some compilation attempts"&gt;
&lt;p&gt;Yet I think it’s worth it. Some of the errors I’ve fixed groping in the dark, kind of randomly: I have now revisited them and I feel I have a much more solid understanding of what’s going on.&lt;/p&gt;&lt;p&gt;And finally: if you’re into Rust, Amos’s blog (&lt;a href="https://mastodon.social/@nathell/110725780205595986"&gt;fasterthanli.me&lt;/a&gt;) is an excellent resource. Go sponsor him on GitHub if these articles are of value to you.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2023-07-06:post:learning-to-learn-rust</id>
    <title>Learning to learn Rust</title>
    <link href="http://blog.danieljanus.pl/learning-to-learn-rust/"/>
    <updated>2023-07-06T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;I’m enjoying a two-month sabbatical this summer. It’s been great so far! I’ve used almost half of the time to &lt;a href="https://danieljanus.substack.com/about"&gt;cycle through the entire Great Britain&lt;/a&gt; and let my body work physically and my mind rest (usually, the opposite is true). And now that I’m back, I’ve switched focus to a few personal projects that I have really wanted to work on for a while but never found time.&lt;/p&gt;&lt;p&gt;One of these projects is to learn Rust. Clojure has made me lazy and it’s really high time for me to flex the language-learning muscles. But while the title says “Rust,” there is nothing Rust-specific about the tip I’m about to share: it can be applied to many programming languages.&lt;/p&gt;&lt;p&gt;I learn best by doing, so after learning the first few chapters of &lt;a href="https://doc.rust-lang.org/book/"&gt;the Rust book&lt;/a&gt;, I set off to write a simple but non-trivial program: a console-based tree viewer. The idea is to have a TUI that you could feed with a set of slash-separated paths:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;one/two
one/three/four
five/six
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;and have it render the tree visually:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;├─ one
│  ├─ two
│  └─ three
│     └─ four
└─ five
   └─ six
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;allowing to scroll it, search it and (un)fold individual subtrees. The paths may come from the filesystem (e.g. you could pipe &lt;code&gt;find . -type f&lt;/code&gt; into it), but not necessarily: they might be S3 object paths, hierarchical names of RocksDB keys (my actual use case), or represent any other tree.&lt;/p&gt;&lt;p&gt;Today I hit a major milestone: I &lt;a href="https://github.com/nathell/treeviewer/commit/fb1332aa5bd0f695604522492ccd893dac28066a"&gt;wrote a function&lt;/a&gt;, &lt;code&gt;append_path&lt;/code&gt;, that, given a tree of strings and a slash-separated path, creates new nodes as needed and adds them to the tree. Needless to say, I didn’t get it right on the first attempt. I fought with the compiler and its borrow checker &lt;em&gt;a lot&lt;/em&gt;.&lt;/p&gt;&lt;p&gt;I guess that’s a typical ordeal that a Rust newbie goes through. But along treeviewer’s code, I keep an org-mode file called &lt;code&gt;LEARN&lt;/code&gt; where I jot down things that I might want to remember for the future. So after getting &lt;code&gt;append_path&lt;/code&gt; right, I wanted to pause and look back at the failed attempts and the corresponding compiler errors, to try to make sense of them, armed with my new knowledge.&lt;/p&gt;&lt;p&gt;But… &lt;em&gt;which&lt;/em&gt; versions of the code caused &lt;em&gt;which&lt;/em&gt; errors? I had no idea! And the Emacs undo tree is really hard to dive in.&lt;/p&gt;&lt;p&gt;An obvious way out is to commit early and often. But this (1) requires a discipline that I don’t have at the moment, and (2) pollutes the Git history. So, instead, I automated it.&lt;/p&gt;&lt;p&gt;I’ve added a Makefile to my repo. Instead of &lt;code&gt;cargo run&lt;/code&gt;, I will now be compiling and executing the code via &lt;code&gt;make run&lt;/code&gt;. In addition to Cargo, this runs &lt;a href="https://github.com/nathell/treeviewer/blob/main/scripts/record.sh"&gt;a script&lt;/a&gt; that:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;Commits everything that’s uncommitted yet&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;Creates an annotated tag with that commit, named &lt;code&gt;build-$TIMESTAMP&lt;/code&gt;, that serves as a snapshot of the code that was built&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;Reverts the working tree to the state it was in (whatever was staged stays staged, whatever was unstaged remains unstaged)&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;This workflow change has the nice property of being unintrusive. I can hack on the code, compile, commit and rebase to my heart’s delight. But when I need to look back at the most recent compilation attempts, all I need to do is &lt;code&gt;git tag&lt;/code&gt; and from there I can meditate on individual mistakes I made.&lt;/p&gt;&lt;p&gt;Why tags and not branches, one might ask? I guess this is a matter of personal preference. I opted for tags because I want to minimise the chance of accidentally pushing the branch. The resulting tags are technically dangling, which I don’t see as an issue: the older the build tag, the less likely I am to need it in the future, so I see myself cleaning up old builds every now and then.&lt;/p&gt;&lt;p&gt;When working with a language I’m proficient in, I don’t need this. But as a learning aid, I already see the idea as indispensable. Feel free to reuse it!&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2021-09-25:post:testing-lithium</id>
    <title>Testing a compiler that can’t even print stuff out</title>
    <link href="http://blog.danieljanus.pl/testing-lithium/"/>
    <updated>2021-09-25T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;I’m enjoying a week-long vacation. In addition to other vacationy things (a trip to Prague, yay!), I wanted to do some off-work programming Just For Fun™ and revisit one of my dormant pet projects, to see if I can make some progress.&lt;/p&gt;&lt;p&gt;I opted for Lithium, my toy x86 assembler and Lisp compiler that hasn’t seen new development since 2014. But before that, I had &lt;a href="/2012/05/14/lithium/"&gt;blogged&lt;/a&gt; &lt;a href="/2013/05/26/lithium-revisited/"&gt;about it&lt;/a&gt; and even &lt;a href="https://danieljanus.pl/talks/reveal.js/2013-euroclojure.html#/"&gt;talked about it&lt;/a&gt; at EuroClojure one time.&lt;/p&gt;&lt;p&gt;Over the week, I’ve re-read the &lt;a href="http://scheme2006.cs.uchicago.edu/11-ghuloum.pdf"&gt;paper&lt;/a&gt; that I’ve been loosely following while developing Lithium. In it, Abdulaziz Ghuloum advocates to have a testing infrastructure from day one, so that one can ensure that the compiler continues to work after each small modification. I’d cut corners on it before, but today, I’ve finally added one.&lt;/p&gt;&lt;p&gt;What’s the big deal? And why not earlier?&lt;/p&gt;&lt;p&gt;One of the original goals that I set myself for Lithium is that it have no runtime dependencies. Not even a C library; not even an OS. It produces raw x86 binaries targetting real mode – non-relocatable blobs of raw machine code. I’m running them in DOSBox, because it’s convenient, but the point is it’s not necessary.&lt;/p&gt;&lt;p&gt;(Some day, I’ll write a mission statement to explain why. But that’s a story for another day.)&lt;/p&gt;&lt;p&gt;And because the setup is so minimalistic, the setup suggested by Ghuloum becomes unfeasible. Ghuloum presupposes the existence of a host C compiler and linker; I have no such privilege. By itself, Lithium can barely output stuff to screen. There’s a &lt;code&gt;write-char&lt;/code&gt; primitive that emits one character, but nothing more than that. And there’s as yet no library to add things to, because there’s no &lt;code&gt;defn&lt;/code&gt; and not much of a global environment.&lt;/p&gt;&lt;p&gt;So what to do? I thought about the invariant in Ghuloum’s design, one that Lithium inherits as well:&lt;/p&gt;&lt;p&gt;&lt;em&gt;Every expression is compiled to machine code that puts its value in the &lt;code&gt;AX&lt;/code&gt; register.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;If I could somehow obtain the values that the CPU registers have at the end of executing a Lithium-compiled program, then I could compare them to the expected value in a test. But how to grab those registers?&lt;/p&gt;&lt;p&gt;That turned out to be easier than expected. Instead of extending Lithium to support printing decimal or hexadecimal numbers, I just grabbed &lt;a href="http://www.fysnet.net/yourhelp.htm"&gt;some pre-existing assembly code&lt;/a&gt; to affix to the program as an epilog. (It does depend on DOS’s interrupt &lt;code&gt;21h&lt;/code&gt;, but hey, it doesn’t hurt to have it for debugging/testing only.) Surprise: the snippet failed to compile, because Lithium’s assembler is woefully incomplete! But it was easy enough to extend it until it worked.&lt;/p&gt;&lt;p&gt;So this gave me a way to view the program’s results.&lt;/p&gt;&lt;img src="/img/blog/lithium-testing.png"&gt;
&lt;p&gt;But there’s another problem: these results are printed within DOSBox. In the emulated DOS machine. I needed a way to transfer them back to the host. Can you guess how?&lt;/p&gt;&lt;p&gt;Yes, you’re right: the simplest thing (DOS redirection to a file, as in &lt;code&gt;PROG.COM &gt;REG.TXT&lt;/code&gt;) works. And you’ll laugh at me that it hasn’t occurred to me until now, when I’m writing up the &lt;a href="https://github.com/nathell/lithium/commit/27563b3c5b92f32b24f750d98248d013f924a700"&gt;commit&lt;/a&gt; that’s already out in the wild. Another proof that it pays to write documentation.&lt;/p&gt;&lt;p&gt;My original idea was… SCREEN CAPTURE!&lt;/p&gt;&lt;p&gt;I’ve scavenged Google for a DOS screen grabber that can produce text files and is not a TSR, &lt;a href="http://www.pc-tools.net/dos/dosutils/"&gt;found one&lt;/a&gt;, bundled it with Lithium, and wrote &lt;a href="https://github.com/nathell/lithium/blob/27563b3c5b92f32b24f750d98248d013f924a700/src/lithium/driver.clj#L23-L36"&gt;some duct-tape code&lt;/a&gt; that invokes the compiled program and the screen grabber in turn and then parses the output. With that, I can finally have &lt;a href="https://github.com/nathell/lithium/blob/27563b3c5b92f32b24f750d98248d013f924a700/test/lithium/compiler_test.clj"&gt;tests&lt;/a&gt; that check whether &lt;code&gt;(+ 3 4)&lt;/code&gt; is really &lt;code&gt;7&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;And now let me go refactor it…&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2021-07-01:post:commit-groups</id>
    <title>Things I wish Git had: Commit groups</title>
    <link href="http://blog.danieljanus.pl/commit-groups/"/>
    <updated>2021-07-01T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;h2 id="intro"&gt;Intro&lt;/h2&gt;&lt;p&gt;Everyone &lt;sup class="sidenote-ref" data-label="footnote1"&gt;1&lt;/sup&gt; and their dog &lt;sup class="sidenote-ref" data-label="footnote2"&gt;2&lt;/sup&gt; loves Git. I know I do. It works, it’s efficient, it has a brilliant data model, and it sports &lt;a href="https://git-scm.com/book/en/v2/Git-Tools-Rerere"&gt;every feature under the sun&lt;/a&gt;. In 13 years of using it, I’ve never found myself needing a feature it didn’t have. Until recently.&lt;/p&gt;&lt;p&gt;But before I tell you about it, let’s talk about GitHub.&lt;/p&gt;&lt;p&gt;There are three groups of GitHub users, distinguished by how they prefer to merge pull requests:&lt;/p&gt;&lt;img src="/img/blog/3-groups-of-gh-users.png"&gt;
&lt;p&gt;Merge commit, squash, or rebase? There’s no single best answer to that question. A number of factors are at play in choosing the merge strategy: the type of the project, the size, workflow and preferences of the team, business considerations, and so on. You probably have your own preference if you’ve used GitHub to collaborate with a team.&lt;/p&gt;&lt;p&gt;I’ll talk for a while about the pros and cons of each approach. But first, let’s establish a setting. Imagine that your project has a &lt;code&gt;main&lt;/code&gt; branch, from which a &lt;code&gt;feature&lt;/code&gt; branch was created off at one point. Since then, both branches have seen developments, and now after &lt;code&gt;feature&lt;/code&gt; has undergone reviews and testing, it’s ready to be merged back to &lt;code&gt;main&lt;/code&gt;:&lt;/p&gt;&lt;img src="/img/blog/orig.svg"&gt;
&lt;h2 id="create-a-merge-commit"&gt;Create a merge commit&lt;/h2&gt;&lt;p&gt;Merge commits are the original answer that Git has to combining changes. A merge commit has two or more parents and brings in all the changes from them and their ancestors:&lt;/p&gt;&lt;img src="/img/blog/merge-commit.svg"&gt;
&lt;p&gt;In this example, Git has created a new commit, number 9, that merges commits 6 and 8. The branch &lt;code&gt;main&lt;/code&gt; now points to that new commit, and so contains all changes in the range 1–8.&lt;/p&gt;&lt;p&gt;Merge commits are extremely versatile and scale well, especially for complicated workflows with multiple maintainers, each responsible for different part of the code; for example, they’re pervasively used by the Linux kernel developers. However, for small, agile teams (especially in the business context), they can be overkill and pose potential problems.&lt;/p&gt;&lt;p&gt;In such a team, you typically have one eternal branch, from which production releases are made, and to which people merge changes from short-lived feature branches. In such a setting, it’s hard to tell how the history of a project has progressed. &lt;a href="https://nvie.com/posts/a-successful-git-branching-model/"&gt;GitFlow&lt;/a&gt;, a popular way of working with Git, advocates merge commits everywhere, and &lt;a href="https://www.endoflineblog.com/gitflow-considered-harmful"&gt;people are struggling with it&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;I’ll refer you to the visual argument from that last post:&lt;/p&gt;&lt;img src="/img/blog/gitflow-mess.png"&gt;
&lt;p&gt;Setting aside the fact that this history is littered with merge commits, the author makes a point that with this kind of an entangled graph, it’s practically impossible to find anything in it. Whether that’s true or not I’ll leave for you to decide, but there’s definitely a case for linear history there.&lt;/p&gt;&lt;p&gt;There’s another, oft-overlooked quirk here. Quick: look again at the second image above, the one with merge commit number 9. Can you tell, from the image alone, which commit was the tip of &lt;code&gt;main&lt;/code&gt; before the merge happened? Surely it must be 8, because it’s on the gray line, right?&lt;/p&gt;&lt;p&gt;Yeah: on the image. But when you look at the merge commit itself, it’s not that obvious. Under the hood, all the commit really says is:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;Merge: 8 6
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;So it tells you that these two parents have been merged together, &lt;em&gt;but it doesn’t tell you which one used to be &lt;code&gt;main&lt;/code&gt;&lt;/em&gt;. You might guess 8, because it’s the leftmost one, but you don’t know for sure. (Remember, branches in Git are just pointers to commits.) The only way (that I know of) to be sure is to use the &lt;a href="https://git-scm.com/docs/git-reflog"&gt;reflog&lt;/a&gt;, but that is ephemeral: Git occassionally prunes old entries from reflogs.&lt;/p&gt;&lt;p&gt;So this prevents you from being able to confidently answer questions such as: “which features were released over the given time period?”, or “what was the state of &lt;code&gt;main&lt;/code&gt; as of a given date?”.&lt;/p&gt;&lt;p&gt;That’s also why you can’t &lt;code&gt;git revert&lt;/code&gt; a merge commit—that is, unless you tell Git which of the parent commits you want to keep and which to discard.&lt;/p&gt;&lt;h2 id="squash-and-merge"&gt;Squash and merge&lt;/h2&gt;&lt;p&gt;In the merge commit-based approach, we don’t rewrite history: once a commit is made, it stays; repository only grows by accretion. In contrast, the other two approaches use Git’s facilities for rewriting history. As we’ll see, the fundamentals are the same: where they differ is commit granularity.&lt;/p&gt;&lt;p&gt;Coming back to our example: when squashing, we mash together the changes introduced by commits 4, 5, and 6 into a single commit (“S”), and then replay that commit on top of &lt;code&gt;main&lt;/code&gt;.&lt;/p&gt;&lt;img src="/img/blog/squash-and-merge.svg"&gt;
&lt;p&gt;The &lt;code&gt;feature&lt;/code&gt; branch is still there, but I didn’t include it on this picture because it’s no longer relevant—it typically gets deleted upon merge (which, as we will see, might not actually be a good idea).&lt;/p&gt;&lt;p&gt;There’s a lot to like about this approach, and &lt;a href="https://blog.dnsimple.com/2019/01/two-years-of-squash-merge/"&gt;some teams&lt;/a&gt; &lt;a href="https://christopher.xyz/2020/07/13/squash-merge.html"&gt;advocate for it&lt;/a&gt;. The biggest and most obvious benefit is likely that &lt;em&gt;the history becomes very legible&lt;/em&gt;. It’s linear and there’s a one-to-one correspondence between commits on &lt;code&gt;main&lt;/code&gt; and pull requests (and, mostly, either features or bugfixes). Such a history can be of great help in project management: it becomes very easy to answer the questions which were nigh impossible to answer in the merge-commit approach.&lt;/p&gt;&lt;h2 id="rebase-and-merge"&gt;Rebase and merge&lt;/h2&gt;&lt;p&gt;This situation is similar to the previous one, except that we don’t squash commits 4–6 together. Instead, we directly replay them on top of &lt;code&gt;main&lt;/code&gt;.&lt;/p&gt;&lt;img src="/img/blog/rebase-and-merge.svg"&gt;
&lt;p&gt;Let me start with a long digression. You might guess, from the GitHub screenshot at the top of this post, that I’m in this camp, and you’d be right. In fact, I used to squash and merge feature branches, but I switched to the rebase-and-merge approach after introducing probably the single biggest improvement to the quality of my work over recent years:&lt;/p&gt;&lt;p&gt;I started writing &lt;a href="https://chris.beams.io/posts/git-commit/"&gt;meaningful commit messages&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;In the not-too-distant past, my commit messages used to be one-liners, as evidenced, for example, in the &lt;a href="https://github.com/nathell/skyscraper/commits/master"&gt;history of Skyscraper&lt;/a&gt;. These first lines haven’t changed much, but now I strive to augment them with explanation of &lt;em&gt;why&lt;/em&gt; the change is being made. When it fixes a bug, I explain what was causing it and how the change makes the bug go away; when it implements a feature, I highlight the specifics of the implementation. I might not write more code these days, but I certainly write more prose: it’s not uncommon for me to write two or three paragraphs about a +1/−1 change.&lt;/p&gt;&lt;p&gt;So my commit messages now look like this (I’m taking a recent random example from the &lt;a href="https://iamfy.co"&gt;Fy!&lt;/a&gt; app’s repo):&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs text"&gt;app/tests: allow to mock config

Tests expected the code-push events to fire, but now that I’ve
disabled CP in dev, and the tests are built with the dev aero profile,
they’d fail.

This could have been fixed by building them with AERO_PROFILE=staging
in CI, but it doesn’t feel right: I think tests shouldn’t depend on
varying configuration. If a test requires a given bit of configuration
to be present, it’s better to configure it that way explicitly.

Hence this commit. It adds a wrap-config mock and a corresponding
:extra-config fixture, which, when present (and it is by default),
will merge the value onto generated-config.
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;I’m very conscious about having a clean history. I’m aiming for each commit to be small (with the threshold at approximately +20/−20 LOCs) and introduce a coherent, logical change.&lt;/p&gt;&lt;p&gt;That’s not to say I always &lt;em&gt;develop&lt;/em&gt; that way, of course. If you looked at a &lt;code&gt;git log&lt;/code&gt; of my work-in-progress branch, chances are you’d see something like this:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs text"&gt;5d64b71 wip
392b1e0 wip
0a3ad89 more wip
3db02d3 wip
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;But before declaring the PR ready to review, I’ll throw &lt;em&gt;this&lt;/em&gt; history away (by &lt;code&gt;git reset --mixed $(git merge-base feature main)&lt;/code&gt;) and re-commit the changes, dividing them into logical units and writing the rationales, bit by bit.&lt;/p&gt;&lt;p&gt;The net result of rigorously applying this practice is that&lt;/p&gt;&lt;p&gt;&lt;strong&gt;you can do &lt;code&gt;git annotate&lt;/code&gt; anywhere, and learn about why any line of code in the codebase is the way it is.&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;I can’t emphasize enough how huge, huge impact for the developer’s wellbeing this has. These commits messages, when I read them back weeks or months later, working on something different but related, almost read as little love letters from me-in-the-past to me-now. They reduce the all-important WTFs/minute metric to zero.&lt;/p&gt;&lt;img src="/img/blog/wtfm.jpg"&gt;
&lt;p&gt;They’re also an aid in reviewing code. My PR notes usually say “please read each commit in isolation.” I’ve found it easier to follow a PR when it tries to tell a story, and each commit is a milestone down that road.&lt;/p&gt;&lt;p&gt;Ending the digression: can you see why I prefer rebase-and-merge over squash-and-merge? Because, all the benefits notwithstanding, squashing &lt;em&gt;irrevocably loses context&lt;/em&gt;.&lt;/p&gt;&lt;p&gt;Now, instead of each line being a result of a small, +20/−20 change, you can only tell that it’s part of a set of such changes — maybe ten of them, maybe fifty. You don’t know. Sure you can go look in the original branch, but it’s an overhead, and what if it’s been deleted?&lt;/p&gt;&lt;p&gt;So yeah. Having those love letters all in place, each carefully placed and not glued to others, is just too much of a boon to let go. But it’s not to say that rebasing-and-merging is without downsides.&lt;/p&gt;&lt;p&gt;For example, it’s again hard to tell how many features were deployed over a given period of time. More troublesomely, it’s harder to revert changes: typically you want to operate on a feature level there. With squash-and-merge, it takes one &lt;code&gt;git revert&lt;/code&gt; to revert a buggy feature. With rebase-and-merge, you need to know the range.&lt;/p&gt;&lt;p&gt;Worse yet: it’s more likely for a squashed-and-merged commit to be cleanly undone (or cherry-picked) than for a series of small commits. (I sometimes deliberately commit wrong or half-baked approaches that are changed in subsequent commits, just to tell the story more convincingly, and it’s possible that each of these changes individually causes trouble but that they cancel each other in squash.)&lt;/p&gt;&lt;p&gt;So I’m not completely happy with either of the three approaches. Which finally brings me to my preferred fourth approach, one that Git (yet?) doesn’t allow for:&lt;/p&gt;&lt;h2 id="rebase,-group-and-merge"&gt;Rebase, group and merge&lt;/h2&gt;&lt;p&gt;You know the “group” facility of vector graphics programs? You draw a couple of shapes, you group them together, and then you can apply transformations to the entire group at once, operating on it as if it were an atomic thing. But when need arises, you can “ungroup” it and look deeper.&lt;/p&gt;&lt;p&gt;That’s because sometimes there’s a need to have a “high-level” view of things, and sometimes you need to delve deeper. Each of these needs is valid. Each is prompted by different circumstances that we all encounter.&lt;/p&gt;&lt;p&gt;I’d love to see that same idea applied to Git commits. In Git, a commit group might just be a named and annotated range of commits: &lt;code&gt;feature-a&lt;/code&gt; might be the same as &lt;code&gt;5d64b71..3db02d3&lt;/code&gt;. Every Git command that currently accepts commit ranges could accept group names. I envision groups to have descriptions, so that &lt;code&gt;git log&lt;/code&gt;, &lt;code&gt;git blame&lt;/code&gt;, etc could take &lt;code&gt;--grouped&lt;/code&gt; or &lt;code&gt;--ungrouped&lt;/code&gt; options and act appropriately.&lt;/p&gt;&lt;p&gt;Obviously, details would need to be fleshed out (can groups overlap? can groups be part of other groups?), and I’m not that familiar with Git innards to say with confidence that it’s doable. But the more I think about it, the more sound the idea seems to me.&lt;/p&gt;&lt;p&gt;I think creating a group when doing a rebase-and-merge could bring together the best of all three worlds, so that we can have all our cakes and eat them too.&lt;/p&gt;&lt;hr /&gt;&lt;div class="footnote"&gt;&lt;p&gt;&lt;sup class="footnote-ref" data-ref="0"&gt;1&lt;/sup&gt; &lt;a href="https://www.mercurial-scm.org/"&gt;Well,&lt;/a&gt; &lt;a href="https://fossil-scm.org/"&gt;almost&lt;/a&gt; &lt;a href="https://pijul.org/"&gt;everyone&lt;/a&gt;.&lt;/p&gt;&lt;/div&gt;&lt;div class="footnote"&gt;&lt;p&gt;&lt;sup class="footnote-ref" data-ref="1"&gt;2&lt;/sup&gt; It’s Dog Day here in Poland as I write these words. Happy Dog Day!&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2020-11-08:post:coronalotto</id>
    <title>I made a website to guess tomorrow’s number of COVID-19 cases, and here’s what happened</title>
    <link href="http://blog.danieljanus.pl/coronalotto/"/>
    <updated>2020-11-08T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;h2 id="before"&gt;Before&lt;/h2&gt;&lt;p&gt;It seems so obvious in hindsight. Here in Poland, people have been guessing it ever since the pandemic breakout: in private conversations, in random threads on social media, in comments under governmental information outlets. It seemed a matter of time before someone came up with something like this. In fact, on one Sunday evening in October, I found myself flabbergasted that apparently no one yet has.&lt;/p&gt;&lt;p&gt;I doled out $4 for a domain, &lt;a href="http://koronalotek.pl"&gt;koronalotek.pl&lt;/a&gt; (can be translated as “coronalotto” or “coronalottery” – occurrences of the name on Twitter date back at least as far as April), and fired up a REPL. A few hours and 250 Clojure LOCs later, the site was up.&lt;/p&gt;&lt;p&gt;I wanted it to be as simple as possible. A form with two fields: “your name” and “how many cases tomorrow?” A top-ten list of today’s winners, sorted by the absolute difference between the guess and the actual number of cases, as &lt;a href="https://twitter.com/mz_gov_pl"&gt;reported daily on Twitter&lt;/a&gt; by the Polish Ministry of Health. The official number, prominently displayed. And that’s all.&lt;/p&gt;&lt;img src="/img/blog/koronalotek.png"&gt;
&lt;p&gt;On 17 October, I posted the link on my Facebook and Twitter feeds, and waited. The stream of guesses started to trickle in.&lt;/p&gt;&lt;h2 id="after"&gt;After&lt;/h2&gt;&lt;p&gt;It never grew to be more than a stream, but it hasn’t gone completely unnoticed either.&lt;/p&gt;&lt;img src="/img/blog/koronalotek-g1.png"&gt;
&lt;p&gt;The above plot shows daily number of accepted guesses (i.e., those that were used to generate the next day’s winners) over time – a metric of popularity. Each day’s number means guesses cast in the 24 hours up until 10:30 (Warsaw time) on that day, which is when the official numbers are published by the Ministry of Health.&lt;/p&gt;&lt;p&gt;I’ve been filtering out automated submissions, as well as excess manual submissions by the same IP that seemed to skew the results too much – I’ve arbitrarily set the “excess” threshold at 10. The missing datapoint for 19 October is not a zero, but a N/A: I’ve lost that datapoint due to a glitch. More on this below.&lt;/p&gt;&lt;p&gt;The interest peaked on October 23, with more than a thousand guesses for that day (I think it was reposted by someone with a significant outreach back then), and has been slowly declining since.&lt;/p&gt;&lt;p&gt;I have privately received some feedback. One person has pointed out that they found the site distasteful and that making fun of pandemic tragedies made them uncomfortable. (I empathise; for me it’s not so much making fun as it is a coping mechanism—a way to put distance between my thoughts and the difficult times we’re in and to keep fears at bay.) Some people, however, have thanked me for making them smile when they guessed more or less correctly.&lt;/p&gt;&lt;p&gt;Back to data. Being a data junkie, I looked at what I had been collecting. First things first: how accurate is the collective predictive power of the guessers?&lt;/p&gt;&lt;img src="/img/blog/koronalotek-g2.png"&gt;
&lt;p&gt;Quite accurate, in fact! Data for this plot has only been slightly preprocessed, by filtering out “unreasonable” guesses that don’t fall within the range &lt;code&gt;[100; 50000]&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;People have over- and underguesstimated the number of new cases, but not by much. There were only a few occasions where the actual case count didn’t fall within one standard deviation of the mean of guesses (represented by the whiskers around blue bars on the plot). Granted, the daily standard deviation tends to be large (on the order of a few thousand), but still, I’m impressed. A paper on estimating the growth of pandemic based on coronalottery results coming soon to a journal near you! ;-)&lt;/p&gt;&lt;p&gt;Just for the heck of it, I’ve also been looking at individual votes. Specifically, names. Here’s a snapshot of unique guessers’ names sorted by decreasing length, on 23 October. (NSFW warning: expletives ahead!)&lt;/p&gt;&lt;img src="/img/blog/koronalotek-names.jpg"&gt;
&lt;p&gt;Let me translate a few of these for those of you who don’t speak Polish:&lt;/p&gt;&lt;p&gt;1 is “Sasin has fucked over 70 million zlotys for elections that didn’t take place and was never held responsible.” This alludes to the &lt;a href="https://notesfrompoland.com/2020/05/27/70-million-zloty-bill-for-polands-abandoned-presidential-election/"&gt;ghost election in Poland&lt;/a&gt; from May. This news had gone memetic, going so far as Minister Sasin’s name being ironically used as a dimensionless unit of 70 million (think Avogadro’s number). You’ll discover the same theme in #2, #3, #5, and others.&lt;/p&gt;&lt;p&gt;6 is “CT {Constitutional Tribunal}, you focking botch, stop repressing my abortion”. Just a day before, the Polish constitutional court (whose current legality is &lt;a href="https://en.wikipedia.org/wiki/Constitutional_Tribunal_(Poland)#2015%E2%80%93present:_Polish_Constitutional_Court_crisis"&gt;disputed at best&lt;/a&gt;) has &lt;a href="https://notesfrompoland.com/2020/10/22/constitutional-court-ruling-ends-almost-all-legal-abortion-in-poland/"&gt;decreed a ban on almost all legal abortion&lt;/a&gt; in Poland, giving rise to &lt;a href="https://edition.cnn.com/2020/10/31/europe/poland-abortion-protests-scli-intl/index.html"&gt;the biggest street protests in decades&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Not all is political: 4 is “Why study for the exam if we’re not gonna survive until November anyway?”. I hope whoever wrote this is alive and well.&lt;/p&gt;&lt;p&gt;Corollary? Give people a text field, and they’ll use it to express themselves: politically or otherwise.&lt;/p&gt;&lt;p&gt;In fact, I have taken the liberty of chiming in. Shortly after, I altered the thank-you page (which used to just say “thanks for guessing”) to proudly display one of the emblems of the Women’s Strike, along with a link to a &lt;a href="https://zrzutka.pl/kasa-na-aborcyjny-dream-team-55g5gx"&gt;crowdfounding campaign&lt;/a&gt; for an NGO that supports women needing abortion.&lt;/p&gt;&lt;img src="/img/blog/koronalotek-thanks.jpg"&gt;
&lt;h2 id="inside-out"&gt;Inside out&lt;/h2&gt;&lt;p&gt;I’m not much of a DevOps person, so I deployed it the quick and dirty way, not caring about scalability or performance. The maxim “make it as simple as possible” permeates the setup.&lt;/p&gt;&lt;p&gt;I just started a REPL within a &lt;code&gt;screen&lt;/code&gt; session on the tiny Scaleway C1 server that also hosts this blog and some of my other personal stuff. I launched a Jetty server within it, and set up a nginx proxy. And that’s pretty much it. I liberally tinker with the app’s state in “production,” evaluating all kinds of expressions when I feel like it.&lt;/p&gt;&lt;p&gt;Code changes are deployed by &lt;code&gt;git pull&lt;/code&gt;ing new developments and doing &lt;code&gt;(require 'koronalotek.core :reload)&lt;/code&gt; in the REPL.&lt;/p&gt;&lt;p&gt;Someone tried a SQL injection attack. This is doomed to fail because there’s no SQL involved. In fact, there’s no database at all. The entire state is kept in an in-memory atom and periodically synced out to an EDN file. In addition, state is reset and archived daily at the time of announcing winners. (I’ve added the archiving after forgetting it on one occasion – hence the lack of data for 19 October.)&lt;/p&gt;&lt;p&gt;I also don’t yet have a mechanism of automatically pulling in the Ministry of Health’s data. Every morning, I spend two minutes checking if there’s excess automatic votes, removing them if any, and then filling in the blanks:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;new-data!&lt;/span&gt; #inst &lt;span class="hljs-string"&gt;&amp;quot;2020-11-08T10:30+01:00&amp;quot;&lt;/span&gt; &lt;span class="hljs-number"&gt;24785&lt;/span&gt;)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;For all the violations of good practices in this setup, it has worked out surprisingly well so far. I’ve resorted to removing automated votes a handful of times, and blacklisting IPs of voting bots in the nginx setup twice, but otherwise it’s been a low-maintenance toy. People seem to be willing to have fun, and I’m just not interfering.&lt;/p&gt;&lt;h2 id="takeaways"&gt;Takeaways&lt;/h2&gt;&lt;ol&gt;&lt;li&gt;&lt;span&gt;You should call on your country’s authorities to exert pressure on the Polish government to respect women’s choices and stop actively repressing them.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;Give people a text field, and they’ll use it to express themselves.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;Release early, release often.&lt;/span&gt;&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2020-05-08:post:making-of-clojure-dependency</id>
    <title>Making of “Clojure as a dependency”</title>
    <link href="http://blog.danieljanus.pl/making-of-clojure-dependency/"/>
    <updated>2020-05-08T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;In my previous post, &lt;a href="/2020/05/02/clojure-dependency/"&gt;“Clojure as a dependency”&lt;/a&gt;, I’ve presented the results of some toy research on Clojure version numbers seen in the wild. I’m a big believer in &lt;a href="https://en.wikipedia.org/wiki/Reproducibility#Reproducible_research"&gt;reproducible research&lt;/a&gt;, so I’m making available a &lt;a href="https://github.com/nathell/versions"&gt;Git repo&lt;/a&gt; that contains code you can run yourself to reproduce these results. This post is an experience report from writing that code.&lt;/p&gt;&lt;p&gt;There are two main components to this project: acquisition and analysis of data (implemented in the namespaces &lt;code&gt;versions.scrape&lt;/code&gt; and &lt;code&gt;versions.analyze&lt;/code&gt;, respectively). Let’s look at each of these in turn.&lt;/p&gt;&lt;h2 id="data-acquisition"&gt;Data acquisition&lt;/h2&gt;&lt;p&gt;This step uses the &lt;a href="https://developer.github.com/v3/"&gt;GitHub API v3&lt;/a&gt; to:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;retrieve the 1000 most popular Clojure repositories (using the &lt;a href="https://developer.github.com/v3/search/#search-repositories"&gt;Search repositories&lt;/a&gt; endpoint and going through all &lt;a href="https://developer.github.com/v3/#pagination"&gt;pages&lt;/a&gt; of the paginated result);&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;for each of these repositories, look at its file list (in the master branch) and pick up any files named &lt;code&gt;project.clj&lt;/code&gt; or &lt;code&gt;deps.edn&lt;/code&gt; in the root directory, using the &lt;a href="https://developer.github.com/v3/repos/contents/"&gt;Contents&lt;/a&gt; endpoint);&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;parse each of these files and extract the list of dependencies.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;As hinted by the namespace, I’ve opted to use &lt;a href="https://github.com/nathell/skyscraper"&gt;Skyscraper&lt;/a&gt; to orchestrate the process. It would arguably have been simpler to use GitHub’s &lt;a href="https://developer.github.com/v4/"&gt;GraphQL v4 API&lt;/a&gt;, but I wanted to showcase Skyscraper’s custom parsing facilities.&lt;/p&gt;&lt;p&gt;There’s no actual HTML scraping going on (all processors use either JSON or Clojure parsers), but Skyscraper is still able to “restructure” the result – traverse the graph endpoint in a manner similar to that of GraphQL – with very little effort. It would have been possible with any other RESTful API. Plus, we get goodies like caching or tree pruning for free.&lt;/p&gt;&lt;p&gt;Most of the code is straightforward, but parsing of &lt;code&gt;project.clj&lt;/code&gt; merits some explanation. Some of my initial assumptions proved incorrect, and it’s fun to see how. I initially tried to use &lt;a href="https://clojure.github.io/clojure/clojure.edn-api.html#clojure.edn/read"&gt;&lt;code&gt;clojure.edn&lt;/code&gt;&lt;/a&gt;, but Leiningen project definitions are not actually EDN – they are Clojure code, which is a superset of EDN. So I had to resort to &lt;code&gt;read-string&lt;/code&gt; from core – with &lt;code&gt;*read-eval*&lt;/code&gt; bound to nil (otherwise the code would have a Clojure injection vulnerability – think &lt;a href="https://xkcd.com/327/"&gt;Bobby Tables&lt;/a&gt;). Needless to say, some &lt;code&gt;project.clj&lt;/code&gt;s turned out to depend on read-eval.&lt;/p&gt;&lt;p&gt;Some projects (I’m looking at you, &lt;a href="https://github.com/dundalek/closh"&gt;Closh&lt;/a&gt;, &lt;a href="https://github.com/borkdude/babashka"&gt;Babashka&lt;/a&gt; and &lt;a href="https://github.com/borkdude/sci"&gt;sci&lt;/a&gt;) keep the version number outside of &lt;code&gt;project.clj&lt;/code&gt;, in a text file (typically in &lt;code&gt;resources/&lt;/code&gt;), and slurp it back into &lt;code&gt;project.clj&lt;/code&gt; with a read-eval’d expression:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;defproject&lt;/span&gt; closh-sci
  #=(&lt;span class="hljs-name"&gt;clojure.string/trim&lt;/span&gt;
     #=(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;slurp&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;resources/CLOSH_VERSION&amp;quot;&lt;/span&gt;))
  …)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;A trick employed by one project, &lt;a href="https://github.com/metabase/metabase"&gt;Metabase&lt;/a&gt;, is to dynamically generate JVM options containing a port number at parse time, so that test suites running at the same time don’t clash with each other:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;#=(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;eval&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;format&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;-Dmb.jetty.port=%d&amp;quot;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;+&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;3001&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;rand-int&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;500&lt;/span&gt;))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Finally, it turned out that &lt;code&gt;defproject&lt;/code&gt; is not always a first form in &lt;code&gt;project.clj&lt;/code&gt;. Some projects, like &lt;a href="https://github.com/robert-stuttaford/bridge"&gt;bridge&lt;/a&gt;, only contain a placeholder &lt;code&gt;project.clj&lt;/code&gt; with no forms; others, like &lt;a href="https://github.com/ztellman/aleph"&gt;aleph&lt;/a&gt;, first define some constants, and then refer to them in a &lt;code&gt;defproject&lt;/code&gt; form. If those constants contain parts of the dependencies list, then those dependencies won’t be processed correctly. Fortunately, not a lot of projects do this, so it doesn’t skew the results much.&lt;/p&gt;&lt;p&gt;Anyway, the end result of the acquisition phase is a sequence of maps describing project definitions. They look like this:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;{&lt;span class="hljs-symbol"&gt;:name&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;clojure-koans&amp;quot;&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt;
 &lt;span class="hljs-symbol"&gt;:full-name&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;functional-koans/clojure-koans&amp;quot;&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt;
 &lt;span class="hljs-symbol"&gt;:deps-type&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:leiningen&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt;
 &lt;span class="hljs-symbol"&gt;:page&lt;/span&gt; &lt;span class="hljs-number"&gt;1&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt;
 &lt;span class="hljs-symbol"&gt;:deps&lt;/span&gt; {org.clojure/clojure #:mvn{&lt;span class="hljs-symbol"&gt;:version&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;1.10.0&amp;quot;&lt;/span&gt;}&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt;
        koan-engine #:mvn{&lt;span class="hljs-symbol"&gt;:version&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;0.2.5&amp;quot;&lt;/span&gt;}}}&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt;
 &lt;span class="hljs-symbol"&gt;:profile-deps&lt;/span&gt; {&lt;span class="hljs-symbol"&gt;:dev&lt;/span&gt; {lein-koan #:mvn{&lt;span class="hljs-symbol"&gt;:version&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;0.1.5&amp;quot;&lt;/span&gt;}}}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Homogeneity is important: every dependency description has been converted to the cli-tools format, even if it comes from a &lt;code&gt;project.clj&lt;/code&gt;.&lt;/p&gt;&lt;h2 id="data-analysis"&gt;Data analysis&lt;/h2&gt;&lt;p&gt;I’ve long been searching for a way to do exploratory programming in Clojure without turning the code to a tangled mess, portable only along with my computer.&lt;/p&gt;&lt;p&gt;Exploratory (or research) programming is very different from “normal” programming. In the latter, most of the time you typically focus on a coherent project – a program or a library. In contrast, in the former, you spend a lot of time in the REPL, trying all sorts of different things and &lt;code&gt;def&lt;/code&gt;ing new values derived from already computed ones.&lt;/p&gt;&lt;p&gt;This is very convenient, but it’s extremely easy to get carried away in the REPL and get lost in a sea of &lt;code&gt;def&lt;/code&gt;s. If you want to redo your computations from scratch, just about your only option is to take your REPL transcript and re-evaluate the expressions one by one, in the correct order. Cleaning up the code (e.g. deglobalizing) as you go is very difficult.&lt;/p&gt;&lt;p&gt;I’ve found an answer: &lt;a href="https://plumatic.github.io/prismatics-graph-at-strange-loop"&gt;Plumatic Graph&lt;/a&gt;, part of the &lt;a href="https://github.com/plumatic/plumbing"&gt;plumbing&lt;/a&gt; library. There are a plethora of uses for it: for example, at &lt;a href="https://iamfy.co"&gt;Fy&lt;/a&gt;, my current workplace, we’re using it to define our test fixtures. But as it turns out, it makes exploratory programming enjoyable.&lt;/p&gt;&lt;p&gt;The bulk of code in &lt;a href="https://github.com/nathell/versions/blob/master/src/clj/versions/analyze.clj#L41"&gt;&lt;code&gt;versions.analyze&lt;/code&gt;&lt;/a&gt; consists of a big definition of a graph, with nodes representing computations – things that I’d normally have &lt;code&gt;def&lt;/code&gt;’d in a REPL. Consequently, most of these definitions are short and to the point. I also gave the nodes verbose, descriptive, explicit names. Name and conquer. &lt;code&gt;raw-repos&lt;/code&gt; is the output from data acquisition, &lt;code&gt;repos&lt;/code&gt; is an all-important node containing those &lt;code&gt;raw-repos&lt;/code&gt; that were successfully parsed, and most other things depend on it.&lt;/p&gt;&lt;p&gt;It also doesn’t obstruct much the normal REPL research flow. My normal workflow with REPL and Graph is something along the lines of:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;&lt;span&gt;&lt;code&gt;(def result (main))&lt;/code&gt;&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;evaluate something using inputs from &lt;code&gt;result&lt;/code&gt;&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;nah, it leads nowhere&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;evaluate something else&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;hey, that’s interesting!&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;add a new node to the graph definition&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;GOTO 1&lt;/span&gt;&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;Thanks to Graph’s lazy compiler, I can re-evaluate anything at need and have it evaluate only the things needed, and nothing else. Also, because the graph is explicit, it’s fairly easy to &lt;a href="https://github.com/RedBrainLabs/graph-fnk-viz"&gt;visualize it&lt;/a&gt;. (Click the image to open it in full-size in another tab.)&lt;/p&gt;&lt;p&gt;&lt;a href="/img/blog/computation-graph.png" target="_blank"&gt;&lt;img src="/img/blog/computation-graph.png"&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;Because it’s lazy, it doesn’t hurt to put extra things in there just in case, even when you’re not going to report them. For example, I was curious what things besides a version number people put in dependencies. &lt;code&gt;:exclusions&lt;/code&gt;, for sure, but what else? This is the &lt;code&gt;:what-other-things-besides-versions&lt;/code&gt; node.&lt;/p&gt;&lt;p&gt;Imagine my surprise when I found &lt;code&gt;:exlusions&lt;/code&gt; (&lt;em&gt;sic&lt;/em&gt;) in there, which turned out to be a typo in shadow-cljs’ &lt;code&gt;project.clj&lt;/code&gt;! I submitted &lt;a href="https://github.com/thheller/shadow-cljs/pull/699"&gt;a PR&lt;/a&gt;, and Thomas Heller merged it a few days after.&lt;/p&gt;&lt;p&gt;My only gripe with Graph is that it runs somewhat contrary to the current trends in the Clojure community: for example, it doesn’t support namespaced keywords (although there’s an &lt;a href="https://github.com/plumatic/plumbing/issues/126"&gt;open ticket&lt;/a&gt; for that). But on the whole, I’m sold. I’ll definitely be using it in the next piece of research in Clojure, and I’m on a lookout for something similar in pure R. If you know something, do tell me!&lt;/p&gt;&lt;h2 id="some-words-on-plotting"&gt;Some words on plotting&lt;/h2&gt;&lt;p&gt;The plot from previous post has been generated in pure R, using &lt;a href="https://ggplot2.tidyverse.org"&gt;ggplot2&lt;/a&gt; (an extremely versatile API). Clojure generates a CSV with munged data, and then R reads that CSV as a data frame and generates the plot in a few lines.&lt;/p&gt;&lt;p&gt;I’ve briefly played around with &lt;a href="https://github.com/scicloj/clojisr"&gt;clojisr&lt;/a&gt;, a bridge between Clojure and R. It was an enlightening experiment, and it would let me avoid the intermediate CSV, but I decided to ditch it for a few reasons:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;It pulls in quite a few dependencies (I wanted to keep them down to a minimum), and requires some previous setup on the R side.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;I’d much rather write my R as R, since I’m comfortable with it, rather than spend time wondering how it maps to Clojure. This is similar to the SQL story: these days I prefer &lt;a href="https://www.hugsql.org"&gt;HugSQL&lt;/a&gt; over &lt;a href="https://github.com/korma/Korma"&gt;Korma&lt;/a&gt;, unless I have good reasons to choose otherwise.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;clojisr opens up a child R process just by &lt;code&gt;require&lt;/code&gt;ing a namespace. I’m not a fan of that.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;But it’s definitely very promising! I applaud the effort and I’ll keep a close eye on it.&lt;/p&gt;&lt;h2 id="key-takeaways"&gt;Key takeaways&lt;/h2&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;Skyscraper makes data acquisition bearable, if not fun.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;Plumatic Graph makes writing research code in Clojure fun.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;ggplot makes plotting data fun.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;Clojure makes programming fun. (But you knew that already.)&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2020-05-02:post:clojure-dependency</id>
    <title>Clojure as a dependency</title>
    <link href="http://blog.danieljanus.pl/clojure-dependency/"/>
    <updated>2020-05-02T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;I have a shameful confession to make: I have long neglected an open-source library that I maintain, &lt;a href="https://github.com/nathell/clj-tagsoup"&gt;clj-tagsoup&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;This would have been less of an issue, but this is my second-most-starred project on GitHub. Granted, I don’t feel a need for it anymore, but apparently people do. I wish I had spent some time reviewing and merging the incoming PRs.&lt;/p&gt;&lt;p&gt;Anyway, I’ve recently been prompted to revive it, and I’m preparing a new release. While on it, I’ve been updating dependencies to their latest versions, and upon seeing a dependency on &lt;code&gt;[org.clojure/clojure "1.2.0"]&lt;/code&gt; in &lt;code&gt;project.clj&lt;/code&gt; (yes, it’s been neglected for that long), I started wondering: which Clojure to depend on? Actually, should Clojure itself be a dependency at all?&lt;/p&gt;&lt;p&gt;I’ve googled around for best practices, but with no conclusive answer. So I set out to do some research.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;TLDR:&lt;/strong&gt; with Leiningen, add it with &lt;code&gt;:scope "provided"&lt;/code&gt;; with cli-tools, you don’t have to, unless you want to be explicit.&lt;/p&gt;&lt;h2 id="is-it-possible-for-a-clojure-project-to-declare-no-dependency-on-clojure-at-all?"&gt;Is it possible for a Clojure project to declare no dependency on Clojure at all?&lt;/h2&gt;&lt;p&gt;Quite possible, as it turns out. But the details depend on the build tool.&lt;/p&gt;&lt;p&gt;Obviously, this only makes sense for libraries. Or, more broadly, for projects that are not meant to be used standalone, but rather included in other projects (which will have a Clojure dependency of their own).&lt;/p&gt;&lt;h3 id="leiningen"&gt;Leiningen&lt;/h3&gt;&lt;p&gt;If you try to create a Leiningen project that has no dependencies:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;defproject&lt;/span&gt; foo &lt;span class="hljs-string"&gt;&amp;quot;0.1.0&amp;quot;&lt;/span&gt;
  &lt;span class="hljs-symbol"&gt;:dependencies&lt;/span&gt; [])
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;then Leiningen (as of version 2.9.3, but I’d guess older versions behave similarly) won’t allow you to launch a REPL:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;$ lein repl
Error: Could not find or load main class clojure.main
Caused by: java.lang.ClassNotFoundException: clojure.main
Subprocess failed (exit code: 1)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;But all is not lost: &lt;code&gt;lein jar&lt;/code&gt; works just fine (as long as you don’t AOT-compile any namespaces), as does &lt;code&gt;lein install&lt;/code&gt;. The resulting library will happily function as a dependency of other projects.&lt;/p&gt;&lt;p&gt;The upside of depending on no particular Clojure version is that you don’t impose it on your consumers. If a library depends on Clojure 1.9.0, but a project that uses it depends on Clojure 1.10.1, then Leiningen will fetch 1.9.0’s &lt;code&gt;pom.xml&lt;/code&gt; (it’s smart enough to figure out that the jar itself won’t be needed, as the conflict will always be resolved in favour of the direct dependency), and &lt;code&gt;lein deps :tree&lt;/code&gt; will report “possibly confusing dependencies”.&lt;/p&gt;&lt;p&gt;It’s not very useful to have a library that you can’t launch a REPL against, though. So what some people do is declare a dependency on Clojure not in the main &lt;code&gt;:dependencies&lt;/code&gt;, but in a profile.&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;defproject&lt;/span&gt; foo &lt;span class="hljs-string"&gt;&amp;quot;0.1.0&amp;quot;&lt;/span&gt;
  &lt;span class="hljs-symbol"&gt;:dependencies&lt;/span&gt; []
  &lt;span class="hljs-symbol"&gt;:profiles&lt;/span&gt; {&lt;span class="hljs-symbol"&gt;:dev&lt;/span&gt; {&lt;span class="hljs-symbol"&gt;:dependencies&lt;/span&gt; [[org.clojure/clojure &lt;span class="hljs-string"&gt;&amp;quot;1.10.1&amp;quot;&lt;/span&gt;]]}})
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This avoids conflicts and brings back the possibility to launch a REPL. Sometimes, people create multiple profiles for different Clojure versions; &lt;a href="https://github.com/technomancy/leiningen/blob/master/doc/PROFILES.md"&gt;Leiningen’s documentation&lt;/a&gt; mentions this possibility.&lt;/p&gt;&lt;p&gt;Unfortunately, with this approach it’s still not possible to AOT-compile things or create uberjars with Leiningen. (Putting Clojure in the &lt;code&gt;:provided&lt;/code&gt; profile causes building the uberjar to succeed, but the resulting &lt;code&gt;-standalone&lt;/code&gt; jar doesn’t actually contain Clojure).&lt;/p&gt;&lt;p&gt;Another option is to add Clojure to the main &lt;code&gt;:dependencies&lt;/code&gt;, but with &lt;code&gt;:scope "provided"&lt;/code&gt;. Per the &lt;a href="http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html"&gt;Maven documentation&lt;/a&gt;, this means:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;This is much like &lt;code&gt;compile&lt;/code&gt;, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope &lt;code&gt;provided&lt;/code&gt; because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.&lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;The key are the last words: “not transitive.” If project A depends on a library B that declares a “provided” dependency C, then C won’t be automatically put in A’s dependencies, and A is expected to explicitly declare its own C.&lt;/p&gt;&lt;p&gt;This means that it’s adequate for both libraries and standalone projects when it comes to declaring a Clojure dependency. It doesn’t break anything, doesn’t cause any ephemeral conflicts, and can be combined with the profiles approach when multiple configurations are called for.&lt;/p&gt;&lt;h3 id="cli-tools"&gt;cli-tools&lt;/h3&gt;&lt;p&gt;cli-tools will accept a &lt;code&gt;deps.edn&lt;/code&gt; as simple as &lt;code&gt;{}&lt;/code&gt;. Even passing &lt;code&gt;-Srepro&lt;/code&gt; to &lt;code&gt;clojure&lt;/code&gt; or &lt;code&gt;clj&lt;/code&gt; (which excludes the Clojure dependency that you probably have in your &lt;code&gt;~/.clojure/deps.edn&lt;/code&gt;) doesn’t break anything: cli-tools will just use 1.10.1 (at least as of version 1.10.1.536).&lt;/p&gt;&lt;p&gt;With cli-tools, as a library author you probably don’t have to declare a Clojure dependency at all. But things are less uniform in this land than they are in Leiningen (for example, there are quite a few uberjarrers to choose from), so it’s reasonable to check with your tooling first.&lt;/p&gt;&lt;h3 id="boot"&gt;Boot&lt;/h3&gt;&lt;p&gt;I’m no longer a Boot user, so I can’t tell. But from what I know, it uses Aether just like Leiningen and Maven do, so I’d wager a guess the same caveats apply as for Leiningen. Haven’t checked, though.&lt;/p&gt;&lt;h2 id="so-what-do-the-existing-projects-do?"&gt;So what do the existing projects do?&lt;/h2&gt;&lt;p&gt;I figured it would be a fun piece of research to examine how the popular projects depend (or don’t depend) on Clojure. I queried GitHub’s API for the 1000 most starred Clojure projects, fetched and parsed their &lt;code&gt;project.clj&lt;/code&gt;s and/or &lt;code&gt;deps.edn&lt;/code&gt;s, and tallied things up.&lt;/p&gt;&lt;p&gt;I’ll write a separate “making of” post, because it turned out to be an even more fun weekend project than I had anticipated. But for now, let me share the conclusions.&lt;/p&gt;&lt;p&gt;I ended up with 968 project definition files that I was able to successfully parse: 140 &lt;code&gt;deps.edn&lt;/code&gt;s and 828 &lt;code&gt;project.clj&lt;/code&gt;s. Here’s a breakdown of Clojure version declared as a “main” dependency (i.e., not in a profile or alias):&lt;/p&gt;&lt;img src="/img/blog/clojure-versions.png"&gt;
&lt;p&gt;N/A means that there’s no dependency on Clojure declared, and “other” is an umbrella for the zoo of alphas, betas and snapshots.&lt;/p&gt;&lt;p&gt;As expected, not depending on Clojure is comparatively more popular in the cli-tools land: almost half (48.6%) of cli-tools projects don’t declare a Clojure dependency, versus 21.5% (174 projects) for Leiningen.&lt;/p&gt;&lt;p&gt;That Leiningen number still seemed quite high to me, so I dug a little deeper. Out of those 174 projects, 100 have Clojure somewhere in their &lt;code&gt;:profiles&lt;/code&gt;. The remaining 74 are somewhat of outliers:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;some, like Ring or Pedestal, are umbrella projects composed of sub-projects (with the &lt;code&gt;lein-sub&lt;/code&gt; plugin) that have actual dependencies themselves;&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;some, like Klipse or Reagent, are essentially ClojureScript-only;&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;some, like Overtone, use the &lt;code&gt;lein-tools-deps&lt;/code&gt; plugin to store their dependencies in &lt;code&gt;deps.edn&lt;/code&gt; while using Leiningen for other tasks.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Finally, the popularity of &lt;code&gt;:scope "provided"&lt;/code&gt; is much lower. Only 68 Leiningen projects specify it (8.9% of those that declare any dependencies), and only two &lt;code&gt;deps.edn&lt;/code&gt; files do so (re-frame and fulcro – note that re-frame actually has both a &lt;code&gt;project.clj&lt;/code&gt; and a &lt;code&gt;deps.edn&lt;/code&gt;).&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2020-02-10:post:cond-indentation</id>
    <title>Indenting cond forms</title>
    <link href="http://blog.danieljanus.pl/cond-indentation/"/>
    <updated>2020-02-10T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;Indentation matters when reading Clojure code. It is the primary visual cue that helps the reader discern the code structure. Most Clojure code seen in the wild conforms to either the &lt;a href="https://github.com/bbatsov/clojure-style-guide#source-code-layout-organization"&gt;community style guide&lt;/a&gt; or the proposed &lt;a href="https://tonsky.me/blog/clojurefmt/"&gt;simplified rules&lt;/a&gt;; the existing editors make it easy to reformat code to match them.&lt;/p&gt;&lt;p&gt;I find both these rulesets to be helpful when reading code. But there’s one corner-case that’s been irking me: &lt;code&gt;cond&lt;/code&gt; forms.&lt;/p&gt;&lt;p&gt;&lt;code&gt;cond&lt;/code&gt; takes an even number of arguments: alternating test-expression pairs. They are commonly put next to each other, two forms per line.&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;cond&lt;/span&gt;&lt;/span&gt;
  test expr-1
  another-test expr-2
  &lt;span class="hljs-symbol"&gt;:else&lt;/span&gt; expr-3)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Sometimes, people align the expressions under one another, in a tabular fashion:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;cond&lt;/span&gt;&lt;/span&gt;
  test         expr-1
  another-test expr-2
  &lt;span class="hljs-symbol"&gt;:else&lt;/span&gt;        expr-3)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;But things get out of hand when either &lt;code&gt;tests&lt;/code&gt; or &lt;code&gt;exprs&lt;/code&gt; get longer and call for multiple lines themselves. There are several options here, all of them less than ideal.&lt;/p&gt;&lt;h3 id="tests-and-expressions-next-to-each-other"&gt;Tests and expressions next to each other&lt;/h3&gt;&lt;p&gt;In other words, keep the above rule. Because we’ll have multiple lines in a form, this tends to make the resulting code axe-shaped:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;cond&lt;/span&gt;&lt;/span&gt;
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;=&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;some-function&lt;/span&gt; something) expected-value) (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;do&lt;/span&gt;&lt;/span&gt;
                                                 (&lt;span class="hljs-name"&gt;do-this&lt;/span&gt;)
                                                 (&lt;span class="hljs-name"&gt;and-also-do-that&lt;/span&gt;))
  (&lt;span class="hljs-name"&gt;another-predicate&lt;/span&gt; something-else) (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;try&lt;/span&gt;&lt;/span&gt;
                                       (&lt;span class="hljs-name"&gt;do-another-thing&lt;/span&gt;)
                                       (&lt;span class="hljs-name"&gt;catch&lt;/span&gt; Exception _
                                         (&lt;span class="hljs-name"&gt;println&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;Whoops!&amp;quot;&lt;/span&gt;))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This yields code that is indented abnormally far to the right, forcing the reader’s eyeballs to move in two dimensions – even more so if the tabular feel is desired. If &lt;em&gt;both&lt;/em&gt; the test and the expression is multi-lined, it just looks plain weird.&lt;/p&gt;&lt;h3 id="stack-all-forms-vertically,-no-extra-spacing"&gt;Stack all forms vertically, no extra spacing&lt;/h3&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;cond&lt;/span&gt;&lt;/span&gt;
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;=&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;some-function&lt;/span&gt; something) expected-value)
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;do&lt;/span&gt;&lt;/span&gt;
    (&lt;span class="hljs-name"&gt;do-this&lt;/span&gt;)
    (&lt;span class="hljs-name"&gt;and-also-do-that&lt;/span&gt;))
  (&lt;span class="hljs-name"&gt;another-predicate&lt;/span&gt; something-else)
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;try&lt;/span&gt;&lt;/span&gt;
    (&lt;span class="hljs-name"&gt;do-another-thing&lt;/span&gt;)
    (&lt;span class="hljs-name"&gt;catch&lt;/span&gt; Exception _
      (&lt;span class="hljs-name"&gt;println&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;Whoops!&amp;quot;&lt;/span&gt;))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This gets rid of the long lines, but introduces another problem: it’s hard to tell at a glance&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;where a given test or expression starts or ends;&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;which tests are paired with which expression;&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;whether a given line corresponds to a test or an expression, and which one.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;h3 id="stack-all-forms-vertically,-blank-lines-between-test/expr-pairs"&gt;Stack all forms vertically, blank lines between test/expr pairs&lt;/h3&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;cond&lt;/span&gt;&lt;/span&gt;
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;=&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;some-function&lt;/span&gt; something) expected-value)
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;do&lt;/span&gt;&lt;/span&gt;
    (&lt;span class="hljs-name"&gt;do-this&lt;/span&gt;)
    (&lt;span class="hljs-name"&gt;and-also-do-that&lt;/span&gt;))

  (&lt;span class="hljs-name"&gt;another-predicate&lt;/span&gt; something-else)
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;try&lt;/span&gt;&lt;/span&gt;
    (&lt;span class="hljs-name"&gt;do-another-thing&lt;/span&gt;)
    (&lt;span class="hljs-name"&gt;catch&lt;/span&gt; Exception _
      (&lt;span class="hljs-name"&gt;println&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;Whoops!&amp;quot;&lt;/span&gt;))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The Style Guide &lt;a href="https://github.com/bbatsov/clojure-style-guide#short-forms-in-cond"&gt;says&lt;/a&gt; that this is an “ok-ish” thing to do.&lt;/p&gt;&lt;p&gt;But with the added blank lines, logical structure of the code is much more apparent. However, it breaks another assumption that I make when reading the code: &lt;em&gt;functions contain no blank lines.&lt;/em&gt; The Style Guide even &lt;a href="https://github.com/bbatsov/clojure-style-guide#no-blank-lines-within-def-forms"&gt;mentions it&lt;/a&gt;, saying that &lt;code&gt;cond&lt;/code&gt; forms are an acceptable exception.&lt;/p&gt;&lt;p&gt;It is now harder to tell at a glance where the enclosing function starts or ends. And once this assumption is broken once, the brain expects it to be broken again, causing reading disruption across the entire file.&lt;/p&gt;&lt;h3 id="forms-one-under-another,-extra-indentation-for-expressions-only"&gt;Forms one under another, extra indentation for expressions only&lt;/h3&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;cond&lt;/span&gt;&lt;/span&gt;
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;=&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;some-function&lt;/span&gt; something) expected-value)
    (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;do&lt;/span&gt;&lt;/span&gt;
      (&lt;span class="hljs-name"&gt;do-this&lt;/span&gt;)
      (&lt;span class="hljs-name"&gt;and-also-do-that&lt;/span&gt;))
  (&lt;span class="hljs-name"&gt;another-predicate&lt;/span&gt; something-else)
    (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;try&lt;/span&gt;&lt;/span&gt;
      (&lt;span class="hljs-name"&gt;do-another-thing&lt;/span&gt;)
      (&lt;span class="hljs-name"&gt;catch&lt;/span&gt; Exception _
        (&lt;span class="hljs-name"&gt;println&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;Whoops!&amp;quot;&lt;/span&gt;))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;I resorted to this several times. The lines are not too long; the visual cues are there; it’s obvious what is the condition, what is the test, and what goes with what.&lt;/p&gt;&lt;p&gt;Except… it’s against the rules. List items stacked vertically should be aligned one under the other. I have to actively fight my Emacs to enforce this formatting, and it will be lost next time I press &lt;code&gt;C-M-q&lt;/code&gt; on this form. No good.&lt;/p&gt;&lt;h3 id="forms-one-under-another,-expressions-prefixed-by-#-=&amp;gt;"&gt;Forms one under another, expressions prefixed by &lt;code&gt;#_=&gt;&lt;/code&gt;&lt;/h3&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;cond&lt;/span&gt;&lt;/span&gt;
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;=&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;some-function&lt;/span&gt; something) expected-value)
  #_=&amp;gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;do&lt;/span&gt;&lt;/span&gt;
         (&lt;span class="hljs-name"&gt;do-this&lt;/span&gt;)
         (&lt;span class="hljs-name"&gt;and-also-do-that&lt;/span&gt;))
  (&lt;span class="hljs-name"&gt;another-predicate&lt;/span&gt; something-else)
  #_=&amp;gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;try&lt;/span&gt;&lt;/span&gt;
         (&lt;span class="hljs-name"&gt;do-another-thing&lt;/span&gt;)
         (&lt;span class="hljs-name"&gt;catch&lt;/span&gt; Exception _
           (&lt;span class="hljs-name"&gt;println&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;Whoops!&amp;quot;&lt;/span&gt;))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This one is my own invention: I haven’t seen it anywhere else. But I think it manages to avoid most problems.&lt;/p&gt;&lt;p&gt;&lt;code&gt;#_&lt;/code&gt; is a reader macro that causes the next form to be elided and not seen by the compiler. &lt;code&gt;=&gt;&lt;/code&gt; is a valid form. Thus, &lt;code&gt;#_=&gt;&lt;/code&gt; is effectively whitespace as far as the compiler is concerned, and the indentation rules treat it as yet another symbol (although it technically isn’t one). No tooling is broken, no assumptions are broken, and the &lt;code&gt;#_=&gt;&lt;/code&gt; tends to be syntax-highlighted unintrusively so it doesn’t stand out. I tend to read it aloud as “then.”&lt;/p&gt;&lt;h3 id="meanwhile,-in-another-galaxy"&gt;Meanwhile, in another galaxy&lt;/h3&gt;&lt;p&gt;Other Lisps (Scheme and CL) wrap each test/expression pair in an extra pair of parens, thereby avoiding the blending of conditions and expressions when indented one under the other. But I’m still happy Clojure went with fewer parens. As I say, this is a corner case where additional pair of parens would somewhat help, but most of the time I find them less aesthetic and a visual clutter.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2020-01-21:post:middleware</id>
    <title>Careful with that middleware, Eugene</title>
    <link href="http://blog.danieljanus.pl/middleware/"/>
    <updated>2020-01-21T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;h2 id="prologue"&gt;Prologue&lt;/h2&gt;&lt;p&gt;I’ll be releasing version 0.3 of &lt;a href="https://github.com/nathell/skyscraper"&gt;Skyscraper&lt;/a&gt;, my Clojure framework for scraping entire sites, in a few days.&lt;/p&gt;&lt;p&gt;More than three years have passed since its last release. During that time, I’ve made a number of attempts at redesigning it to be more robust, more usable, and faster; the last one, resulting in an almost complete rewrite, is now almost ready for public use as I’m ironing out the rough edges, documenting it, and adding tests.&lt;/p&gt;&lt;p&gt;It’s been a long journey and I’ll blog about it someday; but today, I’d like to tell another story: one of a nasty bug I had encountered.&lt;/p&gt;&lt;h2 id="part-one:-wrap,-wrap,-wrap,-wrap"&gt;Part One: Wrap, wrap, wrap, wrap&lt;/h2&gt;&lt;p&gt;While updating the code of one of my old scrapers to use the API of Skyscraper 0.3, I noticed an odd thing: some of the output records contained scrambled text. Apparently, the character encoding was not recognised properly.&lt;/p&gt;&lt;p&gt;“Weird,” I thought. Skyscraper should be extra careful about honoring the encoding of pages being scraped (declared either in the headers, or the &lt;code&gt;&lt;meta http-equiv&gt;&lt;/code&gt; tag). In fact, I remembered having seen it working. What was wrong?&lt;/p&gt;&lt;p&gt;For every page that it downloads, Skyscraper 0.3 caches the HTTP response body along with the headers so that it doesn’t have to be downloaded again; the headers are needed to ensure proper encoding when parsing a cached page. The headers are lower-cased, so that Skyscraper can then call &lt;code&gt;(get all-headers "content-type")&lt;/code&gt; to get the encoding declared in headers. If this step is missed, and the server returns the encoding in a header named &lt;code&gt;Content-Type&lt;/code&gt;, it won’t be matched. Kaboom!&lt;/p&gt;&lt;p&gt;I looked at the cache, and sure enough, the header names in the cache were not lower-cased, even though they should be. But why?&lt;/p&gt;&lt;p&gt;Maybe I was mistaken, and I had forgotten the lower-casing after all? A glance at the code: no. The lower-casing was there, right around the call to the download function.&lt;/p&gt;&lt;p&gt;Digression: Skyscraper uses &lt;a href="https://github.com/dakrone/clj-http"&gt;clj-http&lt;/a&gt; to download pages. clj-http, in turn, uses the &lt;a href="http://clojure-doc.org/articles/cookbooks/middleware.html"&gt;middleware pattern&lt;/a&gt;: there’s a “bare” request function, and then there are wrapper functions that implement things like redirects, OAuth, exception handling, and what have you. I say “wrapper” because they literally wrap the bare function: &lt;code&gt;(wrap-something request)&lt;/code&gt; returns another function that acts just like &lt;code&gt;request&lt;/code&gt;, but with added functionality. And that other function can in turn be wrapped with yet another one, and so on.&lt;/p&gt;&lt;p&gt;There’s a default set of middleware wrappers defined by clj-http, and it also provides a macro, &lt;code&gt;with-additional-middleware&lt;/code&gt;, which allows you to specify additional wrappers. One such wrapper is &lt;code&gt;wrap-lower-case-headers&lt;/code&gt;, which, as the name suggests, causes the response’s header keys to be returned in lower case.&lt;/p&gt;&lt;p&gt;Back to Skyscraper. We’re ready to look at the code now. Can you spot the problem?&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [request-fn (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;or&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-symbol"&gt;:request-fn&lt;/span&gt; options)
                     http/request)]
  (&lt;span class="hljs-name"&gt;http/with-additional-middleware&lt;/span&gt; [http/wrap-lower-case-headers]
    (&lt;span class="hljs-name"&gt;request-fn&lt;/span&gt; req
                success-fn
                error-fn)))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;I stared at it for several minutes, did some dirty experiments in the REPL, perused the code of clj-http, until it dawned on me.&lt;/p&gt;&lt;p&gt;See that &lt;code&gt;request-fn&lt;/code&gt;? Even though Skyscraper uses &lt;code&gt;http/request&lt;/code&gt; by default, you can override it in the options to supply your own way of doing HTTP. (Some of the tests use it to mock calls to a HTTP server.) In this particular case, it was not overridden, though: the usual &lt;code&gt;http/request&lt;/code&gt; was used. So things looked good: within the body of &lt;code&gt;http/with-additional-middleware&lt;/code&gt;, headers should be lower-cased because &lt;code&gt;request-fn&lt;/code&gt; is &lt;code&gt;http/request&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;Or is it?&lt;/p&gt;&lt;p&gt;Let me show you how &lt;code&gt;with-additional-middleware&lt;/code&gt; is implemented. It expands to another macro, &lt;code&gt;with-middleware&lt;/code&gt;, which is defined as follows (docstring redacted):&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;defmacro&lt;/span&gt; &lt;span class="hljs-title"&gt;with-middleware&lt;/span&gt;
  [middleware &amp;amp; body]
  `(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [m# ~middleware]
     (&lt;span class="hljs-name"&gt;binding&lt;/span&gt; [*current-middleware* m#
               clj-http.client/request (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;reduce&lt;/span&gt;&lt;/span&gt; #(%&lt;span class="hljs-number"&gt;2&lt;/span&gt; %&lt;span class="hljs-number"&gt;1&lt;/span&gt;)
                                               clj-http.core/request
                                               m#)]
       ~@body)))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;That’s right: &lt;code&gt;with-middleware&lt;/code&gt; works by dynamically rebinding &lt;code&gt;http/request&lt;/code&gt;. Which means the &lt;code&gt;request-fn&lt;/code&gt; I was calling is not actually the wrapped version, but the one captured by the outer &lt;code&gt;let&lt;/code&gt;, the one that wasn’t rebound, the one without the additional middleware!&lt;/p&gt;&lt;p&gt;After this light-bulb moment, I moved &lt;code&gt;with-additional-middleware&lt;/code&gt; outside of the &lt;code&gt;let&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;http/with-additional-middleware&lt;/span&gt; [http/wrap-lower-case-headers]
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [request-fn (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;or&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-symbol"&gt;:request-fn&lt;/span&gt; options)
                       http/request)]
    (&lt;span class="hljs-name"&gt;request-fn&lt;/span&gt; req
                success-fn
                error-fn)))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And, sure enough, it worked.&lt;/p&gt;&lt;h2 id="part-two:-the-tests-are-screaming-loud"&gt;Part Two: The tests are screaming loud&lt;/h2&gt;&lt;p&gt;Is it the end of the story? I’m guessing you’re thinking it is. I thought so too. But I wanted to add one last thing: a regression test, so I’d never run into the same problem in the future.&lt;/p&gt;&lt;p&gt;I whipped up a test in which one ISO-8859-2-encoded page was scraped, and a check for the correct string was made. I ran it against the fixed code. It was green. I ran it against the previous, broken version…&lt;/p&gt;&lt;p&gt;It was &lt;em&gt;green&lt;/em&gt;, too.&lt;/p&gt;&lt;p&gt;At this point, I knew I had to get to the bottom of this.&lt;/p&gt;&lt;p&gt;Back to experimenting. After a while, I found out that extracting encoding from a freshly-downloaded page actually worked fine! It only failed when parsing headers fetched from a cache. But the map was the same in both cases! In both cases, the code was effectively doing&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;get&lt;/span&gt;&lt;/span&gt; {&lt;span class="hljs-string"&gt;&amp;quot;Content-Type&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;text/html; charset=ISO-8859-2&amp;quot;&lt;/span&gt;}
     &lt;span class="hljs-string"&gt;&amp;quot;content-type&amp;quot;&lt;/span&gt;)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This lookup &lt;em&gt;shouldn’t&lt;/em&gt; succeed: in map lookup, string comparison is case-sensitive. And yet, for freshly-downloaded headers, it &lt;em&gt;did&lt;/em&gt; succeed!&lt;/p&gt;&lt;p&gt;I checked the &lt;code&gt;type&lt;/code&gt; of both maps. One of them was a &lt;code&gt;clojure.lang.PersistentHashMap&lt;/code&gt;, as expected. The other one was not. It was actually a &lt;code&gt;clj_http.headers.HeaderMap&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;I’ll let the comment of that one speak for itself:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;a map implementation that stores both the original (or canonical) key and value for each key/value pair, but performs lookups and other operations using the normalized – this allows a value to be looked up by many similar keys, and not just the exact precise key it was originally stored with.&lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;And so it turned out that the library authors have actually foreseen the need for looking up headers irrespective of case, and provided a helpful means for that. The whole lowercasing business was not needed, after all!&lt;/p&gt;&lt;p&gt;I stripped out the &lt;code&gt;with-additional-middleware&lt;/code&gt; altogether, added some code elsewhere to ensure that the header map is a &lt;code&gt;HeaderMap&lt;/code&gt; regardless of whether it comes from the cache or not, and they lived happily ever after.&lt;/p&gt;&lt;h2 id="epilogue"&gt;Epilogue&lt;/h2&gt;&lt;p&gt;Moral of the story? It’s twofold.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;Dynamic rebinding can be dangerous. Having a public API that is implemented in terms of dynamic rebinding, even more so. I’d prefer if clj-http just allowed the custom middleware to be explicitly specified as an argument, thusly:&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;http/request&lt;/span&gt; req
              &lt;span class="hljs-symbol"&gt;:additional-middleware&lt;/span&gt; [http/wrap-lower-case-headers])
&lt;/code&gt;&lt;/pre&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;Know your dependencies. If you have a problem that might be generically addressed by the library you’re using, look deeper. It might be there already.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Thanks to &lt;a href="https://www.3jane.co.uk"&gt;3Jane&lt;/a&gt; for proofreading this article.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2020-01-03:post:word-champions</id>
    <title>Word Champions</title>
    <link href="http://blog.danieljanus.pl/word-champions/"/>
    <updated>2020-01-03T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;This story begins on August 9, 2017, when a friend messaged me on Facebook: “Hey, I’m going to be on a TV talent show this weekend. They’ll be giving me this kind of problems. Any ideas how to prepare?”&lt;/p&gt;&lt;p&gt;He attached a link to this video:&lt;/p&gt;&lt;iframe width="100%" height="500" src="https://www.youtube.com/embed/34AcKyYdNBo" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;
&lt;p&gt;Now, we’re both avid Scrabble players, so we explored some ideas about extracting helpful data out of the &lt;a href="http://www.pfs.org.pl/english.php"&gt;Official Polish Scrabble Player’s Dictionary&lt;/a&gt;. I launched a Clojure REPL and wrote some throwaway code to generate sample training problems for Krzysztof. The code used a brute-force algorithm, so it was dog slow, but it was a start. It was Wednesday.&lt;/p&gt;&lt;p&gt;I woke up next morning with the problem still in my head. Clearly, I had found myself in a &lt;a href="https://xkcd.com/356/"&gt;nerd sniping&lt;/a&gt; situation.&lt;/p&gt;&lt;img src="https://imgs.xkcd.com/comics/nerd_sniping.png"&gt;
&lt;p&gt;There was only one obvious way out—to write a full-blown training app so that Krzysztof could practice as if he were in the studio. The clock was ticking: we had two days left.&lt;/p&gt;&lt;p&gt;After work, I started a fresh &lt;a href="https://github.com/day8/re-frame/"&gt;re-frame&lt;/a&gt; project. (I was a recent re-frame convert those days, so I wanted to see how well it could cope with the task at hand.) Late that night, or rather early next morning, the prototype was ready.&lt;/p&gt;&lt;p&gt;It had very messy code. It only worked on Chrome. It failed miserably on mobile. It took ages to load. It had native JS dependencies, notably &lt;a href="https://material-ui.com/"&gt;Material-UI&lt;/a&gt; and &lt;a href="https://react-dnd.github.io/react-dnd/about"&gt;react-dnd&lt;/a&gt;, and for some reason it would not compile with ClojureScript’s advanced optimization turned on; so it weighed in at more than 6 MB, slurping in more than 300 JS files on load.&lt;/p&gt;&lt;p&gt;But it worked.&lt;/p&gt;&lt;p&gt;Krzysztof didn’t win his episode against the other contestants, ending up third, but he completed his challenge successfully. It took him 3 minutes and 42 seconds, out of 5 minutes allotted. The episode aired on 24 October.&lt;/p&gt;&lt;iframe width="100%" height="500" src="https://www.youtube.com/embed/7ec6j31nlAk" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;
&lt;p&gt;Krzysztof said that the problem he ended up solving on the show was way easier than the ones generated by the app: had they been more difficult, the wow factor might have been higher.&lt;/p&gt;&lt;p&gt;Several months later, we met at a Scrabble tournament, and I received a present. I wish I had photographed that bottle of wine, so I could show it here, but I hadn’t.&lt;/p&gt;&lt;p&gt;Meanwhile, the code remained messy and low-priority. But I kept returning to it when I felt like it, fixing up things one at a time. I’ve added difficulty levels, so you can have only one diagram, or three. I’ve made it work on Firefox. I’ve done a major rewrite, restructuring the code in a sane way and removing the JS dependencies other than React. I’ve made advanced compilation work, getting the JS down to 400K. I’ve made it work on mobile devices. I’ve written a puzzle generator in C, which ended up several orders of magnitude faster than the prototype Clojure version (it’s still brute-force, but uses some dirty C tricks to speed things up; I hope to rewrite it in Rust someday).&lt;/p&gt;&lt;p&gt;And now, 2½ years later, I’ve added an English version, with an accompanying set of puzzles (generated from a wordlist taken from &lt;a href="https://github.com/first20hours/google-10000-english"&gt;this repo&lt;/a&gt;), for the English-speaking world to enjoy.&lt;/p&gt;&lt;p&gt;&lt;a href="http://danieljanus.pl/wladcyslow/"&gt;Play Word Champions now!&lt;/a&gt;&lt;/p&gt;&lt;p&gt;The code is &lt;a href="https://github.com/nathell/wordchampions"&gt;on GitHub&lt;/a&gt; if you’d like to check it out or try hacking on it. It’s small, less than 1KLOC in total, so I think it can be a learning tool for re-frame or ClojureScript.&lt;/p&gt;&lt;p&gt;(This game as featured on the TV shows is called Gridlock. The name “Word Champions” was inspired by the title of Krzysztof’s video on YouTube, literally meaning “Lord of the Words”. There is no pun in the Polish title.)&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2019-02-05:post:clj-tvision</id>
    <title>Re-framing text-mode apps</title>
    <link href="http://blog.danieljanus.pl/clj-tvision/"/>
    <updated>2019-02-05T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;h2 id="intro"&gt;Intro&lt;/h2&gt;&lt;blockquote&gt;&lt;p&gt;“But, you know, many explorers liked to go to places that are unusual. And, it’s only for the fun of it.” – Richard P. Feynman&lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;A couple of nights ago, I hacked together a small Clojure program.&lt;/p&gt;&lt;p&gt;All it does is displays a terminal window with a red rectangle in it. You can use your cursor keys to move it around the window, and space bar to change its colour. It’s fun, but it doesn’t sound very useful, does it?&lt;/p&gt;&lt;p&gt;In this post, I’ll try to convince you that there’s more to this little toy than might at first sight appear. You may want to check out &lt;a href="https://github.com/nathell/clj-tvision"&gt;the repo&lt;/a&gt; as you go along.&lt;/p&gt;&lt;h2 id="in-which-an-unexpected-appearance-is-made"&gt;In which an unexpected appearance is made&lt;/h2&gt;&lt;p&gt;(I’ve always envied &lt;a href="https://technomancy.us"&gt;Phil Hagelberg&lt;/a&gt; this kind of headlines.)&lt;/p&gt;&lt;p&gt;As you might have guessed from this article’s title, clj-tvision (a working name for the program) is a &lt;a href="https://github.com/Day8/re-frame"&gt;re-frame&lt;/a&gt; app.&lt;/p&gt;&lt;p&gt;For those of you who haven’t heard of re-frame, a word of explanation: it’s a ClojureScripty way of writing React apps, with Redux-like management of application state. If you do know re-frame (shameless plug: we at &lt;a href="https://works-hub.com"&gt;WorksHub&lt;/a&gt; do, and use it a lot: it powers the site you’re looking at right now!), you’ll instantly find yourself at home. However, a few moments later, a thought might dawn upon you, and you might start to feel a little uneasy…&lt;/p&gt;&lt;p&gt;Because I’ve mentioned React and ClojureScript, and yet I’d said earlier that we’re talking a text-mode application here. And I’ve mentioned that it’s written in Clojure. It is, in fact, not using React at all, and it has nothing to do whatsoever with ClojureScript, JavaScript, or the browser.&lt;/p&gt;&lt;p&gt;How is that even possible?&lt;/p&gt;&lt;p&gt;Here’s the catch: re-frame is implemented in &lt;code&gt;.cljc&lt;/code&gt; files. So while it’s mostly used in the ClojureScript frontend, it &lt;em&gt;can&lt;/em&gt; be used from Clojure. You may know this if you’re testing your events or subscriptions on the JVM.&lt;/p&gt;&lt;p&gt;While it’s mostly – if not hitherto exclusively – used for just that, I wanted to explore whether it could be used to manage state in an actual, non-web app. Text-mode is a great playground for this kind of exploration. Rather than picking a GUI toolkit and concern myself with its intricacies, I chose to just put things on a rectangular sheet of text characters.&lt;/p&gt;&lt;p&gt;(But if you are interested in pursuing a React-ish approach for GUIs, check out what Bodil Stokke’s been doing in &lt;a href="https://github.com/bodil/vgtk"&gt;vgtk&lt;/a&gt;.)&lt;/p&gt;&lt;h2 id="living-without-the-dom"&gt;Living without the DOM&lt;/h2&gt;&lt;p&gt;The building blocks of a re-frame app are subscriptions, events, and views. While the first two work in Clojureland pretty much the same way they do in the browser (although there are differences, of which more anon), views are a different beast.&lt;/p&gt;&lt;p&gt;&lt;a href="https://github.com/Day8/re-frame/blob/master/docs/SubscriptionFlow.md"&gt;re-frame’s documentation&lt;/a&gt; says that views are “data in, Hiccup out. Hiccup is ClojureScript data structures which represent DOM.” But outside of the browser realm, there’s no DOM. So let’s rephrase that more generally: re-frame views should produce &lt;em&gt;data structures which declaratively describe the component’s appearance to the user&lt;/em&gt;. In web apps, those structures correspond to the DOM. What they will look like outside is up to us. We’ll be growing our own DOM-like model, piecemeal, as needs arise.&lt;/p&gt;&lt;p&gt;For clj-tvision, I’ve opted for a very simple thing. Let’s start with a concrete example. Here’s a view:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;defn&lt;/span&gt; &lt;span class="hljs-title"&gt;view&lt;/span&gt; []
  [{&lt;span class="hljs-symbol"&gt;:type&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:rectangle&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:x1&lt;/span&gt; &lt;span class="hljs-number"&gt;10&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:y1&lt;/span&gt; &lt;span class="hljs-number"&gt;5&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:x2&lt;/span&gt; &lt;span class="hljs-number"&gt;20&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:y2&lt;/span&gt; &lt;span class="hljs-number"&gt;10&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:color&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:red&lt;/span&gt;}])
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Unlike in the DOM, in this model the UI state isn’t a tree. It’s a flat sequence of maps that each represent individual “primitive elements”. We could come up with a fancy buzzword-compliant name and call it Component List Model, or CLiM for short, in homage to &lt;a href="https://en.wikipedia.org/wiki/Common_Lisp_Interface_Manager"&gt;the venerable GUI toolkit&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Like normal re-frame views, CLiM views can include subviews. An example follows:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;defn&lt;/span&gt; &lt;span class="hljs-title"&gt;square&lt;/span&gt; [left top size color]
  [{&lt;span class="hljs-symbol"&gt;:type&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:rectangle&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt;
    &lt;span class="hljs-symbol"&gt;:x1&lt;/span&gt; left&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt;
    &lt;span class="hljs-symbol"&gt;:y1&lt;/span&gt; top&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt;
    &lt;span class="hljs-symbol"&gt;:x2&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;+&lt;/span&gt;&lt;/span&gt; left size &lt;span class="hljs-number"&gt;-1&lt;/span&gt;)&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt;
    &lt;span class="hljs-symbol"&gt;:y2&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;+&lt;/span&gt;&lt;/span&gt; top size &lt;span class="hljs-number"&gt;-1&lt;/span&gt;)&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt;
    &lt;span class="hljs-symbol"&gt;:color&lt;/span&gt; color}])

(&lt;span class="hljs-keyword"&gt;defn&lt;/span&gt; &lt;span class="hljs-title"&gt;view&lt;/span&gt; []
  [[square &lt;span class="hljs-number"&gt;1&lt;/span&gt; &lt;span class="hljs-number"&gt;1&lt;/span&gt; &lt;span class="hljs-number"&gt;5&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:red&lt;/span&gt;]
   [square &lt;span class="hljs-number"&gt;9&lt;/span&gt; &lt;span class="hljs-number"&gt;9&lt;/span&gt; &lt;span class="hljs-number"&gt;5&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:blue&lt;/span&gt;]])
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;How to render a view? Simple. First, flatten the list, performing funcalls on subviews so that you get a sequence containing only primitives. Then, draw each of them in order. (If there is an overlap, the trailers will obscure the leaders. Almost biblical.)&lt;/p&gt;&lt;p&gt;I’ve defined a multimethod, &lt;code&gt;render-primitive&lt;/code&gt;, dispatching on &lt;code&gt;:type&lt;/code&gt;. Its methods draw the corresponding primitive to a Lanterna screen.&lt;/p&gt;&lt;p&gt;Oh, didn’t I mention &lt;a href="https://github.com/mabe02/lanterna"&gt;Lanterna&lt;/a&gt;? It’s a Java library for terminals. Either real ones or emulated in Swing (easier to work with when you’re in a CIDER REPL). Plus, it sports virtual screens which can be blitted to a real terminal. This gives us a rough poor man’s equivalent of React’s VDOM. And it has a &lt;a href="https://github.com/AvramRobert/clojure-lanterna"&gt;Clojure wrapper&lt;/a&gt;!&lt;/p&gt;&lt;h2 id="events-at-eventide"&gt;Events at eventide&lt;/h2&gt;&lt;p&gt;So now we know how to draw our UI. But an app isn’t made up of just drawing. It has a main loop: it listens to events, which cause the app state to change and the corresponding components to redraw.&lt;/p&gt;&lt;p&gt;re-frame does provide an event mechanism, but it doesn’t &lt;em&gt;define&lt;/em&gt; any events per se. So we need to ask ourselves: who calls &lt;em&gt;dispatch&lt;/em&gt;? How do events originate? How to write the main loop?&lt;/p&gt;&lt;p&gt;clj-tvision is a proof-of-concept, so it doesn’t concern itself with mouse support. There’s only one way a user can interact with the app: via the keyboard. So keystrokes will be the only “source events”, as it were, for the app; and so writing the event loop should be simple. Sketching pseudocode:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;loop&lt;/span&gt;&lt;/span&gt; []
  (&lt;span class="hljs-name"&gt;render-app&lt;/span&gt;)
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [keystroke (&lt;span class="hljs-name"&gt;wait-for-key&lt;/span&gt;)] &lt;span class="hljs-comment"&gt;;; blocking!&lt;/span&gt;
    (&lt;span class="hljs-name"&gt;dispatch&lt;/span&gt; [&lt;span class="hljs-symbol"&gt;:key-pressed&lt;/span&gt; keystroke])
    (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;recur&lt;/span&gt;&lt;/span&gt;)))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Simple as that, should work, right?&lt;/p&gt;&lt;p&gt;Wrong.&lt;/p&gt;&lt;p&gt;If you actually try that, it’ll &lt;em&gt;somewhat&lt;/em&gt; work. Hit right arrow to move the rectangle, nothing happens! Hit right arrow again, it moves. Hit left, it moves right. Hit right, it moves left. Not what you want.&lt;/p&gt;&lt;p&gt;You see, there’s a complication stemming from the fact that re-frame’s events are asynchronous by default. (Hence the &lt;code&gt;dispatch&lt;/code&gt; vs. &lt;code&gt;dispatch-sync&lt;/code&gt; dichotomy.) They don’t get dispatched immediately; rather, re-frame places them on a queue and processes them asynchronously, so that they don’t hog the browser. The Clojure version of re-frame handles that using a single-threaded executor with a dedicated thread.&lt;/p&gt;&lt;p&gt;We &lt;em&gt;almost&lt;/em&gt; could use &lt;code&gt;dispatch-sync&lt;/code&gt; everywhere, but for re-frame that’s a no-no: once within a &lt;code&gt;dispatch-sync&lt;/code&gt; handler, you cannot dispatch other events. If you try anyway, re-frame will detect it and politely point its dragon-scaly head at you, explaining it doesn’t like it. (It is a benevolent dragon, you know.)&lt;/p&gt;&lt;p&gt;So we need to hook into that “next-tick” machinery of re-frame’s somehow. There are probably better ways of doing this, but I opted to blatantly redefine &lt;code&gt;re-frame.interop/next-tick&lt;/code&gt; to tell the main loop: “hey, events have been handled and we have a new state, dispatch an event so we can redraw.” This is one of the rare cases where monkey-patching third-party code with &lt;code&gt;alter-var-root&lt;/code&gt; saves you the hassle of forking that entire codebase.&lt;/p&gt;&lt;p&gt;So now we have &lt;em&gt;two&lt;/em&gt; sources of events: keystrokes, and &lt;code&gt;next-tick&lt;/code&gt;. To multiplex them, I’ve whipped up a channel with core.async. Feels hacky, but allows to add mouse support in the future. Or time-based events that will be fired periodically every so often.&lt;/p&gt;&lt;p&gt;For completeness, I should also add that Clojure-side re-frame doesn’t have the luxury of having reactive atoms provided by Reagent. Its ratoms are ordinary Clojure atoms. Unlike in ClojureScript, any time the app state changes, &lt;em&gt;every&lt;/em&gt; subscription in the signal graph will be recomputed. It may well be possible to port Reagent’s ratoms to Clojure, but it is a far more advanced exercise. For simple apps, what re-frame provides on its own might just be enough.&lt;/p&gt;&lt;p&gt;And with that final bit, we can swipe all that hackitude under the carpet… or, should I say, tuck it into an internal ns that hopefully no-one will ever look into. And we’re left with shiny, declarative, re-framey, beautiful UI code on the surface. &lt;a href="https://github.com/nathell/clj-tvision/blob/master/src/tvision/core.clj"&gt;Just look&lt;/a&gt;.&lt;/p&gt;&lt;h2 id="closing-thoughts"&gt;Closing thoughts&lt;/h2&gt;&lt;blockquote&gt;&lt;p&gt;“Within C++, there is a much smaller and cleaner language struggling to get out.” – Bjarne Stroustrup&lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;If you’ve ever encountered legacy C++ code, this will ring true. Come to think of it, Stroustrup’s words are true of every system that has grown organically over its lifetime, with features being added to it but hardly ever removed.&lt;/p&gt;&lt;p&gt;And modern webapps may well be the epitome of that kind of system. We now have desktop apps that are fully self-contained on a single machine, yet use an overwhelmingly complex and vast machinery grown out of a simple system originally devised to &lt;a href="http://info.cern.ch/hypertext/WWW/TheProject.html"&gt;view static documents over the Internet&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;For all that complexity, we continue to use it. Partly owing to its ubiquity, partly for convenience. In my experience, the abstractions provided by re-frame allow you to wrap your head around large apps and reason about them much more easily than, say, object-oriented approaches. It just feels right. Conversely, writing an app in, say, GTK+ would now feel like a setback by some twenty years.&lt;/p&gt;&lt;p&gt;So this toy, this movable rectangle on a black screen, is not so much an app as it is a philosophical exercise. It is what my typing fingers produced while I pondered, weak and weary: “can we throw away most of that cruft, while still enjoying the abstractions that make life so much easier?”&lt;/p&gt;&lt;p&gt;Can we?&lt;/p&gt;&lt;p&gt;This post was originally published on &lt;a href="https://functional.works-hub.com/learn/re-framing-text-mode-apps-fd5cf"&gt;Functional Works&lt;/a&gt;.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2014-09-13:post:happy-programmers-day</id>
    <title>Happy Programmers’ Day!</title>
    <link href="http://blog.danieljanus.pl/happy-programmers-day/"/>
    <updated>2014-09-13T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;Happy &lt;a href="https://en.wikipedia.org/wiki/Programmers&amp;apos;_Day"&gt;Programmers’ Day&lt;/a&gt;, everyone!&lt;/p&gt;&lt;p&gt;A feast isn’t a feast, though, until it has a proper way of celebrating it. The &lt;a href="https://en.wikipedia.org/wiki/Pi_Day"&gt;Pi Day&lt;/a&gt;, for instance, has one: you eat a pie (preferably exactly at 1:59:26.535am), but I haven’t heard of any way of celebrating the Programmers’ Day, so I had to invent one. An obvious way would be to write a program, preferably a non-trivial one, but that requires time and dedication, which not everyone is able to readily spare.&lt;/p&gt;&lt;p&gt;So here’s my idea: on Programmers’ Day, dust off a program that you wrote some time ago — something that is just lying around in some far corner of your hard disk, that you haven’t looked at in years, but that you had fun writing — and put it on &lt;a href="https://github.com/"&gt;GitHub&lt;/a&gt; for all the world to see, to share the joy of programming.&lt;/p&gt;&lt;p&gt;Let me initialize the new tradition by doing this myself. Here’s &lt;a href="https://github.com/nathell/haze"&gt;HAZE&lt;/a&gt;, the Haskellish Abominable Z-machine Emulator. It was my final assignment for a course in Advanced Functional Programming, in my fourth year at the Uni, way back in 2004. It is an emulator for an ancient kind of virtual machine, the &lt;a href="https://en.wikipedia.org/wiki/Z-machine"&gt;Z-machine&lt;/a&gt;, written from scratch in Haskell. It allows you to play text adventure games, such as &lt;a href="https://en.wikipedia.org/wiki/Zork"&gt;Zork&lt;/a&gt;, much in the vein of &lt;a href="https://davidgriffith.gitlab.io/frotz/"&gt;Frotz&lt;/a&gt;. It’s not very complete, and supports versions of the Z-machine up to 3 only, so newer games won’t run on it as it stands, but Zork is playable.&lt;/p&gt;&lt;p&gt;It probably won’t even compile in modern Haskell systems: it was originally written for GHC version 6.2.1, and extensively uses the FiniteMap data type, which was obsoleted shortly after and is no longer found in modern systems. I should have Linux and Windows binaries lying around (yes, I had compiled it under Windows, using MinGW/PDCurses); I’ll put them on GitHub once I find them.&lt;/p&gt;&lt;p&gt;My mind now wanders ten years back in time, to the days when I was writing it. It took me about three summer weeks to write HAZE from scratch, most of that time on a slow laptop where it took quite a lot of seconds to get GHC to compile even a simple thing. I would do some of it differently if I were doing it now — for one, the state of a &lt;code&gt;ZMachine&lt;/code&gt; is a central datatype to HAZE, and you’ll find a lot of functions that take and return ZMachines, so a state monad is an obvious choice; I didn’t understand monads well enough back then. But I still remember how I had the framework in place already and I was adding implementations of Z-code opcodes, one by one, to &lt;code&gt;ZMachine/ZCode/Impl.hs&lt;/code&gt;, recompiling, rerunning, getting messages about unimplemented opcodes, when all of a sudden I got the familiar message about a white house and a small mailbox. Freude!&lt;/p&gt;&lt;p&gt;I hope you enjoy looking at it at least half as much as I had enjoyed writing it.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2014-05-20:post:you-already-use-lisp-syntax</id>
    <title>You already use Lisp syntax</title>
    <link href="http://blog.danieljanus.pl/you-already-use-lisp-syntax/"/>
    <updated>2014-05-20T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;&lt;strong&gt;Unix Developer:&lt;/strong&gt; I’m not going to touch Lisp. It’s horrible!&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Me:&lt;/strong&gt; Why so?&lt;/p&gt;&lt;p&gt;&lt;strong&gt;UD:&lt;/strong&gt; The syntax! This illegible prefix-RPN syntax that nobody else uses. And just look at all these parens!&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Me:&lt;/strong&gt; Well, many people find it perfectly legible, although most agree that it takes some time to get accustomed to. But I think you’re mistaken. Lots of people are using Lisp syntax on a daily basis…&lt;/p&gt;&lt;p&gt;&lt;strong&gt;UD:&lt;/strong&gt; I happen to know no one doing this.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Me:&lt;/strong&gt; …without actually realizing this. In fact, I think &lt;em&gt;you&lt;/em&gt; yourself are using it.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;UD:&lt;/strong&gt; Wait, &lt;em&gt;what&lt;/em&gt;?!&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Me:&lt;/strong&gt; And the particular variant of Lisp syntax you’re using is called Bourne shell.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;UD:&lt;/strong&gt; Now I don’t understand. What on earth does the shell have to do with Lisp?&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Me:&lt;/strong&gt; Just look: in the shell, you put the name of the program first, followed by the arguments, separated by spaces. In Lisp it’s exactly the same, except that you put an opening paren at the beginning and a closing paren at the end.&lt;/p&gt;&lt;p&gt;Shell: &lt;code&gt;run-something arg1 arg2 arg3&lt;/code&gt;&lt;/p&gt;&lt;p&gt;Lisp: &lt;code&gt;(run-something arg1 arg2 arg3)&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;strong&gt;UD:&lt;/strong&gt; I still don’t get the analogy.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Me:&lt;/strong&gt; Then you need a mechanism for expression composition — putting the output of one expression as an input to another. In Lisp, you just nest the lists. And in the shell?&lt;/p&gt;&lt;p&gt;&lt;strong&gt;UD:&lt;/strong&gt; Backticks.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Me:&lt;/strong&gt; That’s right. Or &lt;code&gt;$()&lt;/code&gt;, which has the advantage of being more easily nestable. Let’s try arithmetic. How do you do arithmetic in the shell?&lt;/p&gt;&lt;p&gt;&lt;strong&gt;UD:&lt;/strong&gt; &lt;code&gt;expr&lt;/code&gt;. Or the Bash builtin &lt;code&gt;let&lt;/code&gt;. For example,&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs bash"&gt;$ &lt;span class="hljs-built_in"&gt;let&lt;/span&gt; x=&lt;span class="hljs-string"&gt;&amp;#x27;2*((10+4)/7)&amp;#x27;&lt;/span&gt;; &lt;span class="hljs-built_in"&gt;echo&lt;/span&gt; &lt;span class="hljs-variable"&gt;$x&lt;/span&gt;
4
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;strong&gt;Me:&lt;/strong&gt; Now wouldn’t it be in line with the spirit of Unix — to have programs do just one thing — if we had one program to do addition, and another to do subtraction, and yet another to do multiplication and division?&lt;/p&gt;&lt;p&gt;It’s trivial to write it in C:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs c"&gt;&lt;span class="hljs-meta"&gt;#&lt;span class="hljs-keyword"&gt;include&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;lt;stdio.h&amp;gt;&lt;/span&gt;&lt;/span&gt;
&lt;span class="hljs-meta"&gt;#&lt;span class="hljs-keyword"&gt;include&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;lt;stdlib.h&amp;gt;&lt;/span&gt;&lt;/span&gt;
&lt;span class="hljs-meta"&gt;#&lt;span class="hljs-keyword"&gt;include&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;lt;string.h&amp;gt;&lt;/span&gt;&lt;/span&gt;

&lt;span class="hljs-type"&gt;int&lt;/span&gt; &lt;span class="hljs-title function_"&gt;main&lt;/span&gt;&lt;span class="hljs-params"&gt;(&lt;span class="hljs-type"&gt;int&lt;/span&gt; argc, &lt;span class="hljs-type"&gt;char&lt;/span&gt; **argv)&lt;/span&gt; {
  &lt;span class="hljs-type"&gt;int&lt;/span&gt; mode = &lt;span class="hljs-number"&gt;-1&lt;/span&gt;, cnt = argc - &lt;span class="hljs-number"&gt;1&lt;/span&gt;, val, i;
  &lt;span class="hljs-type"&gt;char&lt;/span&gt; **args = argv + &lt;span class="hljs-number"&gt;1&lt;/span&gt;;
  &lt;span class="hljs-keyword"&gt;switch&lt;/span&gt; (argv[&lt;span class="hljs-number"&gt;0&lt;/span&gt;][&lt;span class="hljs-built_in"&gt;strlen&lt;/span&gt;(argv[&lt;span class="hljs-number"&gt;0&lt;/span&gt;]) - &lt;span class="hljs-number"&gt;1&lt;/span&gt;]) {
    &lt;span class="hljs-keyword"&gt;case&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;#x27;+&amp;#x27;&lt;/span&gt;: mode = &lt;span class="hljs-number"&gt;0&lt;/span&gt;; &lt;span class="hljs-keyword"&gt;break&lt;/span&gt;;
    &lt;span class="hljs-keyword"&gt;case&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;#x27;-&amp;#x27;&lt;/span&gt;: mode = &lt;span class="hljs-number"&gt;1&lt;/span&gt;; &lt;span class="hljs-keyword"&gt;break&lt;/span&gt;;
    &lt;span class="hljs-keyword"&gt;case&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;#x27;x&amp;#x27;&lt;/span&gt;: mode = &lt;span class="hljs-number"&gt;2&lt;/span&gt;; &lt;span class="hljs-keyword"&gt;break&lt;/span&gt;;
    &lt;span class="hljs-keyword"&gt;case&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;#x27;d&amp;#x27;&lt;/span&gt;: mode = &lt;span class="hljs-number"&gt;3&lt;/span&gt;; &lt;span class="hljs-keyword"&gt;break&lt;/span&gt;;
  }
  &lt;span class="hljs-keyword"&gt;if&lt;/span&gt; (mode == &lt;span class="hljs-number"&gt;-1&lt;/span&gt;) {
    &lt;span class="hljs-built_in"&gt;fprintf&lt;/span&gt;(&lt;span class="hljs-built_in"&gt;stderr&lt;/span&gt;, &lt;span class="hljs-string"&gt;&amp;quot;invalid math operation\n&amp;quot;&lt;/span&gt;);
    &lt;span class="hljs-keyword"&gt;return&lt;/span&gt; &lt;span class="hljs-number"&gt;1&lt;/span&gt;;
  }
  &lt;span class="hljs-keyword"&gt;if&lt;/span&gt; ((mode == &lt;span class="hljs-number"&gt;1&lt;/span&gt; || mode == &lt;span class="hljs-number"&gt;3&lt;/span&gt;) &amp;amp;&amp;amp; !cnt) {
    &lt;span class="hljs-built_in"&gt;fprintf&lt;/span&gt;(&lt;span class="hljs-built_in"&gt;stderr&lt;/span&gt;, &lt;span class="hljs-string"&gt;&amp;quot;%s requires at least one arg\n&amp;quot;&lt;/span&gt;, argv[&lt;span class="hljs-number"&gt;0&lt;/span&gt;]);
    &lt;span class="hljs-keyword"&gt;return&lt;/span&gt; &lt;span class="hljs-number"&gt;1&lt;/span&gt;;
  }
  &lt;span class="hljs-keyword"&gt;switch&lt;/span&gt; (mode) {
    &lt;span class="hljs-keyword"&gt;case&lt;/span&gt; &lt;span class="hljs-number"&gt;0&lt;/span&gt;: val = &lt;span class="hljs-number"&gt;0&lt;/span&gt;; &lt;span class="hljs-keyword"&gt;break&lt;/span&gt;;
    &lt;span class="hljs-keyword"&gt;case&lt;/span&gt; &lt;span class="hljs-number"&gt;2&lt;/span&gt;: val = &lt;span class="hljs-number"&gt;1&lt;/span&gt;; &lt;span class="hljs-keyword"&gt;break&lt;/span&gt;;
    &lt;span class="hljs-keyword"&gt;default&lt;/span&gt;: val = atoi(*args++); cnt--; &lt;span class="hljs-keyword"&gt;break&lt;/span&gt;;
  }
  &lt;span class="hljs-keyword"&gt;while&lt;/span&gt; (cnt--) {
    &lt;span class="hljs-keyword"&gt;switch&lt;/span&gt; (mode) {
      &lt;span class="hljs-keyword"&gt;case&lt;/span&gt; &lt;span class="hljs-number"&gt;0&lt;/span&gt;: val += atoi(*args++); &lt;span class="hljs-keyword"&gt;break&lt;/span&gt;;
      &lt;span class="hljs-keyword"&gt;case&lt;/span&gt; &lt;span class="hljs-number"&gt;1&lt;/span&gt;: val -= atoi(*args++); &lt;span class="hljs-keyword"&gt;break&lt;/span&gt;;
      &lt;span class="hljs-keyword"&gt;case&lt;/span&gt; &lt;span class="hljs-number"&gt;2&lt;/span&gt;: val *= atoi(*args++); &lt;span class="hljs-keyword"&gt;break&lt;/span&gt;;
      &lt;span class="hljs-keyword"&gt;case&lt;/span&gt; &lt;span class="hljs-number"&gt;3&lt;/span&gt;: val /= atoi(*args++); &lt;span class="hljs-keyword"&gt;break&lt;/span&gt;;
    }
  }
  &lt;span class="hljs-built_in"&gt;printf&lt;/span&gt;(&lt;span class="hljs-string"&gt;&amp;quot;%d\n&amp;quot;&lt;/span&gt;, val);
  &lt;span class="hljs-keyword"&gt;return&lt;/span&gt; &lt;span class="hljs-number"&gt;0&lt;/span&gt;;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This dispatches on the last character of its name, so it can be symlinked to &lt;code&gt;+&lt;/code&gt;, &lt;code&gt;-&lt;/code&gt;, &lt;code&gt;x&lt;/code&gt; and &lt;code&gt;d&lt;/code&gt; (I picked unusual names for multiplication and division to make them legal and avoid escaping).&lt;/p&gt;&lt;p&gt;Now behold:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs bash"&gt;$ x 2 $(d $(+ 10 4) 7)
4
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;strong&gt;UD:&lt;/strong&gt; Wow, this sure looks a lot like Lisp!&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Me:&lt;/strong&gt; And yet it’s the shell. Our two basic rules — program-name-first and &lt;code&gt;$()&lt;/code&gt;-for-composition — allowed us to explicitly specify the order of evaluation, so there was no need to do any fancy parsing beyond what the shell already provides.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;UD:&lt;/strong&gt; So is the shell a Lisp?&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Me:&lt;/strong&gt; Not really. The shell is &lt;a href="http://blog.codinghorror.com/new-programming-jargon/"&gt;stringly typed&lt;/a&gt;: a program takes textual parameters and produces textual output. To qualify as a Lisp, it would have to have a composite type: a list or a cons cell to build lists on top of. Then, you’d be able to represent code as this data structure, and write programs to transform code to other code.&lt;/p&gt;&lt;p&gt;But the Tao of Lisp lingers in the shell syntax.&lt;/p&gt;&lt;hr&gt;
&lt;p&gt;I know I’ve glossed over many details here, like the shell syntax for redirection, globbing, subprocesses, the fact that programs have standard input in addition to command-line arguments, pipes, etc. — all these make the analogy rather weak. But I think it’s an interesting way to teach Lisp syntax to people.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2014-04-06:post:dos-debugging-quirk</id>
    <title>DOS debugging quirk</title>
    <link href="http://blog.danieljanus.pl/dos-debugging-quirk/"/>
    <updated>2014-04-06T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;While hacking on Lithium, I’ve noticed an interesting thing. Here’s a sample DOS program in assembly (TASM syntax):&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs x86asm"&gt;&lt;span class="hljs-meta"&gt;.model&lt;/span&gt; tiny
&lt;span class="hljs-meta"&gt;.code&lt;/span&gt;
  org &lt;span class="hljs-number"&gt;100h&lt;/span&gt;

N &lt;span class="hljs-built_in"&gt;equ&lt;/span&gt; &lt;span class="hljs-number"&gt;2&lt;/span&gt;
&lt;span class="hljs-symbol"&gt;
start:&lt;/span&gt;
  &lt;span class="hljs-keyword"&gt;mov&lt;/span&gt; &lt;span class="hljs-built_in"&gt;bp&lt;/span&gt;,&lt;span class="hljs-built_in"&gt;sp&lt;/span&gt;
  &lt;span class="hljs-keyword"&gt;mov&lt;/span&gt; &lt;span class="hljs-built_in"&gt;ax&lt;/span&gt;,&lt;span class="hljs-number"&gt;100&lt;/span&gt;
  &lt;span class="hljs-keyword"&gt;mov&lt;/span&gt; [&lt;span class="hljs-built_in"&gt;bp&lt;/span&gt;-N],&lt;span class="hljs-built_in"&gt;ax&lt;/span&gt;
  &lt;span class="hljs-keyword"&gt;mov&lt;/span&gt; &lt;span class="hljs-built_in"&gt;cx&lt;/span&gt;,[&lt;span class="hljs-built_in"&gt;bp&lt;/span&gt;-N]
  &lt;span class="hljs-keyword"&gt;cmp&lt;/span&gt; &lt;span class="hljs-built_in"&gt;cx&lt;/span&gt;,&lt;span class="hljs-built_in"&gt;ax&lt;/span&gt;
  &lt;span class="hljs-keyword"&gt;jne&lt;/span&gt; wrong
  &lt;span class="hljs-keyword"&gt;mov&lt;/span&gt; &lt;span class="hljs-built_in"&gt;dx&lt;/span&gt;,offset msg
  &lt;span class="hljs-keyword"&gt;jmp&lt;/span&gt; disp
&lt;span class="hljs-symbol"&gt;wrong:&lt;/span&gt;
  &lt;span class="hljs-keyword"&gt;mov&lt;/span&gt; &lt;span class="hljs-built_in"&gt;dx&lt;/span&gt;,offset msg2
&lt;span class="hljs-symbol"&gt;disp:&lt;/span&gt;
  &lt;span class="hljs-keyword"&gt;mov&lt;/span&gt; &lt;span class="hljs-number"&gt;ah&lt;/span&gt;,&lt;span class="hljs-number"&gt;9&lt;/span&gt;
  &lt;span class="hljs-keyword"&gt;int&lt;/span&gt; &lt;span class="hljs-number"&gt;21h&lt;/span&gt;
  &lt;span class="hljs-keyword"&gt;mov&lt;/span&gt; &lt;span class="hljs-built_in"&gt;ax&lt;/span&gt;,&lt;span class="hljs-number"&gt;4c00h&lt;/span&gt;
  &lt;span class="hljs-keyword"&gt;int&lt;/span&gt; &lt;span class="hljs-number"&gt;21h&lt;/span&gt;

msg &lt;span class="hljs-built_in"&gt;db&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;ok$&amp;quot;&lt;/span&gt;
msg2 &lt;span class="hljs-built_in"&gt;db&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;wrong$&amp;quot;&lt;/span&gt;
end start
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;If you assemble, link and then execute it normally, typing &lt;code&gt;prog&lt;/code&gt; in the DOS command line, it will output the string “ok”. But if you trace through the program in a debugger instead, it will say “wrong”! What’s wrong?&lt;/p&gt;&lt;p&gt;The problem is in lines 10-11 (instructions 3-4). Here’s what happens when you trace through this program in DOS 6.22’s &lt;code&gt;DEBUG.EXE&lt;/code&gt;:&lt;/p&gt;&lt;img src="/img/blog/debug.png"&gt;
&lt;p&gt;Note how in instruction 3 (actually displayed as the second above) we set the word &lt;code&gt;SS:0xFFFC&lt;/code&gt; to &lt;code&gt;100&lt;/code&gt;. When about to execute the following instruction, we would expect that word to continue to hold the value &lt;code&gt;100&lt;/code&gt;, because nothing which could have changed that value has happened in between. Instead, the debugger still reports it as &lt;code&gt;0x0D8A&lt;/code&gt;, as if instruction 3 had not been executed at all — and, interestingly, after actually executing this instruction, &lt;code&gt;CX&lt;/code&gt; gets yet another value of &lt;code&gt;0x7302&lt;/code&gt;!&lt;/p&gt;&lt;p&gt;Normally, thinking of DOS &lt;code&gt;.COM&lt;/code&gt; programs, you assume a 64KB-long chunk of memory that the program has all to itself: the code starts at &lt;code&gt;0x100&lt;/code&gt;, the stack grows from &lt;code&gt;0xFFFE&lt;/code&gt; downwards (at any given time, the region from &lt;code&gt;SP&lt;/code&gt; to &lt;code&gt;0xFFFE&lt;/code&gt; contains data currently on the stack), and all memory in between is free for the program to use however it deems fit. It turns out that, when debugging, it is not the case: the debuggers need to manipulate the region just underneath the program’s stack in order to handle the tracing/breakpoint interrupt traps.&lt;/p&gt;&lt;p&gt;I’ve verified that both DOS’s DEBUG and Borland’s Turbo Debugger 5 do this. The unsafe-to-touch amount of space below SP that they need, however, varies. Manipulating the N constant in the original program, I’ve determined that DEBUG only needs 8 bytes below SP, whereas for TD it is a whopping 18 bytes.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2014-04-02:post:2048</id>
    <title>2048: A close look at the source</title>
    <link href="http://blog.danieljanus.pl/2048/"/>
    <updated>2014-04-02T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;Dust has now mostly settled down on &lt;a href="https://gabrielecirulli.github.io/2048/"&gt;2048&lt;/a&gt;. Yet, in all the deluge of variants and clones that has swept through &lt;a href="https://news.ycombinator.com/"&gt;Hacker News&lt;/a&gt;, little has been written about the experience of modifying the game. As I too have jumped on the 2048-modding bandwagon, it’s time to fill that gap, because, as we shall see, the code more than deserves a close look.&lt;/p&gt;&lt;p&gt;I’ll start with briefly describing my variant. It’s called &lt;a href="http://danieljanus.pl/wosg"&gt;“words oh so great”&lt;/a&gt; (a rather miserable attempt at a pun on “two-oh-four-eight”) and is a consequence of a thought I had, being an avid Scrabble player, after seeing the &lt;a href="http://joppi.github.io/2048-3D/"&gt;3D&lt;/a&gt; and &lt;a href="http://huonw.github.io/2048-4D/"&gt;4D&lt;/a&gt; versions: “what if we mashed 2048 and Scrabble together?” The answer just lended itself automatically.&lt;/p&gt;&lt;p&gt;Letters instead of number tiles, that was obvious. And you use them to form words. It is unclear how merging tiles should work: merging two identical tiles, as in the original, just wouldn’t make sense here, so drop the concept of merging and make the tiles disappear instead when you form a word. In Scrabble, the minimum length of a word is two, but allowing two-letter words here would mean too many words formed accidentally, so make it at least three. And 16 squares sounds like too tight a space, so increase it to 5x5. And there you have the modified rules.&lt;/p&gt;&lt;p&gt;I &lt;a href="https://github.com/nathell/wosg"&gt;cloned&lt;/a&gt; the Git repo, downloaded an English word list (&lt;a href="http://dreamsteep.com/projects/the-english-open-word-list.html"&gt;EOWL&lt;/a&gt;), and set out to work. It took me just over three hours from the initial idea to putting the modified version online and submitting a link to HN. I think three hours is not bad, considering that I’ve significantly changed the game mechanics. And, in my opinion, this is a testimony to the quality of Gabriele Cirulli’s code.&lt;/p&gt;&lt;p&gt;The code follows the MVC pattern, despite not relying on any frameworks or libraries. The model is comprised of the &lt;code&gt;Tile&lt;/code&gt; and &lt;code&gt;Grid&lt;/code&gt; classes, laying out the universe for the game as well as some basic rules governing it, and the &lt;code&gt;GameManager&lt;/code&gt; that implements the game mechanics: how tiles move around, when they can merge together, when the game ends, and so on. It also uses a helper class called &lt;code&gt;LocalStorageManager&lt;/code&gt; to keep the score and save it in the browser’s local storage.&lt;/p&gt;&lt;p&gt;The view part is called an “actuator” in 2048 parlance. The &lt;code&gt;HTMLActuator&lt;/code&gt; takes the game state and updates the DOM tree accordingly. It also uses a micro-framework for animations. The controller takes the form of a &lt;code&gt;KeyboardInputManager&lt;/code&gt;, whose job is to receive keyboard events and translate them to changes of the model.&lt;/p&gt;&lt;p&gt;The &lt;code&gt;GameManager&lt;/code&gt; also contains some code to tie it all together — not really a part of the model as in MVC. Despite this slight inconsistency, the separation of concerns is very neatly executed in 2048’s code; I would even go so far as to say that it could be used as a demonstration in teaching MVC to people.&lt;/p&gt;&lt;p&gt;The only gripe I had with the code is that it violates the DRY principle in several places. Specifically, to change the board size to 5x5, I had to modify as many as three places: the HTML (it contains the initial definition for the DOM, including 16 empty divs making up the grid, which is unfortunate — I’d change it to set up the DOM at runtime during initialization); the model (instantiation of &lt;code&gt;GameManager&lt;/code&gt;); and the &lt;code&gt;.scss&lt;/code&gt; file from which the CSS is generated.&lt;/p&gt;&lt;p&gt;While on this topic, let me add that 2048’s usage of SASS is a prime example of its capabilities. It is very instructive to see how the sizing and positioning of the grid, and also styling for the tiles down to the glow, is done programmatically. I was aware of the existence of SASS before, but never got around to explore it. Now, I’m sold on it.&lt;/p&gt;&lt;p&gt;To sum up: 2048 rocks. And it’s fun to modify. Go try it.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2013-05-26:post:lithium-revisited</id>
    <title>Lithium revisited: A 16-bit kernel (well, sort of) written in Clojure (well, sort of)</title>
    <link href="http://blog.danieljanus.pl/lithium-revisited/"/>
    <updated>2013-05-26T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;Remember &lt;a href="http://blog.danieljanus.pl/blog/2012/05/14/lithium/"&gt;Lithium&lt;/a&gt;? The x86 assembler written in Clojure, and a simple stripes effect written in it? Well, here’s another take on that effect:&lt;/p&gt;&lt;img src="/img/blog/stripes2.png"&gt;
&lt;p&gt;And here is the source code:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;do&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;init-graph&lt;/span&gt;)
    (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;loop&lt;/span&gt;&lt;/span&gt; [x &lt;span class="hljs-number"&gt;0&lt;/span&gt; y &lt;span class="hljs-number"&gt;0&lt;/span&gt;]
      (&lt;span class="hljs-name"&gt;put-pixel&lt;/span&gt; x y (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [z (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;mod&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;+&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;-&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;319&lt;/span&gt; x) y) &lt;span class="hljs-number"&gt;32&lt;/span&gt;)]
                       (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;if&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;&amp;lt;&lt;/span&gt;&lt;/span&gt; z &lt;span class="hljs-number"&gt;16&lt;/span&gt;) (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;+&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;16&lt;/span&gt; z) (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;+&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;16&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;-&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;31&lt;/span&gt; z)))))
      (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;if&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;=&lt;/span&gt;&lt;/span&gt; y &lt;span class="hljs-number"&gt;200&lt;/span&gt;)
        &lt;span class="hljs-literal"&gt;nil&lt;/span&gt;
        (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;if&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;=&lt;/span&gt;&lt;/span&gt; x &lt;span class="hljs-number"&gt;319&lt;/span&gt;)
          (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;recur&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;0&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;inc&lt;/span&gt;&lt;/span&gt; y))
          (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;recur&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;inc&lt;/span&gt;&lt;/span&gt; x) y)))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;I’ve implemented this several months ago, pushed it to Github and development has pretty much stalled since then. And after seeing &lt;a href="https://news.ycombinator.com/item?id=5771276"&gt;this recent post&lt;/a&gt; on HN today, I’ve decided to give Lithium a little more publicity, in the hope that it will provide a boost of motivation to me. Because what we have here is pretty similar to Rustboot: it’s a 16-bit kernel written in Clojure.&lt;/p&gt;&lt;p&gt;Well, sort of.&lt;/p&gt;&lt;p&gt;After writing a basic assembler capable of building bare binaries of simple x86 real-mode programs, I’ve decided to make it a building block of a larger entity. So I’ve embarked on a project to implement a compiler for a toy Lisp-like language following the paper &lt;a href="http://scheme2006.cs.uchicago.edu/11-ghuloum.pdf"&gt;“An Incremental Approach to Compiler Construction”&lt;/a&gt;, doing it in Clojure and making the implemented language similar to Clojure rather than to Scheme.&lt;/p&gt;&lt;p&gt;(Whether it actually can be called Clojure is debatable. It’s unclear what the definition of Clojure the language is. Is running on JVM a part of what makes Clojure Clojure? Or running on any host platform? Is ClojureScript Clojure? What about ClojureCLR, or clojure-py?)&lt;/p&gt;&lt;p&gt;So far I’ve only gotten to step 7 of 24 or so, but that’s already enough to have a working &lt;code&gt;loop/recur&lt;/code&gt; implementation, and it was trivial to throw in some graphical mode 13h primitives to be able to implement this effect.&lt;/p&gt;&lt;p&gt;By default I’m running Lithium programs as DOS .COM binaries under DOSBox, but technically, the code doesn’t depend on DOS in any way (it doesn’t ever invoke interrupt 21h) and so it can be combined with a simple bootloader into a kernel runnable on the bare metal.&lt;/p&gt;&lt;p&gt;The obligatory HOWTO on reproducing the effect: install DOSBox and Leiningen, checkout [the code][3], launch a REPL with &lt;code&gt;lein repl&lt;/code&gt;, execute the following forms, and enjoy the slowness with which individual pixels are painted:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;require&lt;/span&gt; &amp;#x27;lithium.compiler)
(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;in-ns&lt;/span&gt;&lt;/span&gt; &amp;#x27;lithium.compiler)
(&lt;span class="hljs-name"&gt;run!&lt;/span&gt; (&lt;span class="hljs-name"&gt;compile-program&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;/path/to/lithium/examples/stripes-grey.clj&amp;quot;&lt;/span&gt;))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2012-05-14:post:lithium</id>
    <title>Lithium: an x86 assembler for Clojure</title>
    <link href="http://blog.danieljanus.pl/lithium/"/>
    <updated>2012-05-14T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;Ah, the golden days of childhood’s hackage. Don’t you have fond memories of them?&lt;/p&gt;&lt;p&gt;I got my first PC when I was 10. It was a 486DX2/66 with 4 megs of RAM and a 170 meg HDD; it ran DOS and had lots of things installed on it, notably Turbo Pascal 6. I hacked a lot in it. These were pre-internet days when knowledge was hard to come by, especially for someone living in a &lt;a href="http://en.wikipedia.org/wiki/W%C4%85chock"&gt;small town in Poland&lt;/a&gt;; my main sources were the software I had (TP’s online help was of excellent quality), a couple of books, and a &lt;a href="http://www.cpcwiki.eu/index.php/Bajtek"&gt;popular computing magazine&lt;/a&gt; that published articles on programming. From the latter, I learned how to program the VGA: how to enter mode 13h, draw pixels on screen, wait for vertical retrace, manipulate the palette and how to combine these things into neat effects. One of the very first thing I discovered was when you plot every pixel using sum of its coordinates modulo 40 as color, you get a nice-looking diagonal stripes effect. Because of the initially incomprehensible inline assembly snippets appearing all over the place, I eventually learned x86 assembly, too.&lt;/p&gt;&lt;img src="/img/blog/stripes.png"&gt;
&lt;p&gt;Back to 2012: I’ve long been wanting to hack on something just for pure fun, a side pet project. Writing code for the bare metal is fun because it’s just about as close as you can get to wielding the ultimate power. And yet, since Clojure is so much fun too, I wanted the project to have something to do with Clojure.&lt;/p&gt;&lt;p&gt;So here’s &lt;a href="http://github.com/nathell/lithium"&gt;Lithium&lt;/a&gt;, an x86 16-bit assembler written in pure Clojure and capable of assembling a binary version of the stripes effect.&lt;/p&gt;&lt;p&gt;To try it, clone the git repo to your Linux or OS X machine, install DOSBox, launch a REPL with Leiningen, change to the &lt;code&gt;lithium&lt;/code&gt; namespace and say:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;run!&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;/home/you/lithium/src/stripes.li.clj&amp;quot;&lt;/span&gt;)
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id="faq"&gt;FAQ&lt;/h3&gt;&lt;p&gt;(Well, this is not really a FAQ since nobody actually asked me any questions about Lithium yet. This is more in anticipation of questions that may arise.)&lt;/p&gt;&lt;p&gt;&lt;strong&gt;What’s the importance of this?&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;&lt;a href="http://www.physics.ohio-state.edu/~kilcup/262/feynman.html"&gt;None whatsoever&lt;/a&gt;. It’s just for fun.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;How complete is it?&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Very incomplete. To even call it pre-pre-alpha would be an exaggeration. It’s currently little more than pure minimum required to assemble &lt;code&gt;stripes.li.clj&lt;/code&gt;. Output format wise, it only produces bare binaries (similar to DOS .COMs), and that’s unlikely to change anytime soon.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Do you intend to continue developing it?&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Absolutely. I will try to make it more complete, add 32- and possibly 64-bit modes, see how to add a macro system (since the input is s-expressions, it should be easy to produce Clojure macros to write assembly), write something nontrivial in it, and see how it can be used as a backend for some higher-level language compiler (I’m not sure yet which language that will turn out to be).&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2012-04-25:post:how-to-call-a-private-function-in-clojure</id>
    <title>How to call a private function in Clojure</title>
    <link href="http://blog.danieljanus.pl/how-to-call-a-private-function-in-clojure/"/>
    <updated>2012-04-25T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;&lt;strong&gt;tl;dr:&lt;/strong&gt; Don’t do it. If you really have to, use &lt;code&gt;(#'other-library/private-function args)&lt;/code&gt;.&lt;/p&gt;&lt;hr&gt;
&lt;p&gt;A private function in Clojure is one that has been defined using the &lt;code&gt;defn-&lt;/code&gt; macro, or equivalently by setting the metadata key &lt;code&gt;:private&lt;/code&gt; to &lt;code&gt;true&lt;/code&gt; on the var that holds the function. It is normally not allowed in Clojure to call such functions from outside of the namespace where they have been defined. Trying to do so results in an &lt;code&gt;IllegalStateException&lt;/code&gt; stating that the var is not public.&lt;/p&gt;&lt;p&gt;It is possible to circumvent this and call the private function, but it is not recommended. That the author of the library decided to make a function private probably means that he considers it to be an implementation detail, subject to change at any time, and that you should not rely on it being there. If you think it would be useful to have this functionality available as part of the public API, your best bet is to contact the library author and consult the change, so that it may be included officially in a future version.&lt;/p&gt;&lt;p&gt;Contacting the author, however, is not always feasible: she may not be available or you might be in haste. In this case, several workarounds are available. The simplest is to use &lt;code&gt;(#'other-library/private-function args)&lt;/code&gt;, which works in Clojure 1.2.1 and 1.3.0 (it probably works in other versions of Clojure as well, but I haven’t checked that).&lt;/p&gt;&lt;p&gt;Why does this work? When the Clojure compiler encounters a form &lt;code&gt;(sym args)&lt;/code&gt;, it invokes &lt;code&gt;analyzeSeq&lt;/code&gt; on that form. If its first element is a symbol, it proceeds to analyze that symbol. One of the first operation in that analysis is checking if it names an inline function, by calling &lt;code&gt;isInline&lt;/code&gt;. That function looks into the metadata of the Var named by the symbol in question. If it’s not public, it &lt;a href="https://github.com/clojure/clojure/blob/clojure-1.3.0/src/jvm/clojure/lang/Compiler.java#L6281"&gt;throws an exception&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;On the other hand, &lt;code&gt;#'&lt;/code&gt; is the reader macro for var. So our workaround is equivalent to &lt;code&gt;((var other-library/private-function) args)&lt;/code&gt;. In this case, the first element of the form is not a symbol, but a form that evaluates to a var. The compiler is not able to check for this so it does not insert a check for privateness. So the code compiles to calling a Var object.&lt;/p&gt;&lt;p&gt;Here’s the catch: Vars are callable, just like functions. They &lt;a href="https://github.com/clojure/clojure/blob/clojure-1.3.0/src/jvm/clojure/lang/Var.java#L18"&gt;implement &lt;code&gt;IFn&lt;/code&gt;&lt;/a&gt;. When a var is called, it delegates the call to the &lt;code&gt;IFn&lt;/code&gt; object it is holding. This has been recently &lt;a href="https://groups.google.com/d/msg/clojure/1Su9o_8JZ8g/uZL-n4uRSiUJ"&gt;discussed on the Clojure group&lt;/a&gt;. Since that delegation does not check for the var’s privateness either, the net effect is that we are able to call a private function this way.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2012-04-12:post:lifehacking-gumtree</id>
    <title>Lifehacking: How to get cheap home equipment using Clojure</title>
    <link href="http://blog.danieljanus.pl/lifehacking-gumtree/"/>
    <updated>2012-04-12T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;I’ve moved to London last September. Like many new Londoners, I have changed accommodation fairly quickly, being already after one removal and with another looming in a couple of months; my current flat was largely unfurnished when I moved in, so I had to buy some basic homeware. I didn’t want to invest much in it, since it’d be only for a few months. Luckily, it is not hard to do that cheaply: many people are moving out and getting rid of their stuff, so quite often you can search for the desired item on &lt;a href="http://www.gumtree.com/london"&gt;Gumtree&lt;/a&gt; and find there’s a cheap one a short bike ride away.&lt;/p&gt;&lt;p&gt;Except when there isn’t. In this case, it’s worthwhile to check again within a few days as new items are constantly being posted. Being lazy, I’ve decided to automate this. A few hours and a hundred lines of Clojure later, &lt;a href="https://github.com/nathell/gumtree-scraper"&gt;gumtree-scraper&lt;/a&gt; was born.&lt;/p&gt;&lt;p&gt;I’ve packaged it using &lt;code&gt;lein uberjar&lt;/code&gt; into a standalone jar, which, when run, produces a &lt;code&gt;gumtree.rss&lt;/code&gt; that is included in my Google Reader subscriptions. This way, whenever something I’m interested in appears, I get notified within an hour or so.&lt;/p&gt;&lt;p&gt;It’s driven by a Google spreadsheet. I’ve created a sheet that has three columns: item name, minimum price, maximum price; then I’ve made it available to anyone who knows the URL. This way I can edit it pretty much from everywhere without touching the script. Each time the script is run (by cron), it downloads that spreadsheet as a CSV that looks like this:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;hand blender,,5
bike rack,,15
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;For each row the script queries Gumtree’s category “For Sale” within London given the price range, gets each result and transforms it to a RSS entry.&lt;/p&gt;&lt;p&gt;Gumtree has no API, so I’m using screenscraping to retrieve all the data. Because the structure of the pages is much simpler, I’m actually scraping the &lt;a href="http://m.gumtree.com/"&gt;mobile version&lt;/a&gt;; a technical twist here is that the mobile version is only served to actual browsers so I’m supplying a custom User-Agent, pretending to be Safari. For actual scraping, the code uses &lt;a href="https://github.com/cgrand/enlive"&gt;Enlive&lt;/a&gt;; it works out nicely.&lt;/p&gt;&lt;p&gt;About half of the code is RSS generation — mostly XML emitting. I’d use &lt;code&gt;clojure.xml/emit&lt;/code&gt; but it’s known to &lt;a href="http://clojure-log.n01se.net/date/2012-01-03.html#17:28a"&gt;produce malformed XML&lt;/a&gt; at times, so I include a variant that should work.&lt;/p&gt;&lt;p&gt;In case anyone wants to tries it out, be aware that the location and category are hardcoded in the search URL template; if you want, change the template line in &lt;code&gt;get-page&lt;/code&gt;. The controller spreadsheet URL is not, however, hardcoded; it’s built up using the &lt;code&gt;spreadsheet.key&lt;/code&gt; system property. Here’s the wrapper script I use that is actually run by cron:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs bash"&gt;&lt;span class="hljs-meta"&gt;#!/bin/bash&lt;/span&gt;
&lt;span class="hljs-keyword"&gt;if&lt;/span&gt; [ &lt;span class="hljs-string"&gt;&amp;quot;`ps ax | grep java | grep gumtree`&amp;quot;&lt;/span&gt; ]; &lt;span class="hljs-keyword"&gt;then&lt;/span&gt;
  &lt;span class="hljs-built_in"&gt;echo&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;already running, exiting&amp;quot;&lt;/span&gt;
  &lt;span class="hljs-built_in"&gt;exit&lt;/span&gt; 0
&lt;span class="hljs-keyword"&gt;fi&lt;/span&gt;
&lt;span class="hljs-built_in"&gt;cd&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;`dirname &lt;span class="hljs-variable"&gt;$0&lt;/span&gt;`&amp;quot;&lt;/span&gt;
java -Dspreadsheet.key=MY_SECRET_KEY -jar &lt;span class="hljs-variable"&gt;$HOME&lt;/span&gt;/gumtree/gumtree.jar
&lt;span class="hljs-built_in"&gt;cp&lt;/span&gt; &lt;span class="hljs-variable"&gt;$HOME&lt;/span&gt;/gumtree/gumtree.rss &lt;span class="hljs-variable"&gt;$HOME&lt;/span&gt;/public_html
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now let me remove that entry for a blender — I’ve bought one yesterday for £4…&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2012-03-21:post:court-with-an-api</id>
    <title>Ever wanted to programmatically file a lawsuit? In Poland, you can.</title>
    <link href="http://blog.danieljanus.pl/court-with-an-api/"/>
    <updated>2012-03-21T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;This has somehow escaped me: just over a year ago, the Sixth Civil Division of the Lublin-West Regional Court in Lublin, Poland, has opened its &lt;a href="https://www.e-sad.gov.pl/"&gt;online branch&lt;/a&gt;. It serves the entire territory of Poland and is competent to recognize lawsuits concerning payment claims. There is &lt;a href="https://www.e-sad.gov.pl/Subpage.aspx?page_id=35"&gt;basic information&lt;/a&gt; available in English. It has proven immensely popular, having processed about two million cases in its first year of operation.&lt;/p&gt;&lt;p&gt;And the really cool thing is, &lt;em&gt;they have an API&lt;/em&gt;.&lt;/p&gt;&lt;p&gt;It’s SOAP-based and has a &lt;a href="https://www.e-sad.gov.pl/Subpage.aspx?page_id=32"&gt;publicly available spec&lt;/a&gt;. (Due to the way their web site is constructed, I cannot link to the spec directly; this last link leads to a collection of files related to the web service. The spec is called &lt;code&gt;EpuWS_ver.1.14.1.pdf&lt;/code&gt;; it’s in Polish only, but it should be easy to run it through Google Translate.) There are a couple of XML schemas as well, plus the spec contains links to a WSDL and some code samples (in C#) at the end.&lt;/p&gt;&lt;p&gt;To actually use the API, you need to get yourself an account of the appropriate type (there are two types corresponding to two groups of methods one can use: that of a bailiff and of a mass plaintiff). You then log on to the system, where you can create an API key that is later used for authentication. They throttle the speed down to 1 req/s per user to mitigate DoS attacks.&lt;/p&gt;&lt;p&gt;The methods include &lt;code&gt;FileLawsuits&lt;/code&gt;, &lt;code&gt;FileComplaints&lt;/code&gt;, &lt;code&gt;SupplyDocuments&lt;/code&gt;, &lt;code&gt;GetCaseHistory&lt;/code&gt; and so on (the actual names are in Polish). To give you an example, the &lt;code&gt;FileLawsuits&lt;/code&gt; method returns a structure that consists of, &lt;em&gt;inter alia&lt;/em&gt;, the amount of court fee to pay, the value of the matter of dispute (both broken down into individual lawsuits), and a status code with a description.&lt;/p&gt;&lt;p&gt;iOS app, anyone?&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2011-12-09:post:combining-virtual-sequences</id>
    <title>Combining virtual sequences&lt;br&gt;or, Sequential Fun with Macros&lt;br&gt;or, How to Implement Clojure-Like Pseudo-Sequences with Poor Man’s Laziness in a Predominantly Imperative Language</title>
    <link href="http://blog.danieljanus.pl/combining-virtual-sequences/"/>
    <updated>2011-12-09T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;h2 id="sequences-and-iteration"&gt;Sequences and iteration&lt;/h2&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, [The Evolution of a Haskell Programmer][1]. If you don’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;pre&gt;&lt;code class="hljs haskell"&gt;&lt;span class="hljs-title"&gt;fac&lt;/span&gt; n = product [&lt;span class="hljs-number"&gt;1&lt;/span&gt;..n]
&lt;/code&gt;&lt;/pre&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;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;defn&lt;/span&gt; &lt;span class="hljs-title"&gt;fac&lt;/span&gt; [n]
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;reduce&lt;/span&gt;&lt;/span&gt; * &lt;span class="hljs-number"&gt;1&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;range&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-number"&gt;1&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;inc&lt;/span&gt;&lt;/span&gt; n)))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now, I thought to myself, how would I write factorial in an imperative language? Say, Pascal?&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs pascal"&gt;&lt;span class="hljs-function"&gt;&lt;span class="hljs-keyword"&gt;function&lt;/span&gt; &lt;span class="hljs-title"&gt;fac&lt;/span&gt;&lt;span class="hljs-params"&gt;(n : integer)&lt;/span&gt; :&lt;/span&gt; integer;
&lt;span class="hljs-keyword"&gt;var&lt;/span&gt;
  i, res : integer;
&lt;span class="hljs-keyword"&gt;begin&lt;/span&gt;
  res := &lt;span class="hljs-number"&gt;1&lt;/span&gt;;
  &lt;span class="hljs-keyword"&gt;for&lt;/span&gt; i := &lt;span class="hljs-number"&gt;1&lt;/span&gt; &lt;span class="hljs-keyword"&gt;to&lt;/span&gt; n &lt;span class="hljs-keyword"&gt;do&lt;/span&gt;
    res := res * i;
  fac := res;
&lt;span class="hljs-keyword"&gt;end&lt;/span&gt;;
&lt;/code&gt;&lt;/pre&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’s memory efficient: it’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’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 “virtual” sequence, since it is not an actual data structure; it’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;h2 id="let’s-write-some-code!"&gt;Let’s write some code!&lt;/h2&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;&lt;span&gt;It allows for imperative style, including GOTO-like statements. This will enable us to generate very low-level code.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;Thanks to macros, we will be able to obtain interesting transformations.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Okay, so let’s have a look at how to generate a one-element sequence. Simple enough:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defmacro&lt;/span&gt; vsingle (&lt;span class="hljs-name"&gt;x&lt;/span&gt;)
 `(yield ,x))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The name &lt;code&gt;VSINGLE&lt;/code&gt; stands for “Virtual sequence that just yields a SINGLE element”. (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;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defun&lt;/span&gt; yield (&lt;span class="hljs-name"&gt;x&lt;/span&gt;)
  (&lt;span class="hljs-name"&gt;format&lt;/span&gt; &lt;span class="hljs-literal"&gt;t&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;~A~%&amp;quot;&lt;/span&gt; x))
&lt;/code&gt;&lt;/pre&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;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defmacro&lt;/span&gt; vseq (&lt;span class="hljs-name"&gt;list&lt;/span&gt;)
  `(loop for x in ,list do (yield x)))

(&lt;span class="hljs-name"&gt;defmacro&lt;/span&gt; vlist (&lt;span class="hljs-name"&gt;&amp;amp;rest&lt;/span&gt; elems)
  `(vseq (list ,@elems)))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now let’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’s pretend that it doesn’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;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defmacro&lt;/span&gt; range (&lt;span class="hljs-name"&gt;start&lt;/span&gt; &lt;span class="hljs-symbol"&gt;&amp;amp;optional&lt;/span&gt; end (&lt;span class="hljs-name"&gt;step&lt;/span&gt; &lt;span class="hljs-number"&gt;1&lt;/span&gt;))
  (&lt;span class="hljs-name"&gt;unless&lt;/span&gt; end
    (&lt;span class="hljs-name"&gt;setf&lt;/span&gt; end start start &lt;span class="hljs-number"&gt;0&lt;/span&gt;))
  (&lt;span class="hljs-name"&gt;let&lt;/span&gt; ((&lt;span class="hljs-name"&gt;fv&lt;/span&gt; (&lt;span class="hljs-name"&gt;gensym&lt;/span&gt;)))
    `(let ((,fv ,start))
       (tagbody
        loop
          (when (&amp;gt;= ,fv ,end)
            (go out))
          (yield ,fv)
          (incf ,fv ,step)
          (go loop)
       out))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;em&gt;Infinite&lt;/em&gt; virtual sequences are also possible. After all, there’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’s iterate: 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;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defmacro&lt;/span&gt; iterate (&lt;span class="hljs-name"&gt;fun&lt;/span&gt; val)
  (&lt;span class="hljs-name"&gt;let&lt;/span&gt; ((&lt;span class="hljs-name"&gt;fv&lt;/span&gt; (&lt;span class="hljs-name"&gt;gensym&lt;/span&gt;)))
    `(let ((,fv ,val))
       (tagbody loop
          (yield ,fv)
          (setf ,fv (funcall ,fun ,fv))
          (go loop)))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;So far, we have defined a number of ways to create virtual sequences. Now let’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;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defun&lt;/span&gt; replace-yield (&lt;span class="hljs-name"&gt;tree&lt;/span&gt; replace)
  (&lt;span class="hljs-name"&gt;if&lt;/span&gt; (&lt;span class="hljs-name"&gt;consp&lt;/span&gt; tree)
      (&lt;span class="hljs-name"&gt;if&lt;/span&gt; (&lt;span class="hljs-name"&gt;eql&lt;/span&gt; (&lt;span class="hljs-name"&gt;car&lt;/span&gt; tree) &amp;#x27;yield)
          (&lt;span class="hljs-name"&gt;funcall&lt;/span&gt; replace (&lt;span class="hljs-name"&gt;cadr&lt;/span&gt; tree))
          (&lt;span class="hljs-name"&gt;loop&lt;/span&gt; for x in tree collect (&lt;span class="hljs-name"&gt;replace-yield&lt;/span&gt; x replace)))
      tree))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We can now write &lt;code&gt;filter&lt;/code&gt; like this:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defmacro&lt;/span&gt; filter (&lt;span class="hljs-name"&gt;pred&lt;/span&gt; vseq &lt;span class="hljs-symbol"&gt;&amp;amp;environment&lt;/span&gt; env)
  (&lt;span class="hljs-name"&gt;replace-yield&lt;/span&gt; (&lt;span class="hljs-name"&gt;macroexpand&lt;/span&gt; vseq env)
                 (&lt;span class="hljs-name"&gt;lambda&lt;/span&gt; (&lt;span class="hljs-name"&gt;x&lt;/span&gt;) `(when (funcall ,pred ,x) (yield ,x)))))
&lt;/code&gt;&lt;/pre&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;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;LET&lt;/span&gt; ((&lt;span class="hljs-name"&gt;#&lt;/span&gt;&lt;span class="hljs-symbol"&gt;:G70192&lt;/span&gt; &lt;span class="hljs-number"&gt;0&lt;/span&gt;))
  (&lt;span class="hljs-name"&gt;TAGBODY&lt;/span&gt;
    LOOP (&lt;span class="hljs-name"&gt;IF&lt;/span&gt; (&lt;span class="hljs-name"&gt;&amp;gt;=&lt;/span&gt; #&lt;span class="hljs-symbol"&gt;:G70192&lt;/span&gt; &lt;span class="hljs-number"&gt;10&lt;/span&gt;)
           (&lt;span class="hljs-name"&gt;PROGN&lt;/span&gt; (&lt;span class="hljs-name"&gt;GO&lt;/span&gt; OUT)))
         (&lt;span class="hljs-name"&gt;IF&lt;/span&gt; (&lt;span class="hljs-name"&gt;FUNCALL&lt;/span&gt; #&amp;#x27;EVENP #&lt;span class="hljs-symbol"&gt;:G70192&lt;/span&gt;)
           (&lt;span class="hljs-name"&gt;PROGN&lt;/span&gt; (&lt;span class="hljs-name"&gt;YIELD&lt;/span&gt; #&lt;span class="hljs-symbol"&gt;:G70192&lt;/span&gt;)))
         (&lt;span class="hljs-name"&gt;SETQ&lt;/span&gt; #&lt;span class="hljs-symbol"&gt;:G70192&lt;/span&gt; (&lt;span class="hljs-name"&gt;+&lt;/span&gt; #&lt;span class="hljs-symbol"&gt;:G70192&lt;/span&gt; &lt;span class="hljs-number"&gt;1&lt;/span&gt;))
         (&lt;span class="hljs-name"&gt;GO&lt;/span&gt; LOOP)
    OUT))
&lt;/code&gt;&lt;/pre&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;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defmacro&lt;/span&gt; concat (&lt;span class="hljs-name"&gt;&amp;amp;rest&lt;/span&gt; vseqs)
  `(progn ,@vseqs))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;To define &lt;code&gt;take&lt;/code&gt;, we’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’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;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defmacro&lt;/span&gt; take (&lt;span class="hljs-name"&gt;n&lt;/span&gt; vseq &lt;span class="hljs-symbol"&gt;&amp;amp;environment&lt;/span&gt; env)
  (&lt;span class="hljs-name"&gt;let&lt;/span&gt; ((&lt;span class="hljs-name"&gt;x&lt;/span&gt; (&lt;span class="hljs-name"&gt;gensym&lt;/span&gt;))
        (&lt;span class="hljs-name"&gt;b&lt;/span&gt; (&lt;span class="hljs-name"&gt;gensym&lt;/span&gt;)))
    `(let ((,x ,n))
       (block ,b
         ,(replace-yield (macroexpand vseq env)
                         (lambda (y) `(progn (yield ,y)
                                             (decf ,x)
                                             (when (zerop ,x)
                                               (return-from ,b)))))))))
&lt;/code&gt;&lt;/pre&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;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defmacro&lt;/span&gt; vrest (&lt;span class="hljs-name"&gt;vseq&lt;/span&gt; &lt;span class="hljs-symbol"&gt;&amp;amp;environment&lt;/span&gt; env)
  (&lt;span class="hljs-name"&gt;let&lt;/span&gt; ((&lt;span class="hljs-name"&gt;skipped&lt;/span&gt; (&lt;span class="hljs-name"&gt;gensym&lt;/span&gt;)))
    (&lt;span class="hljs-name"&gt;replace-yield&lt;/span&gt;
     `(let ((,skipped &lt;span class="hljs-literal"&gt;nil&lt;/span&gt;)) ,(macroexpand vseq env))
     (&lt;span class="hljs-name"&gt;lambda&lt;/span&gt; (&lt;span class="hljs-name"&gt;x&lt;/span&gt;) `(if ,skipped (yield ,x) (setf ,skipped &lt;span class="hljs-literal"&gt;t&lt;/span&gt;))))))
&lt;/code&gt;&lt;/pre&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 — 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;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defmacro&lt;/span&gt; vfirst (&lt;span class="hljs-name"&gt;vseq&lt;/span&gt;)
  (&lt;span class="hljs-name"&gt;let&lt;/span&gt; ((&lt;span class="hljs-name"&gt;block-name&lt;/span&gt; (&lt;span class="hljs-name"&gt;gensym&lt;/span&gt;)))
   `(block ,block-name
      (flet ((yield (x) (return-from ,block-name x)))
        ,vseq))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Note that so far we’ve seen three classes of macros:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;macros that create virtual sequences;&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;macros that transform virtual sequences to another virtual sequences;&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;and finally, vfirst is our first example of a macro that produces a result out of a virtual sequence.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Our next logical step is &lt;code&gt;vreduce&lt;/code&gt;. Again, we’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’s old value and the value being yielded.&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defmacro&lt;/span&gt; vreduce (&lt;span class="hljs-name"&gt;f&lt;/span&gt; val vseq)
  `(let ((accu ,val))
     (flet ((yield (x) (setf accu (funcall ,f accu x))))
       ,vseq
       accu)))
&lt;/code&gt;&lt;/pre&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;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defun&lt;/span&gt; conj (&lt;span class="hljs-name"&gt;x&lt;/span&gt; y)
  (&lt;span class="hljs-name"&gt;cons&lt;/span&gt; y x))

(&lt;span class="hljs-name"&gt;defmacro&lt;/span&gt; realize (&lt;span class="hljs-name"&gt;vseq&lt;/span&gt;)
 `(nreverse (vreduce #&amp;#x27;conj &lt;span class="hljs-literal"&gt;nil&lt;/span&gt; ,vseq)))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Let’s verify that it works:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs lisp"&gt;CL-USER&amp;gt; (&lt;span class="hljs-name"&gt;realize&lt;/span&gt; (&lt;span class="hljs-name"&gt;range&lt;/span&gt; &lt;span class="hljs-number"&gt;10&lt;/span&gt;))
(&lt;span class="hljs-number"&gt;0&lt;/span&gt; &lt;span class="hljs-number"&gt;1&lt;/span&gt; &lt;span class="hljs-number"&gt;2&lt;/span&gt; &lt;span class="hljs-number"&gt;3&lt;/span&gt; &lt;span class="hljs-number"&gt;4&lt;/span&gt; &lt;span class="hljs-number"&gt;5&lt;/span&gt; &lt;span class="hljs-number"&gt;6&lt;/span&gt; &lt;span class="hljs-number"&gt;7&lt;/span&gt; &lt;span class="hljs-number"&gt;8&lt;/span&gt; &lt;span class="hljs-number"&gt;9&lt;/span&gt;)

CL-USER&amp;gt; (&lt;span class="hljs-name"&gt;realize&lt;/span&gt; (&lt;span class="hljs-name"&gt;take&lt;/span&gt; &lt;span class="hljs-number"&gt;5&lt;/span&gt; (&lt;span class="hljs-name"&gt;filter&lt;/span&gt; #&amp;#x27;oddp (&lt;span class="hljs-name"&gt;iterate&lt;/span&gt; #&amp;#x27;&lt;span class="hljs-number"&gt;1&lt;/span&gt;+ &lt;span class="hljs-number"&gt;0&lt;/span&gt;))))
(&lt;span class="hljs-number"&gt;1&lt;/span&gt; &lt;span class="hljs-number"&gt;3&lt;/span&gt; &lt;span class="hljs-number"&gt;5&lt;/span&gt; &lt;span class="hljs-number"&gt;7&lt;/span&gt; &lt;span class="hljs-number"&gt;9&lt;/span&gt;)
&lt;/code&gt;&lt;/pre&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’s finally define our factorial:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defun&lt;/span&gt; fac (&lt;span class="hljs-name"&gt;n&lt;/span&gt;)
  (&lt;span class="hljs-name"&gt;vreduce&lt;/span&gt; #&amp;#x27;* &lt;span class="hljs-number"&gt;1&lt;/span&gt; (&lt;span class="hljs-name"&gt;range&lt;/span&gt; &lt;span class="hljs-number"&gt;1&lt;/span&gt; (&lt;span class="hljs-number"&gt;1&lt;/span&gt;+ n))))
&lt;/code&gt;&lt;/pre&gt;&lt;h2 id="benchmarking"&gt;Benchmarking&lt;/h2&gt;&lt;p&gt;Factorials grow too fast, so for the purpose of benchmarking let’s write a function that adds numbers from 0 below n, in sequence-y style. First using Common Lisp builtins:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defun&lt;/span&gt; sum-below (&lt;span class="hljs-name"&gt;n&lt;/span&gt;)
  (&lt;span class="hljs-name"&gt;reduce&lt;/span&gt; #&amp;#x27;+ (&lt;span class="hljs-name"&gt;loop&lt;/span&gt; for i from &lt;span class="hljs-number"&gt;0&lt;/span&gt; below n collect i) &lt;span class="hljs-symbol"&gt;:initial-value&lt;/span&gt; &lt;span class="hljs-number"&gt;0&lt;/span&gt;))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And now with our virtual sequences:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defun&lt;/span&gt; sum-below-2 (&lt;span class="hljs-name"&gt;n&lt;/span&gt;)
  (&lt;span class="hljs-name"&gt;vreduce&lt;/span&gt; #&amp;#x27;+ &lt;span class="hljs-number"&gt;0&lt;/span&gt; (&lt;span class="hljs-name"&gt;range&lt;/span&gt; n)))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Let’s try to time the two versions. On my Mac running Clozure CL 1.7, this gives:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs lisp"&gt;CL-USER&amp;gt; (&lt;span class="hljs-name"&gt;time&lt;/span&gt; (&lt;span class="hljs-name"&gt;sum-below&lt;/span&gt; &lt;span class="hljs-number"&gt;10000000&lt;/span&gt;))
(&lt;span class="hljs-name"&gt;SUM-BELOW&lt;/span&gt; &lt;span class="hljs-number"&gt;10000000&lt;/span&gt;) took &lt;span class="hljs-number"&gt;8&lt;/span&gt;,&lt;span class="hljs-number"&gt;545&lt;/span&gt;,&lt;span class="hljs-number"&gt;512&lt;/span&gt; microseconds (&lt;span class="hljs-number"&gt;8.545512&lt;/span&gt; seconds) to run
                    with &lt;span class="hljs-number"&gt;2&lt;/span&gt; available CPU cores.
During that period, &lt;span class="hljs-number"&gt;2&lt;/span&gt;,&lt;span class="hljs-number"&gt;367&lt;/span&gt;,&lt;span class="hljs-number"&gt;207&lt;/span&gt; microseconds (&lt;span class="hljs-number"&gt;2.367207&lt;/span&gt; seconds) were spent in user mode
                    &lt;span class="hljs-number"&gt;270&lt;/span&gt;,&lt;span class="hljs-number"&gt;481&lt;/span&gt; microseconds (&lt;span class="hljs-number"&gt;0.270481&lt;/span&gt; seconds) were spent in system mode
&lt;span class="hljs-number"&gt;5&lt;/span&gt;,&lt;span class="hljs-number"&gt;906&lt;/span&gt;,&lt;span class="hljs-number"&gt;274&lt;/span&gt; microseconds (&lt;span class="hljs-number"&gt;5.906274&lt;/span&gt; seconds) was spent in GC.
 &lt;span class="hljs-number"&gt;160&lt;/span&gt;,&lt;span class="hljs-number"&gt;000&lt;/span&gt;,&lt;span class="hljs-number"&gt;016&lt;/span&gt; bytes of memory allocated.
 &lt;span class="hljs-number"&gt;39&lt;/span&gt;,&lt;span class="hljs-number"&gt;479&lt;/span&gt; minor page faults, &lt;span class="hljs-number"&gt;1&lt;/span&gt;,&lt;span class="hljs-number"&gt;359&lt;/span&gt; major page faults, &lt;span class="hljs-number"&gt;0&lt;/span&gt; swaps.
&lt;span class="hljs-number"&gt;49999995000000&lt;/span&gt;

CL-USER&amp;gt; (&lt;span class="hljs-name"&gt;time&lt;/span&gt; (&lt;span class="hljs-name"&gt;sum-below-2&lt;/span&gt; &lt;span class="hljs-number"&gt;10000000&lt;/span&gt;))
(&lt;span class="hljs-name"&gt;SUM-BELOW-2&lt;/span&gt; &lt;span class="hljs-number"&gt;10000000&lt;/span&gt;) took &lt;span class="hljs-number"&gt;123&lt;/span&gt;,&lt;span class="hljs-number"&gt;081&lt;/span&gt; microseconds (&lt;span class="hljs-number"&gt;0.123081&lt;/span&gt; seconds) to run
                    with &lt;span class="hljs-number"&gt;2&lt;/span&gt; available CPU cores.
During that period, &lt;span class="hljs-number"&gt;127&lt;/span&gt;,&lt;span class="hljs-number"&gt;632&lt;/span&gt; microseconds (&lt;span class="hljs-number"&gt;0.127632&lt;/span&gt; seconds) were spent in user mode
                    &lt;span class="hljs-number"&gt;666&lt;/span&gt; microseconds (&lt;span class="hljs-number"&gt;0.000666&lt;/span&gt; seconds) were spent in system mode
 &lt;span class="hljs-number"&gt;4&lt;/span&gt; minor page faults, &lt;span class="hljs-number"&gt;0&lt;/span&gt; major page faults, &lt;span class="hljs-number"&gt;0&lt;/span&gt; swaps.
&lt;span class="hljs-number"&gt;49999995000000&lt;/span&gt;
&lt;/code&gt;&lt;/pre&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;’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; — something that &lt;code&gt;LOOP&lt;/code&gt; has not built in as a clause — this would not be an option.)&lt;/p&gt;&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&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 “ordinary” sequences such as Clojure’s. The fact that we’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’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 worlds. 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’ve written don’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’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;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2011-07-11:post:color-your-own-europe</id>
    <title>Color your own Europe with Clojure!</title>
    <link href="http://blog.danieljanus.pl/color-your-own-europe/"/>
    <updated>2011-07-11T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;This is a slightly edited translation of &lt;a href="http://plblog.danieljanus.pl/zippery-w-clojure"&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 id="the-problem"&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;img src="/img/blog/europa.png"&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 id="svg"&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’d often encountered images in this format on Wikipedia — but editing it by hand was new to me. Luckily, it turned out that the image has a simple structure. Each country’s envelope curve is described with a &lt;code&gt;path&lt;/code&gt; element that looks like this:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs xml"&gt;&lt;span class="hljs-tag"&gt;&amp;lt;&lt;span class="hljs-name"&gt;path&lt;/span&gt;
   &lt;span class="hljs-attr"&gt;id&lt;/span&gt;=&lt;span class="hljs-string"&gt;&amp;quot;pl&amp;quot;&lt;/span&gt;
   &lt;span class="hljs-attr"&gt;class&lt;/span&gt;=&lt;span class="hljs-string"&gt;&amp;quot;eu europe&amp;quot;&lt;/span&gt;
   &lt;span class="hljs-attr"&gt;d&lt;/span&gt;=&lt;span class="hljs-string"&gt;&amp;quot;a long list of curve node coordinates&amp;quot;&lt;/span&gt; /&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;An important thing to note here is the &lt;code&gt;id&lt;/code&gt; attribute — 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;pre&gt;&lt;code class="hljs xml"&gt;&lt;span class="hljs-tag"&gt;&amp;lt;&lt;span class="hljs-name"&gt;path&lt;/span&gt;
   &lt;span class="hljs-attr"&gt;id&lt;/span&gt;=&lt;span class="hljs-string"&gt;&amp;quot;pl&amp;quot;&lt;/span&gt;
   &lt;span class="hljs-attr"&gt;style&lt;/span&gt;=&lt;span class="hljs-string"&gt;&amp;quot;fill: #ff0000;&amp;quot;&lt;/span&gt;
   &lt;span class="hljs-attr"&gt;class&lt;/span&gt;=&lt;span class="hljs-string"&gt;&amp;quot;eu europe&amp;quot;&lt;/span&gt;
   &lt;span class="hljs-attr"&gt;d&lt;/span&gt;=&lt;span class="hljs-string"&gt;&amp;quot;a long list of curve node coordinates&amp;quot;&lt;/span&gt; /&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now that we know all this, let’s start coding!&lt;/p&gt;&lt;h2 id="xml-in-clojure"&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;pre&gt;&lt;code class="hljs clojure"&gt;&amp;gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;use&lt;/span&gt;&lt;/span&gt; &amp;#x27;clojure.xml)
&lt;span class="hljs-literal"&gt;nil&lt;/span&gt;
&amp;gt; (&lt;span class="hljs-keyword"&gt;def&lt;/span&gt; &lt;span class="hljs-title"&gt;m&lt;/span&gt; (&lt;span class="hljs-name"&gt;parse&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;/home/nathell/eur/Blank_map_of_Europe.svg&amp;quot;&lt;/span&gt;))
[...a long while...]
Unexpected end of file from server
  [Thrown class java.net.SocketException]
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Hold on in there! What’s that &lt;code&gt;SocketException&lt;/code&gt; doing here? Firefox displays this map properly, so does Chrome, WTF?! Shouldn’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 — 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’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?cat=68"&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;pre&gt;&lt;code class="hljs clojure"&gt;&amp;gt; (&lt;span class="hljs-keyword"&gt;def&lt;/span&gt; &lt;span class="hljs-title"&gt;m&lt;/span&gt; (&lt;span class="hljs-name"&gt;parse&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;/home/nathell/eur/bm.svg&amp;quot;&lt;/span&gt;))
#&amp;#x27;user/m
&amp;gt; m
[...many screenfuls of numbers...]
&lt;/code&gt;&lt;/pre&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’s output we can make out that’s it a Clojure map (no pun intended). Let’s examine its keys:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;&amp;gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;keys&lt;/span&gt;&lt;/span&gt; m)
(&lt;span class="hljs-symbol"&gt;:tag&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:attrs&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:content&lt;/span&gt;)
&lt;/code&gt;&lt;/pre&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 element, &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’s a text node):&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;&amp;gt; (&lt;span class="hljs-symbol"&gt;:tag&lt;/span&gt; m)
&lt;span class="hljs-symbol"&gt;:svg&lt;/span&gt;
&amp;gt; (&lt;span class="hljs-symbol"&gt;:attrs&lt;/span&gt; m)
{&lt;span class="hljs-symbol"&gt;:xmlns&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;http://www.w3.org/2000/svg&amp;quot;&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:width&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;680&amp;quot;&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:height&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;520&amp;quot;&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:viewBox&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;1754 161 9938 7945&amp;quot;&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:version&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;1.0&amp;quot;&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:id&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;svg2&amp;quot;&lt;/span&gt;}
&amp;gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;count&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-symbol"&gt;:content&lt;/span&gt; m))
&lt;span class="hljs-number"&gt;68&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Just for the sake of practice, let’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;pre&gt;&lt;code class="hljs clojure"&gt;&amp;gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;use&lt;/span&gt;&lt;/span&gt; &amp;#x27;clojure.contrib.io)
&lt;span class="hljs-literal"&gt;nil&lt;/span&gt;
&amp;gt; (&lt;span class="hljs-name"&gt;with-out-writer&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;/tmp/a.svg&amp;quot;&lt;/span&gt; (&lt;span class="hljs-name"&gt;emit&lt;/span&gt; m))
&lt;span class="hljs-literal"&gt;nil&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We try to view &lt;code&gt;a.svg&lt;/code&gt; in Firefox and…&lt;/p&gt;&lt;pre&gt;&lt;code&gt;Error parsing XML: not well-formed
Area: file:///tmp/a.xml
Row 15, column 44: Updated to reflect dissolution of Serbia &amp; Montenegro: http://commons.wikimedia.org/wiki/User:Zirland
                 -------------------------------------------^
&lt;/code&gt;&lt;/pre&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’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’s just a comment).&lt;/p&gt;&lt;h2 id="coloring-poland"&gt;Coloring Poland&lt;/h2&gt;&lt;p&gt;We saw earlier that our main XML node contains 68 subnodes. Let’s see what they are — tag names will suffice:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;&amp;gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;map&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:tag&lt;/span&gt; (&lt;span class="hljs-symbol"&gt;:content&lt;/span&gt; m))
(&lt;span class="hljs-symbol"&gt;:title&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:desc&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:defs&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:rect&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:g&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:g&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt;)
&lt;/code&gt;&lt;/pre&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;pre&gt;&lt;code&gt;&gt; (count (filter #(and (= (:tag %) :path)
                       (= ((:attrs %) :id) "pl"))
                 (:content m)))
1
&lt;/code&gt;&lt;/pre&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’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;pre&gt;&lt;code class="hljs clojure"&gt;&amp;gt; (&lt;span class="hljs-keyword"&gt;def&lt;/span&gt; &lt;span class="hljs-title"&gt;m2&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;assoc&lt;/span&gt;&lt;/span&gt; m
                &lt;span class="hljs-symbol"&gt;:content&lt;/span&gt;
                (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;map&lt;/span&gt;&lt;/span&gt; #(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;if&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;and&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;=&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-symbol"&gt;:tag&lt;/span&gt; %) &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt;)
                               (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;=&lt;/span&gt;&lt;/span&gt; ((&lt;span class="hljs-symbol"&gt;:attrs&lt;/span&gt; %) &lt;span class="hljs-symbol"&gt;:id&lt;/span&gt;) &lt;span class="hljs-string"&gt;&amp;quot;pl&amp;quot;&lt;/span&gt;))
                        (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;assoc&lt;/span&gt;&lt;/span&gt; % &lt;span class="hljs-symbol"&gt;:attrs&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;assoc&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-symbol"&gt;:attrs&lt;/span&gt; %) &lt;span class="hljs-symbol"&gt;:style&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;fill: #ff0000;&amp;quot;&lt;/span&gt;))
                        %)
                     (&lt;span class="hljs-symbol"&gt;:content&lt;/span&gt; m))))
#&amp;#x27;user/m&lt;span class="hljs-number"&gt;2&lt;/span&gt;
&amp;gt; (&lt;span class="hljs-name"&gt;with-out-writer&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;/tmp/a.svg&amp;quot;&lt;/span&gt; (&lt;span class="hljs-name"&gt;emit&lt;/span&gt; m2))
&lt;span class="hljs-literal"&gt;nil&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We open the created file and see a map with Poland colored red. Yay!&lt;/p&gt;&lt;h2 id="generalization"&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;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;defn&lt;/span&gt; &lt;span class="hljs-title"&gt;color-state&lt;/span&gt;
  [{&lt;span class="hljs-symbol"&gt;:keys&lt;/span&gt; [tag attrs] &lt;span class="hljs-symbol"&gt;:as&lt;/span&gt; element} colorize-fn]
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [state (&lt;span class="hljs-symbol"&gt;:id&lt;/span&gt; attrs)]
    (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;if-let&lt;/span&gt;&lt;/span&gt; [color (&lt;span class="hljs-name"&gt;colorize-fn&lt;/span&gt; state)]
      (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;assoc&lt;/span&gt;&lt;/span&gt; element &lt;span class="hljs-symbol"&gt;:attrs&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;assoc&lt;/span&gt;&lt;/span&gt; attrs &lt;span class="hljs-symbol"&gt;:style&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;str&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;fill:&amp;quot;&lt;/span&gt; color)))
      element)))
&lt;/code&gt;&lt;/pre&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… 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’s color is not specified — &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;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;defn&lt;/span&gt; &lt;span class="hljs-title"&gt;save-color-map&lt;/span&gt;
  [svg colorize-fn outfile]
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [colored-map (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;assoc&lt;/span&gt;&lt;/span&gt; svg &lt;span class="hljs-symbol"&gt;:content&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;map&lt;/span&gt;&lt;/span&gt; #(&lt;span class="hljs-name"&gt;color-state&lt;/span&gt; % colorize-fn) (&lt;span class="hljs-symbol"&gt;:content&lt;/span&gt; svg)))]
    (&lt;span class="hljs-name"&gt;with-out-writer&lt;/span&gt; out
      (&lt;span class="hljs-name"&gt;emit&lt;/span&gt; colored-map))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Let’s test it:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;&amp;gt; (&lt;span class="hljs-name"&gt;save-color-map&lt;/span&gt; m {&lt;span class="hljs-string"&gt;&amp;quot;pl&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;#00ff00&amp;quot;&lt;/span&gt;} &lt;span class="hljs-string"&gt;&amp;quot;/tmp/a.svg&amp;quot;&lt;/span&gt;)
&lt;span class="hljs-literal"&gt;nil&lt;/span&gt;
&lt;/code&gt;&lt;/pre&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’s try to add blue Germany:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;&amp;gt; (&lt;span class="hljs-name"&gt;save-color-map&lt;/span&gt; m {&lt;span class="hljs-string"&gt;&amp;quot;pl&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;#00ff00&amp;quot;&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;de&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;#0000ff&amp;quot;&lt;/span&gt;} &lt;span class="hljs-string"&gt;&amp;quot;/tmp/a.svg&amp;quot;&lt;/span&gt;)
&lt;span class="hljs-literal"&gt;nil&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;It works!&lt;/p&gt;&lt;h2 id="problem-with-the-uk"&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 “uk” or “gb”. We resort to the source of our image, and the beginning comment once again proves helpful:&lt;/p&gt;&lt;blockquote&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 “British Islands” (the UK with its Crown Dependencies – Jersey, Guernsey and the Isle of Man)&lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;Perhaps we have to specify “gb-gbn” and “gb-nir”, instead of just “gb”? 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 “flat” 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;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;defn&lt;/span&gt; &lt;span class="hljs-title"&gt;map-zipper&lt;/span&gt; [f pred z]
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;if&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;zip/end?&lt;/span&gt; z)
    (&lt;span class="hljs-name"&gt;zip/root&lt;/span&gt; z)
    (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;recur&lt;/span&gt;&lt;/span&gt; f pred (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;-&amp;gt;&lt;/span&gt;&lt;/span&gt; z (&lt;span class="hljs-name"&gt;zip/edit&lt;/span&gt; #(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;if&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;pred&lt;/span&gt; %) (&lt;span class="hljs-name"&gt;f&lt;/span&gt; %) %)) zip/next)))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now we rewrite &lt;code&gt;save-color-map&lt;/code&gt; as:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;defn&lt;/span&gt; &lt;span class="hljs-title"&gt;save-color-map&lt;/span&gt;
  [svg colorize-fn outfile]
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [colored-map (&lt;span class="hljs-name"&gt;map-zipper&lt;/span&gt; #(&lt;span class="hljs-name"&gt;color-state&lt;/span&gt; % colorize-fn) (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;fn&lt;/span&gt;&lt;/span&gt; [x] (#{&lt;span class="hljs-symbol"&gt;:g&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:path&lt;/span&gt;} (&lt;span class="hljs-symbol"&gt;:tag&lt;/span&gt; x))) (&lt;span class="hljs-name"&gt;zip/xml-zip&lt;/span&gt; svg))]
    (&lt;span class="hljs-name"&gt;with-out-writer&lt;/span&gt; out
      (&lt;span class="hljs-name"&gt;emit&lt;/span&gt; colored-map))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This time the UK can be colored.&lt;/p&gt;&lt;h2 id="colorizers"&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’ve been using maps for this).&lt;/p&gt;&lt;p&gt;Let’s start by writing a function 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;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;defn&lt;/span&gt; &lt;span class="hljs-title"&gt;htmlize-color&lt;/span&gt;
  [[r g b]]
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;format&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;#%02x%02x%02x&amp;quot;&lt;/span&gt; r g b))
&lt;/code&gt;&lt;/pre&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;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;defn&lt;/span&gt; &lt;span class="hljs-title"&gt;color-state&lt;/span&gt;
  [{&lt;span class="hljs-symbol"&gt;:keys&lt;/span&gt; [tag attrs] &lt;span class="hljs-symbol"&gt;:as&lt;/span&gt; element} colorize-fn]
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [state (&lt;span class="hljs-symbol"&gt;:id&lt;/span&gt; attrs)]
    (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;if-let&lt;/span&gt;&lt;/span&gt; [color (&lt;span class="hljs-name"&gt;colorize-fn&lt;/span&gt; state)]
      (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;assoc&lt;/span&gt;&lt;/span&gt; element &lt;span class="hljs-symbol"&gt;:attrs&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;assoc&lt;/span&gt;&lt;/span&gt; attrs &lt;span class="hljs-symbol"&gt;:style&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;str&lt;/span&gt;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;fill:&amp;quot;&lt;/span&gt; (&lt;span class="hljs-name"&gt;htmlize-color&lt;/span&gt; color))))
      element)))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now imagine we have a table with numeric values for states, like this:&lt;/p&gt;&lt;table class="entry"&gt;
&lt;tr class="header"&gt;&lt;th&gt;State&lt;/th&gt;&lt;th&gt;Value&lt;/th&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Poland&lt;/td&gt;&lt;td class="center"&gt;20&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Germany&lt;/td&gt;&lt;td class="center"&gt;15&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Netherlands&lt;/td&gt;&lt;td class="center"&gt;30&lt;/td&gt;&lt;/tr&gt;
&lt;/table&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’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;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;defn&lt;/span&gt; &lt;span class="hljs-title"&gt;make-colorizer&lt;/span&gt;
  [dataset ranges]
  (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [minv (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;apply&lt;/span&gt;&lt;/span&gt; min (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;vals&lt;/span&gt;&lt;/span&gt; dataset))
        maxv (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;apply&lt;/span&gt;&lt;/span&gt; max (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;vals&lt;/span&gt;&lt;/span&gt; dataset))
        progress (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;map&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;fn&lt;/span&gt;&lt;/span&gt; [[min-col max-col]] (/ (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;-&lt;/span&gt;&lt;/span&gt; max-col min-col) (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;-&lt;/span&gt;&lt;/span&gt; maxv minv))) ranges)]
    (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;into&lt;/span&gt;&lt;/span&gt; {}
          (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;map&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;fn&lt;/span&gt;&lt;/span&gt; [[k v]] [(&lt;span class="hljs-name"&gt;.toLowerCase&lt;/span&gt; k) (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;map&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;fn&lt;/span&gt;&lt;/span&gt; [progress [min-color _]] (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;int&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;+&lt;/span&gt;&lt;/span&gt; min-color (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;*&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;-&lt;/span&gt;&lt;/span&gt; v minv) progress)))) progress ranges)])
               dataset))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Let us see how it works on our sample data:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;&amp;gt; (&lt;span class="hljs-name"&gt;make-colorizer&lt;/span&gt; {&lt;span class="hljs-string"&gt;&amp;quot;pl&amp;quot;&lt;/span&gt; &lt;span class="hljs-number"&gt;20&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;de&amp;quot;&lt;/span&gt; &lt;span class="hljs-number"&gt;15&lt;/span&gt;&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;nl&amp;quot;&lt;/span&gt; &lt;span class="hljs-number"&gt;30&lt;/span&gt;} [[&lt;span class="hljs-number"&gt;0&lt;/span&gt; &lt;span class="hljs-number"&gt;255&lt;/span&gt;] [&lt;span class="hljs-number"&gt;0&lt;/span&gt; &lt;span class="hljs-number"&gt;0&lt;/span&gt;] [&lt;span class="hljs-number"&gt;0&lt;/span&gt; &lt;span class="hljs-number"&gt;0&lt;/span&gt;]])
{&lt;span class="hljs-string"&gt;&amp;quot;pl&amp;quot;&lt;/span&gt; (&lt;span class="hljs-number"&gt;85&lt;/span&gt; &lt;span class="hljs-number"&gt;0&lt;/span&gt; &lt;span class="hljs-number"&gt;0&lt;/span&gt;)&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;de&amp;quot;&lt;/span&gt; (&lt;span class="hljs-number"&gt;0&lt;/span&gt; &lt;span class="hljs-number"&gt;0&lt;/span&gt; &lt;span class="hljs-number"&gt;0&lt;/span&gt;)&lt;span class="hljs-punctuation"&gt;,&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;nl&amp;quot;&lt;/span&gt; (&lt;span class="hljs-number"&gt;255&lt;/span&gt; &lt;span class="hljs-number"&gt;0&lt;/span&gt; &lt;span class="hljs-number"&gt;0&lt;/span&gt;)}
&lt;/code&gt;&lt;/pre&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’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 id="wrapping-up"&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 — 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’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;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2011-07-08:post:meet-my-little-friend-createtree</id>
    <title>Meet my little friend createTree</title>
    <link href="http://blog.danieljanus.pl/meet-my-little-friend-createtree/"/>
    <updated>2011-07-08T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;I’ve recently been developing an iPhone application in my spare time. I’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’m writing it in JavaScript and HTML5, using [PhoneGap][1] and [jQTouch][2] 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 [this blog post][3] that gave me a clue.&lt;/p&gt;&lt;p&gt;My code was using jQuery’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’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’s &lt;code&gt;.html()&lt;/code&gt; method. I considered this for a while, but finally decided against it — I didn’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;pre&gt;&lt;code class="hljs javascript"&gt;&lt;span class="hljs-keyword"&gt;function&lt;/span&gt; &lt;span class="hljs-title function_"&gt;createTree&lt;/span&gt;(&lt;span class="hljs-params"&gt;tree&lt;/span&gt;) {
    &lt;span class="hljs-keyword"&gt;if&lt;/span&gt; (&lt;span class="hljs-keyword"&gt;typeof&lt;/span&gt; tree === &lt;span class="hljs-string"&gt;&amp;#x27;string&amp;#x27;&lt;/span&gt; || &lt;span class="hljs-keyword"&gt;typeof&lt;/span&gt; tree === &lt;span class="hljs-string"&gt;&amp;#x27;number&amp;#x27;&lt;/span&gt;)
        &lt;span class="hljs-keyword"&gt;return&lt;/span&gt; &lt;span class="hljs-variable language_"&gt;document&lt;/span&gt;.&lt;span class="hljs-title function_"&gt;createTextNode&lt;/span&gt;(tree);
    &lt;span class="hljs-keyword"&gt;var&lt;/span&gt; tag = tree[&lt;span class="hljs-number"&gt;0&lt;/span&gt;], attrs = tree[&lt;span class="hljs-number"&gt;1&lt;/span&gt;], res = &lt;span class="hljs-variable language_"&gt;document&lt;/span&gt;.&lt;span class="hljs-title function_"&gt;createElement&lt;/span&gt;(tag);
    &lt;span class="hljs-keyword"&gt;for&lt;/span&gt; (&lt;span class="hljs-keyword"&gt;var&lt;/span&gt; attr &lt;span class="hljs-keyword"&gt;in&lt;/span&gt; attrs) {
        val = attrs[attr];
        &lt;span class="hljs-keyword"&gt;if&lt;/span&gt; (attr === &lt;span class="hljs-string"&gt;&amp;#x27;class&amp;#x27;&lt;/span&gt;)
            res.&lt;span class="hljs-property"&gt;className&lt;/span&gt; = val;
        &lt;span class="hljs-keyword"&gt;else&lt;/span&gt;
            $(res).&lt;span class="hljs-title function_"&gt;attr&lt;/span&gt;(attr, val);
    }
     &lt;span class="hljs-keyword"&gt;for&lt;/span&gt; (&lt;span class="hljs-keyword"&gt;var&lt;/span&gt; i = &lt;span class="hljs-number"&gt;2&lt;/span&gt;; i &amp;lt; tree.&lt;span class="hljs-property"&gt;length&lt;/span&gt;; i++)
        res.&lt;span class="hljs-title function_"&gt;appendChild&lt;/span&gt;(&lt;span class="hljs-title function_"&gt;createTree&lt;/span&gt;(tree[i]));
    &lt;span class="hljs-keyword"&gt;return&lt;/span&gt; res;
}
&lt;/code&gt;&lt;/pre&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;pre&gt;&lt;code class="hljs javascript"&gt;&lt;span class="hljs-keyword"&gt;var&lt;/span&gt; html = &lt;span class="hljs-string"&gt;&amp;#x27;&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;&amp;#x27;&lt;/span&gt;;
$(&lt;span class="hljs-string"&gt;&amp;#x27;#myDiv&amp;#x27;&lt;/span&gt;).&lt;span class="hljs-title function_"&gt;html&lt;/span&gt;(html);
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Using &lt;code&gt;createTree&lt;/code&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs javascript"&gt;&lt;span class="hljs-keyword"&gt;var&lt;/span&gt; tree = [&lt;span class="hljs-string"&gt;&amp;#x27;p&amp;#x27;&lt;/span&gt;, {},
            &lt;span class="hljs-string"&gt;&amp;#x27;This is an &amp;#x27;&lt;/span&gt;,
            [&lt;span class="hljs-string"&gt;&amp;#x27;span&amp;#x27;&lt;/span&gt;, {&lt;span class="hljs-string"&gt;&amp;#x27;class&amp;#x27;&lt;/span&gt;: &lt;span class="hljs-string"&gt;&amp;#x27;red&amp;#x27;&lt;/span&gt;}, &lt;span class="hljs-string"&gt;&amp;#x27;example.&amp;#x27;&lt;/span&gt;]];
$(&lt;span class="hljs-string"&gt;&amp;#x27;#myDiv&amp;#x27;&lt;/span&gt;).&lt;span class="hljs-title function_"&gt;empty&lt;/span&gt;().&lt;span class="hljs-title function_"&gt;append&lt;/span&gt;(&lt;span class="hljs-title function_"&gt;createTree&lt;/span&gt;(tree));
&lt;/code&gt;&lt;/pre&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;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2011-05-15:post:a-quirk-with-javascript-closures</id>
    <title>A quirk with JavaScript closures</title>
    <link href="http://blog.danieljanus.pl/a-quirk-with-javascript-closures/"/>
    <updated>2011-05-15T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;I keep running into this obstacle every now and then. Consider this example:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs javascript"&gt;&amp;gt; q = []
[]
&amp;gt; &lt;span class="hljs-keyword"&gt;for&lt;/span&gt; (&lt;span class="hljs-keyword"&gt;var&lt;/span&gt; i = &lt;span class="hljs-number"&gt;0&lt;/span&gt;; i &amp;lt; &lt;span class="hljs-number"&gt;3&lt;/span&gt;; i++)
    q.&lt;span class="hljs-title function_"&gt;push&lt;/span&gt;(&lt;span class="hljs-keyword"&gt;function&lt;/span&gt;(&lt;span class="hljs-params"&gt;&lt;/span&gt;) { &lt;span class="hljs-variable language_"&gt;console&lt;/span&gt;.&lt;span class="hljs-title function_"&gt;log&lt;/span&gt;(i); });
&amp;gt; q[&lt;span class="hljs-number"&gt;0&lt;/span&gt;]()
&lt;span class="hljs-number"&gt;3&lt;/span&gt;
&lt;/code&gt;&lt;/pre&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; &lt;code&gt;i&lt;/code&gt; 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;pre&gt;&lt;code class="hljs javascript"&gt;&lt;span class="hljs-keyword"&gt;for&lt;/span&gt; (&lt;span class="hljs-keyword"&gt;var&lt;/span&gt; i = &lt;span class="hljs-number"&gt;0&lt;/span&gt;; i &amp;lt; &lt;span class="hljs-number"&gt;3&lt;/span&gt;; i++)
  (&lt;span class="hljs-keyword"&gt;function&lt;/span&gt;(&lt;span class="hljs-params"&gt;v&lt;/span&gt;) {
    q.&lt;span class="hljs-title function_"&gt;push&lt;/span&gt;(&lt;span class="hljs-keyword"&gt;function&lt;/span&gt;(&lt;span class="hljs-params"&gt;&lt;/span&gt;) { &lt;span class="hljs-variable language_"&gt;console&lt;/span&gt;.&lt;span class="hljs-title function_"&gt;log&lt;/span&gt;(v); });
  })(i);
&lt;/code&gt;&lt;/pre&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;pre&gt;&lt;code class="hljs javascript"&gt;&lt;span class="hljs-title function_"&gt;_&lt;/span&gt;([&lt;span class="hljs-number"&gt;1&lt;/span&gt;,&lt;span class="hljs-number"&gt;2&lt;/span&gt;,&lt;span class="hljs-number"&gt;3&lt;/span&gt;]).&lt;span class="hljs-title function_"&gt;each&lt;/span&gt;(&lt;span class="hljs-keyword"&gt;function&lt;/span&gt;(&lt;span class="hljs-params"&gt;i&lt;/span&gt;) {
  q.&lt;span class="hljs-title function_"&gt;push&lt;/span&gt;(&lt;span class="hljs-keyword"&gt;function&lt;/span&gt;(&lt;span class="hljs-params"&gt;&lt;/span&gt;) { &lt;span class="hljs-variable language_"&gt;console&lt;/span&gt;.&lt;span class="hljs-title function_"&gt;log&lt;/span&gt;(i); });
});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2011-03-28:post:the-dijkstran-wheel-of-fortune</id>
    <title>The Dijkstran wheel of fortune: SPSS, Excel, VBA</title>
    <link href="http://blog.danieljanus.pl/the-dijkstran-wheel-of-fortune/"/>
    <updated>2011-03-28T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;blockquote&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 style="text-align: right;"&gt;— 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’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’ve spend the last few days writing BASIC code. I’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 [SPSS][1] 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’d have to write). So I went the Excel way, and in this post I’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’t have to number my lines, and it is possible to structure the code nicely so that it doesn’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 “Immediate” 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’ll only note down the things pertaining to Excel interop; hopefully it will save somebody’s time.&lt;/p&gt;&lt;p&gt;Problem is, SPSS 19’s Excel export is buggy. In fact, it’s so unreliable that I’ve wasted more hours struggling with it than actually writing my macros. (We’re talking SPSS 19 here; I’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 — 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 → Copy special&lt;/code&gt; and select Excel BIFF format, to make sure you’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;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2010-05-04:post:defnk</id>
    <title>Keyword arguments</title>
    <link href="http://blog.danieljanus.pl/defnk/"/>
    <updated>2010-05-04T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;There’s been an &lt;a href="http://stuartsierra.com/2010/01/15/keyword-arguments-in-clojure"&gt;ongoing&lt;/a&gt; &lt;a href="http://www.fatvat.co.uk/2009/01/passing-parameters-in-clojure.html"&gt;debate&lt;/a&gt; about how to pass optional named arguments to Clojure functions. One way to do this is the &lt;a href="http://richhickey.github.com/clojure-contrib/def-api.html#clojure.contrib.def/defnk"&gt;defnk&lt;/a&gt; macro from &lt;code&gt;clojure.contrib.def&lt;/code&gt;; I hesitate to call it &lt;em&gt;canonical&lt;/em&gt;, since apparently not everyone uses it, but I’ve found it useful a number of times. Here’s a sample:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;user&amp;gt; (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;use&lt;/span&gt;&lt;/span&gt; &amp;#x27;clojure.contrib.def)
&lt;span class="hljs-literal"&gt;nil&lt;/span&gt;
user&amp;gt; (&lt;span class="hljs-name"&gt;defnk&lt;/span&gt; f [&lt;span class="hljs-symbol"&gt;:b&lt;/span&gt; &lt;span class="hljs-number"&gt;43&lt;/span&gt;] (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;inc&lt;/span&gt;&lt;/span&gt; b))
#&amp;#x27;user/f
user&amp;gt; (&lt;span class="hljs-name"&gt;f&lt;/span&gt;)
&lt;span class="hljs-number"&gt;44&lt;/span&gt;
user&amp;gt; (&lt;span class="hljs-name"&gt;f&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:b&lt;/span&gt; &lt;span class="hljs-number"&gt;100&lt;/span&gt;)
&lt;span class="hljs-number"&gt;101&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This is an example of &lt;em&gt;keyword arguments&lt;/em&gt; in action. Keyword arguments are a core feature of some languages, notably &lt;a href="http://www.gigamonkeys.com/book/functions.html#keyword-parameters"&gt;Common Lisp&lt;/a&gt; and &lt;a href="http://caml.inria.fr/pub/docs/manual-ocaml/manual006.html#htoc38"&gt;Objective Caml&lt;/a&gt;. Clojure doesn’t have them, but it’s pretty easy to emulate their basic usage with macros, as &lt;code&gt;defnk&lt;/code&gt; does.&lt;/p&gt;&lt;p&gt;But there’s more to Common Lisp’s keyword arguments than &lt;code&gt;defnk&lt;/code&gt; provides. In CL, the default value of a keyword argument can be an expression referring to other arguments of the same function. For example:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs lisp"&gt;CL-USER&amp;gt; (&lt;span class="hljs-name"&gt;defun&lt;/span&gt; f (&lt;span class="hljs-name"&gt;&amp;amp;key&lt;/span&gt; (&lt;span class="hljs-name"&gt;a&lt;/span&gt; &lt;span class="hljs-number"&gt;1&lt;/span&gt;) (&lt;span class="hljs-name"&gt;b&lt;/span&gt; a))
           (&lt;span class="hljs-name"&gt;+&lt;/span&gt; a b))
F
CL-USER&amp;gt; (&lt;span class="hljs-name"&gt;f&lt;/span&gt;)
&lt;span class="hljs-number"&gt;2&lt;/span&gt;
CL-USER&amp;gt; (&lt;span class="hljs-name"&gt;f&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:a&lt;/span&gt; &lt;span class="hljs-number"&gt;45&lt;/span&gt;)
&lt;span class="hljs-number"&gt;90&lt;/span&gt;
CL-USER&amp;gt; (&lt;span class="hljs-name"&gt;f&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:b&lt;/span&gt; &lt;span class="hljs-number"&gt;101&lt;/span&gt;)
&lt;span class="hljs-number"&gt;102&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;I wish &lt;code&gt;defnk&lt;/code&gt; had this feature. Or is there some better way that I don’t know of?&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2010-04-18:post:sunflower</id>
    <title>Sunflower</title>
    <link href="http://blog.danieljanus.pl/sunflower/"/>
    <updated>2010-04-18T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;The program I’ve been [writing about recently][1] has come to a point where I think it can be shown to the wide public. It’s called [Sunflower][2] and has its home on GitHub. It’s nowhere near being completed, and of alpha quality right now, but even at this stage it might be useful.&lt;/p&gt;&lt;p&gt;Just as sunflower seed kernels come wrapped in hulls, most HTML documents seen in the wild come wrapped in noise that is not really part of the document itself. Take any news site: a document from such a site contains things such as advertisements, header, footer, and many links. Now suppose you have many documents grabbed from the same site. Is it possible to somehow automate the extraction of the document “essences”?&lt;/p&gt;&lt;p&gt;Sunflower to the rescue. It relies on the assumption that documents coming from the same source have the same structure. It presents a list of strings to the user, and asks to pick those that are contained in the text essence. Then it finds the coordinates of the smallest HTML subtree that contains all those strings, and uses those coordinates to extract information from all documents. And it comes with a nice, easily understandable GUI for that.&lt;/p&gt;&lt;p&gt;This technique works remarkably well for many collections, although not all. An earlier, proof-of-concept implementation (in Common Lisp) has been used to extract many press texts for the [National Corpus of Polish][3].&lt;/p&gt;&lt;p&gt;I’ve given up on the symbol-capturing approach to wizards I’ve presented in my previous posts. Inspired by the DOM tree in Web apps, with a bag of elements with identifiers, I now have a central bag of Swing widgets (implemented as an atom) identified by keywords. This bag contains tidbits of the mutable state of Sunflower. This means that I can write callback functions like this:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;#(&lt;span class="hljs-name"&gt;with-components&lt;/span&gt; [strings-model selected-dir]
   (&lt;span class="hljs-name"&gt;.removeAllElements&lt;/span&gt; strings-model)
   (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [p (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;-&amp;gt;&lt;/span&gt;&lt;/span&gt; selected-dir htmls first parse)]
     (&lt;span class="hljs-name"&gt;add-component&lt;/span&gt; &lt;span class="hljs-symbol"&gt;:parsed&lt;/span&gt; p)
     (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;doseq&lt;/span&gt;&lt;/span&gt; [x (&lt;span class="hljs-name"&gt;strings&lt;/span&gt; p)]
       (&lt;span class="hljs-name"&gt;.addElement&lt;/span&gt; strings-model x))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Name and conquer: having parts of state explicitly named mean that I can reliably access them from just about anywhere. This reduces confusion and allows for less tangled, more self-contained and understandable code.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2010-04-05:post:symbol-capture</id>
    <title>A case for symbol capture</title>
    <link href="http://blog.danieljanus.pl/symbol-capture/"/>
    <updated>2010-04-05T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;Clojure by default protects macro authors from incidentally capturing a local symbol. Stuart Halloway &lt;a href="http://blog.thinkrelevance.com/2008/12/17/on-lisp-clojure-chapter-9"&gt;describes this&lt;/a&gt; in more detail, explaining why this is a Good Thing. However, sometimes this kind of symbol capture is called for. I’ve encountered one such case today while hacking a Swing application.&lt;/p&gt;&lt;p&gt;As I develop the app, I find new ways to express Swing concepts and interact with Swing objects in a more Clojuresque way, so a library of GUI macros and functions gets written. One of them is a &lt;code&gt;wizard&lt;/code&gt; macro for easy creation of installer-like wizards, where there is a sequence of screens that can be navigated with &lt;em&gt;Back&lt;/em&gt; and &lt;em&gt;Next&lt;/em&gt; buttons at the bottom of the window.&lt;/p&gt;&lt;p&gt;The API (certainly not finished yet) currently looks like this:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;wizard&lt;/span&gt; &amp;amp; components)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;where each Swing &lt;code&gt;component&lt;/code&gt; corresponding to one wizard screen can be augmented by a supplementary map, which can contain, &lt;em&gt;inter alia&lt;/em&gt;, a function to execute upon showing the screen in question.&lt;/p&gt;&lt;p&gt;Now, I want those functions to be able to access the &lt;em&gt;Back&lt;/em&gt; and &lt;em&gt;Next&lt;/em&gt; buttons in case they want to disable or enable them at need. I thus want the API user to be able to use two symbols, &lt;code&gt;back-button&lt;/code&gt; and &lt;code&gt;next-button&lt;/code&gt;, in the macro body, and have them bound to the corresponding buttons.&lt;/p&gt;&lt;p&gt;It is crucial that these bindings be lexical and not dynamic. If they were dynamic, they would be only effective during the definition of the wizard, but not when my closures are invoked later on. Thus, my implementation looks like this:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-keyword"&gt;defmacro&lt;/span&gt; &lt;span class="hljs-title"&gt;wizard&lt;/span&gt; [&amp;amp; panels]
  `(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;let&lt;/span&gt;&lt;/span&gt; [~&amp;#x27;back-button (&lt;span class="hljs-name"&gt;button&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;&amp;lt; Back&amp;quot;&lt;/span&gt;)
         ~&amp;#x27;next-button (&lt;span class="hljs-name"&gt;button&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;Next &amp;gt;&amp;quot;&lt;/span&gt;)]
   (&lt;span class="hljs-name"&gt;do-wizard&lt;/span&gt; ~&amp;#x27;back-button ~&amp;#x27;next-button ~(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;vec&lt;/span&gt;&lt;/span&gt; panels))))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;where &lt;code&gt;do-wizard&lt;/code&gt; is a private function implementing the actual wizard creation, and the &lt;code&gt;~'foo&lt;/code&gt; syntax forces symbol capture.&lt;/p&gt;&lt;p&gt;By the way, if all goes well, this blog post should be the first one syndicated to Planet Clojure. Hello, Planet Clojure readers!&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2010-03-31:post:lein-swank</id>
    <title>The pitfalls of &lt;code&gt;lein swank&lt;/code&gt;</title>
    <link href="http://blog.danieljanus.pl/lein-swank/"/>
    <updated>2010-03-31T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;A couple of weeks ago I finally got around to acquainting myself with [Leiningen][1], one of the most popular build tools for Clojure. The thing that stopped me the most was that Leiningen uses [Maven][2] under the hood, which seemed a scary beast at first sight — but once I’ve overcome the initial fear, it turned out to be a quite simple and useful tool.&lt;/p&gt;&lt;p&gt;One feature in particular is very useful for Emacs users like me: &lt;code&gt;lein swank&lt;/code&gt;. You define all dependencies in &lt;code&gt;project.clj&lt;/code&gt; as usual, add a magical line to &lt;code&gt;:dev-dependencies&lt;/code&gt;, then say&lt;/p&gt;&lt;pre&gt;&lt;code&gt;$ lein swank
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;and lo and behold, you can &lt;code&gt;M-x slime-connect&lt;/code&gt; from your Emacs and have all the code at your disposal.&lt;/p&gt;&lt;p&gt;There is, however, an issue that you must be aware of when using &lt;code&gt;lein swank&lt;/code&gt;: Leiningen uses a custom class loader — [AntClassLoader][3] to be more precise — to load the Java classes referenced by the code. Despite being a seemingly irrelevant thing — an implementation detail — this can bite you in a number of most surprising and obscure ways. Try evaluating the following code in a Leiningen REPL:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs clojure"&gt;(&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;str&lt;/span&gt;&lt;/span&gt; (&lt;span class="hljs-name"&gt;.decode&lt;/span&gt;
       (&lt;span class="hljs-name"&gt;java.nio.charset.Charset/forName&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;ISO-8859-2&amp;quot;&lt;/span&gt;)
       (&lt;span class="hljs-name"&gt;java.nio.ByteBuffer/wrap&lt;/span&gt;
         (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;into-array&lt;/span&gt;&lt;/span&gt; Byte/TYPE (&lt;span class="hljs-name"&gt;&lt;span class="hljs-built_in"&gt;map&lt;/span&gt;&lt;/span&gt; byte [&lt;span class="hljs-number"&gt;-79&lt;/span&gt; &lt;span class="hljs-number"&gt;-26&lt;/span&gt; &lt;span class="hljs-number"&gt;-22&lt;/span&gt;])))))
&lt;span class="hljs-comment"&gt;;=&amp;gt; &amp;quot;???&amp;quot;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The same code evaluated in a plain Clojure REPL will give you &lt;code&gt;"ąćę"&lt;/code&gt;, which is a string represented in ISO-8859-2 by the three bytes from the above snippet.&lt;/p&gt;&lt;p&gt;Whence the difference? Internally, each charset is represented as a unique instance of its specific class. These are loaded lazily as needed by the &lt;code&gt;Charset/forName&lt;/code&gt; method. Presumably, the system class loader is used for that, and somewhere along the way a &lt;code&gt;SecurityException&lt;/code&gt; gets thrown and caught.&lt;/p&gt;&lt;p&gt;Note also that there are parts of Java API which use the charset lookup under the hood and are thus vulnerable to the same problem, for example &lt;code&gt;Reader&lt;/code&gt; constructors taking charset names. If you use &lt;code&gt;clojure.contrib.duck-streams&lt;/code&gt;, then rebinding &lt;code&gt;*default-encoding*&lt;/code&gt; will not work from a Leiningen REPL. Jars and überjars produced by Leiningen should be fine, though.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2010-02-10:post:clojure-set</id>
    <title>Clojure SET</title>
    <link href="http://blog.danieljanus.pl/clojure-set/"/>
    <updated>2010-02-10T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;I’ve just taken a short breath off work to put &lt;a href="http://github.com/nathell/setgame"&gt;some code&lt;/a&gt; on GitHub that I had written over one night some two months ago. It is an implementation of the &lt;a href="http://en.wikipedia.org/wiki/Set_(game)"&gt;Set&lt;/a&gt; game in Clojure, using Swing for GUI.&lt;/p&gt;&lt;p&gt;I do not have time to clean up or comment the code, so I’m leaving it as is for now; however, I hope that even in its current state it can be of interest, especially for Clojure learners.&lt;/p&gt;&lt;p&gt;Some random notes on the code:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;span&gt;Clojure is concise! The whole thing is just under 250 lines of code, complete with game logic and the GUI. Of these, the logic is about 50 LOC. Despite this it reads clearly and has been a pleasure to write, thanks to Clojure’s supports for sets as a data structure (in vein of the game’s title and theme).&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;There are no graphics included. All the drawing is done in the GUI part of code (I’ve replaced the canonical squiggle shape by a triangle and stripes by gradients, for the sake of easier drawing).&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;I’ve toyed around with different Swing layout managers for this game. Back in the days when I wrote in plain Java, I used to use &lt;a href="https://tablelayout.dev.java.net/"&gt;TableLayout&lt;/a&gt;, but it has a non-free license; &lt;a href="http://www.jgoodies.com/freeware/forms/"&gt;JGoodies Forms&lt;/a&gt; is also nice, but has a slightly more complicated API (and it’s an additional dependency, after all). In the end I’ve settled with the standard GridBagLayout, which is similar in spirit to those two, but requires more boilerplate to set up. As it turned out, simple macrology makes it quite pleasurable to use; see &lt;code&gt;add-gridbag&lt;/code&gt; in the code for details.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span&gt;Other things of interest might be my function to randomly shuffle seqs, which strikes a nice balance between simplicity/conciseness of implementation and randomness; and a useful debugging macro.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Comments?&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2008-12-18:post:fighting-procrastination</id>
    <title>anti-procrastination.el</title>
    <link href="http://blog.danieljanus.pl/fighting-procrastination/"/>
    <updated>2008-12-18T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;Fighting procrastination has been my major concern these days. I’ve devised a number of experimental tools to help me with that. One of them is called &lt;a href="http://bach.ipipan.waw.pl/~nathell/projects/snafu.php"&gt;snafu&lt;/a&gt; and can generate reports of your activity throughout the whole day of work. It’s in a preliminary state, but works (at least since I’ve found and fixed a long-standing bug in it which would cause it to barf every now and then), and I already have a number of ideas for its further expansion.&lt;/p&gt;&lt;p&gt;Reports alone, however, do not quite muster enough motivation for work. I’m doing most of my editing/programming work in Emacs, so yesterday I grabbed the Emacs Lisp manual and came up with a couple of extra lines at the end of my &lt;code&gt;.emacs&lt;/code&gt;.&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs lisp"&gt;&lt;span class="hljs-comment"&gt;;;; Written by Daniel Janus, 2008/12/18.&lt;/span&gt;
&lt;span class="hljs-comment"&gt;;;; This snippet is placed into the public domain.  Feel free&lt;/span&gt;
&lt;span class="hljs-comment"&gt;;;; to use it in any way you wish.  I am not responsible for&lt;/span&gt;
&lt;span class="hljs-comment"&gt;;;; any damage resulting from its usage.&lt;/span&gt;

(&lt;span class="hljs-name"&gt;defvar&lt;/span&gt; store-last-modification-time &lt;span class="hljs-literal"&gt;t&lt;/span&gt;)
(&lt;span class="hljs-name"&gt;defvar&lt;/span&gt; last-modification-time &lt;span class="hljs-literal"&gt;nil&lt;/span&gt;)
(&lt;span class="hljs-name"&gt;defun&lt;/span&gt; mark-last-modification-time (&lt;span class="hljs-name"&gt;beg&lt;/span&gt; end len)
  (&lt;span class="hljs-name"&gt;let&lt;/span&gt; ((&lt;span class="hljs-name"&gt;b1&lt;/span&gt; (&lt;span class="hljs-name"&gt;substring&lt;/span&gt; (&lt;span class="hljs-name"&gt;buffer-name&lt;/span&gt; (&lt;span class="hljs-name"&gt;current-buffer&lt;/span&gt;)) &lt;span class="hljs-number"&gt;0&lt;/span&gt; &lt;span class="hljs-number"&gt;1&lt;/span&gt;)))
    (&lt;span class="hljs-name"&gt;when&lt;/span&gt; (&lt;span class="hljs-name"&gt;and&lt;/span&gt; store-last-modification-time
               (&lt;span class="hljs-name"&gt;not&lt;/span&gt; (&lt;span class="hljs-name"&gt;string=&lt;/span&gt; b1 &lt;span class="hljs-string"&gt;&amp;quot; &amp;quot;&lt;/span&gt;))
               (&lt;span class="hljs-name"&gt;not&lt;/span&gt; (&lt;span class="hljs-name"&gt;string=&lt;/span&gt; b1 &lt;span class="hljs-string"&gt;&amp;quot;*&amp;quot;&lt;/span&gt;)))
      (&lt;span class="hljs-name"&gt;setq&lt;/span&gt; last-modification-time (&lt;span class="hljs-name"&gt;current-time&lt;/span&gt;)))))
(&lt;span class="hljs-name"&gt;add-hook&lt;/span&gt; &amp;#x27;after-change-functions &amp;#x27;mark-last-modification-time)
(&lt;span class="hljs-name"&gt;defun&lt;/span&gt; write-lmt ()
  (&lt;span class="hljs-name"&gt;setq&lt;/span&gt; store-last-modification-time &lt;span class="hljs-literal"&gt;nil&lt;/span&gt;)
  (&lt;span class="hljs-name"&gt;when&lt;/span&gt; last-modification-time
    (&lt;span class="hljs-name"&gt;with-temp-file&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;/tmp/emacs-lmt&amp;quot;&lt;/span&gt;
      (&lt;span class="hljs-name"&gt;multiple-value-bind&lt;/span&gt; (&lt;span class="hljs-name"&gt;a&lt;/span&gt; b c) last-modification-time
        (&lt;span class="hljs-name"&gt;princ&lt;/span&gt; a (&lt;span class="hljs-name"&gt;current-buffer&lt;/span&gt;))
        (&lt;span class="hljs-name"&gt;terpri&lt;/span&gt; (&lt;span class="hljs-name"&gt;current-buffer&lt;/span&gt;))
        (&lt;span class="hljs-name"&gt;princ&lt;/span&gt; b (&lt;span class="hljs-name"&gt;current-buffer&lt;/span&gt;)))))
  (&lt;span class="hljs-name"&gt;setq&lt;/span&gt; store-last-modification-time &lt;span class="hljs-literal"&gt;t&lt;/span&gt;))
(&lt;span class="hljs-name"&gt;run-at-time&lt;/span&gt; &lt;span class="hljs-literal"&gt;nil&lt;/span&gt; &lt;span class="hljs-number"&gt;1&lt;/span&gt; &amp;#x27;write-lmt)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Every second (to change that to every 10 seconds, change the &lt;code&gt;1&lt;/code&gt; to &lt;code&gt;10&lt;/code&gt; in the last line) it creates a file named &lt;code&gt;/tmp/emacs-lmt&lt;/code&gt; which contains the time of last modification of any non-system buffer.&lt;/p&gt;&lt;p&gt;That’s all there is to it, at least on the Emacs side. The other part is a simple shell script, which uses &lt;a href="http://www.mplayerhq.hu/"&gt;MPlayer&lt;/a&gt; to display a nag-screen for five seconds, and then give me some time to start doing anything useful before nagging me again:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs bash"&gt;&lt;span class="hljs-meta"&gt;#!/bin/bash&lt;/span&gt;
TIMEOUT=300
&lt;span class="hljs-keyword"&gt;while&lt;/span&gt; &lt;span class="hljs-literal"&gt;true&lt;/span&gt;; &lt;span class="hljs-keyword"&gt;do&lt;/span&gt;
   &lt;span class="hljs-built_in"&gt;cat&lt;/span&gt; /tmp/emacs-lmt | (
      &lt;span class="hljs-built_in"&gt;read&lt;/span&gt; a; &lt;span class="hljs-built_in"&gt;read&lt;/span&gt; b;
      c=&lt;span class="hljs-string"&gt;&amp;quot;`date +%s`&amp;quot;&lt;/span&gt;;
      &lt;span class="hljs-built_in"&gt;let&lt;/span&gt; x=c-65536*a-b;
      &lt;span class="hljs-keyword"&gt;if&lt;/span&gt; &lt;span class="hljs-built_in"&gt;test&lt;/span&gt; &lt;span class="hljs-variable"&gt;$x&lt;/span&gt; -gt &lt;span class="hljs-variable"&gt;$TIMEOUT&lt;/span&gt;;
          &lt;span class="hljs-keyword"&gt;then&lt;/span&gt; mplayer -fs &lt;span class="hljs-variable"&gt;$HOME&lt;/span&gt;/p.avi;
               &lt;span class="hljs-built_in"&gt;sleep&lt;/span&gt; 15;
      &lt;span class="hljs-keyword"&gt;fi&lt;/span&gt;)
   &lt;span class="hljs-built_in"&gt;sleep&lt;/span&gt; 1
&lt;span class="hljs-keyword"&gt;done&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The nag-screen in my case is an animation which I’ve created using MEncoder from a single frame which looks &lt;a href="http://bach.ipipan.waw.pl/~nathell/procrastination.png"&gt;like this&lt;/a&gt;. Beware the expletives! (This is one of the few cases I find their usage justified, as the strong message bites the conscience more strongly.)&lt;/p&gt;&lt;p&gt;I’ve only been testing this setup for one day, but so far it’s working flawlessly: I got more done yesterday than for the two previous days combined, and that’s excluding the hour or so that took me to write these snippets.&lt;/p&gt;&lt;p&gt;If anyone else happens to give it a try, I’d love to hear any comments.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2008-08-09:post:small-lisp</id>
    <title>Who said Common Lisp programs cannot be small?</title>
    <link href="http://blog.danieljanus.pl/small-lisp/"/>
    <updated>2008-08-09T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;So, how much disk space does your average CL image eat up? A hundred megs? Fifty? Twenty? Five, perhaps, if you’re using LispWorks with a tree-shaker? Well then, how about this?&lt;/p&gt;&lt;pre&gt;&lt;code&gt;[nathell@chamsin salza2-2.0.4]$ ./cl-gzip closures.lisp test.gz
[nathell@chamsin salza2-2.0.4]$ gunzip test
[nathell@chamsin salza2-2.0.4]$ diff closures.lisp test
[nathell@chamsin salza2-2.0.4]$ ls -l cl-gzip
-rwxr-xr-x 1 nathell nathell 386356 2008-08-09 11:08 cl-gzip
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;That’s right. A standalone executable of a mini-gzip, written in Common Lisp, taking up &lt;em&gt;under 400K!&lt;/em&gt; And it only depends on glibc and GMP, which are available by default on pretty much every Linux installation. (This is on a 32-bit x86 machine, by the way).&lt;/p&gt;&lt;p&gt;I used the most recent version of &lt;a href="http://ecls.sourceforge.net/"&gt;ECL&lt;/a&gt; for compiling this tiny example. The key to the size was configuring ECL with &lt;code&gt;--disable-shared --enable-static CFLAGS="-Os -ffunction-sections -fdata-sections" LDFLAGS="-Wl,-gc-sections"&lt;/code&gt;. This essentially gives you a poor man’s tree shaker for free at a linker level. And ECL in itself produces comparatively tiny code.&lt;/p&gt;&lt;p&gt;I built this example from &lt;a href="http://www.xach.com/lisp/salza2"&gt;Salza2&lt;/a&gt;’s source by loading the following code snippet:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;defvar&lt;/span&gt; salza
  &amp;#x27;(&lt;span class="hljs-string"&gt;&amp;quot;package&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;reset&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;specials&amp;quot;&lt;/span&gt;
    &lt;span class="hljs-string"&gt;&amp;quot;types&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;checksum&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;adler32&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;crc32&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;chains&amp;quot;&lt;/span&gt;
    &lt;span class="hljs-string"&gt;&amp;quot;bitstream&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;matches&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;compress&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;huffman&amp;quot;&lt;/span&gt;
    &lt;span class="hljs-string"&gt;&amp;quot;closures&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;compressor&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;utilities&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;zlib&amp;quot;&lt;/span&gt;
    &lt;span class="hljs-string"&gt;&amp;quot;gzip&amp;quot;&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;user&amp;quot;&lt;/span&gt;))

(&lt;span class="hljs-name"&gt;defvar&lt;/span&gt; salza2
  (&lt;span class="hljs-name"&gt;mapcar&lt;/span&gt; (&lt;span class="hljs-name"&gt;lambda&lt;/span&gt; (&lt;span class="hljs-name"&gt;x&lt;/span&gt;) (&lt;span class="hljs-name"&gt;format&lt;/span&gt; &lt;span class="hljs-literal"&gt;nil&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;~A.lisp&amp;quot;&lt;/span&gt; x))
          salza))

(&lt;span class="hljs-name"&gt;defvar&lt;/span&gt; salza3
  (&lt;span class="hljs-name"&gt;mapcar&lt;/span&gt; (&lt;span class="hljs-name"&gt;lambda&lt;/span&gt; (&lt;span class="hljs-name"&gt;x&lt;/span&gt;) (&lt;span class="hljs-name"&gt;format&lt;/span&gt; &lt;span class="hljs-literal"&gt;nil&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;~A.o&amp;quot;&lt;/span&gt; x))
          salza))

(&lt;span class="hljs-name"&gt;defun&lt;/span&gt; build-cl-gzip ()
  (&lt;span class="hljs-name"&gt;dolist&lt;/span&gt; (&lt;span class="hljs-name"&gt;x&lt;/span&gt; salza2)
          (&lt;span class="hljs-name"&gt;load&lt;/span&gt; x)
          (&lt;span class="hljs-name"&gt;compile-file&lt;/span&gt; x &lt;span class="hljs-symbol"&gt;:system-p&lt;/span&gt; &lt;span class="hljs-literal"&gt;t&lt;/span&gt;))
  (&lt;span class="hljs-name"&gt;c&lt;/span&gt;&lt;span class="hljs-symbol"&gt;:build-program&lt;/span&gt;
   &lt;span class="hljs-string"&gt;&amp;quot;cl-gzip&amp;quot;&lt;/span&gt;
   &lt;span class="hljs-symbol"&gt;:lisp-files&lt;/span&gt; salza3
   &lt;span class="hljs-symbol"&gt;:epilogue-code&lt;/span&gt;
     &amp;#x27;(progn
       (in-package :salza2)
       (gzip-file (second (si::command-args))
                  (third (si::command-args))))))

(&lt;span class="hljs-name"&gt;build-cl-gzip&lt;/span&gt;)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;(Sadly enough, there’s no ASDF in here. I have yet to figure out how to leverage ASDF to build small binaries in this constrained environment.)&lt;/p&gt;&lt;p&gt;This gave me a standalone executable 1.2 meg in size. I then proceeded to compress it with &lt;a href="http://upx.sourceforge.net/"&gt;UPX&lt;/a&gt; (with arguments &lt;code&gt;--best --crp-ms=999999&lt;/code&gt;) and got the final result. How cool is that?&lt;/p&gt;&lt;p&gt;I am actively looking for a new job. If you happen to like my writings and think I might be just the right man for the team you’re building up, please feel free to consult my &lt;a href="http://bach.ipipan.waw.pl/~nathell/cv-en.pdf"&gt;résumé&lt;/a&gt; or pass it on.&lt;/p&gt;&lt;p&gt;&lt;em&gt;Update 2010-Jan-17&lt;/em&gt;: the above paragraph is no longer valid.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2008-06-23:post:cl-morfeusz</id>
    <title>cl-morfeusz: A ninety minutes’ hack</title>
    <link href="http://blog.danieljanus.pl/cl-morfeusz/"/>
    <updated>2008-06-23T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;Here’s what I came up with today, after no more than 90 minutes of coding (complete with comments and all):&lt;/p&gt;&lt;pre&gt;&lt;code&gt;MORFEUSZ&gt; (morfeusz-analyse "zażółć gęślą jaźń")
((0 1 "zażółć" "zażółcić" "impt:sg:sec:perf")
 (1 2 "gęślą" "gęśl" "subst:sg:inst:f")
 (2 3 "jaźń" "jaźń" "subst:sg:nom.acc:f"))
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This is &lt;a href="http://danieljanus.pl/code/morfeusz.lisp"&gt;cl-morfeusz&lt;/a&gt; in action, a Common Lisp interface to &lt;a href="http://nlp.ipipan.waw.pl/~wolinski/morfeusz/"&gt;Morfeusz&lt;/a&gt;, the morphological analyser for Polish.&lt;/p&gt;&lt;p&gt;It’s a single Lisp file, so there’s no ASDF system definition or asdf-installability for now. I’m not putting it under version control, either. Or, should I say, not yet. When I get around to it, I plan to write a simple parser and write a Polish-language version of &lt;a href="http://en.wikipedia.org/wiki/Colossal_Cave_Adventure"&gt;the text adventure that started it all&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Meanwhile, you may use cl-morfeusz for anything you wish (of course, as long as you comply with Morfeusz’s license). Have fun!&lt;/p&gt;&lt;p&gt;&lt;em&gt;Update 2010-Jan-17&lt;/em&gt;: With the advent of UTF-8 support in CFFI, the ugly workarounds in the code are probably no longer necessary; I don’t have time to check it right now, though.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2008-04-30:post:cl-netstrings</id>
    <title>cl-netstrings</title>
    <link href="http://blog.danieljanus.pl/cl-netstrings/"/>
    <updated>2008-04-30T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;I’ve just packaged up the Common Lisp netstring handling code that I &lt;a href="http://blog.danieljanus.pl/hacking-away-with-json-rpc.html"&gt;wrote a week ago&lt;/a&gt; into a neat library. Unsurprisingly enough, it is called cl-netstrings and has its own &lt;a href="http://github.com/nathell/cl-netstrings"&gt;home on the Web&lt;/a&gt;. It’s even asdf-installable! I wonder whether this one turns out to be useful for anybody besides me…&lt;/p&gt;&lt;p&gt;The other thing I’ve been working on is a new build system for Poliqarp. But that’s the story for another post — most probably I will write about it when it gets out of a state of constant flux.&lt;/p&gt;&lt;p&gt;&lt;em&gt;Update 2010-Jan-17&lt;/em&gt;: cl-netstrings is now hosted on GitHub; I’ve updated the link.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2008-04-24:post:hacking-away-with-json-rpc</id>
    <title>Hacking away with JSON-RPC</title>
    <link href="http://blog.danieljanus.pl/hacking-away-with-json-rpc/"/>
    <updated>2008-04-24T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;Let’s try:&lt;/p&gt;&lt;pre&gt;&lt;code class="hljs lisp"&gt;(&lt;span class="hljs-name"&gt;let&lt;/span&gt; ((&lt;span class="hljs-name"&gt;s&lt;/span&gt; (&lt;span class="hljs-name"&gt;socket-stream&lt;/span&gt;
          (&lt;span class="hljs-name"&gt;socket-connect&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;localhost&amp;quot;&lt;/span&gt; &lt;span class="hljs-number"&gt;10081&lt;/span&gt;
                          &lt;span class="hljs-symbol"&gt;:element-type&lt;/span&gt; &amp;#x27;(unsigned-byte &lt;span class="hljs-number"&gt;8&lt;/span&gt;)))))
  (&lt;span class="hljs-name"&gt;write-netstring&lt;/span&gt; &lt;span class="hljs-string"&gt;&amp;quot;{\&amp;quot;method\&amp;quot;:\&amp;quot;ping\&amp;quot;,\&amp;quot;params\&amp;quot;:[],\&amp;quot;id\&amp;quot;:1}&amp;quot;&lt;/span&gt; s)
  (&lt;span class="hljs-name"&gt;finish-output&lt;/span&gt; s)
  (&lt;span class="hljs-name"&gt;princ&lt;/span&gt; (&lt;span class="hljs-name"&gt;read-netstring&lt;/span&gt; s))
  (&lt;span class="hljs-name"&gt;close&lt;/span&gt; s))
&lt;span class="hljs-comment"&gt;; { &amp;quot;result&amp;quot;: &amp;quot;pong&amp;quot; }&lt;/span&gt;
&lt;span class="hljs-comment"&gt;; --&amp;gt; T&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Yay! This is Common Lisp talking to a &lt;a href="http://json-rpc.org/"&gt;JSON-RPC&lt;/a&gt; server written in C. This means that I have now the foundations for rewriting Poliqarp on top of JSON-RPC (according to the &lt;a href="http://blog.danieljanus.pl/poliqarp-new-protocol.html"&gt;protocol spec&lt;/a&gt; I have recently posted) up and running, and all that remains is to fill the remainder.&lt;/p&gt;&lt;p&gt;Well, to be honest, this is not exactly JSON-RPC. First off, as you might have noticed, the above snippet of code sends JSON-RPC requests as &lt;a href="http://cr.yp.to/proto/netstrings.txt"&gt;netstrings&lt;/a&gt;. This is actually intentional, and the reasons for adopting this encoding have been described in detail in the spec (it basically boils down to the fact that it greatly simplifies reading from and writing to network, especially in C). I wrote some crude code to handle netstrings in CL — now it occurred to me that it might actually be worthwhile to polish it up a little, write some documentation and put on &lt;a href="http://www.cliki.net/"&gt;CLiki&lt;/a&gt; as an asdf-installable library. I’ll probably get on to this quite soon.&lt;/p&gt;&lt;p&gt;Second, the resulting JSON object does not have all the necessary stuff. It contains the result, but not the error or id (as mandated by the &lt;a href="http://json-rpc.org/wiki/specification"&gt;JSON-RPC spec&lt;/a&gt;). This is actually a deficiency of the &lt;a href="http://www.big-llc.com/software.jsp"&gt;JSON-RPC C library&lt;/a&gt; I’m currently using. It places the burden of constructing objects that are proper JSON-RPC responses on the programmer, instead of doing that itself. This will be easy to sort out, however, because the library is small and adheres to the &lt;a href="http://en.wikipedia.org/wiki/KISS_principle"&gt;KISS principle&lt;/a&gt;. More of a problem is that the licensing of that library is unclear; I emailed the maintainers to explain the status.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2008-04-16:post:poliqarp-new-protocol</id>
    <title>Poliqarp’s new protocol</title>
    <link href="http://blog.danieljanus.pl/poliqarp-new-protocol/"/>
    <updated>2008-04-16T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;The first version of the document I’ve been writing about &lt;a href="http://blog.danieljanus.pl/tex-hackery.html"&gt;a couple of days ago&lt;/a&gt; is now &lt;a href="http://bach.ipipan.waw.pl/~nathell/new-protocol.pdf"&gt;ready for public review&lt;/a&gt;. I’ll be making an initial attempt at the implementation once I return from the &lt;a href="http://weitz.de/eclm2008/"&gt;European Common Lisp Meeting ‘08&lt;/a&gt; and write a report.&lt;/p&gt;&lt;/div&gt;</content>
  </entry>
  <entry>
    <id>tag:blog.danieljanus.pl,2008-04-14:post:im-not-playing-this-stupid-game-anymore</id>
    <title>I’m not playing this stupid game anymore</title>
    <link href="http://blog.danieljanus.pl/im-not-playing-this-stupid-game-anymore/"/>
    <updated>2008-04-14T00:00:00Z</updated>
    <content type="html">&lt;div&gt;&lt;p&gt;Not until the next tournament, that is. My achievements in the 12th Scrabble Championship of Warsaw can be described as “mediocre” at best; four won, one drawn and seven lost games mean that my general rating will drop down by two points or so. Oh well. Everybody knows it’s a stupid game. ;-) At least I’ve managed to get a decent small score, with an average of 377 points per game.&lt;/p&gt;&lt;p&gt;Random resolutions for the indefinite future:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;&lt;p&gt;Get a final draft of the C++09 standard when it’s ready and acquaint myself with it as closely as possible. I strongly dislike C++ (and I’m not alone in this — see the &lt;a href="http://yosefk.com/c++fqa/"&gt;Frequently Questioned Answers&lt;/a&gt; about C++ for very detailed criticisms); however, I’ve long wanted to learn that language better just to know all the strengths and weaknesses of the enemy. The ideal moment for this will be when the new standard is out; this will give me the advantage of not having to unlearn the things changed by the standard, while staying on a cutting and competitive edge.&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;Get a copy of &lt;a href="http://en.wikipedia.org/wiki/Federico_Garc%C3%ADa_Lorca"&gt;Federico García Lorca&lt;/a&gt;’s poems translated into Polish by Jerzy Ficowski. I have only a very vague knowledge of Lorca (just his Romance of the Spanish Civil Guard (&lt;a href="http://www.poesia-inter.net/index214.htm"&gt;Romance de la Guardia Civil Española&lt;/a&gt;)), but I very much like what little I know.&lt;/p&gt;&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;</content>
  </entry>
</feed>
