
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
    <channel>
        <title>Unqualified</title>
        <description>A litany of cogitations on code and other things.</description>
        <link>https://blog.flowthing.me</link>
        <lastBuildDate>2026-11-02</lastBuildDate>
        <language>en-us</language>
        
        <item>
            <pubDate>2024-02-20</pubDate>
            <title>The anatomy of a REPL</title>
            <description>What sets Lisp REPLs apart from the interactive shells many other languages have?</description>
            <link>https://blog.flowthing.me/repl</link>
            <content:encoded><![CDATA[
<blockquote>
<p>One of the most appealing features of Lisp is that it is interactive, as contrasted with most other higher-level languages, which are noninteractive.</p>
<p>—Douglas Hofstadter, “Lisp: Atoms and Lists” (1983)</p>
</blockquote>
<blockquote>
<p>It is common to conflate any interactive language prompt with a REPL, but I think it is an important aspect of Lisp REPLs that they are a composition of  read-eval-print.</p>
<p>—Rich Hickey, “A History of Clojure” (2020)</p>
</blockquote>
<pre><code><svg xmlns="http://www.w3.org/2000/svg" width="568" height="176" class="svgbob"><style>.svgbob line, .svgbob path, .svgbob circle, .svgbob rect, .svgbob polygon {
  stroke: black;
  stroke-width: 2;
  stroke-opacity: 1;
  fill-opacity: 1;
  stroke-linecap: round;
  stroke-linejoin: miter;
}

.svgbob text {
  white-space: pre;
  fill: black;
  font-family: Iosevka Fixed, monospace;
  font-size: 14px;
}

.svgbob rect.backdrop {
  stroke: none;
  fill: white;
}

.svgbob .broken {
  stroke-dasharray: 8;
}

.svgbob .filled {
  fill: black;
}

.svgbob .bg_filled {
  fill: white;
  stroke-width: 1;
}

.svgbob .nofill {
  fill: white;
}

.svgbob .end_marked_arrow {
  marker-end: url(#arrow);
}

.svgbob .start_marked_arrow {
  marker-start: url(#arrow);
}

.svgbob .end_marked_diamond {
  marker-end: url(#diamond);
}

.svgbob .start_marked_diamond {
  marker-start: url(#diamond);
}

.svgbob .end_marked_circle {
  marker-end: url(#circle);
}

.svgbob .start_marked_circle {
  marker-start: url(#circle);
}

.svgbob .end_marked_open_circle {
  marker-end: url(#open_circle);
}

.svgbob .start_marked_open_circle {
  marker-start: url(#open_circle);
}

.svgbob .end_marked_big_open_circle {
  marker-end: url(#big_open_circle);
}

.svgbob .start_marked_big_open_circle {
  marker-start: url(#big_open_circle);
}

</style><defs><marker id="arrow" viewBox="-2 -2 8 8" refX="4" refY="2" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><polygon points="0,0 0,4 4,2 0,0"></polygon></marker><marker id="diamond" viewBox="-2 -2 8 8" refX="4" refY="2" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><polygon points="0,2 2,0 4,2 2,4 0,2"></polygon></marker><marker id="circle" viewBox="0 0 8 8" refX="4" refY="4" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><circle cx="4" cy="4" r="2" class="filled"></circle></marker><marker id="open_circle" viewBox="0 0 8 8" refX="4" refY="4" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><circle cx="4" cy="4" r="2" class="bg_filled"></circle></marker><marker id="big_open_circle" viewBox="0 0 8 8" refX="4" refY="4" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><circle cx="4" cy="4" r="3" class="bg_filled"></circle></marker></defs><rect class="backdrop" x="0" y="0" width="568" height="176"></rect><rect x="508" y="88" width="32" height="32" class="solid nofill" rx="4"></rect><text x="522" y="108" >L</text><rect x="508" y="8" width="48" height="32" class="solid nofill" rx="0"></rect><text x="522" y="28" >OUT</text><rect x="388" y="88" width="32" height="32" class="solid nofill" rx="4"></rect><text x="402" y="108" >P</text><rect x="116" y="88" width="32" height="32" class="solid nofill" rx="4"></rect><text x="130" y="108" >R</text><rect x="252" y="88" width="32" height="32" class="solid nofill" rx="4"></rect><text x="266" y="108" >E</text><text x="34" y="28" >chars</text><text x="130" y="28" >IN</text><polygon points="8,68 16,68 12,80" class="filled"></polygon><line x1="12" y1="80" x2="12" y2="104" class="solid end_marked_circle"></line><line x1="12" y1="104" x2="32" y2="104" class="solid"></line><text x="34" y="108" >chars</text><polygon points="272,148 264,152 272,156" class="filled"></polygon><text x="426" y="28" >chars</text><line x1="472" y1="24" x2="488" y2="24" class="solid"></line><polygon points="488,20 496,24 488,28" class="filled"></polygon><line x1="80" y1="104" x2="96" y2="104" class="solid"></line><polygon points="96,100 104,104 96,108" class="filled"></polygon><line x1="160" y1="104" x2="176" y2="104" class="solid"></line><text x="178" y="108" >data</text><line x1="216" y1="104" x2="232" y2="104" class="solid"></line><polygon points="232,100 240,104 232,108" class="filled"></polygon><line x1="296" y1="104" x2="312" y2="104" class="solid"></line><text x="314" y="108" >data</text><line x1="352" y1="104" x2="368" y2="104" class="solid"></line><polygon points="368,100 376,104 368,108" class="filled"></polygon><line x1="432" y1="104" x2="488" y2="104" class="solid"></line><polygon points="488,100 496,104 488,108" class="filled"></polygon><g><line x1="116" y1="8" x2="156" y2="8" class="solid"></line><line x1="116" y1="8" x2="116" y2="40" class="solid"></line><line x1="156" y1="8" x2="156" y2="40" class="solid"></line><line x1="72" y1="24" x2="116" y2="24" class="solid"></line><line x1="116" y1="40" x2="156" y2="40" class="solid"></line></g><g><path d="M 16,24 A 4,4 0,0,0 12,28" class="nofill"></path><line x1="12" y1="28" x2="12" y2="68" class="solid"></line><line x1="16" y1="24" x2="32" y2="24" class="solid"></line></g><g><line x1="12" y1="108" x2="12" y2="148" class="solid"></line><path d="M 12,148 A 4,4 0,0,0 16,152" class="nofill"></path><line x1="16" y1="152" x2="264" y2="152" class="solid"></line></g><g><line x1="524" y1="128" x2="524" y2="148" class="solid"></line><line x1="272" y1="152" x2="520" y2="152" class="solid"></line><path d="M 524,148 A 4,4 0,0,1 520,152" class="nofill"></path></g><g><path d="M 408,24 A 4,4 0,0,0 404,28" class="nofill"></path><line x1="404" y1="28" x2="404" y2="80" class="solid"></line><line x1="408" y1="24" x2="424" y2="24" class="solid"></line></g></svg></code></pre>
<p>REPL is short for “read-eval-print loop”. Many programming languages <a href="https://docs.oracle.com/en/java/javase/20/jshell/introduction-jshell.html#GUID-630F27C8-1195-4989-9F6B-2C51D46F52C8">purport</a> to <a href="https://nodejs.org/api/repl.html#repl">have</a> <a href="https://www.jetbrains.com/help/idea/kotlin-repl.html#kotlin-repl">one</a>. Here’s a rough sketch of how what most of these languages call a REPL works:</p>
<ol>
<li><strong>Read</strong> a chunk of user input into memory.</li>
<li><strong>Evaluate</strong> the read input.</li>
<li><strong>Print</strong> a string representation of the evaluation result into the standard output.</li>
<li><strong>Loop</strong> back to the beginning.</li>
</ol>
<p>It is rare that you are able to (or, indeed, interested in) altering any of these steps. What would it even mean to swap out the “read” step of a Node.js or Kotlin REPL for something else?</p>
<p>In <a href="https://clojure.org">Clojure</a> (and other <a href="https://en.wikipedia.org/wiki/Lisp_(programming_language)">Lisps</a>), however, R, E, and P are discrete, exchangeable steps. You can, for example, make an R that rewrites parts of your code before handing it off to E. You can make an E that, every time you redefine a function, runs the tests for that function. Or, you can make a P that, instead of printing the evaluation result into <a href="https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#index-stdout">standard output</a>, puts it into a <a href="https://github.com/quoll/asami">database</a>, or sends it to the data visualization tool <a href="https://github.com/eerohele/tab">of</a> <a href="https://github.com/djblue/portal">your</a> <a href="https://clojure.org/news/2023/04/28/introducing-morse">choice</a>.</p>
<p>In this article, I will examine what sets a Lisp REPL apart from an interactive language shell and explore some of the opportunities having access to a REPL offers. I will use Clojure in all of the examples, because that’s the Lisp I’m most familiar with.</p>
<p>I will give examples of how and why you might customize each of R, E, and P. These examples are not complete, polished solutions, but I hope they suffice to inspire you to give the REPL a try and perhaps spur you to discover the possibilities of the REPL yourself. Finally, we’ll look at an alternative to a REPL: a Remote Procedure Call (RPC) server that knows how to evaluate code you send it. We’ll discuss how it differs from a REPL and why you might want to prefer it to a REPL.</p>
<p>To get started, let’s take a look at R: read.</p>
<h2><a href="#r-is-for-read" aria-hidden="true" class="anchor" id="r-is-for-read"></a>R is for read</h2>
<p>The R in REPL is often taken to mean “to read a line from standard (or other) input”. In Clojure and other Lisps, however, to “read” means to extract a <strong>form</strong> from a character stream. A form is <em>not</em> a string; it is <a href="https://www.expressionsofchange.org/dont-say-homoiconic">code represented as data</a>.</p>
<p>Here’s an example of a string:</p>
<pre><code><span class="source clojure"><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> String
</span><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>(inc 1)<span class="punctuation definition string end edn">&quot;</span></span></span>
</span></code></pre>
<p>In contrast, here’s an example of a form:</p>
<pre><code><span class="source clojure"><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Form
</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">inc</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span><span class="punctuation section parens end edn">)</span>
</span></span></code></pre>
<p>The form <code>(inc 1)</code> is a <a href="https://clojure.org/reference/data_structures">Clojure data structure</a> representing a piece of code. Specifically, it is an <a href="https://clojure.org/reference/data_structures#Lists">immutable list</a>. The first element of the list is a <a href="https://clojure.org/reference/reader#_symbols">symbol</a> naming the function <code>inc</code>. The second element of the list is the number <code>1</code>, an argument to that function.</p>
<p>Because the form is a data structure, you can manipulate it using the functions and macros in <a href="https://clojure.org/api/cheatsheet">the Clojure standard library</a>. For example, you can (if you really want to) change <code>inc</code> (increment) to <code>dec</code> (decrement):</p>
<pre><code><span class="source clojure"><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> rest returns everything but the first item of a sequence.
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span>
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> cons appends a new item to the front of a sequence.
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span>
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> The single quote tells Clojure not to evaluate (inc 1) before handing it off
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> to rest.
</span><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">cons</span></span></span></span> <span class="keyword operator macro clojure">&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn">dec</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">rest</span></span></span></span> <span class="keyword operator macro clojure">&#39;</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">inc</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">dec</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span><span class="punctuation section parens end edn">)</span>
</span></span></span></span></span></code></pre>
<p>(The ability to alter code before evaluation might bring the word <em>macro</em> to mind. Rightly so: having a distinct read step also powers Lisp <a href="https://aphyr.com/posts/305-clojure-from-the-ground-up-macros">macros</a>.)</p>
<p>The R in a standard Clojure REPL is a slightly modified version of <a href="https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/read"><code>read</code></a>, a function that reads forms from a character stream, one at a time. By default, that character stream <a href="https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/*in*">is</a> the <a href="https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#index-stdin">standard input</a>. Clojure allows you to plug in any <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/PushbackReader.html">compatible character stream</a>, though.</p>
<p>Here’s <code>read</code> hard at work, reading a form from a character stream:</p>
<pre><code><span class="source clojure"><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Turn a string into a stream of characters.
</span><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">def</span></span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name constant clojure">reader</span></span></span>
         <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">-&gt;</span></span></span></span> <span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>(+ 1 2 3)<span class="punctuation definition string end edn">&quot;</span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">java.io.StringReader.</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">java.io.PushbackReader.</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Read a form from the character stream.
</span><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">read</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">reader</span></span><span class="punctuation section parens end edn">)</span>
<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">+</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span><span class="punctuation section parens end edn">)</span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> a form, not a string
</span></span></span></span></span></span></code></pre>
<p>There is a downside to reading forms one at a time, however. If you type an incomplete form such as <code>(inc 1</code> (with a missing closing parenthesis) into a REPL, by default, Clojure does not throw a syntax error. Instead, it waits for additional input, expecting to encounter the closing parenthesis eventually.</p>
<p>Here’s where customizing the R of a REPL comes into play. To have Clojure throw an error when you type an S-expression with a missing closing parenthesis, you can make a REPL that reads forms in a line-oriented fashion, rather than form-oriented. Here’s one way to do it:</p>
<pre><code><span class="source clojure"><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure"><span class="meta namespace clojure">clojure.main</span><span class="punctuation accessor clojure">/</span>repl</span></span></span></span>
         <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>read</span></span>
         <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">_</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">_</span></span><span class="punctuation section brackets end edn">]</span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">read-string</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">read-line</span></span></span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
<span class="text plain repl">⁣user=&gt;⁣</span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">inc</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span>
<span class="tutkain repl stderr">⁣⁣Execution error at user/eval1$fn (REPL:3).
EOF while reading⁣⁣</span>
</span></span></span></span></span></span></code></pre>
<p>Here, when Clojure sees the incomplete form <code>(inc 1</code>, it throws an error instead of waiting for more input.</p>
<p>The ability to <code>read</code> code in this manner is only available to languages that <a href="https://www.expressionsofchange.org/dont-say-homoiconic">use the same data structures for both code and data</a>. Languages such as Java or Node.js do not support “reading” in the sense Lisps do. If they did, if you typed <code>1 + 2 + 3</code> into a Node.js interpreter, Node.js would turn the string <code>1 + 2 + 3</code> into <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">a JavaScript array</a> of items. You could then manipulate that array using the array manipulation methods built into JavaScript. Only then would it hand the code off for evaluation (E).</p>
<p>Now that we know how R works and looked at a couple of different ways to customize it, let’s move on to E for evaluate.</p>
<h2><a href="#e-is-for-evaluate" aria-hidden="true" class="anchor" id="e-is-for-evaluate"></a>E is for evaluate</h2>
<p>The E in REPL accepts data. Specifically, it accepts <a href="#r-is-for-read">forms R gives it</a>. In most other languages, E accepts a string, and evaluates the code in that string. In Clojure, evaluating a string yields the string itself. Here’s an example:</p>
<pre><code><span class="source clojure"><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Evaluating a string.
</span><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">eval</span></span></span></span> <span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>(inc 1)<span class="punctuation definition string end edn">&quot;</span></span></span><span class="punctuation section parens end edn">)</span>
<span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>(inc 1)<span class="punctuation definition string end edn">&quot;</span></span></span>

<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Evaluating a form.
</span><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">eval</span></span></span></span> <span class="keyword operator macro clojure">&#39;</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">inc</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
<span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span>
</span></span></span></span></code></pre>
<p>E returns its result as data. It does <em>not</em> return a string representation of the evaluation result. This has three consequences:</p>
<ol>
<li>You can manipulate the <strong>input</strong> of E.</li>
<li>You can manipulate the <strong>output</strong> of E.</li>
<li>E gives P <strong>data</strong>, not a string.</li>
</ol>
<p>Because E both accepts and yields data, we can, for example, make a REPL that, every time you redefine a function, runs the tests for that function. To do that, let’s first write a function with a test:</p>
<pre><code><span class="source clojure"><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration function clojure">defn</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name function clojure">square</span></span></span>
         <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Using :test metadata like this is not a common way of writing
</span>         <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Clojure tests. I use it here because it makes for a self-
</span>         <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> contained and colocated example.
</span>         <span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>test</span></span></span> <span class="meta mapping value edn"><span class="keyword operator macro clojure">#</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">assert</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">=</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">4</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">square</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="invalid illegal stray-bracket-end edn">}</span>
         <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">x</span></span><span class="punctuation section brackets end edn">]</span></span>
         <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> The extra x here is an intentional bug to make the test fail.
</span>         <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">*</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">x</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">x</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">x</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
<span class="keyword operator macro clojure">#&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn"><span class="meta namespace edn">user</span><span class="punctuation accessor edn">/</span>square</span></span>
</span></span></span></span></span></span></span></span></code></pre>
<p>To <a href="https://knowyourmeme.com/memes/xzibit-yo-dawg">test the test</a>, we can use <a href="https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/test"><code>clojure.core/test</code></a>:</p>
<pre><code><span class="source clojure"><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">test</span></span></span></span> <span class="keyword operator macro clojure">#&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn">square</span></span><span class="punctuation section parens end edn">)</span>
<span class="tutkain repl stderr">⁣⁣Execution error (AssertionError) at user/fn (NO_SOURCE_FILE:5).
Assert failed: (= 4 (square 2))⁣⁣</span>
</span></span></code></pre>
<p>Works great. Now that we have a function and a test, let’s make a REPL:</p>
<pre><code><span class="source clojure"><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;⁣</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure"><span class="meta namespace clojure">clojure.main</span><span class="punctuation accessor clojure">/</span>repl</span></span></span></span>
         <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Suppress the user=&gt; prompt for this demo.
</span>         <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>prompt</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">constantly</span></span></span></span> <span class="meta reader-form edn"><span class="constant language edn">nil</span></span><span class="punctuation section parens end edn">)</span>

         <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>eval</span></span>
         <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">form</span></span><span class="punctuation section brackets end edn">]</span></span></span>
           <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Evaluate the form as per usual.
</span>           <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">let</span></span></span></span> <span class="meta binding-vector clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">ret</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">eval</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">form</span></span><span class="punctuation section parens end edn">)</span><span class="invalid illegal stray-bracket-end edn">]</span>
             <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> After evaluation, walk through every form nested inside the
</span>             <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> top-level form given to eval (usually, a list).
</span>             <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure"><span class="meta namespace clojure">clojure.walk</span><span class="punctuation accessor clojure">/</span>prewalk</span></span></span></span>
               <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">sub-form</span></span><span class="punctuation section brackets end edn">]</span></span></span>
                 <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> If the first element of a form is defn...
</span>                 <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword control conditional if clojure">if</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">and</span></span></span></span>
                       <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">list?</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">sub-form</span></span><span class="punctuation section parens end edn">)</span>
                       <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">=</span></span></span></span> <span class="keyword operator macro clojure">#&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn"><span class="meta namespace edn">clojure.core</span><span class="punctuation accessor edn">/</span>defn</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">-&gt;</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">sub-form</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">first</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">resolve</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
                   <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">let</span></span></span></span> <span class="meta binding-vector clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">v</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">-&gt;</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">sub-form</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">second</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">resolve</span></span><span class="punctuation section parens end edn">)</span><span class="invalid illegal stray-bracket-end edn">]</span>
                     <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> If the defn has a :test metadata entry...
</span>                     <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">when</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">-&gt;</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">v</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">meta</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>test</span></span><span class="punctuation section parens end edn">)</span>
                       <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Run the tests defined in that metadata entry.
</span>                       <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">test</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">v</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
               <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">form</span></span></span></span><span class="punctuation section parens end edn">)</span>
             <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Return the return value of the evaluation.
</span>             <span class="meta reader-form edn"><span class="meta symbol edn">ret</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre>
<p>Once you run this REPL, every time you evaluate a form that defines a function (such as <code>(defn square ...)</code>, your REPL will re-run the test defined under the <code>:test</code> <a href="https://clojure.org/reference/metadata">metadata</a> key (if any). For example, if you re-evaluate the same exact <code>(defn square ...)</code> form from above again, you get:</p>
<pre><code><span class="source clojure"><span class="tutkain repl stderr">⁣⁣Execution error (AssertionError) at user/fn (NO_SOURCE_FILE:5).
Assert failed: (= 4 (square 2))⁣⁣</span><span class="text plain repl">⁣
</span></span></code></pre>
<p>You’re getting a test watcher and auto-runner for pretty cheap there. And you don’t have to wait for someone to implement this feature in your programming environment, either.</p>
<p>Another useful way to customize E is to make every evaluation use a certain set of dynamic bindings. Clojure has a small number of thread-local bindings that you can use to configure <a href="#r-is-for-read">reading</a>, <a href="#e-is-for-evaluate">evaluation</a>, <a href="#p-is-for-print">printing</a>, and performance-related warnings.</p>
<p>For example, if the Clojure code you’re writing uses <a href="https://clojure.org/reference/java_interop">Java interoperability</a>, you almost certainly want to see warnings when Clojure has to resort to reflection to figure out which method overload to call. One way to do that is to add <code>(set! *warn-on-reflection true)</code> into your Clojure namespace (and you should always do that anyway when doing Java interop). Sometimes you might forget, though. To combat your forgetful nature, you can make an E that sets <code>*warn-on-reflection*</code> to <code>true</code> for every evaluation:</p>
<pre><code><span class="source clojure"><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure"><span class="meta namespace clojure">clojure.main</span><span class="punctuation accessor clojure">/</span>repl</span></span></span></span>
         <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>eval</span></span>
         <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">form</span></span><span class="punctuation section brackets end edn">]</span></span></span>
           <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">binding</span></span></span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">*warn-on-reflection*</span></span> <span class="meta reader-form edn"><span class="constant language edn">true</span></span><span class="punctuation section brackets end edn">]</span></span>
             <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Evaluate the form as per usual.
</span>             <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">let</span></span></span></span> <span class="meta binding-vector clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">ret</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">eval</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">form</span></span><span class="punctuation section parens end edn">)</span><span class="invalid illegal stray-bracket-end edn">]</span>
               <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Some REPL implementations don&#39;t auto-flush after writing to
</span>               <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> the error stream. We&#39;ll therefore flush manually after
</span>               <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> evaluation to make sure any possible reflection warnings
</span>               <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> become visible.
</span>               <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">flush</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">*err*</span></span><span class="punctuation section parens end edn">)</span>
               <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Return the evaluation result.
</span>               <span class="meta reader-form edn"><span class="meta symbol edn">ret</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Define a function without specifying a type hint.
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span>
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> This forces Clojure to use reflection on the function argument to figure
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> out which .toUpperCase to call.
</span><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration function clojure">defn</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name function clojure">upper-case</span></span></span>
         <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">s</span></span><span class="punctuation section brackets end edn">]</span></span></span>
         <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">.toUpperCase</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">s</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
<span class="tutkain repl stderr">⁣⁣Reflection warning my.clj:3:3 - reference to field toUpperCase can&#39;t be resolved.⁣⁣</span>
<span class="keyword operator macro clojure">#&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn"><span class="meta namespace edn">user</span><span class="punctuation accessor edn">/</span>upper-case</span></span>
</span></span></span></span></span></span></span></span></span></span></code></pre>
<p>Success!</p>
<p>Now that we’ve seen how you can customize E to make your evaluations extra powerful, let’s move on to take a brief look at P is for print.</p>
<h2><a href="#p-is-for-print" aria-hidden="true" class="anchor" id="p-is-for-print"></a>P is for print</h2>
<p>The P in REPL accepts the evaluation result as data and, by default, prints it into the standard output stream. P does <em>not</em> accept a string representation of the evaluation result. P might <em>print</em> a string representation of the evaluation result.</p>
<p>Perhaps the most obvious interesting thing to do with P is to send the result to a tool that can represent the evaluation result in a format more digestible than a string representation. For example, say you want to see the superclasses, fields, and methods of a Java class. Naturally, you’ll reach for <a href="https://clojure.github.io/clojure/clojure.reflect-api.html#clojure.reflect/reflect"><code>clojure.reflect/reflect</code></a>. To your dismay, however, you see that the string representation of the data structure it yields is too large to be digestible either inline in your editor or in a separate output panel:</p>
<pre><code><span class="source clojure"><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Only print the first three items of each collection.
</span><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword other clojure">set!</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">*print-length*</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span><span class="punctuation section parens end edn">)</span>
<span class="constant language edn">nil</span>
<span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">pprint</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure"><span class="meta namespace clojure">clojure.reflect</span><span class="punctuation accessor clojure">/</span>reflect</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">java.time.Clock</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
<span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>bases</span></span></span> <span class="meta mapping value edn"><span class="meta sexp set edn"><span class="keyword operator macro edn">#</span><span class="punctuation section braces begin edn">{</span><span class="meta reader-form edn"><span class="meta symbol edn">java.lang.Object</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">java.time.InstantSource</span></span><span class="punctuation section braces end edn">}</span></span></span>
 <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>flags</span></span></span> <span class="meta mapping value edn"><span class="meta sexp set edn"><span class="keyword operator macro edn">#</span><span class="punctuation section braces begin edn">{</span><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>public</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>abstract</span></span><span class="punctuation section braces end edn">}</span></span></span>
 <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>members</span></span></span>
 <span class="meta mapping value edn"><span class="meta sexp set edn"><span class="keyword operator macro edn">#</span><span class="punctuation section braces begin edn">{</span><span class="meta tagged-element edn"><span class="meta tagged-element tag edn"><span class="keyword operator macro edn">#clojure.reflect.Method</span></span><span class="meta tagged-element element edn"><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>name</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="meta symbol edn">system</span></span></span>
                           <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>return-type</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="meta symbol edn">java.time.Clock</span></span></span>
                           <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>declaring-class</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="meta symbol edn">java.time.Clock</span></span></span>
                           <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="meta symbol edn">...</span></span></span><span class="punctuation section braces end edn">}</span></span></span>
</span>   <span class="meta tagged-element edn"><span class="meta tagged-element tag edn"><span class="keyword operator macro edn">#clojure.reflect.Method</span></span><span class="meta tagged-element element edn"><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>name</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="meta symbol edn">withZone</span></span></span>
                           <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>return-type</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="meta symbol edn">java.time.Clock</span></span></span>
                           <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>declaring-class</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="meta symbol edn">java.time.Clock</span></span></span>
                           <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="meta symbol edn">...</span></span></span><span class="punctuation section braces end edn">}</span></span></span>
</span>   <span class="meta tagged-element edn"><span class="meta tagged-element tag edn"><span class="keyword operator macro edn">#clojure.reflect.Method</span></span><span class="meta tagged-element element edn"><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>name</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="meta symbol edn">tickMillis</span></span></span>
                           <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>return-type</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="meta symbol edn">java.time.Clock</span></span></span>
                           <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>declaring-class</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="meta symbol edn">java.time.Clock</span></span></span>
                           <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="meta symbol edn">...</span></span></span><span class="punctuation section braces end edn">}</span></span></span>
</span>   <span class="meta reader-form edn"><span class="meta symbol edn">...</span></span><span class="punctuation section braces end edn">}</span></span></span><span class="punctuation section braces end edn">}</span></span>
<span class="meta reader-form edn"><span class="constant language edn">nil</span></span>
</span></span></span></span></code></pre>
<p>Luckily, the Clojure ecosystem has a <a href="https://clerk.vision">wealth</a> <a href="https://docs.cider.mx/cider/debugging/inspector.html">of</a> <a href="https://github.com/vlaaad/reveal">tools</a> that know how to visualize Clojure data structures. We can use one of those tools to make a REPL whose P sends the evaluation result it receives from E to such a data visualizer.</p>
<p>For this article, we’ll use <a href="https://github.com/eerohele/tab">Tab</a> (the decidedly least impressive such tool) to turn the big <a href="https://clojure.org/reference/data_structures#Maps">hash map</a> <code>clojure.reflect/reflect</code> returns into a bunch of tables:</p>
<pre><code><span class="source clojure"><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> If using Clojure 1.12 or newer, add a dependency into the Clojure runtime.
</span><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure"><span class="meta namespace clojure">clojure.repl.deps</span><span class="punctuation accessor clojure">/</span>add-lib</span></span></span></span> <span class="keyword operator macro clojure">&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn"><span class="meta namespace edn">io.github.eerohele</span><span class="punctuation accessor edn">/</span>tab</span></span><span class="punctuation section parens end edn">)</span>
<span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn"><span class="meta namespace edn">io.github.eerohele</span><span class="punctuation accessor edn">/</span>tab</span></span><span class="punctuation section brackets end edn">]</span></span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Require Tab.
</span><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">require</span></span></span></span> <span class="keyword operator macro clojure">&#39;</span><span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">tab.api</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>as</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">tab</span></span><span class="punctuation section brackets end edn">]</span></span><span class="punctuation section parens end edn">)</span>
<span class="constant language edn">nil</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Run Tab.
</span><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">def</span></span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name constant clojure">tab</span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure"><span class="meta namespace clojure">tab</span><span class="punctuation accessor clojure">/</span>run</span></span></span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
<span class="keyword operator macro clojure">#&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn"><span class="meta namespace edn">user</span><span class="punctuation accessor edn">/</span>tab</span></span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Run a REPL that, instead of printing every evaluation result into stdout,
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> sends them to Tab, a tool for visualizing Clojure data as tables.
</span><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure"><span class="meta namespace clojure">clojure.main</span><span class="punctuation accessor clojure">/</span>repl</span></span></span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>print</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">value</span></span><span class="punctuation section brackets end edn">]</span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure"><span class="meta namespace clojure">tab</span><span class="punctuation accessor clojure">/</span>tab&gt;</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">tab</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">value</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Reflect on the nature of a Java class, the Clojure way.
</span><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">require</span></span></span></span> <span class="keyword operator macro clojure">&#39;</span><span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">clojure.reflect</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>as</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">reflect</span></span><span class="punctuation section brackets end edn">]</span></span><span class="punctuation section parens end edn">)</span>
<span class="constant language edn">nil</span>
<span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure"><span class="meta namespace clojure">reflect</span><span class="punctuation accessor clojure">/</span>reflect</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">java.time.Clock</span></span><span class="punctuation section parens end edn">)</span>
</span></span></span></span></span></span></span></span></span></span></code></pre>
<p>Here’s a screenshot of Tab visualizing the output of <code>clojure.reflect/reflect</code>:</p>
<img src="tab.webp" alt="A screenshot of Tab, a tool for visualizing Clojure data as tables."/>
<p>(You probably can’t tell from the screenshot, but the tables Tab makes are mildly interactive: you can expand, collapse, and zoom in on nested tables.)</p>
<p>Whether that is more or less digestible than a pretty-printed, textual representation is a matter of taste, of course. The point is that unlike the interactive shells of many other languages, a REPL affords you the complete liberty to decide how to represent your evaluation results.</p>
<h2><a href="#putting-it-all-together" aria-hidden="true" class="anchor" id="putting-it-all-together"></a>Putting it all together</h2>
<p>To see how to customize each of R, E, and P at once, let’s turn a Clojure REPL into a Java shell.</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">let</span></span></span></span> <span class="meta binding-vector clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">jshell</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure"><span class="meta namespace clojure">jdk.jshell.JShell</span><span class="punctuation accessor clojure">/</span>create</span></span></span></span><span class="punctuation section parens end edn">)</span>
      <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">eval-counter</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">atom</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">0</span></span><span class="punctuation section parens end edn">)</span><span class="invalid illegal stray-bracket-end edn">]</span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure"><span class="meta namespace clojure">clojure.main</span><span class="punctuation accessor clojure">/</span>repl</span></span></span></span>
    <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>init</span></span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">reset!</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">eval-counter</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">0</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

    <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>prompt</span></span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span></span>
      <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">println</span></span></span></span><span class="punctuation section parens end edn">)</span>
      <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">print</span></span></span></span> <span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>jshell&gt; <span class="punctuation definition string end edn">&quot;</span></span></span><span class="punctuation section parens end edn">)</span>
      <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">flush</span></span></span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

    <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>read</span></span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">_</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">request-exit</span></span><span class="punctuation section brackets end edn">]</span></span></span>
      <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">let</span></span></span></span> <span class="meta binding-vector clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">input</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">read-line</span></span></span></span><span class="punctuation section parens end edn">)</span><span class="invalid illegal stray-bracket-end edn">]</span>
        <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Ctrl+D to exit
