<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://danielefilaretti.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://danielefilaretti.com/" rel="alternate" type="text/html" /><updated>2026-11-10T07:27:58+00:00</updated><id>https://danielefilaretti.com/feed.xml</id><title type="html">Dan’s website</title><subtitle>Computer science, software and music</subtitle><author><name>Daniele Filaretti</name></author><entry><title type="html">What is static analysis, really?</title><link href="https://danielefilaretti.com/what-is-static-analysis/" rel="alternate" type="text/html" title="What is static analysis, really?" /><published>2026-11-08T00:00:00+00:00</published><updated>2026-11-08T00:00:00+00:00</updated><id>https://danielefilaretti.com/what-is-static-analysis</id><content type="html" xml:base="https://danielefilaretti.com/what-is-static-analysis/"><![CDATA[<p>Many developers have come across the term “static analysis” and related ones such as “soundness” and “program semantics”, but what they mean and how they fit together isn’t always clear (or at least it wasn’t to me).</p>

<p>This post introduces the basic terminology and the intuition behind it.
We start with what static analysis can offer and how it addresses the limitations
of testing and code auditing. We then explore its limits, why undecidability
makes approximation necessary, and the tradeoffs involved in designing useful
analyses, explaining concepts such as soundness, completeness and precision along the way.</p>

<p>This blog post is adapted from material in my <a href="https://danielefilaretti.com/assets/downloads/papers/Filaretti-D-PhD-2016.pdf">PhD thesis</a>, where you can find more
details if desired.</p>

<h2 id="the-limitations-of-testing-and-code-auditing">The limitations of testing and code auditing</h2>

<p>Common practices for software assurance are <em>testing</em> and
code <em>auditing</em>.</p>

<p>At its core, testing consists of <em>running your program on a set of inputs</em> and making
sure it behaves as expected.
When a test fails, a developer investigates the cause and fixes it before re-running the test
suite (perhaps adding more tests based on insights from debugging, improving confidence in the program’s correctness).</p>

<p>The nice thing about testing is that if it finds a bug, then it’s a real bug - there are no
false alarms!
The downside is that testing is <em>not exhaustive</em>: in general, no matter
how many tests are executed, testing will fail to explore all the possible
execution paths a program may take at runtime.</p>

<p>Code auditing essentially consists in convincing yourself
(or your client/boss/coworker) that the code is correct.
An obvious advantage over testing is that when reading code, humans can generalise, infer facts and make connections, which help them reason about multiple executions at once.</p>

<p>Like testing, however, code auditing can be time consuming and is, ultimately, still non exhaustive
(no matter how smart and focused the person reviewing the code is, there will always
be a chance of something being missed).</p>

<p>Now, this may or may not be a problem, depending on the application domain.
I’m no game developer, but I suppose if a bug causes a pixel on the screen to occasionally go black for a fraction of a second during a game,
well, that’s perhaps no big deal. Or if a web page occasionally
doesn’t load and the user has to refresh (provided no important data is lost!), it’s no big deal either, I suppose.</p>

<p>In audio software, however,
that same kind of glitch can be unacceptable: even a single wrong
audio sample can cause a click (and trust me, nobody wants to hear that on stage
or in a recording). In a smart contract, a bug can be exploited to drain all funds in the protocol
(as has happened several times, with millions of dollars lost), and a bug in a website can leave it open to attacks that could expose or destroy users’ data.</p>

<p>This should make it clear that in several domains, investigating techniques  to consider as many execution paths as possible
(or, indeed, all of them) can actually be pretty useful (and not just an academic exercise).</p>

<h2 id="hello-static-analysis">Hello static analysis</h2>

<p><em>Static analysis</em> is one such techniques.
It consists of analysing a program automatically, <em>without running it</em>.</p>

<p>In this, it resembles code auditing, but instead of
being performed by a human, the review is performed by a program, the static analyser.
This has an important advantage: static analysis is able to provide higher coverage than testing
and code auditing, and in some cases it can even explore <em>all possible execution paths</em>
in a program and  <em>guarantee</em> the absence of errors.</p>

<p>If you think this sounds too good to be true, however, you’re not wrong.
The benefits above, in fact, come with a price: static analysers can only check for limited (and generally
simple) properties; they may miss errors, issue false alarms, and they can also be time-consuming
and resource intensive. We’ll explore this more
in the remainder of this post.</p>

<h2 id="the-nature-of-static-analysis-and-its-limitations">The nature of static analysis (and its limitations)</h2>

<p>A static analysis is an algorithm which takes a program as input and attempts to provide an
answer to a question about the set of its possible runtime behaviours
(often called its <em>semantics</em>). Typical questions include:</p>

<ul>
  <li>is every user input sanitised before it flows into a sensitive sink?</li>
  <li>is every SQL query in the program constructed using only trusted input?</li>
  <li>is every array index in bounds?</li>
  <li>is every dereferenced pointer non-null?</li>
  <li>can division-by-zero occur?</li>
  <li>is this smart contract vulnerable to <em>reentrancy</em> attacks?</li>
  <li>can funds get permanently locked in the smart contract?</li>
</ul>

<p>Unfortunately, answering those questions exactly, automatically and for any program is <em>undecidable</em>.</p>

<p>To motivate this, we need to take a step back and consider the
“canonical” static analysis problem: the <em>halting problem</em>. Let <code class="language-plaintext highlighter-rouge">P</code> be an arbitrary program. Does <code class="language-plaintext highlighter-rouge">P</code>
terminate on all inputs? Can we design an algorithm that answers that question for any program?
Unfortunately, the answer is no: it can be shown that the existence of such an algorithm leads to logical
contradictions, and therefore we must conclude that
the algorithm itself cannot exist. I’ve written about this topic in a <a href="https://danielefilaretti.com/Halting-Problem/">previous blog post</a> if
you’d like to know more.</p>

<p>Now, it is also possible to show that many interesting static analysis questions, including
the examples above, are <em>at least as hard as the halting problem</em> and are therefore
undecidable too.</p>

<p>We won’t go into the details here (you can find more in
chapter 4 of my <a href="https://danielefilaretti.com/assets/downloads/papers/Filaretti-D-PhD-2016.pdf">PhD thesis</a>), but
the key idea is this: imagine we have such an analyzer
that is able to answer one of these
questions <em>exactly</em> and  for any program, accounting for all possible inputs; then, it can be shown that
this analyzer could also
be used to solve the halting problem; in other words, the analysis and the halting problem are
somehow “equivalent in difficulty”.
But since we already know that the halting problem cannot
be solved, then we must conclude that also our analysis cannot exist.</p>

<p>Shall we give up then? No!
Those limitations are just telling us that <em>exact</em> static analysis is impossible, but there’s still plenty of room for <em>useful</em> static analysis.
By accepting some approximation and carefully navigating some key design tradeoffs, we can build analyses that are actually useful in
practice (althugh not exact/perfect).</p>

<h2 id="design-tradeoffs">Design tradeoffs</h2>

<p>So what does this approximation look like in practice?
It usually manifests itself as a combination of the following:</p>

<ul>
  <li>the analyser might not terminate</li>
  <li>the analyser might raise false alarms (<em>false positives</em>)</li>
  <li>the analyser might miss errors and claim the program is “safe” when it’s not (<em>false
negatives</em>)</li>
</ul>

<p>The undecidability results briefly discussed above say that there <em>must</em> be some approximation;
as the analysis designers, what we can do is carefully tune the key aspects of the analysis algorithm in order to influence <em>how</em> that approximation
manifests itself.</p>

<p>For starters,
non-terminating analyses are generally avoided for practical reasons (termination is
usually enforced by introducing a loss of information).
Then, we can also choose whether we want only false positives, only false negatives, or a combination of both.
Balancing false positives and false
negatives leads us to the concepts of <em>soundness</em> and <em>completeness</em>, which we discuss next, together with another important tradeoff: <em>precision</em> versus <em>scalability</em>.</p>

<h3 id="soundness-vs-completeness">Soundness vs completeness</h3>

<p>A <em>sound</em> (or correct) static analysis proves true facts about the program semantics (intended as the
set of all possible runtime behaviours). For example, if a sound
analyser says that there are no out-of-bounds array accesses in the program, then the
user can be sure that the program will not exhibit out-of-bounds accesses at runtime.</p>

<p>In general, if a sound analysis says property P is true about a program’s semantics, then P is actually
true. However, the fact that P is true does not necessarily imply that
the analysis claims it is true. For example, a program might be free from division-by-zero
errors (in the sense that there is no execution path that leads to a division where the denominator
is zero) but the analysis might fail to discover that and instead raise a <em>false alarm</em>.</p>

<p><img src="/assets/pics/static-analysis/sound.png" alt="A sound analysis" width="350" style="display: block; margin-left: auto; margin-right: auto;" /></p>

<p>On the other end of the spectrum are <em>complete</em> analyses. If
property P about the semantics of the program is true, a complete analysis claims that P is true.
For example, if the program is free from index-out-of-bounds errors, then the analysis will be able
to detect it, and therefore there are no false alarms. On the other hand, if the analysis says property P is true, there is no guarantee that it will be true. In other
words, a complete analysis might <em>miss errors</em>.</p>

<p><img src="/assets/pics/static-analysis/complete.png" alt="Complete analysis" width="350" style="display: block; margin-left: auto; margin-right: auto;" /></p>

<p>In summary, if a sound analysis finds a bug, it might be a false alarm, but if it
claims the program is error-free, then it must be error-free. With a complete analysis,
if it claims the program is safe, that might not be true, but if it finds a bug, then that bug
must be real.</p>

<p>Finally, a <em>sound and complete</em> analysis is able to verify the absence of errors
without producing false alarms.
A property P about a program holds if and only if the analysis claims the fact.</p>

<p><img src="/assets/pics/static-analysis/sound-and-complete.png" alt="A sound and complete analysis" width="350" style="display: block; margin-left: auto; margin-right: auto;" /></p>