</span>        <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword control conditional if clojure">if</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">nil?</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">input</span></span><span class="punctuation section parens end edn">)</span>
          <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">request-exit</span></span></span></span>
          <span class="meta reader-form edn"><span class="meta symbol edn">input</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

    <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>eval</span></span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">string</span></span><span class="punctuation section brackets end edn">]</span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">.eval</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">jshell</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">string</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

    <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>print</span></span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">events</span></span><span class="punctuation section brackets end edn">]</span></span></span>
      <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">run!</span></span></span></span>
        <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">event</span></span><span class="punctuation section brackets end edn">]</span></span></span>
          <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">println</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">str</span></span></span></span> <span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>$<span class="punctuation definition string end edn">&quot;</span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">swap!</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">eval-counter</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">inc</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span> <span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>==&gt;<span class="punctuation definition string end edn">&quot;</span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">.value</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">event</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
        <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">events</span></span></span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre>
<p>Running this code lets you bask in the exactitude and pith of the Java language from the comfort of your Clojure REPL, like so:</p>
<pre><code><span class="source java">jshell<span class="keyword operator comparison java">&gt;</span> <span class="meta import java"><span class="keyword other import java">import</span> <span class="support class import java">java.util.stream<span class="punctuation accessor dot java">.</span>Collectors</span><span class="punctuation terminator java">;</span></span>
$<span class="constant numeric integer decimal java">1</span> <span class="keyword operator comparison java">==</span><span class="keyword operator comparison java">&gt;</span> nil
jshell<span class="keyword operator comparison java">&gt;</span> <span class="meta import java"><span class="keyword other import java">import</span> <span class="support class import java">java.util.stream<span class="punctuation accessor dot java">.</span>Stream</span><span class="punctuation terminator java">;</span></span>
$<span class="constant numeric integer decimal java">2</span> <span class="keyword operator comparison java">==</span><span class="keyword operator comparison java">&gt;</span> nil
jshell<span class="keyword operator comparison java">&gt;</span> var stream <span class="meta assignment rhs java"><span class="keyword operator assignment java">=</span> <span class="support class java">Stream</span><span class="punctuation accessor dot java">.</span><span class="meta function-call java"><span class="variable function java">of</span><span class="punctuation section parens begin java">(</span><span class="string quoted double java"><span class="punctuation definition string begin java">&quot;</span>a<span class="punctuation definition string end java">&quot;</span></span><span class="punctuation separator java">,</span> <span class="string quoted double java"><span class="punctuation definition string begin java">&quot;</span>b<span class="punctuation definition string end java">&quot;</span></span><span class="punctuation separator java">,</span> <span class="string quoted double java"><span class="punctuation definition string begin java">&quot;</span>c<span class="punctuation definition string end java">&quot;</span></span><span class="punctuation section parens end java">)</span></span></span><span class="punctuation terminator java">;</span>
$<span class="constant numeric integer decimal java">3</span> <span class="keyword operator comparison java">==</span><span class="keyword operator comparison java">&gt;</span> <span class="support class java">java.util.stream<span class="punctuation accessor dot java">.</span>ReferencePipeline$Head</span>@64bfbc86
jshell<span class="keyword operator comparison java">&gt;</span> stream<span class="punctuation accessor dot java">.</span><span class="meta function-call java"><span class="variable function java">filter</span><span class="punctuation section parens begin java">(</span><span class="meta function anonymous parameters java"><span class="variable parameter java">s</span></span> <span class="meta function anonymous body java"><span class="storage type function anonymous java">-&gt;</span> s<span class="punctuation accessor dot java">.</span><span class="meta function-call java"><span class="variable function java">contains</span><span class="punctuation section parens begin java">(</span><span class="string quoted double java"><span class="punctuation definition string begin java">&quot;</span>b<span class="punctuation definition string end java">&quot;</span></span><span class="punctuation section parens end java">)</span></span></span><span class="punctuation section parens end java">)</span></span><span class="punctuation accessor dot java">.</span><span class="meta function-call java"><span class="variable function java">collect</span><span class="punctuation section parens begin java">(</span><span class="support class java">Collectors</span><span class="punctuation accessor dot java">.</span><span class="meta function-call java"><span class="variable function java">toList</span><span class="punctuation section parens begin java">(</span><span class="punctuation section parens end java">)</span></span><span class="punctuation section parens end java">)</span></span><span class="punctuation terminator java">;</span>
$<span class="constant numeric integer decimal java">4</span> <span class="keyword operator comparison java">==</span><span class="keyword operator comparison java">&gt;</span> [b]
</span></code></pre>
<p>It’s not that turning a Clojure REPL into a Java shell is necessarily particularly useful. It’s that <em>it is possible in the first place</em>. Since reading, evaluation, and printing are not discrete steps in JShell and its ilk, it is not possible to turn JShell into a Clojure REPL. This is what makes JShell a shell and the Clojure REPL a REPL.</p>
<h2><a href="#an-alternative" aria-hidden="true" class="anchor" id="an-alternative"></a>An alternative</h2>
<p>A useful alternative to a REPL is a program that, instead of accepting unadorned Lisp forms, accepts messages wrapped in an envelope such as this:</p>
<pre><code><span class="source clojure"><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>op</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>eval</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>code</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>(inc 1)<span class="punctuation definition string end edn">&quot;</span></span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>ns</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>user<span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span>
</span></code></pre>
<p>If you’re familiar with <a href="https://nrepl.org/">nREPL</a>, this <a href="https://nrepl.org/nrepl/1.1/design/overview.html#requests">message format</a> might look familiar to you. There are a number of benefits to using a protocol like this. For one, wrapping your code in an envelope like this allows you to bundle additional context with the code, such as the <a href="https://clojure.org/reference/namespaces">namespace</a> in whose context to evaluate the code. It also allows the client to match requests with responses. This in turn makes it straightforward to, for example, display evaluation results inline in the client, next to the code you’re evaluating.</p>
<p>Additionally, an RPC-style protocol like this is amenable to extension. Besides code evaluation, you can add support for operations such as trafficking editor auto-completion information between the client and the server. In contrast, the only operation a REPL supports is evaluation. To support other operations, the client and the server would need <a href="https://groups.google.com/g/clojure-dev/c/Dl3Stw5iRVA/m/IHoVWiJz5UIJ">an auxiliary communication channel</a>. That decision, while <a href="https://github.com/eerohele/Tutkain/blob/8004698c9895ad0d774fccbfdf4d7f185e4fef00/clojure/src/tutkain/rpc.cljc#L197-L262">viable</a>, comes with its own, significant set of tradeoffs.</p>
<p>All that said, let’s try our hand at making an RPC server of our own.</p>
<pre><code><span class="source clojure"><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> There&#39;s quite a lot of code in this sample. Feel free to skip it if you&#39;re
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> not particularly interested in a half-baked RPC server that knows how to
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> evaluate Clojure.
</span>
<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">ns</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">my.rpc</span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>require</span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">clojure.core</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>as</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">core</span></span><span class="punctuation section brackets end edn">]</span></span>
            <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">clojure.pprint</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>as</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">pprint</span></span><span class="punctuation section brackets end edn">]</span></span>
            <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">clojure.main</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>as</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">main</span></span><span class="punctuation section brackets end edn">]</span></span><span class="punctuation section parens end edn">)</span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>import</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">clojure.lang</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">LineNumberingPushbackReader</span></span><span class="punctuation section parens end edn">)</span>
           <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">java.io</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">StringReader</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> We&#39;ll define this function later.