<p>However, realising a sound and complete analyser
would amount to solving the halting problem and therefore is impossible!</p>

<p>In practice, sound analyses
are used when the primary goal is guaranteeing the <em>absence of bugs</em> (for example in critical
embedded applications), while complete analyses are used when the priority is on <em>finding real bugs</em>
(such as in non-critical application development).</p>

<p>Many interesting analyses try to reach the sweet
spot of finding many bugs with few false positives by being neither sound nor complete.</p>

<h3 id="precision-vs-scalability">Precision vs scalability</h3>

<p>Another design tradeoff in static analysis is between <em>precision and scalability</em>. A precise analysis
models program behaviour very closely in order to reduce the number of false alarms (in the case of
a sound analysis) or to reduce the number of missed bugs (in the case of a complete analysis). A
scalable analysis is able to analyse large codebases within reasonable time and space resources.</p>

<p>Unfortunately, very precise analyses tend to have greater algorithmic complexity, making them
less efficient and less scalable (think about it: the most precise analysis of all would be… executing the actual program on all inputs, which isn’t feasible in practice). On the other hand, a very efficient analysis may be less
precise, producing more false positives (or negatives).</p>

<p>Again, we cannot achieve absolute precision for every program.
If we increase the precision of a
sound analysis we reduce the number of false positives. However, we also get progressively closer to
a sound analysis which does not produce any false positives, which is undecidable.</p>

<p>Similarly, if we
progressively increase the precision of a complete analysis we’ll end up catching exactly all real
bugs and therefore we’ll have obtained, again,  an undecidable analysis.</p>

<p>Balancing these tradeoffs is part art and part science, and the right
combination also depends on the particular language being analysed, its usage and the average
size of programs in the chosen application domain.</p>

<p>But, ultimately, what is a static analyzer trying to do? We provide an intuition next.</p>

<h2 id="approximating-the-set-of-all-possible-runtime-behaviours">Approximating the set of <em>all</em> possible runtime behaviours</h2>

<p>Imagine we could run a program on every possible combination of inputs and record every
state visited during every execution. The set of all these reachable states is usually referred to as the
<em>collecting semantics</em> of the program.</p>

<p>Suppose we now wanted to check that the program never divides by zero or accesses an array out of
bounds. In principle, we could just inspect every state in this set and report an alarm if any of
them exhsibits the “bad behaviour”. If none does, the program is safe with respect to the
property we are checking.</p>

<p>The catch, as we saw earlier, is that a program may have infinitely many inputs and executions
that never terminate. Computing its collecting semantics exactly is therefore impossible in
general. Instead, static analysers attempt to compute a suitable <em>approximation</em> (which we call the <em>abstract semantics</em>) and then compare it with (a representation of) the set of erroneus states.</p>

<p>If the intersection between those two
sets is empty, the program is considered safe. Otherwise the analyser reports a warning. In this
setting, the notions of soundness, completeness, false positives and false negatives can be understood in terms of <em>overapproximation</em> and <em>underapproximation</em> of the program semantics.</p>

<p>A sound analysis computes an <em>overapproximation</em>, that is a superset of the program semantics, as
shown intuitively in this diagram:</p>

<p><img src="/assets/pics/static-analysis/01-false-positive.png" alt="An overapproximation producing a false alarm" width="350" style="display: block; margin-left: auto; margin-right: auto;" /></p>

<p>Here, the <em>abstract semantics</em> <code class="language-plaintext highlighter-rouge">Behaviours#</code> (i.e. the set of program behaviours calculated by the static analyser) intersects the set of erroneous
behaviours, so the analysis produces an alarm. However, it is a false alarm, since the
actual program semantics, <code class="language-plaintext highlighter-rouge">Behaviours</code>, is disjoint from the “erroneous zone”. The analysis had
considered a spurious behaviour, one the program will never exhibit
at runtime.</p>

<p>Increasing precision can be understood as building a “better” and “smaller” approximation of
<code class="language-plaintext highlighter-rouge">Behaviours</code>, still a superset of it but “small enough” to avoid intersecting the dangerous zone:</p>

<p><img src="/assets/pics/static-analysis/02-no-false-positive.png" alt="A more precise overapproximation avoiding a false alarm" width="350" style="display: block; margin-left: auto; margin-right: auto;" /></p>

<p>In this case, the analysis has proved the program safe with no
false alarms.</p>

<p>But, as seen before, precision needs to be traded oﬀ with scalability.
In this last example, the approximation was still coarse enough to be easily
computable (intuitively expressed by the simple shape of <code class="language-plaintext highlighter-rouge">Behaviours#</code>) yet it was
precise enough to prove the property of interest
without false alarms.</p>

<p>Intuitively, we could now make the abstraction even more precise:</p>

<p><img src="/assets/pics/static-analysis/03-very-precise.png" alt="An even more precise overapproximation" width="350" style="display: block; margin-left: auto; margin-right: auto;" /></p>

<p>but that would likely make the analysis less efficient while providing little advantage: the coarser
abstraction of the previous figure was already “good enough”
(and much simpler to calculate).</p>

<p>In other
words, sometimes <em>the cost of a more precise abstraction outweighs the benefits</em>. The goal is
to design an abstraction coarse enough to be easily computed while being
precise enough to minimise false positives for the property
and domain being analysed.</p>

<p>Dually, complete analyses can be understood as underapproximations, that is subsets, of the
program semantics:</p>

<p><img src="/assets/pics/static-analysis/04-underapprox.png" alt="An underapproximation of program behaviours" width="350" style="display: block; margin-left: auto; margin-right: auto;" /></p>

<p>Note that in this case, there is no possibility
for false alarms, since <code class="language-plaintext highlighter-rouge">Behaviours#</code> is a subset of <code class="language-plaintext highlighter-rouge">Behaviours</code> which is the set of actual program
behaviours. However, for the very same reason, the analysis might miss real bugs.</p>

<p>To improve a complete analysis, we need to capture more behaviours. However, capturing more behaviours generally makes the analysis less efficient and less scalable.
The same considerations about overapproximating analyses apply to underapproximating
analyses.</p>

<h2 id="so-which-tradeoff-should-we-choose">So which tradeoff should we choose?</h2>

<p>We should point out that sound analyses are not necessarily better than
unsound ones.</p>

<p>Sound and complete analyses have distinct applications. When
the goal is to prove a program safe, then a sound analysis is appropriate, and the time spent
dealing with false positives may be worth it (e.g. when
analysing a smart contract that will hold millions).</p>

<p>However, in less critical settings
where the focus is on actually finding bugs, missing some bugs may be acceptable
and actually more desirable than a large number of false positives.</p>

<p>Ultimately,
analyses might be neither sound nor complete, instead relying on delicate tradeoffs between false
positives and false negatives to achieve the sweet spot for a particular domain.</p>]]></content><author><name>Daniele Filaretti</name></author><summary type="html"><![CDATA[Many developers have come across terms such as "static analysis" and related ones such as "soundness" and "program semantics", but what they mean and how they fit together isn't always clear.]]></summary></entry><entry><title type="html">Building a DJ set is finding a path on a graph (and how this became a Haskell program)</title><link href="https://danielefilaretti.com/dj-buddy/" rel="alternate" type="text/html" title="Building a DJ set is finding a path on a graph (and how this became a Haskell program)" /><published>2026-10-29T00:00:00+00:00</published><updated>2026-10-29T00:00:00+00:00</updated><id>https://danielefilaretti.com/dj-buddy</id><content type="html" xml:base="https://danielefilaretti.com/dj-buddy/"><![CDATA[<p>Overall, I’ve been making music for ~25 years or so now; in terms of performing, I fiddled with Ableton, grooveboxes,
and even tried <a href="https://www.youtube.com/watch?v=qrEFcg8eyq4">livecoding</a>. But I was never too interested in DJing until a couple of years ago,
when I decided to give it a go, with various breaks here and there.</p>

<p>Recently I picked it up again, got myself a new DJ controller, downloaded ~30 of
my favourite tunes in my target genre, connected everything, loaded <a href="https://www.native-instruments.com/pages/traktor">Traktor</a> and started playing.</p>

<p>Long story short, I ended up building a small Haskell program to help me plan DJ sets.
This post explains where the idea came from and how the problem can be described simply using graphs.
It also gives an overview of how the source code is organized and how its main parts relate to the theoretical concepts discussed here.
The full code is available <a href="https://github.com/dfilaretti/dj-buddy">on GitHub</a>.</p>

<h2 id="where-the-idea-came-from">Where the idea came from</h2>

<p>For those unfamiliar with it, DJing is basically about <em>transitioning smoothly</em> from one song to the
next using volume changes, EQ, effects, etc.</p>

<p>But obviously not all songs blend well together, so transitions can be tricky.
To make a smooth transition between song A and song B, usually a few things need to happen:</p>

<ul>
  <li>the songs have a similar tempo</li>
  <li>they have a compatible musical key  (more on this later)</li>
  <li>they’re “in sync” (meaning they play on time) and lined up in a way that “makes sense” (what we call <em>phrasing</em> - outside the scope of this post)</li>
</ul>

<p>Back in the old days, “real DJs” knew their entire music library
by heart, even if it filled several heavy bags of vinyl records. They knew exactly which songs
blended well together and which didn’t.</p>

<p>Nowadays, the heavy bags are replaced by USB sticks full of MP3s
and we have software tools to help decide which track to play next.</p>

<p>One such tool is what we call <em>harmonic mixing</em> (see e.g. <a href="https://mixedinkey.com/harmonic-mixing-guide/">here</a>), which tries to solve the problem of choosing
tracks that have compatible musical keys.</p>

<p>How does it work in practice?
The DJ software analyzes each song and assigns it one of 24 musical keys, labelled
with a number from 1 to 12 and a letter (usually <code class="language-plaintext highlighter-rouge">d</code> or <code class="language-plaintext highlighter-rouge">m</code>, e.g. in Traktor, or <code class="language-plaintext highlighter-rouge">A</code> or <code class="language-plaintext highlighter-rouge">B</code> in other systems).
Here, for example, the track has been assigned <code class="language-plaintext highlighter-rouge">11d</code>:</p>

<p><img src="/assets/pics/dj-buddy-post/df-okinawa.png" alt="Okinawa!!" width="600" style="display: block; margin-left: auto; margin-right: auto;" /></p>

<p>So what can we do with this information?
That’s where the <em>Camelot wheel</em> comes in handy (see detailed info and interactive example <a href="https://mixedinkey.com/camelot-wheel/">here</a>).
Basically, once we know the key of a song, the wheel suggests a set of tonally compatible keys:</p>

<p><img src="/assets/pics/dj-buddy-post/camelot-2.png" alt="Camelot wheel" width="400" style="display: block; margin-left: auto; margin-right: auto;" /></p>

<p>For example, from 3A we can go “horizontally” to 2A and 4A or “vertically” to 3B (or stay in 3A obviously).</p>

<p>With our song above (<code class="language-plaintext highlighter-rouge">11d</code> in Traktor), the same rules let us go to <code class="language-plaintext highlighter-rouge">12d</code>, <code class="language-plaintext highlighter-rouge">10d</code>, <code class="language-plaintext highlighter-rouge">11m</code> or just stay in <code class="language-plaintext highlighter-rouge">11d</code>.</p>

<p>In general, potentially compatible songs have either:</p>

<ul>
  <li>the same key</li>
  <li>a number one higher or lower (wrapping around between 12 and 1), with the same letter</li>
  <li>the same number but a “flipped” letter (a “vertical” jump to the relative minor or major key, if you’re curious)</li>
</ul>

<p>In our program, this is formalized in <a href="https://github.com/dfilaretti/dj-buddy/blob/main/src/Domain/Camelot.hs"><code class="language-plaintext highlighter-rouge">Camelot.hs</code></a>
(we use Traktor’s Open Key notation, which uses <code class="language-plaintext highlighter-rouge">d</code> for major and <code class="language-plaintext highlighter-rouge">m</code> for minor and numbers the wheel differently, but the idea is the same).</p>

<p>In general, however, as music people often say, music theory is just a guideline; it can definitely
help us make informed decisions or demystify certain phenomena (like why certain chord sequences always seem to sound so good),
but ultimately our ears are the final judge: “if it sounds good, it <em>is</em> good”.</p>

<p>In fact, while using this system to mix songs from my folder I quickly discovered that…</p>

<ul>
  <li>not all compatible songs necessarily sounded great when overlapped</li>
  <li>some songs, although officially incompatible, actually sounded great together and I really loved the transition</li>
</ul>

<p>So I started writing down my discoveries on a notebook page:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Song A --&gt; Song B (OMG really loved this!!)
Song X --&gt; Song Y (Try blending the vocal, sounds great)
Song B --&gt; Song X
...
</code></pre></div></div>

<p>and referring to it as I was mixing, alongside Traktor’s harmonic mixing suggestions.</p>

<p>Eventually, I was using harmonic mixing as a guide for exploration, while also taking the occasional risk
and writing down my discoveries, ending up with something like this:</p>

<p><img src="/assets/pics/dj-buddy-post/notebook.png" alt="Camelot wheel" width="600" style="display: block; margin-left: auto; margin-right: auto;" /></p>

<p>That’s when I realized that I was essentially just building a graph which could, in theory, be used in some
interesting ways not only to decide what to play next, but also to build full playlists and whatnot.</p>

<p>But there was a problem: this was already getting painful to manage. Once I had two pages I had to keep flipping
between them; what would happen when I reached 10?</p>

<p>So I decided to build a program to handle all this.
During that same period I was also (re)learning Haskell
so I thought great, let’s do it in Haskell.
If nothing else, it could be a chance to learn something beyond the usual textbook exercises.</p>

<h2 id="so-this-is-just-a-graph-problem">So, this is just a graph problem…</h2>

<p>Yes, those notebook entries naturally describe a graph of what we will call <em>tested transitions</em>:
transitions between songs that the user has personally tried, loved and decided were worth recording for next time.</p>

<p>The graph looks something like this:</p>

<p><img src="/assets/pics/dj-buddy-post/simple-graph.png" alt="Camelot wheel" width="400" style="display: block; margin-left: auto; margin-right: auto;" /></p>

<p>Here, track <code class="language-plaintext highlighter-rouge">t1</code> transitions nicely into <code class="language-plaintext highlighter-rouge">t2</code> and <code class="language-plaintext highlighter-rouge">t4</code>, which both transition nicely into <code class="language-plaintext highlighter-rouge">t3</code>.
<code class="language-plaintext highlighter-rouge">t5</code> is sadly left out (solution: add more music to the library, explore and add tested transitions once discovered!).</p>

<p>So those are our <em>tested transitions</em>, which we explicitly keep track of.
But, as we saw, we can also use the Camelot wheel to suggest potentially good tracks to play next.</p>

<p>How can we combine the two approaches?</p>

<p>Here, each segment of the Camelot wheel contains songs (the black dots),
and the arrows represent our tested transitions.</p>

<p><img src="/assets/pics/dj-buddy-post/camelot-1.png" alt="Camelot wheel" width="500" style="display: block; margin-left: auto; margin-right: auto;" /></p>

<p>In other words, given a set of songs, the Camelot wheel gives us a <em>partition</em> of that set into 24 groups.
The harmonic mixing rules then give us <em>implicit</em> transitions which we could use alongside the <em>explicit</em> (or <em>tested</em>) transitions.</p>

<p>In summary, given a song we could follow:</p>

<ul>
  <li>the implicit edges given by the Camelot wheel</li>
  <li>explicit edges recorded by the user</li>
</ul>

<p>You should now be able to start seeing how we could, in principle, ask interesting questions such as</p>

<ul>
  <li>give me 5 possible next songs to play after song X</li>
  <li>give me a playlist of 10 songs to play (that sound good with each other), starting from X</li>
  <li>give me a playlist of 10 songs to play starting from a random one</li>
  <li>give me a playlist of 10 songs that must include X, Y and Z and end with T</li>
  <li>…</li>
</ul>

<h2 id="formalizing-the-problem">Formalizing the problem</h2>

<p>To summarize all of the above, the data structure we end up with looks something like this:</p>

<p><img src="/assets/pics/dj-buddy-post/graph.png" alt="Camelot wheel" width="800" style="display: block; margin-left: auto; margin-right: auto;" /></p>

<p>Here, black dots are songs and solid arrows are tested transitions.
Songs are grouped by key into 24 partitions, shown as coloured circles.</p>

<p>Dashed arrows represent transitions suggested by harmonic mixing (only a
subset is shown, but hopefully you get the idea).</p>

<p>In this example we can see that from <code class="language-plaintext highlighter-rouge">9A</code> we can get to <code class="language-plaintext highlighter-rouge">8A</code> and <code class="language-plaintext highlighter-rouge">10A</code> as well as <code class="language-plaintext highlighter-rouge">9B</code> and <code class="language-plaintext highlighter-rouge">9A</code> itself.
Tested transitions can also break the harmonic mixing rules, like <code class="language-plaintext highlighter-rouge">t4</code> to <code class="language-plaintext highlighter-rouge">t9</code> here, which is totally fine.</p>

<p>You might have noticed numbers on the transitions. Those numbers represent the <em>cost</em> of each transition.</p>

<p>For example, a tested transition costs zero, because the user has personally tried it and loves it.
Transitioning to a song with the same key costs 1, while moving to a compatible (but different) key costs 2.
The idea is that a shared key is a safer bet, while a compatible key is a bit more risky.
Neither guarantees a great transition, as we’ve seen (remember, our ears are the judge).</p>

<p>Picking a random song in an incompatible key would, in theory, carry a much higher cost.
But if the user has tested that transition and loves it, it still costs zero:
“tested transition always wins” - our version of “if it sounds good it is good”.</p>

<p>All of this is formalized in Haskell in <a href="https://github.com/dfilaretti/dj-buddy/blob/main/src/Domain/MusicLibrary.hs"><code class="language-plaintext highlighter-rouge">MusicLibrary.hs</code></a> and <a href="https://github.com/dfilaretti/dj-buddy/blob/main/src/Domain/Transitions.hs"><code class="language-plaintext highlighter-rouge">Transitions.hs</code></a>.</p>

<h2 id="ok-so-how-does-it-work-in-practice">OK so how does it work in practice?</h2>

<p>If you’ve followed this far, the rest should be fairly simple.</p>

<p>Given a starting song, we can just follow outgoing edges to figure out which tracks to play next;
if there are any tested transitions (cost = 0) then great, we can pick one of those.
Otherwise, we follow the rules of harmonic mixing, picking a track with the same (cost = 1) or a compatible key (cost = 2).</p>

<p>We use <em>transition costs</em> to help us pick the “best” transition at any given time.</p>

<p>Building an entire playlist or DJ set is just an extension of this where we repeat the process for a
given number of steps (or until we run out of tracks to play) - see <a href="https://github.com/dfilaretti/dj-buddy/blob/main/src/Domain/Playlist.hs"><code class="language-plaintext highlighter-rouge">Playlist.hs</code></a>.</p>

<p>As the user adds new songs to their library and continues using the system, they might eventually discover new
transitions (guided by harmonic mixing and a bit of chaos)
and add them to the graph, which in turn “unlocks” interesting new combinations and potential playlists.</p>

<h2 id="how-is-the-project-built">How is the project built?</h2>

<p>The project is open source and available <a href="https://github.com/dfilaretti/dj-buddy/tree/main">here</a>.</p>

<p>It currently has 3 main parts:</p>

<ul>
  <li>a library of pure functions for modelling the graph, recommending tracks and building playlists. In turn, it has two components:
    <ul>
      <li>a small set of functions that clients (CLI, web app etc.) can call directly (see <a href="https://github.com/dfilaretti/dj-buddy/blob/main/src/App.hs"><code class="language-plaintext highlighter-rouge">App.hs</code></a>).</li>
      <li>a bigger set of internal functions that provide the building blocks (see the <a href="https://github.com/dfilaretti/dj-buddy/tree/main/src/Domain"><code class="language-plaintext highlighter-rouge">Domain</code></a> folder).</li>
    </ul>
  </li>
  <li>a <a href="https://github.com/dfilaretti/dj-buddy/blob/main/app/Main.hs">CLI application</a> that allows (adventurous) DJs to use the program from the terminal. This is built with
<a href="https://hackage.haskell.org/package/optparse-applicative">optparse-applicative</a>.</li>
  <li>a <a href="https://github.com/dfilaretti/dj-buddy/blob/main/web/Main.hs">small web app</a> for the (slightly less adventurous) DJ to use from a browser. This one is built with <a href="https://hackage.haskell.org/package/scotty">Scotty</a>.</li>
</ul>

<p>The idea was to keep both the CLI and web server minimal - basically all they do is call into <a href="https://github.com/dfilaretti/dj-buddy/blob/main/src/App.hs"><code class="language-plaintext highlighter-rouge">App.hs</code></a>,
get their data and present it to the user.</p>

<p>The music library currently lives in a simple YAML file, handwritten by the user
(consistent with the manual curation ethos of the project).</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">tracks</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">id</span><span class="pi">:</span> <span class="s">first_track</span>
    <span class="na">title</span><span class="pi">:</span> <span class="s">First Track</span>
    <span class="na">key</span><span class="pi">:</span> <span class="s2">"</span><span class="s">3D"</span>
  <span class="pi">-</span> <span class="na">id</span><span class="pi">:</span> <span class="s">second_track</span>
    <span class="na">title</span><span class="pi">:</span> <span class="s">Second Track</span>
    <span class="na">key</span><span class="pi">:</span> <span class="s2">"</span><span class="s">4D"</span>
<span class="na">transitions</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">from</span><span class="pi">:</span> <span class="s">first_track</span>
    <span class="na">to</span><span class="pi">:</span> <span class="s">second_track</span>
    <span class="na">notes</span><span class="pi">:</span> <span class="s2">"</span><span class="s">Mix</span><span class="nv"> </span><span class="s">after</span><span class="nv"> </span><span class="s">the</span><span class="nv"> </span><span class="s">breakdown"</span> <span class="c1"># optional</span>
</code></pre></div></div>

<p>The YAML file is read and parsed into a <a href="https://github.com/dfilaretti/dj-buddy/blob/main/src/Domain/MusicLibrary.hs#L65"><code class="language-plaintext highlighter-rouge">MusicLibrary</code></a>, the main data structure handled by
our program (see <a href="https://github.com/dfilaretti/dj-buddy/blob/main/src/Persistence/Yaml.hs"><code class="language-plaintext highlighter-rouge">Yaml.hs</code></a> for details about the parsing,
for which we used <a href="https://hackage.haskell.org/package/aeson">aeson</a>).</p>

<p>The program currently treats the library as <em>read-only</em>: the user maintains it, the program reads it
and does its magic. Adding or removing songs and transitions through the program is left for
future work (see below), along with importing libraries from DJ software such as Traktor, Serato or rekordbox.</p>

<p>Throughout the program we handle errors via <code class="language-plaintext highlighter-rouge">Either AppError _</code>, where <a href="https://github.com/dfilaretti/dj-buddy/blob/main/src/App.hs#L45"><code class="language-plaintext highlighter-rouge">AppError</code></a>
represents the various things that can go wrong.
This gives the CLI and web app details about what happened, so they can show meaningful error messages.</p>

<h2 id="future-work">Future work</h2>

<p>Ultimately, this all reduces to graph problems; the fact that we have “songs” and “transitions” is just a detail.</p>

<h3 id="ability-to-add-more-constraints-in-playlist-generation">Ability to add more constraints in playlist generation</h3>

<p>At the moment we can ask “give me a 10-track playlist starting from song X”.
One cool addition would be “give me a 10-track playlist starting from X, making sure you
include Y and Z and end in T”. Same idea, but with constraints.
This probably maps to some existing graph algorithm but we haven’t looked into it yet.</p>

<h3 id="looking-further-ahead-than-just-the-next-song">Looking further ahead than just the next song</h3>

<p>At the moment, the algorithm only looks at the next step: given song X, it looks at the candidates
and picks the one with the lowest cost (choosing randomly if there’s more than one with that same cost).</p>

<p>This seems to work fine in practice, but isn’t always ideal.</p>

<p>Suppose we’re playing song X and find a tested transition to song Y - great!
It sounds amazing, but unfortunately Y turns out to be a dead end, as now we don’t have any compatible
songs to choose from…</p>

<p>Instead, we could have chosen another song Z: perhaps, going from X to Z wouldn’t be as amazing as going from X to Y,
but once we reached Z, we’d have many more transitions at our disposal, helping us avoid getting stuck and
allowing the DJ set to continue smoothly (perhaps even unlocking interesting new areas of the library).</p>

<h3 id="library-imports-from-established-dj-software">Library imports from established DJ software</h3>

<p>The YAML file is currently maintained by hand. Importing track metadata from Traktor, rekordbox, and similar tools would make larger libraries easier to manage while keeping transition curation manual.</p>

<h3 id="richer-metadata">Richer metadata</h3>

<p>The format is deliberately minimal. BPM is omitted because my sets stay around 138–140 BPM, so I already assume the tracks are tempo-compatible. Artist names are also omitted because I know this small collection well. Both would be useful additions as the library grows, but add little to the current proof of concept.</p>

<h3 id="library-management-via-the-software">Library management via the software</h3>

<p>As mentioned above, the library is currently curated manually by the user.
But this can become cumbersome as the library grows.
It would be nice to manage songs and transitions without editing the YAML.
Also, in a web setting this might have the potential to look very cool (see below).</p>

<h3 id="fancy-web-ui">Fancy Web UI</h3>

<p>Yes, this is a graph, and we <em>could</em> build something really cool looking that runs in a
web browser, letting users visualize and interact with the graph etc… Pretty cool but out of scope.</p>

<h2 id="faqs">FAQs</h2>

<h3 id="so-whats-the-practical-use-of-this-is-this-better-than-harmonic-mixing">So what’s the practical use of this? Is this better than harmonic mixing?</h3>

<p>The two things are not in competition.
Harmonic mixing gives us starting points to experiment and explore.
When the user finds something really exciting, they can record it.
It’s a personal curation system.
Harmonic mixing and the various AI song analysis systems tell us what <em>might</em> sound good; this tells us
what <em>sounds freaking amazing</em> because the user has personally tested it.</p>

<h3 id="is-this-ai-is-there-any-plan-to-integrate-ai">Is this AI? Is there any plan to integrate AI?</h3>

<p>No. In fact, the idea here is just to build a sort of database of personally curated transitions.
There’s already plenty of software that suggests tracks. This is for users to curate
their own library of amazing transitions.</p>]]></content><author><name>Daniele Filaretti</name></author><summary type="html"><![CDATA[I ended up building a small Haskell program to help me plan DJ sets. This post explains where the idea came from and how the problem can be described simply using graphs]]></summary></entry><entry><title type="html">From Haskell to Clojure, and back</title><link href="https://danielefilaretti.com/Haskell-vs-Clojure/" rel="alternate" type="text/html" title="From Haskell to Clojure, and back" /><published>2020-06-01T00:00:00+00:00</published><updated>2020-06-01T00:00:00+00:00</updated><id>https://danielefilaretti.com/Haskell-vs-Clojure</id><content type="html" xml:base="https://danielefilaretti.com/Haskell-vs-Clojure/"><![CDATA[<p>During the last couple of years, I’ve been lucky enough to use Haskell and Clojure professionally (at different companies) and in both cases it’s been a very enjoyable ride.</p>