</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration variable clojure">declare</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name function forward-decl clojure">handle</span></span></span><span class="punctuation section parens end edn">)</span>

<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Save a reference to the standard output for print operations.
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span>
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> *out* here could be anything you can write into: a file, s
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> socket, a null writer, etc.
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span>
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> We&#39;ll need this later.
</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">def</span></span></span></span> <span class="keyword operator macro clojure">^</span><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>dynamic</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant language edn">true</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>doc</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>Original standard output.<span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span>
  <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name constant clojure">*$out$*</span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">*out*</span></span><span class="punctuation section parens end edn">)</span>

<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration function clojure">defn</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name function clojure">read-string*</span></span></span>
  <span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>Like clojure.core/read-string, but retains line and column numbers.<span class="punctuation definition string end edn">&quot;</span></span></span>
  <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">s</span></span><span class="punctuation section brackets end edn">]</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">with-open</span></span></span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">reader</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">-&gt;</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">s</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">StringReader.</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">LineNumberingPushbackReader.</span></span><span class="punctuation section parens end edn">)</span><span class="invalid illegal stray-bracket-end edn">]</span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">read</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">reader</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Define the default R, E, and P for our RPC server.
</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">def</span></span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name constant clojure">default-options</span></span></span>
  <span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>read</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="meta symbol edn">read-string*</span></span></span>
   <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>eval</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="meta symbol edn">eval</span></span></span>
   <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Pretty-print evaluation results by default, because we can.
</span>   <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>print</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="meta symbol edn"><span class="meta namespace edn">pprint</span><span class="punctuation accessor edn">/</span>pprint</span></span></span>
   <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> As a bonus, allow users to specify a custom init function to e.g. load
</span>   <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> additional code upon startup.
</span>   <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>init</span></span></span> <span class="meta mapping value edn"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span></span>
           <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">require</span></span></span></span> <span class="keyword operator macro clojure">&#39;</span><span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">clojure.repl</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>refer</span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">doc</span></span><span class="punctuation section brackets end edn">]</span></span><span class="punctuation section brackets end edn">]</span></span><span class="punctuation section parens end edn">)</span>
           <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">require</span></span></span></span> <span class="keyword operator macro clojure">&#39;</span><span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">clojure.pprint</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>refer</span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">pp</span></span><span class="punctuation section brackets end edn">]</span></span><span class="punctuation section brackets end edn">]</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="invalid illegal stray-bracket-end edn">}</span><span class="punctuation section parens end edn">)</span>

<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Define a function that runs an RPC-style server.
</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration function clojure">defn</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name function clojure">rpc</span></span></span>
  <span class="meta sexp list edn"><span class="meta function-body clojure"><span class="punctuation section parens begin edn">(</span><span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">rpc</span></span></span></span> <span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="punctuation section braces end edn">}</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">options</span></span><span class="punctuation section brackets end edn">]</span></span>
   <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">let</span></span></span></span> <span class="meta binding-vector clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>keys</span></span></span> <span class="meta mapping value edn"><span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">init</span></span><span class="punctuation section brackets end edn">]</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>as</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="meta symbol edn">options</span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">merge</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">default-options</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">options</span></span><span class="punctuation section parens end edn">)</span><span class="invalid illegal stray-bracket-end edn">]</span>
     <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Call the user-supplied init function.
</span>     <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">init</span></span></span></span><span class="punctuation section parens end edn">)</span>

     <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword control loop clojure">loop</span></span></span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span>
       <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Read a message from the standard input for read operations.
</span>       <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">let</span></span></span></span> <span class="meta binding-vector clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>keys</span></span></span> <span class="meta mapping value edn"><span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">id</span></span><span class="punctuation section brackets end edn">]</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>as</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="meta symbol edn">message</span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">read</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">*in*</span></span><span class="punctuation section parens end edn">)</span>

             <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">recur?</span></span></span></span>
             <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Rebind standard output such that any print operations are
</span>             <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> wrapped in an envelope (i.e. {:tag :out :val &quot;Hello, world!&quot;})
</span>             <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">binding</span></span></span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">*out*</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">PrintWriter-on</span></span></span></span>
                                    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">x</span></span><span class="punctuation section brackets end edn">]</span></span></span>
                                      <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Print everything such that it can be
</span>                                      <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> read (via clojure.core/read).
</span>                                      <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">binding</span></span></span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">*print-readably*</span></span> <span class="meta reader-form edn"><span class="constant language edn">true</span></span><span class="punctuation section brackets end edn">]</span></span>
                                        <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Write into the standard output writer
</span>                                        <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> we saved a reference to earlier.
</span>                                        <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">.write</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">*$out$*</span></span>
                                          <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Give the response the ID of the