<p>In this post I’m going to share my two cents about the experience as well as some of the pain points I faced when transitioning from a Haskell to a Clojure codebase.</p>

<h2 id="syntax">Syntax</h2>

<p>As a LISP dialect, some people dislikes Clojure’s syntax because it’s “full of parentheses”.  Personally, I love it because all code follows a uniform structure…</p>

<p>There are  <em>literals</em>:</p>

<figure class="highlight"><pre><code class="language-clojure" data-lang="clojure"><span class="s">"hello world"</span><span class="w">  </span><span class="c1">; a string</span><span class="w">
</span><span class="mi">99</span><span class="w">             </span><span class="c1">; an integer</span><span class="w">
</span><span class="p">[</span><span class="mi">1</span><span class="n">,</span><span class="w"> </span><span class="s">"foo"</span><span class="n">,</span><span class="w"> </span><span class="mi">2</span><span class="p">]</span><span class="w">  </span><span class="c1">; a vector</span><span class="w">
</span><span class="n">foo</span><span class="w">            </span><span class="c1">; a symbol </span><span class="w">
</span><span class="nb">+</span><span class="w">              </span><span class="c1">; another symbol</span></code></pre></figure>

<p>and <em>operations</em>:</p>

<figure class="highlight"><pre><code class="language-clojure" data-lang="clojure"><span class="p">(</span><span class="nb">+</span><span class="w"> </span><span class="mi">2</span><span class="w"> </span><span class="mi">3</span><span class="p">)</span><span class="w">              </span><span class="c1">; adds 2 and 3</span><span class="w">
</span><span class="p">(</span><span class="nb">sort</span><span class="w"> </span><span class="p">[</span><span class="mi">5</span><span class="n">,</span><span class="w"> </span><span class="mi">2</span><span class="n">,</span><span class="w"> </span><span class="mi">4</span><span class="p">])</span><span class="w">     </span><span class="c1">; sort a vector</span><span class="w">
</span><span class="p">(</span><span class="k">if</span><span class="w"> </span><span class="n">true</span><span class="w"> </span><span class="s">"yes"</span><span class="w"> </span><span class="s">"no"</span><span class="p">)</span><span class="w"> </span><span class="c1">; evaluate to "yes"</span></code></pre></figure>

<p>each following the same structure:</p>

<figure class="highlight"><pre><code class="language-clojure" data-lang="clojure"><span class="p">(</span><span class="nf">op</span><span class="w"> </span><span class="n">arg_1</span><span class="w"> </span><span class="n">arg_2</span><span class="w"> </span><span class="n">...</span><span class="w"> </span><span class="n">arg_n</span><span class="p">)</span></code></pre></figure>

<p>and this is <em>almost</em> everything there is to know about syntax.</p>

<p>What is interesting is that any piece of Clojure code is, in fact, just a regular data structure.</p>

<p>For example, the code:</p>

<figure class="highlight"><pre><code class="language-clojure" data-lang="clojure"><span class="p">(</span><span class="nf">add</span><span class="w"> </span><span class="mi">2</span><span class="w"> </span><span class="mi">3</span><span class="p">)</span><span class="w"> </span><span class="c1">; evaluates to 5</span></code></pre></figure>

<p>is a Clojure <em>list</em> containing the symbol <code class="language-plaintext highlighter-rouge">add</code>, followed by integers <code class="language-plaintext highlighter-rouge">2</code> and <code class="language-plaintext highlighter-rouge">3</code> (this is a common concept in LISPs and is called <a href="https://en.wikipedia.org/wiki/Homoiconicity#:~:text=A%20language%20is%20homoiconic%20if,manipulated%20by%20other%20Lisp%20code."><em>homoiconicity</em></a>).</p>

<p>Not only this is interesting in its own right, but it has practical advantages, too; the fact that programs are just data structures means they are easy to manipulate, transform and even generate (something called <a href="https://en.wikipedia.org/wiki/Metaprogramming#:~:text=Metaprogramming%20is%20a%20programming%20technique,even%20modify%20itself%20while%20running."><em>metaprogramming</em></a>). This is why one of LISP’s favourite features are their <a href="http://clojure-doc.org/articles/language/macros.html"><em>macros</em></a> facilities and the ability they bring to easily extend the language or even even create your own DSL.</p>

<p>Let’s face it though: with all the nested parenthesis, Clojure code <em>will</em> eventually get cumbersome to edit. This is where text editor plugins such as <a href="http://danmidwood.com/content/2014/11/21/animated-paredit.html"><em>paredit</em></a> come to the rescue by helping make sure parenthesis remain balanced while also providing a set of powerful <em>structural editing</em> shortcuts to manipulate code at the <em>expression level</em>.
This may feel confusing at first, but stick to it and you’ll see how nice and useful it can be!</p>

<p>Haskell, on the other hand, has a more “mainstream” (or shall we say… modern?) syntax. Similarly to Python, it tries to minimise parenthesis by making indentation count when delimiting blocks of code.</p>

<p>One thing I particularly like about Haskell’s syntax is that it tends to look more uncluttered and similar to actual mathematical notation. 
For example, a function <code class="language-plaintext highlighter-rouge">abs</code> that returns the absolute value of its argument <code class="language-plaintext highlighter-rouge">n</code> can be defined in Haskell as:</p>

<figure class="highlight"><pre><code class="language-haskell" data-lang="haskell"><span class="n">abs</span> <span class="o">::</span> <span class="kt">Int</span> <span class="o">-&gt;</span> <span class="kt">Int</span>
<span class="n">abs</span> <span class="n">n</span> <span class="o">|</span> <span class="n">n</span> <span class="o">&gt;=</span> <span class="mi">0</span>    <span class="o">=</span> <span class="n">n</span> 
      <span class="o">|</span> <span class="n">otherwise</span> <span class="o">=</span> <span class="o">-</span><span class="n">n</span> </code></pre></figure>

<p>which in my opinion looks a bit more readable that its Clojure counterpart:</p>

<figure class="highlight"><pre><code class="language-clojure" data-lang="clojure"><span class="p">(</span><span class="k">defn</span><span class="w"> </span><span class="n">abs</span><span class="w"> 
  </span><span class="p">[</span><span class="n">n</span><span class="p">]</span><span class="w">
  </span><span class="p">(</span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="nb">&gt;=</span><span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="mi">0</span><span class="p">)</span><span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="n">-n</span><span class="p">))</span></code></pre></figure>

<!-- Because Haskell programs are _not_ Haskell data structures, we can't manipulate them as easily as we'd do in Clojure (or other LISPs). 
This doesn't mean that it isn't possible though, bur just that it may not be as easy/elegant as it'd be in a LISP. It is my understanding in fact that metaprogramming in Haskell can indeed be done via _Template Haskell_, a tool in which I have personally never used and therefore I'll abstain from commenting on. -->

<h2 id="type-system">Type System</h2>

<p>One of the main differences between Haskell and Clojure is probably the fact that Haskell is <em>statically typed</em> while Clojure is <em>dynamically typed</em>.
<!-- There already exist plenty of flame wars about the subject online, so I will abstrain from putting gasoline on fire. --></p>

<p>Frankly, I believe that no approach is “better” than the other in absolute terms. 
Both can count on very smart people among their supporters, and while some of us engage in endless online discussions, great software gets written every day using languages in both categories.</p>

<p>Having said that, I shall mention that most of my experience is in statically typed languages.
The first language I ever learnt was Pascal, followed by C, Java, C#, C++ and, much more recently, Haskell.</p>

<p>It’s no surprise then, that as I started familiarising with my first Clojure codebase I found the lack of static typing uncomfortable, and even after being introduced to <a href="https://github.com/plumatic/schema"><em>schema</em></a> (which essentially allow you to place runtime checks to make sure that data matches a certain “shape”), I could’t really shake off the feeling that something was missing.</p>

<!-- In Haskell and other statically typed languages, types are an integral part of the language and eventually becomes second nature. 
On the other hand, tools like schema or clojure.spec not only are _optional_ but, even when adopted, can be selectively turned on or off (e.g. allowing only a selected number of functions or namespaces to be checked).
This certainly introduces extra flexibility, but also can also new opportunity for mistakes (or sloppiness).  -->

<!-- I heard people complain about the overhead of the Haskell type system, and about how dealing with it can sometimes distract you from the actual problem you are trying to solve.
But is working with schemas/specs really much better at the end of the day? Is is really less hassle?
At least in Haskell (and other static languages) you don't have to think about it too much as it's all built in in the language, not to mention all those trivial runtime errors that are automatically rules out at ocmpile time... (and you can always add runtime checks and testing if you want). -->

<p>Maybe it’s just me, but In Clojure-land I spent several hours tracking down trivial errors (such as a <code class="language-plaintext highlighter-rouge">nil</code> being erroneously passed to a function) that just don’t happen in Haskell.
Also, I felt that <em>refactoring</em> can be a bit painful.
In Haskell, things such as e.g. swapping the order of a function’s parameters tends to be trivial: make a small/incremental change, compile and then fix all the errors (broken call sites etc.). 
In Clojure, unfortunately, we don’t have that luxury: you can still make the change, but then is up to you to manually identify all the call sites (or whatever change is required) - an activity that can easily turn error prone and time consuming.</p>

<!-- It certainly happened to me that after a change like that "everything seemed to be working" only to find a day later that indeed something broke along the line.  -->

<!-- I'm sure that you've also heard the aneddote "once Haskell code compiles it almost certianly work" and that "refactoring is cheap".
In my experience, this actually tends to be true.
Make no mistake, there's no magic here; instead of jotting something down and then spending time debugging it, you simply do part of this work upfront when designing your types and the functions operating on them and making sure it all matches nicely.
It may take a few itertions and it can indeed be frustrating, but once it compiles, then you have already made a long way and, yes, quite often it "just works" (TM). -->

<p>It should be clear at this point that my biggest frustration with Clojure at the moment is the lack of a type system (I am aware of <a href="https://github.com/clojure/core.typed"><code class="language-plaintext highlighter-rouge">core.typed</code></a> but I understand it’s not widely used/recommended and I’ve never used it myself - I should really take a look at some point!)</p>

<h2 id="tooling--ecosystem">Tooling &amp; Ecosystem</h2>

<p>When I started working in Haskell I searched for “best tools” (IDEs etc.) but couldn’t find a one-stop answer; I tried some of the existing solutions with varying degrees of success (and frustration), but eventually <a href="https://www.parsonsmatt.org/2018/05/19/ghcid_for_the_win.html">after reading this blog post</a> I  settled with a text editor and two terminal windows - one with a REPL and another with <a href="https://github.com/ndmitchell/ghcid"><code class="language-plaintext highlighter-rouge">ghcid</code></a>.
This may appear to be a rudimentary setup but I found it surprisingly effective and pleasant to use.</p>

<p>Clojure, on the other hand, seems to benefit from a great variety of tried-and-tested IDEs (<a href="https://docs.cider.mx/cider/index.html">CIDER</a>, <a href="https://cursive-ide.com/">Cursive</a>, <a href="https://github.com/BetterThanTomorrow/calva">Calva</a> etc.) and various other tools.
The feeling I’ve got is that while many Haskell programmers are happy to stick to simpler setups (such as the text editor + <code class="language-plaintext highlighter-rouge">ghci</code> mentioned above), Clojure programmers tend to rely more heavily on IDEs and other tools.
<!-- Those are useful and fun, but they sometimes come with a learning curve, not to mention the potential confusion when trying to figure out which combination of tools to pick in the first place. --></p>