</span>                                          <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> request.
</span>                                          <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">pr-str</span></span></span></span> <span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="meta symbol edn">id</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>tag</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>out</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>val</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="meta symbol edn">x</span></span></span><span class="punctuation section braces end edn">}</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
                                        <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">.write</span></span></span></span> *$out$* &quot;\n&quot;)
                                        (<span class="meta reader-form edn"><span class="meta symbol edn">.flush</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">*$out$*</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
                                    <span class="constant language edn">nil</span><span class="punctuation section parens end edn">)</span><span class="invalid illegal stray-bracket-end edn">]</span>
               (<span class="meta reader-form edn"><span class="meta symbol edn">try</span></span>
                 <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Send :quit to exit the loop.
</span>                 (<span class="meta reader-form edn"><span class="meta symbol edn">when-not</span></span> (<span class="meta reader-form edn"><span class="meta symbol edn">identical?</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">message</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>quit</span></span><span class="punctuation section parens end edn">)</span>
                   (try
                     (<span class="meta reader-form edn"><span class="meta symbol edn">handle</span></span>
                       (<span class="meta reader-form edn"><span class="meta symbol edn">-&gt;</span></span>
                         (<span class="meta reader-form edn"><span class="meta symbol edn">merge</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">options</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">message</span></span><span class="punctuation section parens end edn">)</span>
                         <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Set the value of the :reply key to a function that
</span>                         <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> handlers can use to send a reply to the client.
</span>                         (<span class="meta reader-form edn"><span class="meta symbol edn">assoc</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>reply</span></span>
                           (<span class="meta reader-form edn"><span class="meta symbol edn">fn</span></span> [<span class="meta reader-form edn"><span class="meta symbol edn">response</span></span><span class="invalid illegal stray-bracket-end edn">]</span>
                             <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Rebind standard output and to the original standard
</span>                             <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> output.
</span>                             <span class="comment line edn"><span class="punctuation definition comment edn">;;</span>
</span>                             <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Without this, evaluation results would get
</span>                             <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> double-wrapped like this:
</span>                             <span class="comment line edn"><span class="punctuation definition comment edn">;;</span>
</span>                             <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> {:tag :out :val &quot;{:tag :ret :val \&quot;...\&quot;}&quot;}
</span>                             (<span class="meta reader-form edn"><span class="meta symbol edn">binding</span></span> [<span class="meta reader-form edn"><span class="meta symbol edn">*out*</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">*$out$*</span></span><span class="invalid illegal stray-bracket-end edn">]</span>
                               <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Print the response into the standard output.
</span>                               (<span class="meta reader-form edn"><span class="meta symbol edn">prn</span></span> (<span class="meta reader-form edn"><span class="meta symbol edn">merge</span></span> {<span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">id</span></span><span class="invalid illegal stray-bracket-end edn">}</span> <span class="meta reader-form edn"><span class="meta symbol edn">response</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
                     (catch Exception ex
                       (<span class="meta reader-form edn"><span class="meta symbol edn">set!</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">*e</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">ex</span></span><span class="punctuation section parens end edn">)</span>
                       (binding [*out* *$out$*]
                         (<span class="meta reader-form edn"><span class="meta symbol edn">prn</span></span> {<span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">id</span></span>
                               <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>tag</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>err</span></span>
                               <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>val</span></span> (<span class="meta reader-form edn"><span class="meta symbol edn">pr-str</span></span> (<span class="meta reader-form edn"><span class="meta symbol edn">Throwable-&gt;map</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">ex</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="invalid illegal stray-bracket-end edn">}</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
                   <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Return true to recur.
</span>                   <span class="meta reader-form edn"><span class="constant language edn">true</span></span><span class="punctuation section parens end edn">)</span>
                 (catch Exception _
                   <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> We&#39;ll ignore exception handling here and just exit the
</span>                   <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> loop if anything goes wrong.
</span>                   <span class="meta reader-form edn"><span class="constant language edn">false</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="invalid illegal stray-bracket-end edn">]</span>
         <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Only recur if no exceptions were thrown within the loop.
</span>         (<span class="meta reader-form edn"><span class="meta symbol edn">when</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">recur?</span></span> (<span class="meta reader-form edn"><span class="meta symbol edn">recur</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Define a multimethod for handling different kinds of messages to our RPC
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> server.
</span>(<span class="meta reader-form edn"><span class="meta symbol edn">defmulti</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">handle</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>op</span></span><span class="punctuation section parens end edn">)</span>

<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Define a handler for evaluation operations.
</span>(<span class="meta reader-form edn"><span class="meta symbol edn">defmethod</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">handle</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>eval</span></span>
  <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Use user-supplied (or default) R, E, and P.
</span>  [{<span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>keys</span></span> [<span class="meta reader-form edn"><span class="meta symbol edn">read</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">eval</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">print</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">reply</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">code</span></span><span class="invalid illegal stray-bracket-end edn">]</span><span class="invalid illegal stray-bracket-end edn">}</span><span class="invalid illegal stray-bracket-end edn">]</span>
  (<span class="meta reader-form edn"><span class="meta symbol edn">try</span></span>
    (<span class="meta reader-form edn"><span class="meta symbol edn">let</span></span> [<span class="meta reader-form edn"><span class="meta symbol edn">form</span></span> (<span class="meta reader-form edn"><span class="meta symbol edn">read</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">code</span></span><span class="punctuation section parens end edn">)</span>
          <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">ret</span></span></span></span> (eval form)]
      (<span class="meta reader-form edn"><span class="meta symbol edn">set!</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">*3</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">*2</span></span><span class="punctuation section parens end edn">)</span>
      (set! *2 *1)
      (<span class="meta reader-form edn"><span class="meta symbol edn">set!</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">*1</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">ret</span></span><span class="punctuation section parens end edn">)</span>
      (reply {:tag :ret :val (with-out-str (print ret))}))
    (<span class="meta reader-form edn"><span class="meta symbol edn">catch</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">RuntimeException</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">ex</span></span>
      (<span class="meta reader-form edn"><span class="meta symbol edn">reply</span></span> {<span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>tag</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>err</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>val</span></span> (<span class="meta reader-form edn"><span class="meta symbol edn">-&gt;</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">ex</span></span> <span class="meta reader-form edn"><span class="meta symbol edn"><span class="meta namespace edn">main</span><span class="punctuation accessor edn">/</span>ex-triage</span></span> <span class="meta reader-form edn"><span class="meta symbol edn"><span class="meta namespace edn">main</span><span class="punctuation accessor edn">/</span>ex-str</span></span><span class="punctuation section parens end edn">)</span><span class="invalid illegal stray-bracket-end edn">}</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Fallback if the client sends an :op we don&#39;t recognize.
</span>(<span class="meta reader-form edn"><span class="meta symbol edn">defmethod</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">handle</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>default</span></span>
  [{<span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>keys</span></span> [<span class="meta reader-form edn"><span class="meta symbol edn">op</span></span><span class="invalid illegal stray-bracket-end edn">]</span><span class="invalid illegal stray-bracket-end edn">}</span><span class="invalid illegal stray-bracket-end edn">]</span>
  (<span class="meta reader-form edn"><span class="meta symbol edn">throw</span></span> (<span class="meta reader-form edn"><span class="meta symbol edn">ex-info</span></span> &quot;<span class="meta reader-form edn"><span class="meta symbol edn">Not</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">implemented</span></span>&quot; {<span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>op</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">op</span></span><span class="invalid illegal stray-bracket-end edn">}</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre>
<p>All right! Let’s give it a try:</p>
<pre><code><span class="source clojure"><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">rpc</span></span></span></span><span class="punctuation section parens end edn">)</span>
<span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>op</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>eval</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>code</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>(inc 1)<span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Request
</span><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>tag</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>ret</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>val</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>2<span class="constant character escape edn"><span class="punctuation definition character escape begin edn">\</span>n</span><span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Response
</span></span></span></code></pre>
<p>Looks like it works! What about prints to standard output?</p>
<pre><code><span class="source clojure"><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>op</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>eval</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>code</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>(println :hello)<span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Request
</span><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>tag</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>out</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>val</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>:hello<span class="constant character escape edn"><span class="punctuation definition character escape begin edn">\</span>n</span><span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Print output
</span><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>tag</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>ret</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>val</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>nil<span class="constant character escape edn"><span class="punctuation definition character escape begin edn">\</span>n</span><span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Response
</span></span></code></pre>
<p>Just what we wanted: we can easily distinguish between prints (<code>:out</code>) and evaluation results (<code>:ret</code>) so that the client can handle them differently. Additionally, every request and response has an <code>:id</code> so that we can easily match responses with requests on the client.</p>
<p>All right, the basics seem to work fine. What if we try something wild, like running a new REPL?</p>
<pre><code><span class="source clojure"><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span></span>
 <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>op</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>eval</span></span></span>
 <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>code</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>(clojure.main/repl :read clojure.core.server/repl-read)<span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Request
</span><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>tag</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>out</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>val</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>user=&gt; <span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Print output
</span><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>tag</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>out</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>val</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>user=&gt; <span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Print output
</span></span></code></pre>
<p>Hmm. Not sure why the <code>user=&gt;</code> prompt got printed twice, but let’s just ignore that for now. Let’s try evaluating something:</p>
<pre><code><span class="source clojure"><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">5</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>op</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>eval</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>code</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>(inc 1)<span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Request
</span><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">4</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>tag</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>out</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>val</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>{:id 5, :op :eval, :code <span class="constant character escape edn"><span class="punctuation definition character escape begin edn">\</span>&quot;</span>(inc 1)<span class="constant character escape edn"><span class="punctuation definition character escape begin edn">\</span>&quot;</span>}<span class="constant character escape edn"><span class="punctuation definition character escape begin edn">\</span>n</span><span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Print output
</span><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">4</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>tag</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>out</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>val</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>user=&gt; <span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Print output
</span></span></code></pre>
<p>Oh, of course. Our RPC server expects envelopes (<code>{:id 1 :op :eval ...}</code>), but the REPL we ran within expects plain Clojure forms.</p>
<p>Let’s try giving it one of those:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">inc</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span><span class="punctuation section parens end edn">)</span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Request
</span><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">4</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>tag</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>out</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>val</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>2<span class="constant character escape edn"><span class="punctuation definition character escape begin edn">\</span>n</span><span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Print output
</span><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">4</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>tag</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>out</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>val</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>user=&gt; <span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Print output
</span></span></span></code></pre>
<p>It worked otherwise, but now we’re in a bit of a limbo: the input is not in an envelope, but the output is. Also, both evaluation results and prints have the <code>:out</code> tag.</p>
<p>Since we saved a reference to the original output stream, we can solve this problem. Let’s first quit the REPL we’re currently in:</p>
<pre><code><span class="source clojure"><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> clojure.core.server/repl-read is a function that quits the current REPL if
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> you send it :repl/quit, so let&#39;s do that.
</span><span class="meta reader-form edn"><span class="constant other keyword qualified edn"><span class="punctuation definition keyword edn">:</span><span class="meta namespace edn">repl</span><span class="punctuation accessor edn"><span class="punctuation definition constant namespace edn">/</span></span>quit</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Request
</span><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>tag</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>ret</span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>val</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>nil<span class="constant character escape edn"><span class="punctuation definition character escape begin edn">\</span>n</span><span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Response
</span></span></code></pre>
<p>Then, let’s run a new REPL that prints all output into the original output stream we saved a reference to (<code>*$out$*</code>):</p>
<pre><code><span class="source clojure"><span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>id</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">6</span></span></span>
 <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>op</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>eval</span></span></span>
 <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>code</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>(binding [*out* my.rpc/*$out$*] (clojure.main/repl))<span class="punctuation definition string end edn">&quot;</span></span></span></span><span class="punctuation section braces end edn">}</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Request
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Double prompt again for some reason. Likely need to pass :prompt or
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> :need-prompt to clojure.main/repl to fix.
</span><span class="meta reader-form edn"><span class="meta symbol edn">my.rpc=&gt;</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">my.rpc=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">inc</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span><span class="punctuation section parens end edn">)</span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Request
</span><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Print output
</span><span class="meta reader-form edn"><span class="meta symbol edn">my.rpc=&gt;</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;</span> Print output
</span></span></span></code></pre>
<p>Voilà! We finally managed to escape the confines of the RPC envelope.</p>
<p>It did take a bit of work, though, and we made some assumptions along the way. For example, we assumed that the client using our RPC server knows when to send and receive framed messages and when not. We also assumed that it is acceptable that the client must be aware of <code>my.rpc/*$out$*</code> to escape message framing. Furthermore, we assumed that the client can either parse <a href="https://github.com/edn-format/edn">EDN</a>, or that the client and the server can talk using some other <a href="https://nrepl.org/nrepl/1.1/design/transports.html#bencode-transport">shared language</a>.</p>
<p>While the RPC protocol has many benefits, it is slightly more complex than a REPL. The REPL is almost brutal in its simplicity: put code in, get results out. Upgrade to a different protocol if you want. Switching from RPC to REPL is possible, but it’s a bit more work than switching from REPL to RPC (or, indeed, switching from REPL to another type of REPL).</p>
<h2><a href="#closing-words" aria-hidden="true" class="anchor" id="closing-words"></a>Closing words</h2>
<p>We’ve looked at each of the main ingredients of the REPL: read, evaluate, and print. (There’s not much to say about loop: it just goes back to R.) We’ve seen how each of them works, what it means to customize them, and why you might want to do that. We’ve looked at what sets Lisp REPLs apart from the interactive shells in other languages. Finally, we implemented an alternative to a REPL that has some of the same features as a REPL, but a slightly different set of tradeoffs.</p>
<p>What we haven’t discussed is the tooling around REPLs. To my knowledge, the only Clojure programming environments that support REPLs are <a href="https://github.com/clojure-emacs/inf-clojure">inf-clojure</a> for Emacs and <a href="http://tutkain.flowthing.me">Tutkain</a>, which is a tool I’ve made for myself. Sublime Text introduced <a href="https://www.sublimetext.com/dev#changelog">IO panels in build 4198</a>, which opens up new possibilities for improving Tutkain’s REPL support.</p>
<p>So, in the end, all I’ve probably done is waste your time talking about a tool you probably won’t end up using anyway.</p>
<p>Perhaps, though, it helps spark some interest in exploring the possibilities of tooling where reading, evaluating, and printing are distinct, composable steps. You never know.</p>

]]></content:encoded>
        </item>
        <item>
            <pubDate>2022-04-21</pubDate>
            <title>Faster Clojure REPL startup</title>
            <description>A totally rigorous and unbelievably methodical survey into making your Clojure REPL start faster.</description>
            <link>https://blog.flowthing.me/clojure-repl-start</link>
            <content:encoded><![CDATA[
<h2><a href="#tldr" aria-hidden="true" class="anchor" id="tldr"></a>tl;dr</h2>
<p>To make your Clojure <a href="https://clojure.org/guides/repl/introduction">REPL</a> start fast (in about 1.6 seconds), in decreasing order of impact:</p>
<ul>
<li>Avoid requiring namespaces at the top level of your <code>user.clj</code> file; use <code>requiring-resolve</code> to defer loading instead</li>
<li><a href="https://clojure.org/guides/dev_startup_time">Compile your dependencies</a></li>
<li>Use the <a href="https://clojure.org/guides/getting_started#_clojure_installer_and_cli_tools">Clojure CLI</a> instead of Leiningen</li>
<li>Use a <a href="https://clojure.org/reference/repl_and_main#_launching_a_socket_server">socket server</a> instead of nREPL</li>
</ul>
<h2><a href="#off-to-the-races" aria-hidden="true" class="anchor" id="off-to-the-races"></a>Off to the races</h2>
<p>In this article, I’ll discuss some of the things you can do to make sure your Clojure REPL starts as fast as possible. I’ll also mention how to load all the <a href="https://clojure.org/reference/libs">libs</a> your app requires faster.</p>
<p>To whet your appetite, here’s a before-and-after: in one of my work projects (clocking in at about 15,000 lines of Clojure), applying these changes decreased the REPL startup time from 23 seconds to 1.6 seconds. Additionally, it decreased the time it takes to load (<code>require</code>) all of the libs the app needs from 12 seconds to 5.4 seconds.</p>
<p>I’ll discuss, in decreasing order of impact, some of the factors that affect your REPL startup time. I’ll begin by discussing the effect your <code>user.clj</code> file has on the startup time. Then, I’ll briefly discuss avoiding recompiling your dependencies every time you load them. Next, I’ll investigate the impact of choosing between <a href="https://clojure.org/guides/getting_started#_clojure_installer_and_cli_tools">Clojure CLI</a> and <a href="https://leiningen.org/">Leiningen</a>. I’ll also examine whether the <a href="https://clojure.org/reference/repl_and_main#_launching_a_socket_server">socket server</a> built into Clojure starts any faster than <a href="https://nrepl.org/">nREPL</a>, the most popular Clojure network REPL.</p>
<h2><a href="#kind-of-a-weird-artifact" aria-hidden="true" class="anchor" id="kind-of-a-weird-artifact"></a>Kind of a weird artifact</h2>
<p>When Clojure starts, it <a href="https://github.com/clojure/clojure/blob/c01f10bd8c68bd16c657fe352b206573f9306168/src/jvm/clojure/lang/RT.java#L486">loads the first file named <code>user.clj</code> it finds</a> in the <a href="https://clojure.org/reference/deps_and_cli#_basis_and_classpath">classpath</a> of your program. Even though it’s not very well documented (as of this writing), most Clojure developers know this.</p>
<p>Because Clojure automatically loads whatever you put in <code>user.clj</code>, many Clojure developers use it as a repository for development-time helper functions. Here’s an example of a <code>user.clj</code> file that will look familiar to many Clojure developers. It is adapted <a href="https://github.com/stuartsierra/component/tree/929dc7b4dc473b19f1417a918d5707ea8a1c9f2e#reloading">from the README of Component</a>, a Clojure library for managing application state.</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">ns</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">user</span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>require</span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">com.stuartsierra.component</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>as</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">component</span></span><span class="punctuation section brackets end edn">]</span></span>
            <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">my.app</span></span> <span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>as</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">app</span></span><span class="punctuation section brackets end edn">]</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration variable clojure">defonce</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name constant clojure">system</span></span></span> <span class="meta reader-form edn"><span class="constant language edn">nil</span></span><span class="punctuation section parens end edn">)</span>

<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration function clojure">defn</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name function clojure">init</span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">alter-var-root</span></span></span></span> <span class="keyword operator macro clojure">#&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn">system</span></span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">constantly</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure"><span class="meta namespace clojure">app</span><span class="punctuation accessor clojure">/</span>example-system</span></span></span></span> <span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>host</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>dbhost.com<span class="punctuation definition string end edn">&quot;</span></span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>port</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">123</span></span></span><span class="punctuation section braces end edn">}</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration function clojure">defn</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name function clojure">start</span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">alter-var-root</span></span></span></span> <span class="keyword operator macro clojure">#&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn">system</span></span> <span class="meta reader-form edn"><span class="meta symbol edn"><span class="meta namespace edn">component</span><span class="punctuation accessor edn">/</span>start</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration function clojure">defn</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name function clojure">stop</span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">alter-var-root</span></span></span></span> <span class="keyword operator macro clojure">#&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn">system</span></span> <span class="keyword operator macro clojure">#</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">some-&gt;</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">%</span></span> <span class="meta reader-form edn"><span class="meta symbol edn"><span class="meta namespace edn">component</span><span class="punctuation accessor edn">/</span>stop</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">comment</span></span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">init</span></span></span></span><span class="punctuation section parens end edn">)</span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">start</span></span></span></span><span class="punctuation section parens end edn">)</span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">stop</span></span></span></span><span class="punctuation section parens end edn">)</span>
  <span class="punctuation comma edn"><span class="comment punctuation comma edn">,</span></span><span class="punctuation comma edn"><span class="comment punctuation comma edn">,</span></span><span class="punctuation comma edn"><span class="comment punctuation comma edn">,</span></span><span class="punctuation section parens end edn">)</span>
</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre>
<p>In this example, <code>my.app</code> is the entry point namespace of the application. A medium-size Clojure project can have hundreds of loaded libs.</p>
<p>When you require <code>my.app</code> in <code>user.clj</code>, whenever you run Clojure (via <code>clj</code> or <code>lein</code> or whatever), Clojure dutifully loads every lib your application needs to run. That can take a pretty long time. Here’s me loading the entry point namespace of my work project:</p>
<pre><code><span class="source clojure"><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">time</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">require</span></span></span></span> <span class="keyword operator macro clojure">&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn">app.core</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
<span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>Elapsed time: 12156.287987 msecs<span class="punctuation definition string end edn">&quot;</span></span></span>
<span class="meta reader-form edn"><span class="constant language edn">nil</span></span>
<span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">count</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">loaded-libs</span></span></span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
<span class="meta reader-form edn"><span class="constant numeric integer decimal edn">297</span></span>
</span></span></span></span></span></code></pre>
<p>That’s 12 seconds to load ~300 libs.</p>
<p>The takeaway here is that if you require the entry point namespace for your application in your <code>user.clj</code>, you pay a hefty penalty every time you start a REPL. The same is true if you require any (transitively) large namespace. <a href="https://github.com/clojure/core.async">clojure.core.async</a>, in particular, is a usual suspect: requiring core.async alone takes 3.5 seconds on my machine.</p>
<p>Now that we know what the (biggest) factor affecting REPL startup time is, let’s look at how to alleviate it.</p>
<h2><a href="#deferring-code-loading" aria-hidden="true" class="anchor" id="deferring-code-loading"></a>Deferring code loading</h2>
<p>To avoid the startup-time penalty that requiring namespaces in <code>user.clj</code> incurs, we’ll use a clojure.core function called <a href="https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/requiring-resolve"><code>requiring-resolve</code></a>. You can think of <code>requiring-resolve</code> as a function that lazily requires <a href="https://clojure.org/reference/vars">vars</a> from namespaces that might or might not already be loaded. In <code>user.clj</code>, we can use it to avoid having Clojure load any libs when it starts.</p>
<p>Here’s the Component example from earlier rewritten using <code>requiring-resolve</code>:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">ns</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">user</span></span><span class="punctuation section parens end edn">)</span>

<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration variable clojure">defonce</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name constant clojure">system</span></span></span> <span class="meta reader-form edn"><span class="constant language edn">nil</span></span><span class="punctuation section parens end edn">)</span>

<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration function clojure">defn</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name function clojure">init</span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">alter-var-root</span></span></span></span> <span class="keyword operator macro clojure">#&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn">system</span></span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">constantly</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">requiring-resolve</span></span></span></span> <span class="keyword operator macro clojure">&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn"><span class="meta namespace edn">my.app</span><span class="punctuation accessor edn">/</span>example-system</span></span><span class="punctuation section parens end edn">)</span>
                 <span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>host</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>dbhost.com<span class="punctuation definition string end edn">&quot;</span></span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>port</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">123</span></span></span><span class="punctuation section braces end edn">}</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration function clojure">defn</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name function clojure">start</span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">alter-var-root</span></span></span></span> <span class="keyword operator macro clojure">#&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn">system</span></span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">requiring-resolve</span></span></span></span> <span class="keyword operator macro clojure">&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn"><span class="meta namespace edn">com.stuartsierra.component</span><span class="punctuation accessor edn">/</span>start</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration function clojure">defn</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name function clojure">stop</span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">alter-var-root</span></span></span></span> <span class="keyword operator macro clojure">#&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn">system</span></span>
    <span class="keyword operator macro clojure">#</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">some-&gt;</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">%</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">requiring-resolve</span></span></span></span> <span class="keyword operator macro clojure">&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn"><span class="meta namespace edn">com.stuartsierra.component</span><span class="punctuation accessor edn">/</span>stop</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">comment</span></span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">init</span></span></span></span><span class="punctuation section parens end edn">)</span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">start</span></span></span></span><span class="punctuation section parens end edn">)</span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">stop</span></span></span></span><span class="punctuation section parens end edn">)</span>
  <span class="punctuation comma edn"><span class="comment punctuation comma edn">,</span></span><span class="punctuation comma edn"><span class="comment punctuation comma edn">,</span></span><span class="punctuation comma edn"><span class="comment punctuation comma edn">,</span></span><span class="punctuation section parens end edn">)</span>
</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre>
<p>Notice how there’s no <code>:require</code> in the <code>ns</code> form. This might not be what you’d call pretty, but it does make a pretty big difference. Let’s use <a href="https://github.com/sharkdp/hyperfine"><code>hyperfine</code></a> to find out just how big. Here’s how long it takes to start a REPL for my work project <em>before</em> refactoring <code>user.clj</code> to use <code>requiring-resolve</code>:</p>
<pre><code><span class="text plain">λ hyperfine --warmup 3 &quot;echo &#39;:repl/quit&#39; | clj -J-Dclojure.server.repl=&#39;{:port 5555 :accept clojure.core.server/repl}&#39; -M:dev -r&quot;
Benchmark 1: echo &#39;:repl/quit&#39; | clj -J-Dclojure.server.repl=&#39;{:port 5555 :accept clojure.core.server/repl}&#39; -M:dev -r
  Time (mean ± σ):     23.142 s ±  2.761 s    [User: 54.177 s, System: 3.629 s]
  Range (min … max):   19.347 s … 27.199 s    10 runs
</span></code></pre>
<p>23 seconds. Here’s the result of running the same benchmark <em>after</em> using <code>requiring-resolve</code> to remove all <code>:require</code>s from <code>user.clj</code>:</p>
<pre><code><span class="text plain">λ hyperfine --warmup 3 &quot;echo &#39;:repl/quit&#39; | clj -J-Dclojure.server.repl=&#39;{:port 5555 :accept clojure.core.server/repl}&#39; -M:dev -r&quot;
Benchmark 1: echo &#39;:repl/quit&#39; | clj -J-Dclojure.server.repl=&#39;{:port 5555 :accept clojure.core.server/repl}&#39; -M:dev -r
  Time (mean ± σ):      1.611 s ±  0.042 s    [User: 2.296 s, System: 0.274 s]
  Range (min … max):    1.559 s …  1.703 s    10 runs
</span></code></pre>
<p>And so, we’re down to 1.6 seconds.</p>
<p>Of course, you have to pay the cost of requiring all those libs eventually. By using <code>requiring-resolve</code>, you’re simply deferring the payment: you’ll pay it when you actually call one of the functions that calls <code>requiring-resolve</code> (like <code>start</code>, for example). It’s up to you to decide whether the tradeoff is worth it. To me, it is: just because I want to run a REPL doesn’t always mean I want to run the whole app, too.</p>
<p>Besides using <code>requiring-resolve</code> to avoid loading anything on startup, there’s something else we can do to load libs faster: compile our dependencies. Let’s see how.</p>
<h2><a href="#avoiding-dependency-recompilation" aria-hidden="true" class="anchor" id="avoiding-dependency-recompilation"></a>Avoiding dependency recompilation</h2>
<p>Most Clojure libraries are distributed as packages of Clojure source files. That means that every time you load a lib, Clojure must first compile it to bytecode. Compilation accounts for maybe half of the time Clojure spends on loading libs.</p>
<p>To load libs faster, you can compile them beforehand, as proposed in <a href="https://clojure.org/guides/dev_startup_time">the official <em>Improving Development Startup Time</em> guide</a>. As a reminder, before making the changes proposed in the guide, it took 12 seconds to require the entry point namespace for my work project. Here’s how long it takes after following the instructions in the guide:</p>
<pre><code><span class="source clojure"><span class="meta reader-form edn"><span class="meta symbol edn">user=&gt;</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">time</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">require</span></span></span></span> <span class="keyword operator macro clojure">&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn">app.core</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
<span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>Elapsed time: 5428.763059 msecs<span class="punctuation definition string end edn">&quot;</span></span></span>
<span class="meta reader-form edn"><span class="constant language edn">nil</span></span>
</span></span></span></code></pre>
<p>Less than half of the original duration. Not too shabby.</p>
<p>Avoiding lib-loading and compilation on startup have the largest impact on REPL startup time by far, so it’s totally reasonable to stop here. If you want to go as fast as possible, though, you might also want to consider using the Clojure CLI instead of Leiningen. That’s what we’ll look into next.</p>
<h2><a href="#clojure-cli-vs-leiningen" aria-hidden="true" class="anchor" id="clojure-cli-vs-leiningen"></a>Clojure CLI vs. Leiningen</h2>
<p>First, let’s use <a href="https://clojure.org/guides/getting_started#_clojure_installer_and_cli_tools">the Clojure command-line tool</a> (henceforth <code>clj</code>) to start (and immediately quit) a Clojure REPL. To make it a REPL you can connect your <a href="https://tutkain.flowthing.me">editor</a> to, we’ll use the <code>clojure.server</code> Java system property to also <a href="https://clojure.org/reference/repl_and_main#_launching_a_socket_server">launch a socket server</a>.</p>
<pre><code><span class="text plain"># We use --warmup 3 to run the benchmark on a warm disk cache.
λ hyperfine --warmup 3 &quot;echo &#39;:repl/quit&#39; | clj -J-Dclojure.server.repl=&#39;{:port 5555 :accept clojure.core.server/repl}&#39; -M -r&quot;
Benchmark 1: echo &#39;:repl/quit&#39; | clj -J-Dclojure.server.repl=&#39;{:port 5555 :accept clojure.core.server/repl}&#39; -M -r
  Time (mean ± σ):      1.376 s ±  0.137 s    [User: 1.631 s, System: 0.212 s]
  Range (min … max):    1.194 s …  1.606 s    10 runs
</span></code></pre>
<p>Under 1.5 seconds. Let’s see how long it takes to do the same thing using <a href="https://leiningen.org/">Leiningen</a>.</p>
<pre><code><span class="text plain">λ hyperfine --warmup 3 &#39;echo &quot;(exit)&quot; | lein repl&#39;
Benchmark 1: echo &quot;(exit)&quot; | lein repl
  Time (mean ± σ):      3.477 s ±  0.045 s    [User: 4.039 s, System: 0.551 s]
  Range (min … max):    3.427 s …  3.560 s    10 runs
</span></code></pre>
<p>Over twice as long. That’s understandable, because comparing <code>clj</code> to Leiningen is not exactly apples to apples. Leiningen not only loads more code than <code>clj</code>, it also starts an <a href="https://nrepl.org/">nREPL</a> server and connects to it. Still, there’s no way (that I know of) to go any faster than that using Leiningen, so I suppose the comparison isn’t completely unfair.</p>
<p>To be thorough, let’s eliminate Leiningen from the equation and run an nREPL server using <code>clj</code>:</p>
<pre><code><span class="text plain">λ hyperfine --warmup 3 &quot;echo &#39;(exit)&#39; | clj -Sdeps &#39;{:deps {nrepl/nrepl {:mvn/version \&quot;0.9.0\&quot;}}}&#39; -M -m nrepl.cmdline --interactive&quot;
Benchmark 1: echo &#39;(exit)&#39; | clj -Sdeps &#39;{:deps {nrepl/nrepl {:mvn/version &quot;0.9.0&quot;}}}&#39; -M -m nrepl.cmdline --interactive
  Time (mean ± σ):      2.722 s ±  0.180 s    [User: 4.716 s, System: 0.383 s]
  Range (min … max):    2.584 s …  3.204 s    10 runs
</span></code></pre>
<p>Over half a second faster. That’s still twice as long as <code>clj</code> and a socket server, but it’s not too bad.</p>
<p>The upshot is that if you want to minimize your REPL startup time, use <code>clj</code> instead of Leiningen. The penalty nREPL carries isn’t huge, but if you want to go as fast as possible, use the socket server to run <a href="https://clojure.org/reference/repl_and_main">a <code>clojure.main</code> REPL</a> (or <a href="https://clojuredocs.org/clojure.core.server/prepl">prepl</a>, if you prefer, although editor support for that is slim) instead. Opting for <code>clj</code> and the socket server shaves off around two seconds of your REPL startup time.</p>
<h2><a href="#just-a-spoonful-of-sugar" aria-hidden="true" class="anchor" id="just-a-spoonful-of-sugar"></a>Just a spoonful of sugar</h2>
<p>If you like the idea of using <code>requiring-resolve</code> to avoid top-level requires but find it too verbose, here’s a little bit of sugar you might consider sprinkling on your <code>user.clj</code>:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration function clojure">defn</span></span></span> <span class="keyword operator macro clojure">^</span><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>private</span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name function clojure">rapply</span></span></span>
  <span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>Given a qualified symbol naming a function and a variable number of args to
  it, require the function and apply it to args.<span class="punctuation definition string end edn">&quot;</span></span></span>
  <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">sym</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">&amp;</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">args</span></span><span class="punctuation section brackets end edn">]</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">apply</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">requiring-resolve</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">sym</span></span><span class="punctuation section parens end edn">)</span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">args</span></span></span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
</span></span></span></span></code></pre>
<p>Armed with that, <code>init</code>, for example, becomes:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration function clojure">defn</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name function clojure">init</span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">alter-var-root</span></span></span></span> <span class="keyword operator macro clojure">#&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn">system</span></span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">constantly</span></span></span></span>
      <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">rapply</span></span></span></span> <span class="keyword operator macro clojure">&#39;</span><span class="meta reader-form edn"><span class="meta symbol edn"><span class="meta namespace edn">my.app</span><span class="punctuation accessor edn">/</span>example-system</span></span> <span class="meta sexp map edn"><span class="punctuation section braces begin edn">{</span><span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>host</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>dbhost.com<span class="punctuation definition string end edn">&quot;</span></span></span></span> <span class="meta mapping key edn"><span class="meta reader-form edn"><span class="constant other keyword unqualified edn"><span class="punctuation definition keyword edn">:</span>port</span></span></span> <span class="meta mapping value edn"><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">123</span></span></span><span class="punctuation section braces end edn">}</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
</span></span></span></span></span></code></pre>
<p>Not a huge difference in readability here, granted, but you might find it useful if you have many helper functions in your <code>user.clj</code>.</p>
<h2><a href="#wrap-up" aria-hidden="true" class="anchor" id="wrap-up"></a>Wrap-up</h2>
<p>Using one of my work projects as a test subject, using <code>requiring-resolve</code> to avoid requiring anything at the top level of my <code>user.clj</code> brought down the REPL startup time for that project from ~23 seconds to 1.6 seconds. After precompiling dependencies, Clojure loads all the libs the app needs in 5.4 seconds, instead of the 12 seconds sans precompilation.</p>
<p>Those two changes have the biggest impact on REPL startup time. If you want to go further, though, consider using <code>clj</code> instead of Leiningen to shave off a second or so. Finally, using a socket server instead of nREPL might win you an additional one or two seconds.</p>
<h2><a href="#why-though" aria-hidden="true" class="anchor" id="why-though"></a>Why, though?</h2>
<p>You might think that running a REPL with only clojure.core (and a few auxiliary libs, like clojure.repl) loaded isn’t particularly useful. To me, it is: that’s all I need to start evaluating things from my editor. Once I have clojure.core loaded, to start working with a specific part of my app, I can evaluate individual function definitions or namespaces and start using them. I find it’s not necessary to always have the entire app loaded into your runtime. When I need that, though, precompiling my dependencies helps me do that much faster, too.</p>
<h2><a href="#prior-art" aria-hidden="true" class="anchor" id="prior-art"></a>Prior art</h2>
<p>A lot of virtual ink has been spilled on this topic, so this is by no means an exhaustive list, but here’s some more reading on Clojure startup times.</p>
<ul>
<li><a href="https://web.archive.org/web/20170216042612/http://dev.clojure.org/display/design/Improving+Clojure+Start+Time">Improving Clojure Start Time</a> by Alex Miller</li>
<li><a href="https://ericnormand.me/article/the-legend-of-long-jvm-startup-times">Why Clojure starts up slowly — is it really the JVM</a> by Eric Normand</li>
<li><a href="http://clojure-goes-fast.com/blog/clojures-slow-start/">Clojure’s slow start — what’s inside</a> by Alexander Yakushev</li>
<li><a href="https://blog.ndk.io/clojure-bootstrapping.html">Why is Clojure bootstrapping so slow?</a> by Nicholas Kariniemi</li>
</ul>
<h2><a href="#tech-specs" aria-hidden="true" class="anchor" id="tech-specs"></a>Tech specs</h2>
<p>Here’s the Java version and hardware specs I ran these tests on:</p>
<pre><code><span class="text plain">λ java -version
openjdk version &quot;18&quot; 2022-03-22
OpenJDK Runtime Environment (build 18+36-2087)
OpenJDK 64-Bit Server VM (build 18+36-2087, mixed mode, sharing)

λ system_profiler SPHardwareDataType
…
Model Name: MacBook Pro
Model Identifier: MacBookPro16,2
Processor Name: Quad-Core Intel Core i5
Processor Speed: 2 GHz
Number of Processors: 1
Total Number of Cores: 4
Memory: 16 GB
…
</span></code></pre>
<p>For what it’s worth, while running the benchmarks, I noticed that compared to Java 11, Java 18 (and presumably 17, which is the latest long-term support release) shaves something like half a second off the startup time. So that’s another thing you might want to consider if you’re looking to make your REPL start as fast as possible. I didn’t really have time to do a lot of science on that yet, though.</p>

]]></content:encoded>
        </item>
        <item>
            <pubDate>2021-10-14</pubDate>
            <title>Grokking Clojure transducers</title>
            <description>What are transducers and why should I care? Here's an attempt to answer that question.</description>
            <link>https://blog.flowthing.me/transducers</link>
            <content:encoded><![CDATA[
<p>So you’re a Clojure programmer and you need to apply more than one transformation step to a collection of items. Like, for example, you have a big list of things, and you need to remove some of them, transform others, then remove duplicates. What do you do?</p>
<p>The stock approach is to reach for the thread-last macro (<code>-&gt;&gt;</code>). It’s a fine implement for skinning this particular cat, but, well… what if I told you there’s another way? In Clojure, we have this thing called <a href="https://clojure.org/reference/transducers">transducers</a>. They were made for precisely this sort of thing.</p>
<p>In this article, it’s my noble aim to instill in you an intuition for transducers. We’ll start by examining the building blocks of transducers to see how they work. We’ll then make a couple of transducers of our own. Finally, we’ll look at how you can apply your newfound knowledge of transducers in the real world.</p>
<p>You’re in the target audience of this article if:</p>
<ul>
<li>you’re a Clojure programmer who hasn’t paid much attention to transducers up until now, or,</li>
<li>you’re not a Clojure programmer, but you understand what the <code>reduce</code> function does, and you’re curious about transducers.</li>
</ul>
<p>If you already know how <code>reduce</code> works, you probably also know what a reducing function is. If you don’t, though, you’re in luck, because that’s where we’ll set forth on our exciting adventure into the wonderful world of transducers.</p>
<h2><a href="#first-steps" aria-hidden="true" class="anchor" id="first-steps"></a>First steps</h2>
<p>To understand transducers, you must first understand reducing functions. What’s a reducing function?</p>
<p>A <strong>reducing function</strong> is a function you can use as the first argument of  <code>reduce</code>. A reducing function takes an <strong>accumulated result</strong> and an <strong>input</strong> and returns a <strong>new result</strong>.</p>
<p><code>conj</code> is an example of a reducing function. It takes a collection (the result we’ve accumulated so far) and an item (the input) and adds the item into the collection (the new result).</p>
<p>Here’s an example of using <code>conj</code>:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">conj</span></span></span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span><span class="punctuation section brackets end edn">]</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>          ^ input
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span>    ^^^^^ accumulated result
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; [1 2 3]
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span>   ^^^^^^^ new result
</span></span></span></code></pre>
<p>Since <code>conj</code> is a reducing function, let’s try using it with <code>reduce</code>. Here, we use <code>conj</code> to add every number in the given Clojure vector (<code>[1 2 2 3 1]</code>) into an empty hash set (<code>#{}</code>):</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">reduce</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">conj</span></span> <span class="meta sexp set edn"><span class="keyword operator macro edn">#</span><span class="punctuation section braces begin edn">{</span><span class="punctuation section braces end edn">}</span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span><span class="punctuation section brackets end edn">]</span></span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; #{1 3 2}
</span></span></span></code></pre>
<p>Cool! We got what we expected: a set that contains each distinct number in the input collection.</p>
<p>Now that we know what reducing functions are, let’s discuss how they relate to transducers.</p>
<!-- ## Making our first transducer -->
<p>In essence, a <strong>transducer</strong> is <em>a function that takes a reducing function</em> (like <code>conj</code>) and <em>turns it into a new, more awesome reducing function</em>. Let’s give it a try. Let’s make a transducer called <code>inc-transducer</code>:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration function clojure">defn</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name function clojure">inc-transducer</span></span></span>
  <span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>Given a reducing function rf, return a new reducing function that increments
  every input it receives, then calls rf with the result and the incremented
  input.<span class="punctuation definition string end edn">&quot;</span></span></span>
  <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> rf stands for &quot;reducing function&quot;
</span>  <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">rf</span></span><span class="punctuation section brackets end edn">]</span></span></span>
  <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> this here&#39;s a new reducing function
</span>  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">result</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">input</span></span><span class="punctuation section brackets end edn">]</span></span></span>
    <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> here we call the original reducing function
</span>    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">rf</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">result</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">inc</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">input</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> If you already know transducers, you&#39;ll notice that inc-transducer doesn&#39;t
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> actually have everything a real, production-grade transducer needs to have.
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Don&#39;t worry, we&#39;ll get there.
</span></span></span></span></span></span></code></pre>
<p>We’ve made our first transducer! <code>inc-transducer</code> takes a reducing function like <code>conj</code> and returns a modified version of it. Let’s give it a try:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">def</span></span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name constant clojure">inc-then-conj</span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">inc-transducer</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">conj</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; #&#39;user/inc-then-conj
</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">inc-then-conj</span></span></span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span><span class="punctuation section brackets end edn">]</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; [1 2 4]
</span></span></span></span></span></code></pre>
<p>What is <code>inc-then-conj</code> supposed to do again? Let’s recap. It should:</p>
<ol>
<li>Increment the input <code>3</code> by one to get <code>4</code>.</li>
<li>Add the incremented input <code>4</code> into the result to get <code>[1 2 4]</code>.</li>
</ol>
<p>Looks like it works! Can we use it with <code>reduce</code>, like we did with <code>conj</code>?</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">reduce</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">inc-then-conj</span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">4</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">5</span></span><span class="punctuation section brackets end edn">]</span></span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; [2 3 4 5 6]
</span></span></span></code></pre>
<p>Boom! When used with <code>reduce</code>, <code>inc-then-conj</code> incremented every input, then added each incremented input into the result vector (<code>[]</code>).</p>
<p>Of course, we can give <code>inc-transducer</code> <em>any</em> reducing function, not just <code>conj</code>. Let’s try to use it to transform some other reducing function. Let’s pick <code>+</code>, which, happily, is also a reducing function:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">reduce</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">inc-transducer</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">+</span></span><span class="punctuation section parens end edn">)</span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">0</span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">4</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">5</span></span><span class="punctuation section brackets end edn">]</span></span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; 20
</span></span></span></span></code></pre>
<p>It worked! When we used <code>inc-transducer</code> with <code>+</code>, for each number in the input collection, it incremented the number, then added it into the accumulated sum.</p>
<p>However… what if there comes a day when we want to do something other than increment a number? That’s all <code>inc-transducer</code> lets us do, increment numbers! What to do?</p>
<p>Benjamin Franklin used to say, “Functions are like violence: if it’s not working, you’re not using enough of it. Or them. Or whatever, you know.” Stimulated by this enlightening adage, let us beat this problem into submission by employing an additional function. Instead of baking in <code>inc</code> as the function that transforms the input, let’s make a new function. This new function takes any function and uses it to transform the input. Here’s the new function:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration function clojure">defn</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name function clojure">mapping</span></span></span>
  <span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>Given function f, return a transducer that calls f on every input it
  receives.<span class="punctuation definition string end edn">&quot;</span></span></span>
  <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">f</span></span><span class="punctuation section brackets end edn">]</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">rf</span></span><span class="punctuation section brackets end edn">]</span></span></span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">result</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">input</span></span><span class="punctuation section brackets end edn">]</span></span></span>
      <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">rf</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">result</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">f</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">input</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
</span></span></span></span></span></span></code></pre>
<p>Our brand new function bears the inspired name of <code>mapping</code>. <code>mapping</code> is not a transducer. It is a function that <strong>takes a function</strong> and <strong>returns a transducer</strong>. Let this illuminating example shed light on this mystical conundrum of a function:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">def</span></span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name constant clojure">inc-mapper</span></span></span>
  <span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>Given a reducing function rf, return a reducing function that increments its
  input before calling rf.<span class="punctuation definition string end edn">&quot;</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">mapping</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">inc</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">def</span></span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name constant clojure">inc-rf</span></span></span>
  <span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>A reducing function that increments its input, then adds it into the
  accumulated result.<span class="punctuation definition string end edn">&quot;</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">inc-mapper</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">conj</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">reduce</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">inc-rf</span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">4</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">5</span></span><span class="punctuation section brackets end edn">]</span></span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; [2 3 4 5 6]
</span></span></span></span></span></span></span></code></pre>
<p>Right on! We’ve reimplemented <code>inc-transducer</code> without baking in <code>inc</code> into the reducing function.</p>
<p>Although… haven’t we just reimplemented <code>map</code>, kinda?</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">map</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">inc</span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">4</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">5</span></span><span class="punctuation section brackets end edn">]</span></span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; (2 3 4 5 6)
</span></span></span></code></pre>
<p>It might indeed appear so at first, but there are crucial differences that set the transducer version apart from plain old mapping. That’s what we’ll focus on next.</p>
<h2><a href="#whats-so-special-about-transducers" aria-hidden="true" class="anchor" id="whats-so-special-about-transducers"></a>What’s so special about transducers?</h2>
<p>The first difference between using <code>map</code> and using a transducer is this: with <code>map</code>, the reducing function “at the bottom” is always <code>conj</code>. <code>conj</code> is baked into <code>map</code> – there’s no way to pull it out of there.</p>
<p>With transducers (like the one <code>mapping</code> returns), on the other hand, we can decide which reducing function to use. For example, we can use <code>+</code>, like earlier:</p>
<pre><code><span class="source clojure"><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> This is otherwise equivalent to the previous example, but we&#39;re just
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> forgoing the intermediate vars `inc-mapper` and `inc-rf`, and passing in `+`
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> instead of `conj`.
</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">reduce</span></span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">mapping</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">inc</span></span><span class="punctuation section parens end edn">)</span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">+</span></span></span></span><span class="punctuation section parens end edn">)</span>
  <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">0</span></span>
  <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">4</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">5</span></span><span class="punctuation section brackets end edn">]</span></span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; 20
</span></span></span></span></span></code></pre>
<p>Secondly, notice how the transformation (incrementing numbers) is distinct from how the final output is built. In other words, <code>(mapping inc)</code> does not say anything about how to make the final value. This is a crucial feature of transducers: they allow you to define transformations that do not know or care what happens once the transformation is complete. Put another way, <code>(mapping inc)</code> only says “increment numbers”, while <code>(map inc [1 2 3 4 5])</code> says “increment numbers and then add them into a new list”.</p>
<p>This decoupling of the transformation from its inputs and outputs has important repercussions. For one, it means we can also use transducers with things like <code>clojure.core.async</code> channels (which, if you don’t know, are these things that look a bit like queues, if you squint). Before transducers, <code>core.async</code> used to have its own <code>map</code>, <code>filter</code>, etc. implementations. Transducers, because they’re so awesome, have made them unnecessary, so they have since been deprecated. Now, you can just sort of stick a transducer to a channel and the transducer transforms whatever you put in the channel.</p>
<p>Here’s another very important distinction between transducers and traditional methods of transforming collections. Let’s say we want to transform the input collection in more ways than one. For example, let’s say that we only want to increment every <strong>even</strong> number in the input collection. Faced with a case like this, most Clojure programmers reach for the thread-last macro (<code>-&gt;&gt;</code>):</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">-&gt;&gt;</span></span></span></span>
  <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">4</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">5</span></span><span class="punctuation section brackets end edn">]</span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">filter</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">even?</span></span><span class="punctuation section parens end edn">)</span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">map</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">inc</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; (3 5)
</span></span></span></span></span></code></pre>
<p>The thread-last macro is eminently readable, but using it comes at a cost. When we use the thread-last macro, after every step of the transformation process, we create an intermediate collection, only to immediately throw it away. Let’s spell that out:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">-&gt;&gt;</span></span></span></span>
  <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">4</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">5</span></span><span class="punctuation section brackets end edn">]</span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">filter</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">even?</span></span><span class="punctuation section parens end edn">)</span> <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> intermediate collection (2 4), discarded immediately
</span>  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">map</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">inc</span></span><span class="punctuation section parens end edn">)</span> <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> final result (3 5)
</span>  <span class="punctuation section parens end edn">)</span>
</span></span></span></span></code></pre>
<p>Here, we throw away the result of the filtering step (<code>(2 4)</code>) immediately after making it. What a waste! With transducers, we can make the same transformation without making a single unnecessary intermediate collection. Before we can do that, though, we have to make a function that’s like <code>mapping</code>, but it’s, uh… <code>filtering</code>.</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="keyword declaration function clojure">defn</span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name function clojure">filtering</span></span></span>
  <span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>Given a predicate function pred, return a transducer that only retains items
  for which pred returns true.<span class="punctuation definition string end edn">&quot;</span></span></span>
  <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">pred</span></span><span class="punctuation section brackets end edn">]</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">rf</span></span><span class="punctuation section brackets end edn">]</span></span></span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">result</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">input</span></span><span class="punctuation section brackets end edn">]</span></span></span>
      <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword control conditional if clojure">if</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">pred</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">input</span></span><span class="punctuation section parens end edn">)</span>
        <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">rf</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">result</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">input</span></span><span class="punctuation section parens end edn">)</span>
        <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">result</span></span></span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
</span></span></span></span></span></span></span></code></pre>
<p>Like <code>mapping</code>, <code>filtering</code> is a function that takes a function and returns a transducer. However, <code>filtering</code> is different from <code>mapping</code> in that it only calls its reducing function if the input matches the predicate function you give it.</p>
<p>Now that we have <code>filtering</code>, we can compose a multi-step transformation powered by transducers. Watch this:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">def</span></span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name constant clojure">rf</span></span></span>
  <span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>A reducing function that filters even numbers, increments every remaining
  number, then conjoins them into the result.<span class="punctuation definition string end edn">&quot;</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">comp</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">filtering</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">even?</span></span><span class="punctuation section parens end edn">)</span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">mapping</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">inc</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">conj</span></span></span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">reduce</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">rf</span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span> <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">4</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">5</span></span><span class="punctuation section brackets end edn">]</span></span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; [3 5]
</span></span></span></span></span></span></span></span></code></pre>
<p>Blammo! Filtering and mapping in one fell swoop, with zero intermediate collections. Of course, in this example, the transformation has few steps and its input is small, so there’s probably no perceptible performance difference compared to the thread-last version. The larger your input is and the more steps your transformation has, <a href="https://www.grammarly.com/blog/engineering/building-etl-pipelines-with-clojure-and-transducers/">the more significant the performance gains will be</a>.</p>
<p>You might be wondering about the <code>comp</code> there. <code>comp</code> (short for “compose”) is the most common way to make multi-step transformations with transducers – or <em>compose</em> transducers, if you will. Notice how the order of operations is the same with <code>comp</code> as with <code>-&gt;&gt;</code>:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="punctuation comma edn"><span class="comment punctuation comma edn">,</span></span><span class="punctuation comma edn"><span class="comment punctuation comma edn">,</span></span><span class="punctuation comma edn"><span class="comment punctuation comma edn">,</span></span>
 <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">comp</span></span></span></span>
   <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">filtering</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">even?</span></span><span class="punctuation section parens end edn">)</span>
   <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">mapping</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">inc</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
 <span class="punctuation comma edn"><span class="comment punctuation comma edn">,</span></span><span class="punctuation comma edn"><span class="comment punctuation comma edn">,</span></span><span class="punctuation comma edn"><span class="comment punctuation comma edn">,</span></span><span class="punctuation section parens end edn">)</span>

<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">-&gt;&gt;</span></span></span></span>
  <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">4</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">5</span></span><span class="punctuation section brackets end edn">]</span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">filter</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">even?</span></span><span class="punctuation section parens end edn">)</span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">map</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">inc</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
</span></span></span></span></span></span></span></span></code></pre>
<p>Here’s another way to think about the difference between the thread-last macro and transducers:</p>
<p>The thread-last macro <em>transforms collections</em>. Transducers, in turn, <em>transform reducing functions</em>. You can then use those reducing functions to transform things, without caring where those things come from and where they go, without generating any waste in the process.</p>
<p>With all that out of the way, let’s move on to discussing how you’d actually use transducers in your code.</p>
<h2><a href="#using-transducers-in-the-real-world" aria-hidden="true" class="anchor" id="using-transducers-in-the-real-world"></a>Using transducers in the real world</h2>
<p>So far, to illustrate how transducers work, we’ve been creating our own transducers and using them with <code>reduce</code>. In the real world, you rarely need to do the former, and the latter, probably never.</p>
<p>Now, uh… there’s something I must confess. We did not actually need to define <code>mapping</code> and <code>filtering</code> ourselves. Giving only the first argument to the <code>map</code> or <code>filter</code> core functions actually returns a transducer. That means we can simply replace <code>filtering</code> and <code>mapping</code> in our previous example with <code>filter</code> and <code>map</code>, like so:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">reduce</span></span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">comp</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">filter</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">even?</span></span><span class="punctuation section parens end edn">)</span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">map</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">inc</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">conj</span></span></span></span><span class="punctuation section parens end edn">)</span> <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> &lt;- reducing fn (awesome conj)
</span>  <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> &lt;- initial value
</span>  <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">4</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">5</span></span><span class="punctuation section brackets end edn">]</span></span> <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> &lt;- input collection
</span>  <span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; [3 5]
</span></span></span></span></span></span></span></code></pre>
<p>Besides <code>map</code> and <code>filter</code>, there’s <a href="https://clojure.org/reference/transducers#_defining_transformations_with_transducers">a whole bunch of functions</a> in the Clojure core that return a transducer when you give them all the arguments you usually do, <em>except</em> for the input collection (the last argument).</p>
<p>Also… I’ve got another confession to make. <code>mapping</code> and <code>filtering</code> are not “real” transducers. Each transducer returns a function that can take either zero, one, or two arguments. Since that is something you only really need to know when you’re creating your own transducers (which is not likely to be all that often), we won’t discuss that detail here. If you want to know more about the different arities of proper transducers, check out <a href="https://clojure.org/reference/transducers#_creating_transducers">the official documentation</a>.</p>
<p>So if we shouldn’t use <code>reduce</code> with transducers, what should we use? There are four functions in the Clojure core that take transducers as arguments:</p>
<ul>
<li><code>transduce</code></li>
<li><code>into</code></li>
<li><code>sequence</code></li>
<li><code>eduction</code></li>
</ul>
<p>Next, we’ll take a brief look at what each function is good for. We won’t go too deep here, so after you’re done reading this article, make sure you read the docstring for each function and <a href="https://clojure.org/reference/transducers#_using_transducers">the official reference</a> to get a better understanding of how each function works.</p>
<h3><a href="#transduce" aria-hidden="true" class="anchor" id="transduce"></a><code>transduce</code></h3>
<p><code>transduce</code> is like <code>reduce</code>, but specifically for transducers. To show how <code>transduce</code> works, let’s rewrite our previous example using <code>transduce</code> instead of <code>reduce</code>.</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">transduce</span></span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">comp</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">filter</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">even?</span></span><span class="punctuation section parens end edn">)</span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">map</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">inc</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
  <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">conj</span></span></span></span>
  <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="punctuation section brackets end edn">]</span></span>
  <span class="meta sexp vector edn"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">2</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">3</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">4</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">5</span></span><span class="punctuation section brackets end edn">]</span></span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; [3 5]
</span></span></span></span></span></span></code></pre>
<p>The result is the same. So what’s the difference to the <code>reduce</code> version? For one, the <code>transduce</code> version avoids the slightly awkward <code>((comp (filter even?) (map inc)) conj)</code> construction. Also, <code>reduce</code> doesn’t work perfectly with every kind of transducer, for reasons we won’t go into here. The upshot? Don’t use transducers with <code>reduce</code>. Use <code>transduce</code> or one of the other functions we discuss here instead.</p>
<p>Besides that, an important property of <code>transduce</code> is that unless you tell it to stop using <code>halt-when</code>, <code>take</code>, or the like, <code>transduce</code> consumes the entire input collection. If you want to be able to consume only a part of the input, consider using <code>sequence</code> or <code>eduction</code> instead. For a more comprehensive discussion of how <code>transduce</code>, <code>sequence</code>, and <code>eduction</code> consume their inputs, see the section titled “Laziness” in <a href="https://reborg.net/post/621473763865821184/clojure-transducers-from-the-ground-up-the">Renzo Borgatti’s article <em>Clojure transducers from the ground up: the practice</em></a>.</p>
<h3><a href="#into" aria-hidden="true" class="anchor" id="into"></a><code>into</code></h3>
<p>Use <code>into</code> if you want to transform the input collection into a certain type of output collection as fast as possible.</p>
<p>Here’s an example where we generate an infinite sequence of random numbers, take the first million, remove all odd numbers, multiply each number by ten and finally stick the result into a hash set:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">into</span></span></span></span> <span class="meta sexp set edn"><span class="keyword operator macro edn">#</span><span class="punctuation section braces begin edn">{</span><span class="punctuation section braces end edn">}</span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">comp</span></span></span></span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">take</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">1000000</span></span><span class="punctuation section parens end edn">)</span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">remove</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">odd?</span></span><span class="punctuation section parens end edn">)</span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">map</span></span></span></span> <span class="keyword operator macro clojure">#</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">*</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">%</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">10</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">repeatedly</span></span></span></span> <span class="keyword operator macro clojure">#</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">rand-int</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">100</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; #{0 920 580 240 620 20 980 60 360 300 940 260 540 740 460 420 ...}
</span></span></span></span></span></span></span></span></span></span></code></pre>
<p>Personally, I tend to use <code>into</code> whenever I know I need a particular type of output collection.</p>
<p>Note that <code>into</code> doesn’t let you choose which reducing function to transform. With <code>into</code>, it’s always <code>conj</code>.</p>
<h3><a href="#sequence" aria-hidden="true" class="anchor" id="sequence"></a><code>sequence</code></h3>
<p>Use <code>sequence</code> whenever you need your transformation to produce an incrementally computed (technically not <a href="https://www.braveclojure.com/core-functions-in-depth/#Lazy_Seqs">lazy</a>, though) sequence. You often want an incrementally computed sequence. One such case is when you need to use the transformation result more than once. Check out this example:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">def</span></span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name constant clojure">xs</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">sequence</span></span></span></span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">comp</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">filter</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">even?</span></span><span class="punctuation section parens end edn">)</span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">map</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">inc</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">range</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">100</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> in one case, we might need to take the first ten things from `xs`
</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">take</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">10</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">xs</span></span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; (1 3 5 7 9 11 13 15 17 19)
</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> later, in another context, we might need to take just the first five numbers
</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">take</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">5</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">xs</span></span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; (1 3 5 7 9)
</span></span></span></span></span></span></span></span></span></span></code></pre>
<p>In this example, when we call <code>take</code> the second time, the sequence that <code>sequence</code> returns has already transformed and cached the first ten values for us and has them handy when we need them. We do not need to transform the input again to get at the values.</p>
<p>Since most transformations that use the thread-last macro yield a lazy sequence, <code>sequence</code> might be the most straightforward option for refactoring a transformation that uses the thread-last macro into a transducer-powered one.</p>
<h3><a href="#eduction" aria-hidden="true" class="anchor" id="eduction"></a><code>eduction</code></h3>
<p>Out of these four functions, I found <code>eduction</code> the most difficult to understand when I was first learning about transducers. In a nutshell, if <code>sequence</code> is for when you want caching (to reuse the transformation result), <code>eduction</code> is for when you don’t. One case where you might use <code>eduction</code> is <a href="https://www.grammarly.com/blog/engineering/building-etl-pipelines-with-clojure-and-transducers/#enter-transducers">when you want to transform data that you’re reading from an external resource, such as a file</a>.</p>
<p>You might also want to choose <code>eduction</code> over <code>sequence</code> if you know you’re going to consume <strong>all</strong> of the final result, and you’re only going to do it <strong>once</strong>. There is some overhead to making a lazy sequence, and <code>eduction</code> allows you to avoid it when you need to. Don’t take this to mean that you should avoid using <code>sequence</code>. In most cases, the cost of lazy sequences is negligible.</p>
<p>Here’s an example that might clarify the difference between <code>sequence</code> and <code>eduction</code>:</p>
<pre><code><span class="source clojure"><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">def</span></span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name constant clojure">xs1</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">sequence</span></span></span></span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">map</span></span></span></span> <span class="keyword operator macro clojure">#</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword other clojure">do</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">prn</span></span></span></span> <span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>sequencing!<span class="punctuation definition string end edn">&quot;</span></span></span><span class="punctuation section parens end edn">)</span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">inc</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">%</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">range</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">32</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span> <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> prints &quot;sequencing!&quot;
</span>
<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">prn</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">xs1</span></span><span class="punctuation section parens end edn">)</span> <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> prints &quot;sequencing!&quot;
</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">prn</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">xs1</span></span><span class="punctuation section parens end edn">)</span> <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> doesn&#39;t print &quot;sequencing!&quot;
</span>
<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">def</span></span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name constant clojure">xs2</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">eduction</span></span></span></span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">map</span></span></span></span> <span class="keyword operator macro clojure">#</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword other clojure">do</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">prn</span></span></span></span> <span class="meta reader-form edn"><span class="string quoted double edn"><span class="punctuation definition string begin edn">&quot;</span>educing!<span class="punctuation definition string end edn">&quot;</span></span></span><span class="punctuation section parens end edn">)</span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">inc</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">%</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">range</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">32</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span> <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> doesn&#39;t print &quot;educing!&quot;
</span>
<span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">prn</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">xs2</span></span><span class="punctuation section parens end edn">)</span> <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> prints &quot;educing!&quot;
</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">prn</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">xs2</span></span><span class="punctuation section parens end edn">)</span> <span class="comment line edn"><span class="punctuation definition comment edn">;;</span> prints &quot;educing!&quot;
</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre>
<p><code>sequence</code> consumes a part of the input sequence when we define <code>xs1</code>. When we reference <code>xs1</code>, it returns the values it cached when it consumed the input sequence for the first time. Conversely, <code>eduction</code> consumes the input sequence only when we reference <code>xs2</code>, and does so every time we do it.</p>
<p>Here’s another way to think about <code>eduction</code>: it lets you bundle just the input collection and the transformation and defer the decision on which reducing function you want to modify and which initial value (accumulated result) you want to use. Here’s an example:</p>
<pre><code><span class="source clojure"><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Create a transformation that filters the even numbers between 0 and 99 and
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> increments the remaining numbers.
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span>
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Don&#39;t transform anything just yet, though.
</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration variable clojure">def</span></span></span></span> <span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="entity name constant clojure">xf</span></span></span>
  <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">eduction</span></span></span></span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">comp</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">filter</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">even?</span></span><span class="punctuation section parens end edn">)</span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">map</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">inc</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>
    <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">range</span></span></span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">100</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span>

<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Apply the eduction to sum the transformed numbers.
</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">reduce</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">+</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">0</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">xf</span></span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; 2500
</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span> Apply the eduction to multiply each number by ten, then add them into a hash
</span><span class="comment line edn"><span class="punctuation definition comment edn">;;</span> set.
</span><span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">reduce</span></span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta special-form clojure"><span class="keyword declaration function inline clojure">fn</span></span></span></span> <span class="meta sexp vector edn"><span class="meta function parameters clojure"><span class="punctuation section brackets begin edn">[</span><span class="meta reader-form edn"><span class="meta symbol edn">s</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">n</span></span><span class="punctuation section brackets end edn">]</span></span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">conj</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">s</span></span> <span class="meta sexp list edn"><span class="punctuation section parens begin edn">(</span><span class="meta reader-form clojure"><span class="meta symbol clojure"><span class="meta function-call clojure"><span class="variable function clojure">*</span></span></span></span> <span class="meta reader-form edn"><span class="meta symbol edn">n</span></span> <span class="meta reader-form edn"><span class="constant numeric integer decimal edn">10</span></span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span><span class="punctuation section parens end edn">)</span> <span class="meta sexp set edn"><span class="keyword operator macro edn">#</span><span class="punctuation section braces begin edn">{</span><span class="punctuation section braces end edn">}</span></span> <span class="meta reader-form edn"><span class="meta symbol edn">xf</span></span><span class="punctuation section parens end edn">)</span>
<span class="comment line edn"><span class="punctuation definition comment edn">;;</span>=&gt; #{950 530 410 970 70 430 370 110 ...}
</span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre>
<p>Calling <code>reduce</code> on an eduction grabs the transducer (the first argument to <code>eduction</code>) from the eduction and uses it to transform the reducing function we give to <code>reduce</code>. Only then does it carry out the transformation on the input collection that lives inside the eduction.</p>
<p>All right! That’s it for the four core functions that take transducers as arguments. All that’s left is to wrap things up.</p>
<h2><a href="#final-words" aria-hidden="true" class="anchor" id="final-words"></a>Final words</h2>
<p>In a side note of his fantastic book <em>Elements of Clojure</em>, Zach Tellman writes:</p>
<blockquote>
<p>The real value of transducers is not performance, but rather that non-standard data representations like <code>core.async</code> channels can use <code>clojure.core</code> directly rather than having to define their own <code>map</code>, <code>filter</code>, and so on.</p>
</blockquote>
<p>While that is no doubt the <em>raison d’être</em> of transducers, we should not think of them as just this thing that let Cognitect get away with writing less code when implementing <code>core.async</code>. For a long time, that was more or less the way I thought about transducers: something that Clojure takes care of for me that I don’t really need to think that much about.</p>
<p>I was wrong. After all, much of what we do as Clojure programmers is convert data from one shape into another. For that, transducers are a tremendously useful tool. They let us compose powerful transformations from simple parts, apply those transformations to pretty much anything we want, then, separately, decide how to build the final result of those transformations.</p>
<p>With that, we end this tour of transducers. Naturally, there’s much more to transducers than what we’ve discussed here. If you want to learn more about them, see <a href="https://clojure.org/reference/transducers#_creating_transducers">the official reference for transducers</a>. Hopefully, reading this article has made it a bit easier to understand.</p>
<p>Note that you might be able to use transducers even if you don’t use Clojure. There are implementations for <a href="https://github.com/cognitect-labs/transducers-java">Java</a>, <a href="https://github.com/cognitect-labs/transducers-js">JavaScript</a>, <a href="https://github.com/cognitect-labs/transducers-python">Python</a>, <a href="https://github.com/cognitect-labs/transducers-ruby">Ruby</a> and probably other languages as well.</p>
<p><small>This article was originally published in <a href="https://dev.solita.fi/2021/10/14/grokking-clojure-transducers.html">the Solita dev blog</a>.</small></p>
<h2><a href="#acknowledgements" aria-hidden="true" class="anchor" id="acknowledgements"></a>Acknowledgements</h2>
<p>Thanks to Pedro Girardi and Antti Riikonen for their valuable feedback on an earlier version of this article.</p>

]]></content:encoded>
        </item>
        <item>
            <pubDate>2018-11-07</pubDate>
            <title>Securing WebSocket Endpoints Against Cross-Site Attacks</title>
            <description>WS, CSRF, XSS, SOP, CORS, CSP… WTF?</description>
            <link>https://blog.flowthing.me/websocket-csrf</link>
            <content:encoded><![CDATA[
<p>Trying to find accurate information on how to properly secure a WebSocket endpoint from Cross-Site Request Forgery (CSRF) or Cross-Site Scripting (XSS) attacks is surprisingly difficult. Some of the information out there is incomplete, misleading, or just plain wrong.</p>
<p>In this article, I’ll attempt to provide a concise summary of what works and what doesn’t. I’ll try to make it an article I wish I’d have had available back when I first started researching this topic.</p>
<p>To achieve that, I’ll begin by giving a high-level introduction on some common CSRF and XSS mitigation strategies and explain how they relate to WebSockets.</p>
<p><strong>Disclaimer</strong>: I am <em>not</em> a security professional. Don’t take what I write here as gospel. If you spot any mistakes or outright falsehoods, please let me know.</p>
<p><strong>Edit</strong> (2020-08-26): An earlier version of this article incorrectly advised using an HTTP header (such as <code>X-CSRF-Token</code>) in the WebSocket handshake
request to pass the anti-forgery token from the client to the server. However,
<a href="https://github.com/thw0rted">@Thw0rted</a> pointed out that browsers do not allow you to set headers for the WebSocket handshake request. I amended this article to propose
sending the anti-forgery token in a query string instead —  although that
approach comes with its caveats (see the “Cross-Site Request Forgery”
section).</p>
<h2><a href="#same-origin-policy" aria-hidden="true" class="anchor" id="same-origin-policy"></a>Same Origin Policy</h2>
<p>The <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy">Same Origin Policy</a> (SOP) is a security mechanism built into modern web browsers. It stops scripts on one web page from accessing data on another web page.</p>
<p>Many sources mix up Cross-Origin Resource Sharing (CORS) with Same-Origin Policy (SOP). Often, when you see people talking about CORS, they actually mean SOP. CORS is a method for lifting some or all of the restrictions that SOP imposes.</p>
<p>For instance, if you open foo.com in your browser, SOP prevents JavaScript on that page from loading resources on bar.com or anywhere else.</p>
<p>You can try it out yourself:</p>
<ol>
<li>Open <a href="https://www.google.com">google.com</a>.</li>
<li>Open your browser’s developer console.</li>
<li>Type in this JavaScript snippet:</li>
</ol>
<pre><code><span class="source js"><span class="comment line double-slash js"><span class="punctuation definition comment js">//</span> Make an XMLHttpRequest on solita.fi
</span><span class="meta function-call js"><span class="variable function js">fetch</span><span class="meta group js"><span class="punctuation section group js">(</span><span class="string quoted single js"><span class="punctuation definition string begin js">&#39;</span>www.solita.fi<span class="punctuation definition string end js">&#39;</span></span></span><span class="meta group js"><span class="punctuation section group js">)</span></span></span><span class="punctuation accessor js">.</span><span class="meta function-call method js"><span class="variable function js">then</span><span class="meta group js"><span class="punctuation section group js">(</span>
  <span class="comment line double-slash js"><span class="punctuation definition comment js">//</span> Print the response into the console
</span>  <span class="meta function declaration js"><span class="punctuation section group begin js">(</span><span class="variable parameter function js">response</span><span class="punctuation section group end js">)</span><span class="meta function declaration js"> </span><span class="storage type function arrow js">=&gt;</span></span> <span class="meta block js"><span class="meta function-call method js"><span class="support type object console js">console</span><span class="punctuation accessor js">.</span><span class="support function console js">log</span><span class="meta group js"><span class="punctuation section group js">(</span><span class="variable other readwrite js">response</span></span><span class="meta group js"><span class="punctuation section group js">)</span></span></span>
</span></span><span class="meta group js"><span class="punctuation section group js">)</span></span></span><span class="punctuation terminator statement js">;</span>
</span></code></pre>
<p>You’ll get an error that looks something like this:</p>
<blockquote>
<p>Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at <a href="http://www.solita.fi/">www.solita.fi/</a>. (Reason: CORS request did not succeed).</p>
</blockquote>
<p>WebSockets, however, are not subject to Same Origin Policy. That means that if you have foo.com open in your browser, it will let you connect to a WebSocket endpoint at bar.com/ws. Open <a href="https://www.google.com">google.com</a> again and type this into your browser’s developer console:</p>
<pre><code><span class="source js"><span class="storage type js">var</span> <span class="variable other readwrite js">ws</span> <span class="keyword operator assignment js">=</span> <span class="meta instance constructor js"><span class="keyword operator word new js">new</span><span class="meta function-call constructor js"> <span class="variable type js">WebSocket</span><span class="meta group js"><span class="punctuation section group js">(</span><span class="string quoted double js"><span class="punctuation definition string begin js">&quot;</span>wss://echo.websocket.org<span class="punctuation definition string end js">&quot;</span></span></span><span class="meta group js"><span class="punctuation section group js">)</span></span></span></span><span class="punctuation terminator statement js">;</span>
<span class="meta function declaration js"><span class="support class js">ws</span><span class="punctuation accessor js">.</span><span class="meta property object js"><span class="entity name function js">onmessage</span></span> <span class="keyword operator assignment js">=</span> </span><span class="meta function declaration js"><span class="punctuation section group begin js">(</span><span class="variable parameter function js">event</span><span class="punctuation section group end js">)</span><span class="meta function declaration js"> </span><span class="storage type function arrow js">=&gt;</span></span> <span class="meta block js"><span class="meta function-call method js"><span class="support type object console js">console</span><span class="punctuation accessor js">.</span><span class="support function console js">log</span><span class="meta group js"><span class="punctuation section group js">(</span><span class="variable other object js">event</span><span class="punctuation accessor js">.</span><span class="meta property object js">data</span></span><span class="meta group js"><span class="punctuation section group js">)</span></span></span></span><span class="punctuation terminator statement js">;</span>

<span class="comment line double-slash js"><span class="punctuation definition comment js">//</span> Wait for a couple of seconds for the WebSocket connection to open.
</span><span class="variable other object js">ws</span><span class="punctuation accessor js">.</span><span class="meta function-call method js"><span class="variable function js">send</span><span class="meta group js"><span class="punctuation section group js">(</span><span class="string quoted double js"><span class="punctuation definition string begin js">&quot;</span>Hello, world!<span class="punctuation definition string end js">&quot;</span></span></span><span class="meta group js"><span class="punctuation section group js">)</span></span></span><span class="punctuation terminator statement js">;</span>
</span></code></pre>
<p>The text <code>Hello, world!</code> should appear in your console.</p>
<p>This means that unless you take extra steps to protect it, your WebSocket endpoint is vulnerable to CSRF attacks.</p>
<p>Here’s an example of how an attacker could exploit the lack of SOP enforcement on WebSocket connections:</p>
<ol>
<li>The attacker uses social engineering to lure you onto their nefarious web page at evil.com.</li>
<li>The attacker hopes you’re currently logged in to foo.com with the same browser that you used to open evil.com.</li>
<li>evil.com opens a WebSocket connection to foo.com/ws and steals your data.</li>
</ol>
<p>The way browsers work is that if you’re already logged in to foo.com and a script makes an <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a> on that domain, the browser sends your session cookies for foo.com with that request — even if the script makes the request from somewhere else than foo.com.</p>
<p>So, if you’re already logged in to foo.com with the same browser that you’re using to visit evil.com, the browser sends your session cookies for foo.com together with request evil.com makes on the WebSocket endpoint at foo.com/ws, allowing the attacker to bypass authentication for your site.</p>
<p>Next, I’ll go over some of the recommendations I’ve come across for protecting your WebSocket endpoint against CSRF attacks like this and comment on their effectiveness.</p>
<h2><a href="#cross-site-request-forgery" aria-hidden="true" class="anchor" id="cross-site-request-forgery"></a>Cross-Site Request Forgery</h2>
<p>Some sources advocate securing your WebSocket endpoint with an anti-CSRF token. For example, in <a href="https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html">Cross-Site WebSocket Hijacking (CSWSH)</a>, Christian Schneider writes:</p>
<blockquote>
<p>Use session-individual random tokens (like CSRF-Tokens) on the handshake request and verify them on the server.</p>
</blockquote>
<p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#The_WebSocket_Handshake">WebSocket handshake request</a> is an HTTP GET request on your WebSocket endpoint. For example, let’s say the address of your WebSocket endpoint is foo.com/ws. To open a CSRF-proof WebSocket connection, you’d make an HTTP GET request that looks something like this:</p>
<pre><code><span class="text plain">GET /ws?csrf-token=U1e7Zk8mxu9HWVAQQFIVGkR5n0bVE59pq+LYwwbl7YPTrGaF3FySb0hexZhxWlg+LT+DAtBiVvbg32x3 HTTP/1.1
Host: foo.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
</span></code></pre>
<p>The bit we’ll focus on here is the <code>?csrf-token=...</code> query string. It tells the server that the handshake request originates from a source that’s allowed to connect to the WebSocket endpoint. The server compares this token with its own, and if they match, the server sends the client a handshake response, accepting the connection request.</p>
<p>There’s an important caveat here, however: putting sensitive information into a query string might <a href="https://owasp.org/www-community/vulnerabilities/Information_exposure_through_query_strings_in_url">constitute a security risk in itself</a>. If you put the token in the query string, it will probably be stored in plain text at least in the HTTP server logs and your browser history. You should assess whether the risk of putting the anti-CSRF token in the query string outweighs the benefit in your case. Using the <code>Origin</code> header instead (see next section) doesn’t have this issue.</p>
<p>Anti-CSRF tokens, if you decide to use them, are effective against CSRF attacks. However, it might not be immediately clear how to safely deliver the token to the user of your WebSocket endpoint.</p>
<p>Providing it in the handshake response isn’t useful. At that point, the WebSocket connection is already open and there’s nothing left for the token to secure.</p>
<p>Here are two options for delivering the token to your users:</p>
<ol>
<li>
<p>Embed the token into one of the HTML pages of your web application.</p>
</li>
<li>
<p>Create a REST endpoint where your client can fetch the token.</p>
<p>For example, create an endpoint at foo.com/csrf that responds to an HTTP GET request with the anti-CSRF token.</p>
</li>
</ol>
<p>Imagine once more that you get lured onto evil.com. It tries to connect to your WebSocket endpoint at foo.com/ws. SOP doesn’t apply, so the browser allows it, and since you’re already logged in to foo.com, it sends your session cookies, too.</p>
<p>However, evil.com can’t make an XMLHttpRequest to fetch the anti-CSRF token from the HTML page or the REST endpoint at foo.com because SOP prevents it. Even if the anti-CSRF token is in the session cookie, the attacker can’t read the value of the cookie and put it where the server expects it to be. This makes anti-CSRF tokens effective against CSRF attacks.</p>
<p>Note, though, that all of the above only applies when browsers adhere to SOP. There is a mechanism called <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">Cross-Origin Resource Sharing</a> (CORS) that allows you to relax Same Origin Policy. It allows you to set HTTP headers that allow scripts on other web pages to load resources on your web page.</p>
<p>Therefore, whether you deliver the anti-CSRF token embedded into an HTML page or via a separate GET request, you must make sure that your site does not use CORS headers that allow cross-origin requests to those resources. Otherwise evil.com will be able to retrieve your anti-CSRF token and use it to connect to your WebSocket endpoint.</p>
<p>There’s much more to be said about CSRF attacks and anti-CSRF tokens. To get a more complete picture, see <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet">OWASP’s Cross-Site Request Forgery Prevention Cheat Sheet</a>.</p>
<h2><a href="#the-origin-header" aria-hidden="true" class="anchor" id="the-origin-header"></a>The Origin Header</h2>
<p>An alternative to using an anti-CSRF token is to use the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin"><code>Origin</code> HTTP header</a>. Every request that browsers make on one web page that targets another web page include the <code>Origin</code> header. As per its name, it contains the <em>origin</em> of the request. The origin comprises the scheme, hostname, and port of the source of the request.</p>
<p>For example, if a browser makes a request from evil.com:8080/bar to foo.com/ws, <code>Origin</code> looks like this:</p>
<pre><code><span class="text plain">GET foo.com/ws HTTP/1.1
…
Origin: evil.com:8080/bar
</span></code></pre>
<p>To use <code>Origin</code> as an anti-CSRF mechanism, you can check whether the value of <code>Origin</code> matches one of the whitelisted origins in your request handler on the server. If it doesn’t, the server must disallow the request.</p>
<p>There appears to be some confusion on whether an attacker can simply spoof <code>Origin</code> to conduct a CSRF attack. For example, a <a href="https://devcenter.heroku.com/articles/websocket-security#origin-header">Heroku article on WebSocket security</a> says this about the <code>Origin</code> header:</p>
<blockquote>
<p>However, remember that the Origin header is essentially advisory: non-browser clients can easily set the Origin header to any value, and thus “pretend” to be a browser.</p>
</blockquote>
<p>It’s true that non-browser clients (such as cURL) can “pretend to be a browser” insofar as they can spoof the <code>Origin</code> (and any other) headers. <code>Origin</code> is nonetheless a valid anti-CSRF mechanism. Remember how CSRF attacks can bypass authentication: if you’re already logged in to foo.com in your browser, the browser bundles your session cookies with all XMLHttpRequests, regardless of where they originate.</p>
<p>A non-browser client, however, cannot access the session cookies stored in your browser. Even if the attacker spoofs <code>Origin</code>, their request will be denied because they’re not authenticated.</p>
<p>Conversely, browsers control the <code>Origin</code> header. An attacker cannot set the value of <code>Origin</code> with JavaScript such that the value they set actually reaches your web server.</p>
<p>Using <code>Origin</code> can be a simpler way to prevent CSRF requests. There’s a downside to checking <code>Origin</code>, however: if you run many instances of the same website or your site is accessible via multiple different addresses, you’ll have to configure the <code>Origin</code> check to account for all of those addresses.</p>
<h2><a href="#content-security-policy" aria-hidden="true" class="anchor" id="content-security-policy"></a>Content Security Policy</h2>
<p><a href="https://developers.google.com/web/fundamentals/security/csp/">Content Security Policy</a> (CSP) is a mechanism for preventing Cross-Site Scripting (XSS) attacks. Essentially, CSP allows you to set rules that say:</p>
<blockquote>
<p>While you’re on this web page, you’re only allowed to load scripts and styles from this set of sources.</p>
</blockquote>
<p>There are two ways to use CSP:</p>
<ul>
<li>Set the <code>Content-Security-Policy</code> header in your HTTP response</li>
<li>Use the CSP <code>meta</code> element in your HTML</li>
</ul>
<p>Some sources advocate using CSP to secure your WebSocket endpoints. For example, <a href="https://gist.github.com/subudeepak/9897212#websockets---an-introduction">WebSockets - An Introduction</a> says that setting <code>Content-Security-Policy</code> to <code>connect-src ‘self’</code> “prevents webSockets [sic] requests from any place but the current server.”.</p>
<p>This is not true, however. CSP does <em>not</em> prevent evil.com from loading anything at all on foo.com. It works the other way around: it inhibits foo.com/ws from loading anything on other web pages, if you tell it to.</p>
<p>With regard to WebSockets, the only type of attack CSP can prevent is one where an attacker manages to inject JavaScript into foo.com that tries to open a WebSocket connection to a server the attacker controls.</p>
<p>Therefore, while certainly a valuable security mechanism, CSP is not effective against CSRF attacks.</p>
<p>For more information on CSP, see <a href="https://developers.google.com/web/fundamentals/security/csp/">Content Security Policy on MDN</a>.</p>
<h2><a href="#conclusions" aria-hidden="true" class="anchor" id="conclusions"></a>Conclusions</h2>
<p>To secure your WebSocket endpoint against CSRF attacks, arguably the best option is to check the <code>Origin</code> header of every WebSocket handshake request. If you cannot check the <code>Origin</code> header, using an anti-CSRF token is also an option. Note, however, that that option <a href="https://owasp.org/www-community/vulnerabilities/Information_exposure_through_query_strings_in_url">might have security implications</a>.</p>
<p>If you choose to use an anti-CSRF token, deliver it to your users such that cross-origin browser scripts cannot acccess it: either embed it into your HTML page or allow users to fetch it with a separate GET request. In both cases, make sure your CORS headers disallow requests to that resource.</p>
<p>While using a Content Security Policy on your site is effective against XSS attacks, it does nothing to prevent someone from connecting to your WebSocket endpoint. It is therefore not a valid anti-CSRF strategy.</p>
<p>As an alternative to WebSockets, you could consider <a href="https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events">Server-Sent Events</a> (SSE). Unlike WebSockets, they use the HTTP protocol, and are therefore subject to SOP just like regular XMLHttpRequests.</p>
<p><small>This article was originally published in <a href="https://dev.solita.fi/2018/11/07/securing-websocket-endpoints.html">the Solita dev blog</a>.</small></p>
<h2><a href="#acknowledgements" aria-hidden="true" class="anchor" id="acknowledgements"></a>Acknowledgements</h2>
<p>Thanks to Timo Mihaljov for his insights on CSRF and CSP.</p>

]]></content:encoded>
        </item>
        <item>
            <pubDate>2015-11-07</pubDate>
            <title>Counting nodes quickly with XSLT keys</title>
            <description>Use xsl:keys to go faster than xsl:number.</description>
            <link>https://blog.flowthing.me/xslt-keys</link>
            <content:encoded><![CDATA[
<p>Pretty much everyone who has written any non-trivial XSLT code knows that the answer to most XSLT performance problems is keys. In this article, we’ll first take a look at how XSLT keys work. Then we’ll move onto an example on how to use keys to count things fast.</p>
<p><em>Note</em>: You need XPath 2 to use the technique in this article.</p>
<p><em>For a tl;dr, jump to the <a href="#conclusion">Conclusion</a></em>.</p>
<h2><a href="#an-introduction-to-keys" aria-hidden="true" class="anchor" id="an-introduction-to-keys"></a>An introduction to keys</h2>
<p>Keys are a mechanism that build an index from a value to a set of nodes in the XML tree. The term <em>key</em> might be a bit confusing. You can usually think of it as a key-value pair like any other (map, hash, dictionary, table, what have you). So maybe it should have been called <em>index</em> instead of <em>key</em>.</p>
<p>Here’s a simple example of using a key:</p>
<pre><code><span class="text xml"><span class="comment block xml"><span class="punctuation definition comment begin xml">&lt;!--</span> input.xml <span class="punctuation definition comment end xml">--&gt;</span></span>

<span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag localname xml">sect</span> <span class="entity other attribute-name localname xml">id</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>s2<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">&gt;</span></span>
  <span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag localname xml">sect</span> <span class="entity other attribute-name localname xml">id</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>s2-1<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">&gt;</span></span> ... <span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;/</span><span class="entity name tag localname xml">sect</span><span class="punctuation definition tag end xml">&gt;</span></span>
  <span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag localname xml">sect</span> <span class="entity other attribute-name localname xml">id</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>s2-2<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">&gt;</span></span> ... <span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;/</span><span class="entity name tag localname xml">sect</span><span class="punctuation definition tag end xml">&gt;</span></span>
<span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;/</span><span class="entity name tag localname xml">sect</span><span class="punctuation definition tag end xml">&gt;</span></span>

<span class="comment block xml"><span class="punctuation definition comment begin xml">&lt;!--</span> stylesheet.xsl <span class="punctuation definition comment end xml">--&gt;</span></span>

<span class="comment block xml"><span class="punctuation definition comment begin xml">&lt;!--</span>
Create a key called &quot;id&quot;.
Put every element that has an @id attribute in it.
Use the value of the @id attribute as the, well, *key* of the entry.
<span class="punctuation definition comment end xml">--&gt;</span></span>
<span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">key</span> <span class="entity other attribute-name localname xml">name</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>id<span class="punctuation definition string end xml">&quot;</span></span> <span class="entity other attribute-name localname xml">match</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>*[@id]<span class="punctuation definition string end xml">&quot;</span></span> <span class="entity other attribute-name localname xml">use</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>@id<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">/&gt;</span></span>

<span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">template</span> <span class="entity other attribute-name localname xml">match</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>/<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">&gt;</span></span>
  <span class="comment block xml"><span class="punctuation definition comment begin xml">&lt;!--</span>
  Fetch the element with the @id attribute value &quot;s2-2&quot;, no matter
  where in the input document it is.
  <span class="punctuation definition comment end xml">--&gt;</span></span>
  <span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">sequence</span> <span class="entity other attribute-name localname xml">select</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>key(&#39;id&#39;, &#39;s2-2&#39;)<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">/&gt;</span></span>
<span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;/</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">template</span><span class="punctuation definition tag end xml">&gt;</span></span>
</span></code></pre>
<p>You can visualize the <code>id</code> key like this:</p>
<pre><code><span class="text plain">&quot;s2&quot;   =&gt; &lt;sect id=&quot;s2&quot;/&gt;
&quot;s2-1&quot; =&gt; &lt;sect id=&quot;s2-1&quot;/&gt;
&quot;s2-2&quot; =&gt; &lt;sect id=&quot;s2-2&quot;/&gt;
</span></code></pre>
<p>Creating a key takes a small amount of time. Once created, though, accessing nodes in the key is usually much faster than doing it without keys.</p>
<p>For example, to get to <code>&lt;sect id=&quot;s2-2&quot;&gt;</code> without keys, you’d do something like this:</p>
<pre><code><span class="text xml"><span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">sequence</span> <span class="entity other attribute-name localname xml">select</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>//sect[@id eq &#39;s2-2&#39;]<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">/&gt;</span></span>
</span></code></pre>
<p>If you do that, your XSLT processor will have to sift through the entire XML tree to find the element whose ID is <code>s2-2</code>. If you use the key, the processor only needs to look up the value <code>s2-2</code> in the index. That’s <em>much</em> faster.</p>
<p>Keys are also lazy. That means they’re only created when you first call the <code>key()</code> function on a key. That way there’s no performance penalty if you create a key but don’t end up using it.</p>
<h2><a href="#using-keys-to-count-things-quickly" aria-hidden="true" class="anchor" id="using-keys-to-count-things-quickly"></a>Using keys to count things quickly</h2>
<p>It’s pretty common to have to count things in your XSLT code.</p>
<p>For example, take <a href="http://sourceforge.net/p/docbook/code/HEAD/tree/trunk/defguide/zh/source/defguide.xml">this big DocBook XML file</a>. It has many tables like this:</p>
<pre><code><span class="text xml"><span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag localname xml">informaltable</span> <span class="entity other attribute-name localname xml">role</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>elemsynop<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">&gt;</span></span> ... <span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;/</span><span class="entity name tag localname xml">informaltable</span><span class="punctuation definition tag end xml">&gt;</span></span>
</span></code></pre>
<p>Say we want to number all <code>&lt;informaltable&gt;</code> elements that have <code>role=&quot;elemsynop&quot;</code>.</p>
<p>The naïve way to do that might be something like this:</p>
<pre><code><span class="text xml"><span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">template</span> <span class="entity other attribute-name localname xml">match</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>informaltable[@role eq &#39;elemsynop&#39;]<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">&gt;</span></span>
  <span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">value-of</span> <span class="entity other attribute-name localname xml">select</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>
    count(preceding::informaltable[@role eq &#39;elemsynop&#39;]) + 1
  <span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">/&gt;</span></span>
<span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;/</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">template</span><span class="punctuation definition tag end xml">&gt;</span></span>

<span class="comment block xml"><span class="punctuation definition comment begin xml">&lt;!--</span>
*** Average execution time over last 25 runs: 5.071908s (5071.908796ms)
<span class="punctuation definition comment end xml">--&gt;</span></span>
</span></code></pre>
<p>That works, but it’s pretty slow. That’s because every time the XSLT processor sees an <code>&lt;informaltable&gt;</code> element, it will need to walk the entire tree backwards to find all previous <code>&lt;informaltable&gt;</code> elements.</p>
<p>The most common way to count things is probably the <code>&lt;xsl:number&gt;</code> element. That’s what it is designed for, after all. Here’s an example:</p>
<pre><code><span class="text xml"><span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">template</span> <span class="entity other attribute-name localname xml">match</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>informaltable[@role eq &#39;elemsynop&#39;]<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">&gt;</span></span>
  <span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">number</span> <span class="entity other attribute-name localname xml">count</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>informaltable[@role eq &#39;elemsynop&#39;]<span class="punctuation definition string end xml">&quot;</span></span>
              <span class="entity other attribute-name localname xml">level</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>any<span class="punctuation definition string end xml">&quot;</span></span> <span class="entity other attribute-name localname xml">from</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>/<span class="punctuation definition string end xml">&quot;</span></span> <span class="entity other attribute-name localname xml">format</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>1<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">/&gt;</span></span>
<span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;/</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">template</span><span class="punctuation definition tag end xml">&gt;</span></span>

<span class="comment block xml"><span class="punctuation definition comment begin xml">&lt;!--</span>
*** Average execution time over last 25 runs: 37.428838s (37428.838434ms)
<span class="punctuation definition comment end xml">--&gt;</span></span>
</span></code></pre>
<p>That also works, but is actually even slower than the naïve count-preceding approach. It’s the slowest method by far. It’s not this slow in every case, though, so if you need <a href="http://saxonica.com/html/documentation/xsl-elements/number.html">any of its useful features</a>, you should probably stick with <code>&lt;xsl:number&gt;</code>.</p>
<p>The fastest method for counting nodes with XSLT that I know of is to create a key and count nodes in the key. Behold:</p>
<pre><code><span class="text xml"><span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">key</span> <span class="entity other attribute-name localname xml">name</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>informaltable-by-role<span class="punctuation definition string end xml">&quot;</span></span>
         <span class="entity other attribute-name localname xml">match</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>informaltable<span class="punctuation definition string end xml">&quot;</span></span> <span class="entity other attribute-name localname xml">use</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>@role<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">/&gt;</span></span>

<span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">template</span> <span class="entity other attribute-name localname xml">match</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>informaltable[@role eq &#39;elemsynop&#39;]<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">&gt;</span></span>
  <span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">value-of</span> <span class="entity other attribute-name localname xml">select</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>
    count(key(&#39;informaltable-by-role&#39;, @role)
          [. <span class="constant character entity xml"><span class="punctuation definition constant xml">&amp;</span>lt<span class="punctuation definition constant xml">;</span></span><span class="constant character entity xml"><span class="punctuation definition constant xml">&amp;</span>lt<span class="punctuation definition constant xml">;</span></span> current() or . is current()])
  <span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">/&gt;</span></span>
<span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;/</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">template</span><span class="punctuation definition tag end xml">&gt;</span></span>

<span class="comment block xml"><span class="punctuation definition comment begin xml">&lt;!--</span>
*** Average execution time over last 25 runs: 440.748063ms
<span class="punctuation definition comment end xml">--&gt;</span></span>
</span></code></pre>
<p>This way, we only have to walk the tree once: when compiling the <code>informaltable-by-role</code> key. The information about the relative position of each node is saved when creating the key . That’s why we don’t need to walk the tree any more when counting the tables.</p>
<p>You can read the code that counts the tables as:</p>
<blockquote>
<p>Count every entry in the <code>informaltable-by-role</code> key that either:</p>
<ul>
<li>occurs in the tree before the current node, or</li>
<li><strong>is</strong> the current node.</li>
</ul>
</blockquote>
<p>The weird <code>&amp;lt;&amp;lt;</code> thing is the XPath 2 <a href="http://www.w3.org/TR/xpath20/#id-node-comparisons">node comparison operator</a>. It’s really <code>&lt;&lt;</code>, which looks much nicer. You can’t use angle brackets in XPath expressions in XSLT, though, so we need to escape them.</p>
<p>It is small sacrifice in readability. However, since it’s around 91–99% faster than the traditional methods, it’s probably worth the tradeoff.</p>
<h2><a href="#restricting-the-scope" aria-hidden="true" class="anchor" id="restricting-the-scope"></a>Restricting the scope</h2>
<p>When counting things like this, you often need to count only a certain subset of elements. You might need to count only those elements that are descendants of a certain element, for instance.</p>
<p>You can do that with keys, too. The <code>key()</code> function also takes an optional third argument. You can use it to specify the root node for your search.</p>
<p>For example, if you wanted to count only those <code>&lt;informaltable role=&quot;elemsynop&quot;&gt;</code> elements that are inside <code>&lt;refentry id=&quot;abbrev.element&quot;&gt;</code>, you could do this:</p>
<pre><code><span class="text xml"><span class="comment block xml"><span class="punctuation definition comment begin xml">&lt;!--</span> Get the element with the @id &#39;abbrev.element&#39;. <span class="punctuation definition comment end xml">--&gt;</span></span>
<span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">variable</span> <span class="entity other attribute-name localname xml">name</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>top<span class="punctuation definition string end xml">&quot;</span></span> <span class="entity other attribute-name localname xml">select</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>key(&#39;id&#39;, &#39;abbrev.element&#39;)<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">/&gt;</span></span>

<span class="comment block xml"><span class="punctuation definition comment begin xml">&lt;!--</span>
Count all &lt;informaltable role=&quot;elemsynop&quot;&gt; elements that are descendants of the
element with the @id &#39;abbrev.element&#39;.
<span class="punctuation definition comment end xml">--&gt;</span></span>
<span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">value-of</span> <span class="entity other attribute-name localname xml">select</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>count(key(&#39;informaltable-by-role&#39;, &#39;elemsynop&#39;, $top))<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">/&gt;</span></span>
</span></code></pre>
<h2><a href="#conclusion" aria-hidden="true" class="anchor" id="conclusion"></a>Conclusion</h2>
<p>If you’re using XSLT and you need to count nodes in the XML file, instead of using the <code>preceding::</code> axis or the <code>&lt;xsl:number&gt;</code> element, consider creating a key and counting the nodes in the key:</p>
<pre><code><span class="text xml"><span class="comment block xml"><span class="punctuation definition comment begin xml">&lt;!--</span>
Create an index from the @type attribute of each &lt;pokemon&gt; element that has one
to the element itself.
<span class="punctuation definition comment end xml">--&gt;</span></span>
<span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">key</span> <span class="entity other attribute-name localname xml">name</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>pokemon<span class="punctuation definition string end xml">&quot;</span></span> <span class="entity other attribute-name localname xml">use</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>@type<span class="punctuation definition string end xml">&quot;</span></span> <span class="entity other attribute-name localname xml">match</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>pokemon[@type]<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">/&gt;</span></span>

<span class="comment block xml"><span class="punctuation definition comment begin xml">&lt;!--</span>
Count all &lt;pokemon type=&quot;lightning&quot;&gt; elements that occur in the tree before the
current node, plus the current element.
<span class="punctuation definition comment end xml">--&gt;</span></span>
<span class="meta tag xml"><span class="punctuation definition tag begin xml">&lt;</span><span class="entity name tag namespace xml">xsl</span><span class="entity name tag xml"><span class="punctuation separator namespace xml">:</span></span><span class="entity name tag localname xml">value-of</span> <span class="entity other attribute-name localname xml">select</span><span class="punctuation separator key-value xml">=</span><span class="string quoted double xml"><span class="punctuation definition string begin xml">&quot;</span>
  count(key(&#39;pokemon&#39;, &#39;lightning&#39;)[. <span class="constant character entity xml"><span class="punctuation definition constant xml">&amp;</span>lt<span class="punctuation definition constant xml">;</span></span><span class="constant character entity xml"><span class="punctuation definition constant xml">&amp;</span>lt<span class="punctuation definition constant xml">;</span></span> current() or . is current()])
<span class="punctuation definition string end xml">&quot;</span></span><span class="punctuation definition tag end xml">/&gt;</span></span>
</span></code></pre>
<p>It’s faster.</p>

]]></content:encoded>
        </item>

    </channel>
</rss>