<p>Something else to be mentioned is that while Haskell compiles to native language, <a href="https://clojure.org/about/jvm_hosted">Clojure is a <em>hosted language</em></a> based on the <em>Java Virtual Machine (JVM)</em> which has the advantage of providing instant access to the wider Java ecosystem including the multitude of real-world, tried-and-tested libraries and tools.
This can be seen as a positive or as a negative, but there’s no doubt it can prove very useful in the right circumstances.</p>

<p>In conclusion, I’d say that while Haskell may appear to be a little behind in terms of tooling and ecosystem, that doesn’t necessarily mean a poor development workflow; with a strong emphasis on the type system and on a workflow revolving around a programmer-compiler dialogue, you may find that you don’t need super-advanced external tools to be productive in Haskell.</p>

<h2 id="learning-curve">Learning curve</h2>

<p>Haskell has a reputation for being difficult to learn, but I tend to disagree.
It may be true that Haskell is different from the languages that most of us are are used to, but that doesn’t necessarily make it harder.</p>

<!-- When I was learning Java in high school, the teacher once said that programming languages are all "the same" and once you know one you can easily switch to another with minor syntax adjustments; I believed her at the time, and I personally held that belief for years.  -->

<p>Some people believe that programming languages are all “the same” and that once you master one it is easy to switch to another with minor syntax adjustments.
This may be true when moving between similar languages such as e.g. Java and C#, but learning a functional language isn’t just about a new syntax - it’s about learning a different way to think about programming!</p>

<p>Many <em>“functional first”</em> languages such as Scala, F# and even Clojure can make this transition smoother since they offer a mix of functional and Object Oriented features in an attempt to combine “the best of both worlds”.</p>

<p>Haskell however is different in that it doesn’t try to combine programming paradigms; instead, it embraces the <em>functional programming</em> style in its purest form.
This basically means that there are no shortcuts - if you are new to it, you’ll have to step back, grab yourself a good textbook and learn with a beginner mentality, just as if you were learning how to program for the first time.
Once you do however, you’ll quickly see that there’s nothing to be afraid of, not even the so dreaded <em>monads</em>!</p>

<!-- When I decided to do that a couple of years ago, I soon realised that there was nothing too scary about Haskell.
Sure, some of the concepts may appear strange at first but if you approach it with a beginner's mentality and some curiosity there really is nothing to be scared of and eventually it'all makes sense (and you'll be asking yourself how could you stay all those years without it). -->

<p>Clojure, on the other hand, seems to enjoy a somehow opposite reputation. 
I remember reading somewhere about how any developer could learn it “on the job” in a week or two and immediately become productive. 
I don’t feel that’s entirely realistic either…</p>

<p>The language feels indeed practical and friendly and let’s face it - being able to do something like this:</p>

<figure class="highlight"><pre><code class="language-clojure" data-lang="clojure"><span class="p">(</span><span class="nb">slurp</span><span class="w"> </span><span class="s">"my-file.txt"</span><span class="p">)</span><span class="w">             </span><span class="c1">; read from a file</span><span class="w">
</span><span class="p">(</span><span class="nb">slurp</span><span class="w"> </span><span class="s">"https://www.google.com/"</span><span class="p">)</span><span class="w"> </span><span class="c1">; read from a URL</span><span class="w">
</span><span class="p">(</span><span class="nb">rand</span><span class="p">)</span><span class="w">                            </span><span class="c1">; generate a random number</span></code></pre></figure>

<p>without worrying about <code class="language-plaintext highlighter-rouge">IO</code>, monads or <code class="language-plaintext highlighter-rouge">do</code> blocks can feel liberating at first.</p>

<!-- However, my learning experience wasn't completely pain free.
After figuring learning some basics, I was still left with questions such as "how does REPL-driven development actually work and how should I structure my code to take advantage of that? How do I make the most of a LISP? How do I write idiomatic code? Should I use editor plugin X or Y? and countless others. -->

<!-- First, I had to face the lack of a type system (discussed earlier); then, I had to figure out how which editor, IDE and tools I wanted to use (which itself took several iterations). 
Then, once I finally had it all working, I had to figure out... well, what to make of it all. 
People celebrate the fast, REPL-driven development experience offered by Clojure, but how does that work in practice? Does having your IDE set up and your REPL up and running mean you are practicing REPL Driven Development or is there more to that? Does the code has to be structueed in a certain wey? And what are the best practices anyway and how do you learn to fully embrace the LISP mentality and write idiomatic code?  -->

<p>But, honestly, I don’t believe that Clojure is so much “easier” than Haskell at the end of the day. 
For sure, the fact that it is dynamically typed and that it allows mixing pure and impure code (unlike Haskell) can make it easier for a beginner to get started, but eventually you’ll still find yourself wondering:</p>
<ul>
  <li>how does REPL-driven development actually work?</li>
  <li>what’s the best way to structure my code?</li>
  <li>how do I take advantage of using a LISP and how do I write idiomatic code?</li>
  <li>how do I make the most of macros?</li>
</ul>

<p>and countless others…</p>

<p>Make no mistake: Clojure it’s a powerful programming language that comes with a rich (and sometimes confusing) ecosystem and a deep cultural heritage (remember LISP?). 
It may be easy to grasp the basics but if you want to get past that you’ll probably still need to set aside some time for some serious learning.</p>

<p>I’m fully aware that different people have different learning styles but, personally, it’s only when I started to approach learning Clojure in a more systematic way that the penny finally dropped and I started to really like it.</p>

<!-- It's when I started reading about it (as I've done previously with Haskell) and making an effort to learn it properly that I really started to love Clojure.
What I'm criticising here is not Clojure, but that myth that want people to believe that it's so easy you can just "learn it on the job" in a couple of weeks. 
This may be convenient for companies, but, if you are like me, do yourself a favour, take some time and learn about it and you won't be disappointed (and, by the way there are _excellent_ learning material about Clojure, free or otherwise). -->

<h2 id="industries--jobs">Industries &amp; jobs</h2>

<p>Both Haskell and Clojure are <em>general purpose</em> programming languages meaning there’s nothing preventing you from adopting them in any given field or domain. 
Having said that, there seem to be certain niches where they tend to get more traction then others.</p>

<p>This may vary depending on your location and network, but, from what I can see (and sadly there aren’t tons of Clojure or Haskell jobs around), Clojure gigs tend to be mostly at startups and involve some form of web programming - often “full-stack” with the backend written in Clojure and the frontend in ClojureScript.</p>

<!-- There are a lot of very cool, user friendly, well documented and actively maintained projects to help you with that. An example I'm particularly familiar with is re-frame, a clojure script framework for writing single page applications in clojurescript based on the reactive functional programming paradigm. 
In my experience those things tend to be easy to setup, are well documented actively maintained and there's a very friendly and actve community to refer to in case you need help.  -->

<p>On the other hand, while it is certainly possible to build web applications with Haskell, my impression is that this isn’t the primary niche. 
Where haskell seems to be gaining momentum instead is in fields such as finance, blockchain, compilers/interpreters/tools, formal methods etc. (and, in general, niches where safety &amp; correctness are perceived as important).</p>

<h2 id="conclusions">Conclusions</h2>

<p>Of all the programming languages I’ve worked with, Clojure and Haskell are without any doubt among my favourites.</p>

<p>I love Clojure for its LISP heritage, focus on getting things done, and the great community and ecosystem (while, sadly, I can’t help but finding the lack of a type system frustrating).
I love Haskell for its conceptual elegance, focus on types and abstractions and for the emphasis on safety and correctness.
Finally, I love both because, ultimately, they are <em>fun</em> and rewarding!</p>

<p>But don’t forget: at the end of the day, <em>programming languages are just tools</em>… a great codebase written in some “uncool” language is still better than a nasty Haskell or Clojure codebase.
Similarly, a healthy, well-functioning team is better than a toxic and dysfunctional one - even if they turn out to be using the latest/fanciest/best technology.</p>

<p>Happy coding!</p>]]></content><author><name>Daniele Filaretti</name></author><summary type="html"><![CDATA[During the last couple of years, I've been lucky enough to use both Haskell and Clojure professionally (at different companies) and in both cases it's been an enjoyable and rewarding experience.]]></summary></entry><entry><title type="html">Turning C++’s switch statement into an expression</title><link href="https://danielefilaretti.com/CppStmts2Exps/" rel="alternate" type="text/html" title="Turning C++’s switch statement into an expression" /><published>2019-01-28T00:00:00+00:00</published><updated>2019-01-28T00:00:00+00:00</updated><id>https://danielefilaretti.com/CppStmts2Exps</id><content type="html" xml:base="https://danielefilaretti.com/CppStmts2Exps/"><![CDATA[<p>In the last few months I got involved in audio software development with C++ and the JUCE framework, and since at the same time I’ve been writing Haskell in my day job (as well as exploring other functional languages on my own) it didn’t take me long to become curious about the whole “functional programming in C++” thing.</p>

<p>In this post I summarise a nice little trick I came across recently while <a href="https://www.youtube.com/watch?v=YgcUuYCCV14">whatching talks</a> and <a href="https://www.amazon.co.uk/Tour-C-Depth/dp/0134997832/ref=pd_lpo_sbs_14_img_0?_encoding=UTF8&amp;psc=1&amp;refRID=0J2C5W50QPMSTGXF833X">reading about C++</a>.</p>

<p>Let’s take a look at the following code:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">enum</span> <span class="k">class</span> <span class="nc">ErrorCode</span> <span class="p">{</span> <span class="n">e_1</span><span class="p">,</span> <span class="n">e_2</span><span class="p">,</span> <span class="n">e_3</span> <span class="p">};</span>

<span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">msg</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">errCode</span> <span class="o">==</span> <span class="n">ErrorCode</span><span class="o">::</span><span class="n">e_1</span><span class="p">)</span>
    <span class="n">msg</span> <span class="o">=</span> <span class="s">"This is a fatal error."</span><span class="p">;</span>
<span class="k">else</span>
    <span class="n">msg</span> <span class="o">=</span> <span class="s">"This is a minor error."</span><span class="p">;</span></code></pre></figure>

<p>Quite common, rigth? Basically, we want to pick one from a set of alternatives to initialise a data structure (here a simple string <code class="language-plaintext highlighter-rouge">msg</code>), potentially doing different operations in each branch.</p>

<p>This is a simple, artificial example, but we can already see where the problems are:</p>

<ul>
  <li>
    <p>the intended purpose of this code is to <em>initialise</em> <code class="language-plaintext highlighter-rouge">msg</code> depending on <code class="language-plaintext highlighter-rouge">errCode</code>, however, what it technically does it to initialise it with a default value and subsequently <em>assign</em> the desired value to it.</p>
  </li>
  <li>
    <p>there’s nothing preventing us from using the variable <code class="language-plaintext highlighter-rouge">msg</code> <em>before</em> it gets the desired value; sure, it may not happen in this example, but it could be possible in larger, messy code.</p>
  </li>
  <li>
    <p>even if we aren’t going to reassign <code class="language-plaintext highlighter-rouge">msg</code> anywhere else, the varieble is now declared as mutable.</p>
  </li>
</ul>

<h2 id="expressions-vs-statements">Expressions vs Statements</h2>

<p>The problem is that in C++ (as in most imperative languages) the <code class="language-plaintext highlighter-rouge">if</code> statement is, indeed, a <em>statement</em> and not an expression.</p>

<p>What this means is that <code class="language-plaintext highlighter-rouge">if</code> doesn’t “return” a value; instead, all it can do is change the program state in some way (for example by assigning a new value to a variable, printing something to the screen etc.). We say that it performs a <em>side effect</em>.</p>

<p>But imagine for a moment that <code class="language-plaintext highlighter-rouge">if</code> was as expression; if that was possible, it would directly evaluate to a value which we could use to initialise <code class="language-plaintext highlighter-rouge">msg</code> without intermediate steps:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">const</span> <span class="k">auto</span> <span class="n">msg</span> <span class="o">=</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">errCode</span> <span class="o">==</span> <span class="n">ErrorCode</span><span class="o">::</span><span class="n">e_1</span><span class="p">)</span>
        <span class="s">"This is a fatal error."</span><span class="p">;</span>
    <span class="k">else</span>
        <span class="s">"This is a minor error."</span><span class="p">;</span></code></pre></figure>

<p>Isn’t this nicer?
Notice that not only it solves all of the problems above, but it also makes the code more compact by allowing us to use <code class="language-plaintext highlighter-rouge">auto</code> instead of manually specifying the type of <code class="language-plaintext highlighter-rouge">msg</code>.</p>

<p>This is how things work “by default” in functional languges. 
For example, this is how our code looks like in Haskell:</p>

<figure class="highlight"><pre><code class="language-haskell" data-lang="haskell"><span class="n">msg</span> <span class="o">=</span> 
    <span class="kr">if</span> <span class="n">errCode</span> <span class="o">==</span> <span class="n">e_1</span>
        <span class="s">"This is a fatal error."</span>
    <span class="kr">else</span>
        <span class="s">"This is a minor error."</span></code></pre></figure>

<p>So, can we use a similar style in C++? 
For this example the answer is yes, as we could simply use a <em>ternary</em> (or <em>conditional</em>) operator:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">const</span> <span class="k">auto</span> <span class="n">msg</span> <span class="o">=</span> 
    <span class="p">(</span><span class="n">errCode</span> <span class="o">==</span> <span class="n">ErrorCode</span><span class="o">::</span><span class="n">e_1</span><span class="p">)</span> 
        <span class="o">?</span> <span class="s">"This is a fatal error."</span> 
        <span class="o">:</span> <span class="s">"This is a minor error."</span><span class="p">;</span></code></pre></figure>

<p>The only problem with this is that it doesn’t scale - what if we have not only two, but more alternatives?</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">msg</span><span class="p">;</span>
<span class="k">switch</span> <span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">case</span> <span class="n">ErrorCode</span><span class="o">::</span><span class="n">e_1</span><span class="p">:</span>
    <span class="n">msg</span> <span class="o">=</span> <span class="s">"Your memory is full."</span><span class="p">;</span>
    <span class="k">break</span><span class="p">;</span>
<span class="k">case</span> <span class="n">ErrorCode</span><span class="o">::</span><span class="n">e_2</span><span class="p">:</span>
    <span class="n">msg</span> <span class="o">=</span> <span class="s">"Your computer has crashed."</span><span class="p">;</span>
    <span class="k">break</span><span class="p">;</span>
<span class="k">case</span> <span class="n">ErrorCode</span><span class="o">::</span><span class="n">e_3</span><span class="p">:</span>
    <span class="n">msg</span> <span class="o">=</span> <span class="s">"I need a reboot!"</span><span class="p">;</span>
    <span class="k">break</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>

<p>Now, it is obvious that a ternary operator won’t work; nesting them, on the other hand, will probably make the code too messy. 
So, what can we do?</p>

<h2 id="wrapping-the-switch-statement-into-a-lambda">Wrapping the <code class="language-plaintext highlighter-rouge">switch</code> statement into a Lambda</h2>

<p>One way to rewrite our initialisation code in a more “expression oriented” manner is to wrap the <code class="language-plaintext highlighter-rouge">switch</code> <em>statement</em> into a lambda function, like this:</p>

<figure class="highlight"><pre><code class="language-cpp" data-lang="cpp"><span class="k">const</span> <span class="k">auto</span> <span class="n">msg</span> <span class="o">=</span> <span class="p">[</span><span class="o">&amp;</span><span class="p">]</span> <span class="p">{</span>
    <span class="k">switch</span> <span class="p">(</span><span class="n">errCode</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">case</span> <span class="n">ErrorCode</span><span class="o">::</span><span class="n">e_1</span><span class="p">:</span>
            <span class="k">return</span> <span class="s">"Your memory is full."</span><span class="p">;</span>
        <span class="k">case</span> <span class="n">ErrorCode</span><span class="o">::</span><span class="n">e_2</span><span class="p">:</span>
            <span class="k">return</span> <span class="s">"Your computer has crashed."</span><span class="p">;</span>
        <span class="k">case</span> <span class="n">ErrorCode</span><span class="o">::</span><span class="n">e_3</span><span class="p">:</span>
            <span class="k">return</span> <span class="s">"I need a reboot!"</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}();</span></code></pre></figure>

<p>It looks nice (to me at least!) and solves all of the problems above making our code more compact, self-contained and less error prone.</p>

<p>Also notice that, although it may look like “extra work” at first, this code is actually shorter than its “non-lambda” counterpart (mostly because we got rid of the <code class="language-plaintext highlighter-rouge">break</code>s).</p>

<p>But what about performance? 
Since we now added some function-calling machinery to our code, it is indeed possible to face a performance cost. 
My understanding however is that compilers should be able to optimise this in such a way that the generated assembly looks pretty much the same as the one generated from the “non-lambda” version. 
I haven’t tried this myself though, so please take it with a pinch of salt (and do your own research/measurements if you are working on highly performance-sensitive code!).</p>

<h2 id="conclusion">Conclusion</h2>

<p>Functional programmig is becoming more and more mainstream;
not only the use of functional programming languages (such as Haskell, OCaml, F# etc.) is increasing, but, at the same time, traditional imperative languages are adopting more and more “functional” features. An example of this is Lambda functions.</p>

<p>This post discusses a simple trick to rewrite your <code class="language-plaintext highlighter-rouge">switch</code> statements in a more functional, expression-oriented style using a lambda function. Although we used C++, this should apply to other high-level imperative/O.O. languages like C#, Java etc.</p>

<h2 id="referenceslinks">References/links</h2>

<ul>
  <li>
    <p><a href="https://www.amazon.co.uk/Tour-C-Depth/dp/0134997832/ref=pd_lpo_sbs_14_img_0?_encoding=UTF8&amp;psc=1&amp;refRID=0J2C5W50QPMSTGXF833X">A Tour of C++ (Second Edition) by Bjarne Stroustrup</a> - this topic is briefly discussed in Section 6.3.3 while introducing lambda functions</p>
  </li>
  <li>
    <p><a href="https://www.youtube.com/watch?v=YgcUuYCCV14">Functional C++ for Fun and Profit by Phil Nash</a> - interesting talk addressing many topics including the one discussed in this post (3:39)</p>
  </li>
  <li>
    <p><a href="https://en.cppreference.com/w/cpp/language/lambda">Lambda expressions reference</a></p>
  </li>
</ul>]]></content><author><name>Daniele Filaretti</name></author><summary type="html"><![CDATA[In the last few months I got involved in audio software development with C++ and the JUCE framework, and since at the same time I’ve been writing Haskell in my day job]]></summary></entry><entry><title type="html">The Halting Problem</title><link href="https://danielefilaretti.com/Halting-Problem/" rel="alternate" type="text/html" title="The Halting Problem" /><published>2016-07-20T00:00:00+00:00</published><updated>2016-07-20T00:00:00+00:00</updated><id>https://danielefilaretti.com/Halting-Problem</id><content type="html" xml:base="https://danielefilaretti.com/Halting-Problem/"><![CDATA[<p>Before looking at the <em>halting problem</em>, it is worth considering why it is interesting in the first place.
One of the reasons the halting problem is important is that it is an entry point to a more fundamental issue: <em>is there anything that computers cannot do</em>?</p>

<p>A couple of clarifications are in order:</p>

<ul>
  <li>
    <p>this is not about processor speed, memory size or other technological details. We are not asking “is there anything that compters cannot do <em>right now</em> but may be able to do in 50 years?”. We are asking: “is there anything no computer can do – doesn’t matter if now or in 50 or 1000 years?”.</p>
  </li>
  <li>
    <p>this is not about things such as “can computers eat and digest ice cream?”. There are no tricks: in this post we will be talking about plain, dumb computer-as-a-calculator stuff: reading a numeric or textual input, doing some work and eventually returning some answer (or performing a set of actions).</p>
  </li>
</ul>

<p>Before answering this questions, let us first take a quick look at two concepts that will be useful for our understanding of the halting problem and its consequences.</p>

<h1 id="terminating-programs">Terminating programs</h1>

<p>What does it mean for a program to terminate?
Well, as the word says, <em>a program terminates when it finishes its job (whatever that is) in a finite amount of time</em> (usually providing an answer or performing some action as a result):</p>

<ul>
  <li>
    <p>a program receiving two integers, performing their sum and returning the result to the user.</p>
  </li>
  <li>
    <p>an mp3 converter taking a raw WAV audio file as input, performing some work and after a minute or so returning a compressed mp3 file.</p>
  </li>
  <li>
    <p>a search engine receiving a string (the search query), and returning a web page containing the search result.</p>
  </li>
</ul>

<p>In reality however, <em>programs may occasionally not terminate</em>.
For example, the following function starts printing the string <code class="language-plaintext highlighter-rouge">"hi"</code> and never stops:</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">alwaysLoops</span> <span class="p">():</span>
    <span class="k">while</span> <span class="n">true</span><span class="p">:</span>
        <span class="k">print</span> <span class="s">"hi"</span></code></pre></figure>

<p>Run it, and your programming environment will likely crash or become unresponsive in some way or another.</p>

<p>This is clearly an extreme example; in reality, this kind of behavior appears sporadically, most likely as a result of some particular input:</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">sometimesLoops</span> <span class="p">(</span><span class="n">n</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="k">while</span> <span class="n">true</span><span class="p">:</span>
            <span class="k">print</span> <span class="s">"hi"</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">print</span> <span class="s">"DONE"</span></code></pre></figure>

<p>Here, we see that <code class="language-plaintext highlighter-rouge">sometimesLoops</code> goes into an infinite loop only when the input is <code class="language-plaintext highlighter-rouge">0</code> and prints the string <code class="language-plaintext highlighter-rouge">"DONE"</code> in all other cases.</p>

<p>While <code class="language-plaintext highlighter-rouge">alwaysLoops</code> never terminates, <code class="language-plaintext highlighter-rouge">sometimesLoops</code>  terminates <em>most of the times</em>; still, we can’t say that it terminates <em>on all inputs</em>, because there is one particular input, <code class="language-plaintext highlighter-rouge">0</code>, for which it does <em>not</em> terminate.</p>

<h1 id="programs-that-eat-programs">Programs that eat programs</h1>

<p>We have seen programs that takes integers, strings or some sort of data as their input in order to produce their output.
But this is not the end of the story. One thing programs can do, for example, is to <em>take another program</em> as their input, and even produce a new program as their output.</p>

<p>This should be no surprise for programmers since tools like <em>compilers</em>, <em>interpreters</em>, and <em>static analysers</em> are nothing but programs whose task is to take another program as their input and either: translate it into another form (compiler), execute it (interpreter) or scan it for possible issues (static analyser).</p>

<p>Since programs are stored as plain text files, it shouldn’t be surprising to know that there’s nothing preventing a program to read another program and do something with it:</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">readAProgram</span> <span class="p">(</span><span class="n">filename</span><span class="p">):</span>
    <span class="n">program</span> <span class="o">=</span> <span class="n">Path</span><span class="p">(</span><span class="n">filename</span><span class="p">).</span><span class="n">read_text</span><span class="p">()</span>
    <span class="c1"># now process 'program' in some way!</span></code></pre></figure>

<p>This is a huge topic and we’ll not go into details here. For now, just bear in mind that as well as taking “data” as their input, program may, in some circumstances, receive, manipulate and return other programs.</p>

<h1 id="the-halting-problem">The halting problem</h1>

<p>Given an aribitrary program <code class="language-plaintext highlighter-rouge">P</code>, does <code class="language-plaintext highlighter-rouge">P</code> <em>always</em> terminate? Or, in other words, does <code class="language-plaintext highlighter-rouge">P</code> terminate <em>on all inputs</em>?
For very simple programs, answering this question is trivial. For example, for both of our examples, <code class="language-plaintext highlighter-rouge">alwaysLoops</code> and <code class="language-plaintext highlighter-rouge">sometimesLoops</code> the answer is a <em>no</em>.
The reason is that <code class="language-plaintext highlighter-rouge">alwaysLoops</code> never terminates, while <code class="language-plaintext highlighter-rouge">sometimesLoops</code> terminates in most cases but it still gets stuck in an <em>infinite loop</em> when the input is <code class="language-plaintext highlighter-rouge">0</code>.
Therefore, we can claim that none of them terminates <em>on all inputs</em>.</p>

<p>So far so good, but what if our program suddently becomes hunderds, thousands or million lines long? 
I’m sure you don’t need me to convice you that <em>our simple reasoning technique will be impractical in this new scenario</em>.
But… wait! <em>Maybe we can write a program for that, right?</em> That is: can we write a program that takes another program <code class="language-plaintext highlighter-rouge">P</code> as its input, and tries to determine whether <code class="language-plaintext highlighter-rouge">P</code> always terminate (or not)?</p>

<p>Let’s think about it. Suppose such an algorithm, called <code class="language-plaintext highlighter-rouge">termination</code>, exists; it takes a <em>file name</em> and returns <code class="language-plaintext highlighter-rouge">true</code> if the program contained in the file terminates (on all inputs) and <code class="language-plaintext highlighter-rouge">false</code> otherwise:</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">termination</span> <span class="p">(</span><span class="n">filename</span><span class="p">):</span>
    <span class="c1"># 1) read program contained in 'filename'
</span>    <span class="c1"># 2) do something smart.
</span>    <span class="c1"># 3) return true/false</span></code></pre></figure>

<p>So far so good. Remember, we are assuming that that our <code class="language-plaintext highlighter-rouge">termination</code> function is smart enough so that it can take <em>any</em> program and respond to the halting question correctly.
Consider the following program then (assuming it is stored in <code class="language-plaintext highlighter-rouge">strangeFunction.py</code>):</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">strangeFunction</span><span class="p">():</span> 
    <span class="k">while</span> <span class="p">(</span><span class="n">termination</span><span class="p">(</span><span class="s">"strangeFunction.py"</span><span class="p">)):</span>
        <span class="c1"># doesn't matter what's here!
</span>    </code></pre></figure>

<p>Does <code class="language-plaintext highlighter-rouge">strangeFunction</code> terminate? We have two cases to consider:</p>

<ul>
  <li>
    <p><em><code class="language-plaintext highlighter-rouge">strangeFunction</code> terminates</em> – In this case, the call <code class="language-plaintext highlighter-rouge">termination(strangeFunction.py)</code> must return <code class="language-plaintext highlighter-rouge">true</code>. Why? Because <code class="language-plaintext highlighter-rouge">termination</code> takes an existing program and determines whether it terminates or not – that’s its job! Now, take a closer look at the code for <code class="language-plaintext highlighter-rouge">strangeFunction</code>: can you see where the problem is? That’s right: <code class="language-plaintext highlighter-rouge">termination(strangeFunction.py)</code> returns true (since <code class="language-plaintext highlighter-rouge">strangeFunction</code> terminates) but this causes the <code class="language-plaintext highlighter-rouge">while</code> loop to loop indefinitely meaning that… <code class="language-plaintext highlighter-rouge">strangeFunction</code> <em>cannot</em> terminate!</p>
  </li>
  <li>
    <p>On the other hand, assume <em><code class="language-plaintext highlighter-rouge">strangeFunction</code> does not terminate</em>. Once again <code class="language-plaintext highlighter-rouge">termination(strangeFunction.py)</code> will do its job correctly, this time returning <code class="language-plaintext highlighter-rouge">false</code>. But we are up for more troubles: given how <code class="language-plaintext highlighter-rouge">strangeFunction</code> is deﬁned, this time the <code class="language-plaintext highlighter-rouge">while</code> loop will finish immediately (since its argument is <code class="language-plaintext highlighter-rouge">false</code>) which means that <em><code class="language-plaintext highlighter-rouge">strangeFunction</code> does actually terminate</em>!</p>
  </li>
</ul>

<p>Since in both cases we reached a contradiction, our assumption about the existence of <code class="language-plaintext highlighter-rouge">termination</code> must have been wrong. Therefore, we must take a step back and accept the fact that <em>a program such as <code class="language-plaintext highlighter-rouge">termination</code> cannot exists</em>.</p>

<p>In other words we have shown that <em>it is not possible to write a program that solves the halting problem</em>!</p>

<h1 id="conclusion">Conclusion</h1>

<p>In this post, we explained the <em>halting problem</em> in an intuitive way and, on the side, we also clarified what we mean by terminating/non-terminating programs and briefly introduced the concept of <em>programs that manipulates other programs</em>.</p>

<p>We have seen that despite it being quite a well defined input-output problem (i.e. no “tricks” involved), <strong>it is not possible to write a program that solves the halting problem</strong>.</p>

<p>More broadly, this means that <em>there exist some problem that cannot be solved by a computer</em>, which answers our initial question: “is there anything that computers cannot do?” The answer is <em>yes</em>, and the halting problem is one example.</p>

<p>So we can’t solve the halting problem with a computer – fair enough. But <em>is there anything else computers can’t do?</em> Or is it the halting problem alone?”
This will be the topic of a future post where we discuss how the halting problem affects (among many other things) the branch of computer science that deals with software verification and static analysis.</p>]]></content><author><name>Daniele Filaretti</name></author><summary type="html"><![CDATA[Before looking at the _halting problem_, it is worth considering why it is interesting in the first place. One of the reasons the halting problem is important is that it is an entry point to a more fundamental issue: _is there anything that computers cannot do_?]]></summary></entry></feed>