<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Asymptotically Typeable</title>
    <link>https://blog.grgz.me/</link>
    <description>Thoughts and experiments of a programming-languages passionate</description>
    <language>en</language>
    <lastBuildDate>Tue, 29 Apr 2025 12:43:38 -0000</lastBuildDate>
	<item>
<title>SIGBOVIK&#x27;25: Programmatic Planned Obsolescence</title>
<description>&lt;p&gt;
&lt;a href=&quot;https://blog.grgz.me/posts/sigbovik24-getting-up-and-running-lambda-calculus.html&quot;&gt;Once again&lt;/a&gt;, I am published in the prestigious &lt;a href=&quot;https://sigbovik.org&quot; target=&quot;_blank&quot;&gt;SIGBOVIK&lt;/a&gt;!
You can read my paper &lt;em&gt;Programmatic Planned Obsolescence&lt;/em&gt; on page 105 of the &lt;a href=&quot;https://sigbovik.org/2025/proceedings.pdf&quot; target=&quot;_blank&quot;&gt;2025 proceedings [pdf]&lt;/a&gt; or you can read it directly &lt;a href=&quot;https://grgz.me/sigbovik25.pdf&quot; target=&quot;_blank&quot;&gt;on my website [pdf]&lt;/a&gt; (without downloading the whole 413-page proceedings) where hyperlinks work and where I may update it to fix typos.
The last paragraph of this blog post is the abstract of the paper.&lt;/p&gt;&lt;p&gt;
&lt;em&gt;What is SIGBOVIK?&lt;/em&gt; In their own words, SIGBOVIK publishes academic work in
&lt;blockquote&gt;
the three neglected quadrants of research: joke realizations of joke ideas, joke realizations of serious ideas, and serious realizations of joke ideas.
&lt;/blockquote&gt;&lt;/p&gt;
&lt;p&gt;
What is included with the paper:
&lt;ul&gt;
&lt;li&gt;A free program to slow down any of your or your comeptitor&#x27;s Java/Scala/Clojure/Jython programs!&lt;/li&gt;
&lt;li&gt;A non-comprehensive history of planned obsolescence,&lt;/li&gt;
&lt;li&gt;Not just one, but two Java implementations of the classic and much-beloved ed text editor,&lt;/li&gt;
&lt;li&gt;Two pages of commutative diagrams that you can quickly skip to if your advisor is lurking nearby,&lt;/li&gt;
&lt;li&gt;Two additional free-of-charge pages of plots and tables that you can quickly skip to if your employer is lurking nearby,&lt;/li&gt;
&lt;li&gt;A never-seen-before compact implementation of the iterative Fibonacci function,&lt;/li&gt;
&lt;li&gt;A novel semantic framework dubbed &lt;em&gt;Foucault&amp;ndash;Deleuze&amp;ndash;Derrida correspondence&lt;/em&gt; a-la Curry&amp;ndash;Howard&amp;ndash;Lambek correspondence used to give dynamic semantics to lifetime,&lt;/li&gt;
&lt;li&gt;A fully-working reusable software artifact &lt;a href=&quot;https://gitlab.com/gzakhour/jgeorge&quot;&gt;here&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;&lt;/p&gt;&lt;p&gt;
&lt;strong&gt;Abstract&lt;/strong&gt;
Should lifetimes have a role beyond memory-safety?
Should they be erased or should they be included in the compilation unit?
Should lifetimes have dynamic semantics?
In this paper we explore a model of programming where these questions are answered in the positive.
First, we revisit the history of object-oriented programming and its broader cultural sphere to identify a dynamic semantic for lifetimes.
Second, we argue that planned obsolescence is not only one such model, but the only model.
Third, we develop this semantics in the framework of category theory and implement it for the Java Virtual Machine.
And finally, We demonstrate empirically through four case studies that programming under planned obsolescence is possible and identify a surprising result:
the paradigm which is the most industry friendly performs the worst while the one which is the least friendly performs the best.&lt;/p&gt;&lt;p&gt;
Happy Reading!&lt;/p&gt;</description>
<link>https://blog.grgz.me/posts/sigbovik25-programmatic-planned-obsolescence.html</link>
<guid isPermaLink="false">https://blog.grgz.me/posts/sigbovik25-programmatic-planned-obsolescence.html</guid>
<pubDate>Tue, 29 Apr 2025</pubDate>
</item>

<item>
<title>SIGBOVIK&#x27;24: Getting Up and Running the λ-Calculus</title>
<description>&lt;p&gt;
I am published in the prestigious &lt;a href=&quot;https://sigbovik.org&quot; target=&quot;_blank&quot;&gt;SIGBOVIK&lt;/a&gt;!
You can go and read my paper &lt;em&gt;Getting Up and Running the λ-Calculus&lt;/em&gt; on page 23 of the &lt;a href=&quot;https://sigbovik.org/2024/proceedings.pdf&quot; target=&quot;_blank&quot;&gt;2024 proceedings [pdf]&lt;/a&gt; or you can read it directly &lt;a href=&quot;https://grgz.me/sigbovik24.pdf&quot; target=&quot;_blank&quot;&gt;on my website [pdf]&lt;/a&gt; (without downloading the whole 482-page proceedings) where I may update it to fix typos.
The last paragraph of this blog post is the abstract of the paper.&lt;/p&gt;&lt;p&gt;
&lt;em&gt;What is SIGBOVIK?&lt;/em&gt; In their own words, SIGBOVIK publishes academic work in
&lt;blockquote&gt;
the three neglected quadrants of research: joke realizations of joke ideas, joke realizations of serious ideas, and serious realizations of joke ideas.
&lt;/blockquote&gt;&lt;/p&gt;
&lt;p&gt;
The paper is relatively long but it&#x27;s jam-packed with goodies that I&#x27;m quite proud of.
You will find:
&lt;ul&gt;
&lt;li&gt;A new one-of-a-kind programming language being proposed (by the author(s), i.e. me),&lt;/li&gt;
&lt;li&gt;1970s minimal jazz music recommendation (seriously),&lt;/li&gt;
&lt;li&gt;A poem about a programming technique, not too dissimilar from my first poem published on this blog: &lt;em&gt;&lt;a href=&quot;https://blog.grgz.me/posts/kosaraju_poem.html&quot; target=&quot;_blank&quot;&gt;Upon Reading a Friend&#x27;s Message about the Awesomeness of the Kosaraju Algorithm&lt;/a&gt;&lt;/em&gt;,&lt;/li&gt;
&lt;li&gt;The short C11 compiler source code for the language I proposed (just 147 lines long!),&lt;/li&gt;
&lt;li&gt;Citations and comments stemming from a historical investigations of some things: is zero a natural number? Who really said &quot;There are only two hard things in Computer Science: cache invalidation and naming things&quot;? And when?&lt;/li&gt;
&lt;li&gt;(Useless) commutative diagrams,&lt;/li&gt;
&lt;li&gt;A meaningful diagram with this abstract angry man hidden inside it:&lt;br&gt;
&lt;center&gt;
&lt;img src=&quot;https://grgz.me/public/img/sigbovik24/angry_man.png&quot; style=&quot;height:10em&quot;&gt;
&lt;/center&gt;
&lt;/li&gt;
&lt;li&gt;An evaluation section where I put my programming language to the test, resulting in this:&lt;br&gt;
&lt;center&gt;
&lt;img src=&quot;https://grgz.me/public/img/sigbovik24/strava_run.png&quot; style=&quot;height:20em&quot;&gt;
&lt;/center&gt;
&lt;/li&gt;
&lt;/ul&gt;&lt;/p&gt;&lt;p&gt;
&lt;strong&gt;Abstract (Spoiler Alert)&lt;/strong&gt;
Programmers, developers, and coders suffer from a myriad of issues pertaining to their health.
These can vary from eye redness to repetitive strain injuries and a diminished life expectancy.
A common exercise that software practicioners can engage in to reduce these health averse conditions is to be in the outdoors and to move&amp;em;bymeans of walking or running&amp;em;longer.
Alas, professionals are hesitant to pursue their physical and mental well-being as that sacrifices productivity and programming-driven joy.&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;In this paper, we address this problem through the lens of programming languages and provide a solution that greases the friction between outdoor activities and programming.
Through the insight that humans leave a trace while moving and the observation that apparatuses to record such traces are ubiquitous, we formalize an encoding of the λ-calculus in those traces.
We develop an alternative front-end to Church&#x27;s language which we call Poololoop and we provide a reference compiler that produces Haskell and Scheme code.
We evaluate Poololoop on two use-cases that we ran and show that the compilation runs in a few milliseconds.&lt;/p&gt;&lt;p&gt;
Happy Reading and Godspeed!&lt;/p&gt;</description>
<link>https://blog.grgz.me/posts/sigbovik24-getting-up-and-running-lambda-calculus.html</link>
<guid isPermaLink="false">https://blog.grgz.me/posts/sigbovik24-getting-up-and-running-lambda-calculus.html</guid>
<pubDate>Mon, 15 Apr 2024</pubDate>
</item>

<item>
<title>A harder-to-crack Wordle</title>
<description>&lt;p&gt;
Wordle is a game that took the Tweetosphere by storm, seemingly transforming Twitter into the now-defunct emoji-only social network &lt;a href=&quot;https://emoj.li&quot; target=&quot;_blank&quot;&gt;Emojli&lt;/a&gt;.
Countless nerds and word junkies likely litter your Twitter timeline with a daily stream of 30 green, grey, and yellow emoji boxes.
So if you haven&#x27;t joined the status-quo and engaged in this sweet new Internet addiction, here&#x27;s the gist of the game.
It&#x27;s really quite simple.
You have to guess the daily secret word with six tries.
After submitting a guess, the letters in the correct position will light in green, those that appear in the answer but are in the wrong place will light in yellow, and those not in the word dwell in a dull grey.
It&#x27;s a very effective game to make you realize how few five-lettered words you remember or can spit out on demand.
&lt;/p&gt;
&lt;p&gt;
Everyone and their mother have been presenting ideal strategies for playing Wordle.
I want to do something different.
I want to crack Wordle and exhibit fixes that make the game uncrackable.
I know, I know, I&#x27;m cheating.
But I like guarantees, and I like to play a game knowing it&#x27;s guaranteed to be fair.
&lt;/p&gt;
&lt;p&gt;
I&#x27;m not trying to condemn the authors of Wordle and its derivatives for not thinking about making the app uncrackable.
Quite the contrary, they made a great game that I enjoy playing (and breaking) every day.
Wordle was literally a labor of love.
Here&#x27;s a quote from the &lt;a href=&quot;https://www.nytimes.com/2022/01/03/technology/wordle-word-game-creator.html&quot; target=&quot;_blank&quot;&gt;New York Times&lt;/a&gt;: &quot;Josh Wardle, a software engineer in Brooklyn, knew his partner loved word games, so he created a guessing game for just the two of them&quot;.
Me? I&#x27;m just the party-pooper who&#x27;s here to tell everyone how to break (and possibly fix) it.
&lt;/p&gt;
&lt;h2&gt;Wordle&#x27;s setup&lt;/h2&gt;
&lt;p&gt;
The game was such a hit that it spun an alternative for &lt;a href=&quot;https://wordle.danielfrg.com/&quot; target=&quot;_blank&quot;&gt;Spanish&lt;/a&gt;, and a couple for Math like &lt;a href=&quot;https://www.mathler.com/&quot; target=&quot;_blank&quot;&gt;Mathler&lt;/a&gt; and &lt;a href=&quot;https://nerdle.com/&quot; target=&quot;_blank&quot;&gt;Nerdle&lt;/a&gt;.
I argue these spin-offs are possible for two reasons: first, the code is easy to fork, and second, the backend is cheap.
&lt;/p&gt;
&lt;p&gt;
The backend is so cheap that it could practically be removed entirely.
The only interaction you&#x27;ll have with the server is the initial page load.
That&#x27;s it.
Zero contact is made to check if a word is in the dictionary.
Zero contact is made to list the correctly-placed letters.
Zero contact is made.
&lt;em&gt;Nil&lt;/em&gt;.
&lt;/p&gt;
&lt;p&gt;
All but Nerdle can be downloaded locally and played independently of any server.
Nerdle requires a server to download the daily answer.
From here on, the post will assume that it&#x27;s perfectly acceptable to run tiny daily computations on the server like in Nerdle&#x27;s case.
&lt;/p&gt;
&lt;h2&gt;Attacks on Wordle and derivatives&lt;/h2&gt;
&lt;p&gt;
The setup of Wordle, and derivatives, implies that the logic and the data it needs: the dictionary and the daily word, are already present in the code.
Both Wordle and Spanish Wordle provide the dictionary in clear text in the application&#x27;s code (if you think about it, Mathler does not need a dictionary, the expression just needs to parse correctly).
And both Wordle and Mathler put the answer in clear text in your web browser&#x27;s local storage.
&lt;/p&gt;
&lt;p&gt;
Ergo, it&#x27;s easy to crack the answer; just read it from the browser&#x27;s localStorage. The cracking code fits in half-a-tweet:
&lt;/p&gt;
&lt;blockquote&gt;Stuck on wordle and want to see the solution? Make a bookmark with this URL: &lt;br&gt;&lt;br&gt;javascript:alert(JSON.parse(localStorage.gameState).solution)&lt;br&gt;&lt;br&gt;and open it in wordle&lt;br&gt;&lt;br&gt;&amp;mdash; GEZ (@_typeable) &lt;a href=&quot;https://twitter.com/_typeable/status/1485584616761307138&quot;&gt;January 24, 2022&lt;/a&gt;&lt;/blockquote&gt;
&lt;br&gt;
&lt;p&gt;
Nerdle does something strange.
It does store the solution in the localStorage, but only after you&#x27;ve interacted with the page beyond loading it.
So if you open the page and look in the localStorage, you won&#x27;t find anything.
Press a key or a button on the screen, and the solution is written right in the localStorage making Wordle&#x27;s crack achievable here.
Now I&#x27;m a lazy guy, and I want my cracks to work with the least amount of interaction with the page as possible.
&lt;/p&gt;
&lt;p&gt;
However, if you look in the Networks tab, you&#x27;ll find a request to a strange URL that returns an 8-character word.
Nerdle is the only one that requires an 8-character solution.
Could this be an encoding of the equation of the day? An invasive operation inserting a &quot;debugger&quot; statement with medical accuracy reveals that it&#x27;s indeed the encoding.
This URL is also the MD5 hash of the number of days between Nerdle&#x27;s launch and today.
&lt;/p&gt;
&lt;style&gt;code pre { line-height: 1rem !important; }&lt;/style&gt;
The crack, this time in Python 2, fits in four lines:
&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;import hashlib, urllib, time&lt;/pre&gt;
&lt;pre&gt;offset=int((time.time()*1000-16426368e5)/864e5)&lt;/pre&gt;
&lt;pre&gt;url=&quot;https://nerdle.com/words/&quot;+hashlib.md5(str(offset)).hexdigest()&lt;/pre&gt;
&lt;pre&gt;print &quot;&quot;.join([chr((ord(c)+113)%126) for c in urllib.urlopen(url).read()])&lt;/pre&gt;
&lt;/code&gt;
&lt;p&gt;
On the other hand, Spanish Wordle is harder to crack at first glance.
The localStorage&#x27;s &quot;solution&quot; entry is encrypted with what appears to be AES.
The encryption key is buried deep in the code&#x27;s logic, but nothing a surgically placed &quot;debugger&quot; placement can&#x27;t step you through.
Inspecting a curious line of code that contains &quot;AES.decrypt(t,c)&quot; that happened to be called with the encrypted solution reveals that the key and the salt (both pre-generated and not updated daily) are respectively &quot;llanos&quot; and &quot;ibai.&quot;
Parenthesis: I googled llanos and ibai out of curiosity.
The results revealed what I assume to be Spanish Wordle&#x27;s creator&#x27;s alter-ego or favorite e-sport internet streamer: &lt;a href=&quot;https://en.wikipedia.org/wiki/Ibai_Llanos&quot; target=&quot;_blank&quot;&gt;Ibai Llanos&lt;/a&gt;.
How is he related to Spanish Wordle?
Your guess is as good as mine.
End Parenthesis.
&lt;/p&gt;
&lt;p&gt;
So it&#x27;s possible to crack, and the cracker still fits in a single tweet:
&lt;/p&gt;
&lt;blockquote&gt;
Wordle(ES) crack bookmark:&lt;br&gt;&lt;br&gt;
javascript:var d=document;var s=d.createElement(&quot;script&quot;);s.onload=()=&gt;alert(CryptoJS.AES.decrypt(JSON.parse(localStorage.getItem(&quot;solution&quot;)),&quot;llanos&quot;).toString(CryptoJS.enc.Utf8).slice(&quot;ibai&quot;.length));s.src=&quot;https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js&quot;;d.body.append(s) &lt;br&gt;&lt;br&gt;
&amp;mdash; GEZ (@_typeable) &lt;a href=&quot;https://twitter.com/_typeable/status/1490810350836629512&quot;&gt;February 7, 2022&lt;/a&gt;&lt;/blockquote&gt;
&lt;p&gt;
The cracker is more involved, but here&#x27;s the gist of it: it starts by loading CryptoJS from the CDNjs, since accessing the internal AES algorithm proved to be a nightmare.
Once loaded, the script uses the library to decrypt the &quot;solution&quot; entry in localStorage, removes the salted string, and reveals it in the most anachronistic pop-up ever.
&lt;/p&gt;
&lt;p&gt;
&lt;em&gt;Post-script:&lt;/em&gt; As I was getting ready to publish this post, I came across &lt;a href=&quot;https://www.youtube.com/watch?v=v68zYyaEmEA&quot; target=&quot;_blank&quot;&gt;3Blue1Brow&#x27;s video&lt;/a&gt; about finding the best strategy to find an answer in Wordle.
Go watch it.
What&#x27;s relevant in this video is that Grant quickly mentions a possible attack at 4:47.
Here&#x27;s what he says: &quot;The way that it&#x27;s [the list of possible answers] visible in the source code is in the specific order in which answers come up from day-to-day. That you can always look up what tomorrow&#x27;s answer will be.&quot;
&lt;/p&gt;
&lt;p&gt;
This brings us to these fundamental questions: can we keep everything encrypted?
Can we compute the properties of a guess without needing to store clear text versions anywhere?
If there are encryption keys, can we avoid providing their generation algorithm?
Can we do that in the least amount of memory possible?
This sounds like a job for homomorphic encryption, but let&#x27;s not get carried away and think of simpler alternatives.
&lt;/p&gt;
&lt;p&gt;
To give you an idea of how much each application uses, Wordle&#x27;s code is in a 173.34KB javascript file, Spanish Wordle&#x27;s code is in a 639.04KB file, and Mathler&#x27;s code is in a 198.71KB file.
&lt;/p&gt;
&lt;h2&gt;Admissible attacks&lt;/h2&gt;
&lt;p&gt;
If we can answer yes to all the questions above, we should be vulnerable to only two attacks.
&lt;/p&gt;
&lt;p&gt;
The first is a naive daily dictionary attack, in which the attacker generates a rainbow table for each combination of letters and tries each individually.
I say each five-letter word combination because the dictionary will be &quot;encrypted,&quot; so the attacker will not know which words we use and which we don&#x27;t.
&lt;/p&gt;
&lt;p&gt;
In the second attack, the attacker utilizes the properties of the guess to improve the searching strategy.
I argue that this is perfectly fine because the attacker is now playing the game, as intended!
&lt;/p&gt;
&lt;h2&gt;The proposed solutions&lt;/h2&gt;
&lt;p&gt;
&lt;em&gt;Disclaimer&lt;/em&gt;: I am not an expert in cryptography or privacy-preserving techniques.
If you are an expert and think my analysis is faulty, please shoot a tweet at me.
&lt;/p&gt;
&lt;p&gt;
In the following, I present three techniques that I experimented with.
All three proposals provide almost-complete secrecy about the guess and the dictionary and the zero-contact requirement of the setup.
There is only some daily code that the backend must execute.
If you want to read what I deem to be the best technique (shortest code, simplest conceptually, and most economical memory-wise), then head over to the last section.
The order in which I present the solutions follows my chronology of discovering them.
&lt;/p&gt;
&lt;p&gt;
&lt;em&gt;Update (12/02/2022):&lt;/em&gt;
I have implemented a proof-of-concept which is available on my &lt;a href=&quot;https://github.com/geezee/poc-no-crack-wordle&quot; target=&quot;_blank&quot;&gt;Github&lt;/a&gt;.
There is also a running instance that generates a new word every hour &lt;a href=&quot;https://grgz.me/wordle&quot; target=&quot;_blank&quot;&gt;on my website&lt;/a&gt;.
To encourage cracking this instance, no code was obfuscated or minimized, no library was used, and only the essential features were implemented.
&lt;/p&gt;
&lt;h3&gt;Bloom Filters&lt;/h3&gt;
&lt;p&gt;
If you are unaware of Bloom Filters, they are fundamentally a set with two operations: adding and checking membership.
A Bloom filter starts as a fixed-length array of 0s.
To add an item to the Bloom filter, you hash it k times, then put a 1 at the index equalling the hash.
To check the membership of an item, you hash it k times and make sure that all the entries in the array at those hashes are 1s.
&lt;/p&gt;
&lt;p&gt;
A Bloom filter of all the words in the dictionary will not store these words, nor their hashes.
So they are perfect for hiding what the elements are.
&lt;/p&gt;
&lt;p&gt;
Great, if the server encodes a Bloom filter in the code, then we can tell if a guess is a valid word or not.
Next question: how do we check if the second letter of the guess is in the correct place?
&lt;/p&gt;
&lt;p&gt;
I propose that we construct a Bloom filter for every word index.
The words we will add to that filter are those valid words with the correct letter in that position.
For example, if today&#x27;s mystery word is &quot;ghost,&quot; we will construct five filters.
The first will contain words like &quot;glass&quot; and &quot;gamer,&quot; the second words like &quot;phase&quot; and &quot;rhyme,&quot; the third words like &quot;khaki&quot; and &quot;twang,&quot; etc...
&lt;/p&gt;
&lt;p&gt;
Notice that if a word is in all those five filters, then the guess is the word of the day.
So nothing special has to be done.
&lt;/p&gt;
&lt;p&gt;
Okay, now how do we check if a letter which appears in the solution is wrongly placed?
&lt;/p&gt;
&lt;p&gt;
Even more bloom filters! To be precise, five more bloom filters.
Each one will be associated with a word index.
So in the first Bloom filter, we will put all the words that start with all the letters which occur in the answer that are not the first letter.
More concretely, if today&#x27;s word is again &quot;ghost,&quot; the first Bloom filter will contain words like &quot;honey,&quot; &quot;octal,&quot; &quot;state,&quot; and &quot;taunt&quot;.
The same is done for the other four indices.
&lt;/p&gt;
&lt;p&gt;
Done.
Problem solved.
Probably though, right?
Right.
A Bloom filter is a probabilistic data structure.
There will be some false positives.
In other words, we may say &quot;correct, the second letter is indeed an E,&quot; yet the actual answer&#x27;s second letter is an S.
Imagine the barrage of intimidating tweets you&#x27;ll receive when this happens.
This actually happened to me while testing out this solution.
Not the stream of tweets, fortunately, but the false positives.
The trivial fix would be to iterate over all 26&lt;sup&gt;5&lt;/sup&gt; possible words, check if the bloom filter has false positives, and regenerate it with new hashes if it&#x27;s the case.
&lt;/p&gt;
&lt;p&gt;
These bloom filters can be constructed in one pass over the dictionary.
So the runtime is linear in the size of the dictionary.
It should be fast to do by a server just before midnight every night.
&lt;/p&gt;
&lt;p&gt;
On the other side, how much will our poor gamer have to download? Sadly no caching can be leveraged (as with all the solutions I present).
&lt;a href=&quot;https://hur.st/bloomfilter&quot; target=&quot;_blank&quot;&gt;This is a fantastic calculator&lt;/a&gt; to find the optimal parameters for a Bloom filter.
Our dictionary will include the 13K words of Wordle and have 1/26&lt;sup&gt;5&lt;/sup&gt; false positive probability that boils down to 53.8KB.
The remaining 10 Bloom filters will contain 13K words in the worst case with a chance of 1/13K of false positives that end up being 31.29KB each.
Total: 366.7KB.
Twice Wordle and some change.
&lt;/p&gt;
&lt;h3&gt;Finite-Field Polynomials&lt;/h3&gt;
&lt;p&gt;
Can we do better memory-wise?
An optimal Bloom filter has 50% of its entries 0s.
Can we get rid of those somehow?
&lt;/p&gt;
&lt;p&gt;
This proposal relies on observing that a polynomial of the shape (x-x&lt;sub&gt;1&lt;/sub&gt;)...(x-x&lt;sub&gt;n&lt;/sub&gt;) precisely has these n roots: x&lt;sub&gt;1&lt;/sub&gt;, x&lt;sub&gt;2&lt;/sub&gt;, until x&lt;sub&gt;n&lt;/sub&gt;, and has n coefficients.
As it so happens, this is also the case in finite fields such as &lt;strong&gt;Z&lt;/strong&gt;&lt;sub&gt;p&lt;/sub&gt; where p is a prime, i.e., all the numbers between 0 (inclusive) and p (exclusive).
&lt;/p&gt;
&lt;p&gt;
It&#x27;s rather critical to work in &lt;strong&gt;Z&lt;/strong&gt;&lt;sub&gt;p&lt;/sub&gt; and not good-ol&#x27; &lt;strong&gt;R&lt;/strong&gt;.
The reason has nothing to do with floating-point errors or compressing coefficients.
Working in &lt;strong&gt;R&lt;/strong&gt; allows an attacker to use Newton&#x27;s method to find all the roots of a given polynomial in just a handful of applications.
We want to hide as many properties about our polynomial as possible from the attacker.
Luckily, root finding in &lt;strong&gt;Z&lt;/strong&gt;&lt;sub&gt;p&lt;/sub&gt; is hard.
The standard algorithm I&#x27;m aware of is &lt;a href=&quot;https://en.wikipedia.org/wiki/Chien_search&quot; target=&quot;_blank&quot;&gt;Chien search&lt;/a&gt; which is essentially just a fancy brute-force search.
&lt;/p&gt;
&lt;p&gt;
To detect whether a guess is in the dictionary or not, we start by choosing a &lt;em&gt;perfect&lt;/em&gt; hashing function for all the possible 26&lt;sup&gt;5&lt;/sup&gt; words.
Next, we compute the coefficients of (x-h(w&lt;sub&gt;1&lt;/sub&gt;))...(x-h(w&lt;sub&gt;n&lt;/sub&gt;)) where w&lt;sub&gt;1&lt;/sub&gt;...w&lt;sub&gt;n&lt;/sub&gt; are the words in our dictionary.
When presented with a guess, we can evaluate the polynomial at the hash of the guess and check whether the answer is zero or not.
&lt;/p&gt;
&lt;p&gt;
In my experience, this perfect hashing function can be found pretty quickly, often in less than 5 trials.
Moreover, computing the polynomial&#x27;s coefficients by expanding its factors can be done in quadratic time in the size of the dictionary.
And the evaluation can be done in linear time in the size of the dictionary.
&lt;/p&gt;
&lt;p&gt;
Since our domain must be &lt;strong&gt;Z&lt;/strong&gt;&lt;sub&gt;p&lt;/sub&gt;, and we must support encoding 26&lt;sup&gt;5&lt;/sup&gt; words, we&#x27;ll choose the prime 11881379.
This is the first prime after 26&lt;sup&gt;5&lt;/sup&gt;.
So all our numbers, hashes, and coefficients can be stored in log&lt;sub&gt;2&lt;/sub&gt;(11881379) = 24 bits.
&lt;/p&gt;
&lt;p&gt;
Next problem: how can we know whether the first letter is correct or exists in the answer?
I propose to encode all these properties in a single small number.
This is the scheme I adopted.
Let&#x27;s work in base 3, where 0 means a letter is correctly placed, 1 means the letter exists in the answer, and 2 means that the letter does not exist.
For example, if today&#x27;s word is once again &quot;ghost,&quot; the guess &quot;chogs&quot; is encoded as 20011 in base 3 or 166 in base 10.
&lt;/p&gt;
&lt;p&gt;
So we can construct another polynomial that interpolates the hash of every dictionary word and its encoding.
However, this time, we need a perfect hashing function not for 26&lt;sup&gt;5&lt;/sup&gt; words but for 13K words.
Luckily 13001 is a nice close prime number.
This means all our numbers for this polynomial will fit in log&lt;sub&gt;2&lt;/sub&gt;(13001) = 14 bits.
&lt;/p&gt;
&lt;p&gt;
This interpolation can be trivially done using Lagrange interpolation in cubic time.
Which in practice will take a long time, hardly less than half an hour.
But it can be squeezed down to a quadratic time which is just fast enough.
&lt;/p&gt;
&lt;p&gt;
The first polynomial has 13K coefficients taking each 24 bits.
The second one also has 13K coefficients, but each takes 14 bits.
Total: 61.75KB.
This is a reduction factor of 5 from the Bloom filter solution!
Putting us at half the size of Wordle.
&lt;/p&gt;
&lt;h3&gt;Hashes to Hashes&lt;/h3&gt;
&lt;p&gt;
The motivation is as follows: there is still some waste in the finite field approach; the result of computing our second polynomial is 14 bits long, yet we only need 8 bits to store the biggest encoding (22222 in ternary = 242 in decimal).
How to represent a function with a domain of 14 bits and a codomain of 8 bits?
Hash-tables, D&#x27;uh!
And do we really need that first polynomial now?
Can&#x27;t we just map these 24 bits directly to these 8 bits?
&lt;/p&gt;
&lt;p&gt;
Of course, we can!
But there&#x27;s a catch, we should salt these 8 bits.
Otherwise, we&#x27;d be vulnerable to a new attack.
The number of words that hash into 21112 in ternary (203 in decimal) is a good enough hint to the answer.
For example, if the attacker sees 103 numbers that hash into 203, they&#x27;ll deduce that the answer must be one of only 31 possible words (tiara, angry, evoke, amigo, latex, to list a few).
If they spot 27 203s, then the range of possible words is 174.
If that number turns out to be still too large for the attacker, they can look at how many hashes map into 21211, for example, and take the intersection of those two lists.
In this fashion, an attacker can avoid a full dictionary attack. Salting the property with the hash of the word (using a different hashing function than the key) eliminates this attack.
&lt;/p&gt;
&lt;style&gt;code pre { line-height: 1rem !important; }&lt;/style&gt;
The whole construction fits neatly in this seven-line Python script:
&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;import random&lt;/pre&gt;
&lt;pre&gt;def n_bits(num, n): return num &amp; ((1&lt;&lt;(n+1))-1)&lt;/pre&gt;
&lt;pre&gt;words = list(filter(lambda x: len(x)==5, map(lambda x: x[:-1], open(&quot;dict.txt&quot;).readlines())))&lt;/pre&gt;
&lt;pre&gt;k1 = random.randint(0, 1&lt;&lt;25)&lt;/pre&gt;
&lt;pre&gt;k2 = random.randint(0, 1&lt;&lt;9)&lt;/pre&gt;
&lt;pre&gt;answer = random.choice(words)&lt;/pre&gt;
&lt;pre&gt;table = { n_bits(hash(w,k1), 24): compare(w,answer) + n_bits(hash(w,k2), 8) for w in words }&lt;/pre&gt;
&lt;/code&gt;
&lt;p&gt;
The code above clearly computes the hash table in one swoop over the dictionary.
So its runtime is linear.
&lt;/p&gt;
&lt;p&gt;
What about memory consumption? The key of the hash table is 24 bits long, and the values are 8 bits long.
So for every entry, we only need 32 bits.
In other words, one integer!
How elegant!
In total, our hashtable will be 52KB big.
That&#x27;s slightly less than the 58.3KB gzipped Wordle code.
&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;
It&#x27;s possible to have versions of Wordle that do not expose either the dictionary or the word of the day to the player.
The downside of the Bloom filter approach, besides its relatively porky size, is its probabilistic nature.
So extra work has to be done to check that no player will complain.
&lt;/p&gt;
&lt;p&gt;
Although the latter two methods are not probabilistic, they rely on perfect hashes.
This undoubtedly means extra work.
But where they shine is in their slim and graceful size.
&lt;/p&gt;
&lt;p&gt;
Earlier I said these schemes provide almost-complete secrecy about the dictionary because there was one property that I couldn&#x27;t hide: the size of the dictionary.
Here, the Bloom filter has the advantage.
Because it can only approximate the number of elements inside it.
This parameter could be a clue for the attacker to factor in his evil scheme.
But I believe that this can be fixed by randomly adding bogus elements that map to invalid properties to the data structures, making them appear larger than they actually are.
However, this entails more bytes to be downloaded.
&lt;/p&gt;</description>
<link>https://blog.grgz.me/posts/crack-wordle.html</link>
<guid isPermaLink="false">https://blog.grgz.me/posts/crack-wordle.html</guid>
<pubDate>Wed, 09 Feb 2022</pubDate>
</item>

<item>
<title>On Computing Derivatives</title>
<description>&lt;script type=&quot;text/x-mathjax-config&quot;&gt;
MathJax.Hub.Config({tex2jax: {inlineMath: [[&#x27;$&#x27;,&#x27;$&#x27;], [&#x27;\\(&#x27;,&#x27;\\)&#x27;]]}});
&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML&quot;&gt;
&lt;/script&gt;
&lt;p&gt;
In this blog post, I review techniques for computing $\frac{\partial}{\partial x_i} f$ for $f: \mathbb{R}^n \to \mathbb{R}^m$.
Broadly, there are three techniques: numerical, symbolic, and automatic differentiation.
Among them, the most remarkable and useful is the Automatic Differentiation (AD) technique in its reverse mode (or adjoint mode).
I will show you how, using first principles, you could&#x27;ve derived it yourself.
(Do not expect code in this blog post, but expect a lot of equations.)
&lt;/p&gt;
&lt;p&gt;
In practice, every time you face an optimization problem, you will have to compute a derivative.
Gradient-descent techniques require the first-order derivative, and Newton&#x27;s method requires a second-order one.
If you still need motivation to carry on, consider that training a neural network is an optimization problem.
The de-facto neural network training algorithm is Backpropagation.
It starts by computing its derivative, updating the weights in reverse, rinsing, and repeating...
And where does AD come into play?
Well, Backpropagation is a special case of AD.
It&#x27;s also precisely this reverse-mode AD I mentioned earlier.
And what&#x27;s more, Backpropagation is an optimized way of implementing reverse-mode AD.
So stick around if you want to know its origins and why you propagate backward.
&lt;/p&gt;
Some of my sources and recommended readings are:
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://www.jmlr.org/papers/v18/17-468.html&quot; target=&quot;_blank&quot;&gt;Automatic Differentiation in Machine Learning: a Survey&lt;/a&gt;
by Baydin, Pearmutter, Radul, and Siskind, in the 2018 Journal of Machine Learning Research (JMLR&#x27;18)&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.cs.princeton.edu/courses/archive/fall19/cos597C/files/wengert1964.pdf&quot; target=&quot;_blank&quot;&gt;A Simple Automatic Derivative Evaluation Program&lt;/a&gt;
by R. E. Wengert in Communications of the ACM, Volume 7, Issue 8, Aug. 1964, doi: 10.1145/355586.364791&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://rufflewind.com/2016-12-30/reverse-mode-automatic-differentiation&quot; target=&quot;_blank&quot;&gt;Reverse-mode automatic differentiation: a tutorial&lt;/a&gt; by Rufflewind&lt;/li&gt;
&lt;li&gt;Some old notes for courses I&#x27;ve assisted in.&lt;/li&gt;
&lt;/ul&gt;
&lt;br&gt;
&lt;h2&gt;Numerical Differentiation&lt;/h2&gt;
&lt;p&gt;
First, a foreward: In this section, I will only consider $f: \mathbb{R} \to \mathbb{R}$ that is once, twice, or four times differentiable.
But the techniques are easily generalizable to any $f: \mathbb{R}^n \to \mathbb{R}^m$.
&lt;/p&gt;
&lt;p&gt;
To compute derivatives the first idea is to use the mathematical definition of the derivative
$$ \frac{d}{dx} f(x_0) = \lim_{h \to 0} \frac{f(x+h)-f(x)}{h} $$
We can choose a small $\varepsilon &gt; 0$ and compute $\frac{f(x+\varepsilon)-f(x)}{\varepsilon}$.
&lt;/p&gt;
&lt;p&gt;
This is an approximation and not an exact value, which begs the question of how good is this approximation?
Using Taylor&#x27;s theorem, we can answer that question.
We know that
$$ f(x) = f(x_0) + f&#x27;(x_0) (x-x_0) + O\left((x-x_0)^2\right) $$
This $O(\cdot)$ is the big-O notation that we computer scientists know and love.
Setting $x \to x+\varepsilon$, and $x_0 \to x$, we get
$$ f(x+\varepsilon) = f(x) + f&#x27;(x)\varepsilon + O(\varepsilon^2) $$
and after rearranging:
$$ f&#x27;(x) = \frac{f(x+\varepsilon)-f(x)}{\varepsilon} + O(\varepsilon) $$
which means that our error is proportional to $\varepsilon$;
cutting $\varepsilon$ in half will cut the error in half too.
&lt;/p&gt;
&lt;p&gt;
Can we approximate better?
Luckily, a fancy trick with a fancy name comes to the rescue: central differencing scheme.
Is tells us to use the following approximation:
$$ f&#x27;(x) \approx \frac{f(x+\varepsilon)-f(x-\varepsilon)}{2h} $$
To analyze its error, we use Taylor&#x27;s theorem twice.
Once with $x \to x+\varepsilon$ and $x_0 \to x$, and once again with $x \to x-\varepsilon$ and $x_0 \to x$.
This leads to these two identities:
$$ f(x+\varepsilon) = f(x) + f&#x27;(x)\varepsilon + \frac{f&#x27;&#x27;(x)}{2}\varepsilon^2 + O(\varepsilon^3) $$
$$ f(x-\varepsilon) = f(x) - f&#x27;(x)\varepsilon + \frac{f&#x27;&#x27;(x)}{2}\varepsilon^2 + O(\varepsilon^3) $$
Subtracting the second identity from the first and rearranging we get:
$$ f&#x27;(x) = \frac{f(x+\varepsilon)-f(x-\varepsilon)}{2h} + O(\varepsilon^2)$$
which means that our error decreases quadratically with $\varepsilon$;
cutting $\varepsilon$ in half will cut the error by four!
&lt;/p&gt;
&lt;p&gt;
Can we still do better?
I will guide you through a scheme that has an error of $O(\varepsilon^4)$ which I hope will show you how to generalize this technique without having me spell it out.
Somehow symmetry plays a role in improving the error, so inspired by the central differencing scheme, let&#x27;s apply Taylor&#x27;s theorem at these four points:
$x-2\varepsilon$, $x-\varepsilon$, $x+\varepsilon$, and $x + 2\varepsilon$.
We get:
$$ f(x+2\varepsilon) = f(x) + 2f&#x27;(x)\varepsilon + 2f&#x27;&#x27;(x)\varepsilon^2 + \frac{4f&#x27;&#x27;&#x27;(x)}{3}\varepsilon^3 + \frac{2f&#x27;&#x27;&#x27;&#x27;(x)}{3}\varepsilon^4 + O(\varepsilon^5) $$
$$ f(x+\varepsilon) = f(x) + f&#x27;(x)\varepsilon + \frac{f&#x27;&#x27;(x)}{2}\varepsilon^2 + \frac{f&#x27;&#x27;&#x27;(x)}{6}\varepsilon^3 + \frac{f&#x27;&#x27;&#x27;&#x27;(x)}{24}\varepsilon^4 + O(\varepsilon^5) $$
$$ f(x-\varepsilon) = f(x) - f&#x27;(x)\varepsilon + \frac{f&#x27;&#x27;(x)}{2}\varepsilon^2 - \frac{f&#x27;&#x27;&#x27;(x)}{6}\varepsilon^3 + \frac{f&#x27;&#x27;&#x27;&#x27;(x)}{24}\varepsilon^4 + O(\varepsilon^5) $$
$$ f(x-2\varepsilon) = f(x) - 2f&#x27;(x)\varepsilon + 2f&#x27;&#x27;(x)\varepsilon^2 - \frac{4f&#x27;&#x27;&#x27;(x)}{3}\varepsilon^3 + \frac{2f&#x27;&#x27;&#x27;&#x27;(x)}{3}\varepsilon^4 + O(\varepsilon^5) $$
Let&#x27;s multiply the first by $-\frac{1}{21}$, the second by $\frac{8}{21}$, the third by $-\frac{8}{21}$, and the fourth by $\frac{1}{21}$.
Then if we add them all together and rearrange, we get:
$$ f&#x27;(x) = \frac{f(x-2\varepsilon)-8f(x-\varepsilon)+8f(x+\varepsilon)-f(x+2\varepsilon)}{21\varepsilon} + O(\varepsilon^4)$$
meaning that cutting $\varepsilon$ in half will cut the error by sixteen!
&lt;/p&gt;
&lt;p&gt;
If you can figure out where these $\pm\frac{1}{21}$ and $\pm\frac{8}{21}$ magic numbers come from then you can generalize this technique to your heart&#x27;s desire and reduce the error as much as you want; as low as $O(\varepsilon^{64})$ if you choose to.
The astute reader can generalize this technique even further to reach &lt;em&gt;Richardson extrapolation&lt;/em&gt;.
&lt;/p&gt;
&lt;p&gt;
The first criticism is that this scheme will always yield an approximation and never an exact value.
That criticism becomes critical when we consider actual implementations using floating-point numbers:
If we choose $\varepsilon$ to be small while we&#x27;re interested in computing the derivative at a relatively large $x$ (orders of magnitude larger than $\varepsilon$) then we&#x27;ll have to add a small number to a large number: the first capital sin.
Moreover, if our function is smooth enough, then $f(x-\varepsilon)$ and $f(x+\varepsilon)$ will be close to each other, and we end up subtracting numbers of a similar magnitude: the second capital sin.
Both are well-known problems that should be avoided when dealing with floating-point arithmetic.
These two problems and some more are highlighted in &lt;a href=&quot;https://www.soa.org/news-and-publications/newsletters/compact/2014/may/com-2014-iss51/losing-my-precision-tips-for-handling-tricky-floating-point-arithmetic/&quot; target=&quot;_blank&quot;&gt;Losing My Precision&lt;/a&gt;.
And, if that is not enough, choosing too-small an $\varepsilon$ leads us to commit the Deadly Sin #4: Ruination by Rounding (explained in McCartin&#x27;s &lt;em&gt;Seven Deadly Sins of Numerical Computation&lt;/em&gt; (1998) doi:10.1080/00029890.1998.12004989 which you should not use sci-hub to read a free version of this).
Shortly, a tiny $\varepsilon$ will reduce the truncation error &amp;mdash; the approximation error &amp;mdash; but will spike the round-off errors too &amp;mdash; rounding error due to floating points!
And to make matters even worse, quoting from that same paper, &quot;The perplexing facet of this phenomenon is that the precise determination of $h_{opt}$ [the optimal $\varepsilon$ that reaches an equilibrium between trunction and round-off errors] is impossible in practice.&quot;
&lt;/p&gt;
&lt;p&gt;
The second criticism is that computing $f&#x27;(x)$ (for an error of $O(\varepsilon^4)$) calls the function $f$ four times.
If $f$ is expensive to call, computing the derivative becomes quadruply expensive.
What if $f$ was a deep neural network with millions of inputs?
In other words, $f: \mathbb{R}^{1,000,000} \to \mathbb{R}$, then to learn via gradient-descent requires computing $\frac{\partial}{\partial x_i}f$ for all million parameters resulting in 4,000,000 evaluations of the neural network for one optimization iteration.
&lt;/p&gt;
&lt;br&gt;
&lt;h2&gt;Symbolic Differentiation&lt;/h2&gt;
&lt;p&gt;
The previous paragraph introduced the two downsides of numerical methods.
They only approximate, and they perform multiple applications per input variable.
Symbolic Differentiation attempts to eliminate both concerns, with a slight caveat mentioned at the end.
Whereas numerical methods are done at runtime, symbolic differentiation is (generally) done at compile-time.
&lt;/p&gt;
&lt;p&gt;
Numerical methods were inspired by the definition of the derivative.
Symbolic methods are inspired by the specific definition of some derivatives.
What do I mean?
We all learned in high school that $\left(x^n\right)&#x27; = nx^{n-1}$, and that $(uv)&#x27; = u&#x27;v + uv&#x27;$, etc...
Notice that these definitions do not use any $\varepsilon$ and are exact.
We use $=$ not $\approx$.
So let&#x27;s make use of them, alongside the insight that a program is just a complicated composition of basic ideas like multiplication, addition, composition, etc... which we know their derivatives.
&lt;/p&gt;
&lt;p&gt;
Provided a program encoding a mathematical expression a compiler manipulates its symbols (a lot like how a high-school student blindly applies the rules of differentiation) to generate another program that will compute the derivative in that exact way.
&lt;/p&gt;
&lt;style&gt;code pre { line-height: 1rem !important; }&lt;/style&gt;
In a basic programming language with a syntax defined like:
&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;t ::= c             (c is a real number)&lt;/pre&gt;
&lt;pre&gt;    | x             (variables)&lt;/pre&gt;
&lt;pre&gt;    | t1 + t2&lt;/pre&gt;
&lt;pre&gt;    | t1 - t2&lt;/pre&gt;
&lt;pre&gt;    | t1 * t2&lt;/pre&gt;
&lt;pre&gt;    | t ^ c         (to a power of a constant)&lt;/pre&gt;
&lt;pre&gt;    | log t | exp t | sin t | cos t&lt;/pre&gt;
&lt;/code&gt;
We can define a recursive function &lt;code&gt;d&lt;/code&gt; which given the variable &lt;code&gt;x&lt;/code&gt; to differentiate with respect to, operates on a syntax tree to produce another syntax tree representing the derivative.
In an ML-like syntax we can define this function like so:
&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;d x c         = 0&lt;/pre&gt;
&lt;pre&gt;d x x         = 1&lt;/pre&gt;
&lt;pre&gt;d x y         = 0&lt;/pre&gt;
&lt;pre&gt;d x (t1 + t2) = (d x t1) + (d x t2)&lt;/pre&gt;
&lt;pre&gt;d x (t1 - t2) = (d x t1) - (d x t2)&lt;/pre&gt;
&lt;pre&gt;d x (t1 * t2) = t1 * (d x t2) + (d x t1) * t2&lt;/pre&gt;
&lt;pre&gt;d x (t ^ c)   = c * t ^ (c-1) * (d x t)&lt;/pre&gt;
&lt;pre&gt;d x (log t)   = (d x t) * t ^ -1&lt;/pre&gt;
&lt;pre&gt;d x (exp t)   = (d x t) * (exp t)&lt;/pre&gt;
&lt;pre&gt;d x (sin t)   = (d x t) * (cos t)&lt;/pre&gt;
&lt;pre&gt;d x (cos t)   = (d x t) * -1 * (sin t)&lt;/pre&gt;
&lt;/code&gt;
&lt;p&gt;
Some languages already have such a built-in construct.
In Maple for example you can do &lt;code&gt;diff(x*sin(cos(x)), x)&lt;/code&gt; and get $sin(cos(x))−xsin(x)cos(cos(x))$ back.
You can also do higher-order derivative like &lt;code&gt;diff(sin(x), x$3)&lt;/code&gt; which is the same as &lt;code&gt;diff(sin(x), x, x, x)&lt;/code&gt;, meaning $\frac{\partial^3}{\partial^3x}sin(x)$ and get back $-cos(x)$.
The documentation of this &lt;code&gt;diff&lt;/code&gt; function can be found &lt;a href=&quot;https://www.maplesoft.com/support/help/maple/view.aspx?path=diff&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.
But by far the most popular, and one that I feel sorry for you dear reader if you didn&#x27;t use during your calculus course, is &lt;a href=&quot;https://reference.wolfram.com/language/ref/Derivative.html&quot; target=&quot;_blank&quot;&gt;Mathematica&#x27;s&lt;/a&gt; that is exposed through a web interface on WolframAlpha.
As an example, if we run the query &lt;a href=&quot;https://www.wolframalpha.com/input/?i=derivative+of+x*sin%28cos%28x%29%29&quot; target=&quot;_blank&quot;&gt;&quot;derivative of x*sin(cos(x))&quot;&lt;/a&gt; on wolframalpha.com we get back the answer &lt;code&gt;-x cos(cos(x)) sin(x) + sin(cos(x))&lt;/code&gt;.
Some other languages are expressive-enough to do symbolic differentiation through libraries.
As an example, you can consult Julia&#x27;s &lt;a href=&quot;https://github.com/JuliaSymbolics/Symbolics.jl&quot; target=&quot;_blank&quot;&gt;Symbolics.js&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Programs are usually more complicated than simple mathematical expressions.
Heck, mathematical expressions can be more complicated than those expressible by our simple language.
Definitions can include recursive calls, branching, a change of variables, or aliasing.
Let&#x27;s see how to add support for aliasing, i.e. variable definitions, i.e. let expressions of the form &lt;code&gt;let x = t1 in t2&lt;/code&gt;.
Here&#x27;s a simple example of a program that we&#x27;d like to take its derivative (with respect to x):
&lt;/p&gt;
&lt;code class=&quot;block&quot; style=&quot;margin:-10px 0px&quot;&gt;
&lt;pre&gt;let y = 2*x*x in&lt;/pre&gt;
&lt;pre&gt;y + cos(y)&lt;/pre&gt;
&lt;/code&gt;
&lt;p&gt;
What could its derivative be?
Mathematically we have two definitions: $y(x) = 2x^2$, and $f(x) = y(x) + cos(y(x))$.
The derivative $\frac{df}{dx}$ is $y&#x27;(x) - y&#x27;(x) * sin(y(x))$ which depends on $y(x)$ and on a new function we call $y&#x27;(x)$.
And we know that $y&#x27;(x) = \frac{dy}{dx} = 4x$.
We could express that in code as follows:
&lt;/p&gt;
&lt;code class=&quot;block&quot; style=&quot;margin:-10px 0px&quot;&gt;
&lt;pre&gt;let y = 2*x*x in&lt;/pre&gt;
&lt;pre&gt;let y&#x27; = 4*x in&lt;/pre&gt;
&lt;pre&gt;y&#x27; + y&#x27; * cos(y)&lt;/pre&gt;
&lt;/code&gt;
&lt;p&gt;
We need to modify our &lt;code&gt;d x t&lt;/code&gt; function to allow &lt;code&gt;let y = t1 in t2&lt;/code&gt;.
It&#x27;s important to remember that our expression may depend on y and its derivative.
So, deriving a let-expression must keep the variable binding as-is, introduce the variable&#x27;s derivative, and derive the body.
The first obvious modification is:
&lt;/p&gt;
&lt;code class=&quot;block&quot; style=&quot;margin:-10px 0px&quot;&gt;
&lt;pre&gt;d x (let y = t1 in t2) =&lt;/pre&gt;
&lt;pre&gt;           let y = t1 in&lt;/pre&gt;
&lt;pre&gt;           let y&#x27; = (d x t1) in&lt;/pre&gt;
&lt;pre&gt;           (d x t2)&lt;/pre&gt;
&lt;/code&gt;
&lt;p&gt;
Of course, we assume that &lt;code&gt;y&#x27;&lt;/code&gt; is a fresh variable that isn&#x27;t introduced, nor mentioned, in the body of the let-expression.
But that is not all.
What will &lt;code&gt;d x (y + cos(y))&lt;/code&gt; yield?
Our &lt;code&gt;d x y&lt;/code&gt; rule says that the result should be 0, so the body will evaluate to &lt;code&gt;d x (y + cos(y)) = 0 - 0 * sin(x)&lt;/code&gt;.
Not good.
Luckily the fix is simple.
Instead of returning 0, we should return the derivative of the variable (which must have been introduced in an earlier let-expression in a term only free in x).
So the second modification should be:
&lt;/p&gt;
&lt;code class=&quot;block&quot; style=&quot;margin:-10px 0px&quot;&gt;
&lt;pre&gt;d x y = y&#x27;&lt;/pre&gt;
&lt;/code&gt;
&lt;p&gt;
I tried to search for a language that allows you to take the derivative of arbitrary expressions, but I turned up empty handed.
By arbitrary expression I mean one where computation and control-flow are mixed in.
For example, I know of no library that can differentiate the following function:
&lt;/p&gt;
&lt;code class=&quot;block&quot; style=&quot;margin:-10px 0px&quot;&gt;
&lt;pre&gt;real foo(real x1, real x2) {&lt;/pre&gt;
&lt;pre&gt;  let f = lambda g: g(lambda y: y^2 + x2);&lt;/pre&gt;
&lt;pre&gt;  let z = x1*sin(x2)/log(x1^2);&lt;/pre&gt;
&lt;pre&gt;  if (x1 &amp;lt; 0) return foo(-x1, z);&lt;/pre&gt;
&lt;pre&gt;  else        return z*f(lambda h: h(x1-cos(x2)));&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;/code&gt;
&lt;p&gt;
Which is a complicated way of computing this function:
$$ f(x_1, x_2) = \begin{cases}
f\left(-x_1, \frac{x_1sin(x_2)}{log(x_1^2)}\right) &amp;\mbox{if } x_1 &lt; 0\\
\frac{x_1sin(x_2)}{log(x_1^2)}\left((x_1-cos\;x_2)^2+x_2\right) &amp;\mbox{otherwise}
\end{cases} $$
&lt;/p&gt;
&lt;p&gt;
There is a downside to using symbolic derivation: it goes by the name &lt;em&gt;expression swell&lt;/em&gt;.
It&#x27;s due to the large sub-expression that the derivative of a product produces.
As an example, deriving the product $x(2x+1)(x-1)^2$ produces the expression $(2x+1)(x-2)^2+2x(x-2)^2+2x(2x+1)(x-2)$.
Multiplying the original expression by the product $(3-x)$ produces the even larger expression
$$2(x+1)(x-2)^2(3-x)+2x(x-2)^2(3-x)+2x(2x+1)(x-2)-x(2x+1)(x-1)^2$$
Of course, such an expression can be reduced to $-10x^4+36x^3-27x^2-2x+3$, but that may not always be possible.
Consider the modified expression
$$cos(x)(2sin(x)+1)(log(x)-1)^2(3-e^x)$$
whose derivative cannot be reduced.
&lt;/p&gt;
&lt;p&gt;
So even if symbolic differentiation produces an exact value and only requires the evaluation of one function per input to compute the derivative,
this derivative function may be more computationally expensive than the original function.
That is the caveat I mentioned at the start of this section.
&lt;/p&gt;
&lt;br&gt;
&lt;h2&gt;Forward-Mode Automatic Differentiation&lt;/h2&gt;
&lt;p&gt;
Here&#x27;s the status till now: numerical differentiation is trivial to implement but is not exact, whereas symbolic differentiation is exact but harder to implement.
And both share the fact that computing a derivative is expensive.
Automatic differentiation tries to take the best of both worlds:
Like symbolic differentiation, AD spits an exact result, and like numeric differentiation, it spits a numerical value, all the while keeping the complexity of evaluating the derivative linear.
&lt;/p&gt;
&lt;p&gt;
Let&#x27;s reconsider that last expression, and test rigorously the claim that its symbolic derivative is much more complicated.
Naively the expression can be expressed as follows:
&lt;/p&gt;
&lt;code class=&quot;block&quot; style=&quot;margin:-10px 0px&quot;&gt;
&lt;pre&gt;cos(x) * (2 * sin(x) + 1) * (log(x) - 1)^2 * (3 - exp(x))&lt;/pre&gt;
&lt;/code&gt;
&lt;p&gt;
And its derivative as defined by the &lt;code&gt;d x&lt;/code&gt; code transformation, which I&#x27;ve naively implemented in Haskell, is:
&lt;/p&gt;
&lt;code class=&quot;block&quot; style=&quot;margin:-10px 0px&quot;&gt;
&lt;pre&gt;  cos(x) * (2 * sin(x) + 1) * (  (log(x) - 1)^2 * (0 - 1 * exp(x))&lt;/pre&gt;
&lt;pre&gt;                               + 2 * (1 * x^-1 - 0) * (log(x) - 1)^1 * (3 - exp(x)))&lt;/pre&gt;
&lt;pre&gt;+ (log(x) - 1)^2 * (3 - exp(x)) * (cos(x) * ((2 * 1 * cos(x) + 0 * sin(x)) + 0)&lt;/pre&gt;
&lt;pre&gt;                               + 1 * 1 * sin(x) * (2 * sin(x) + 1))&lt;/pre&gt;
&lt;/code&gt;
&lt;p&gt;
But using our simple program language there are other programs that are equivalent to this expression.
For example consider &lt;code&gt;let p1 = cos(x) in p1 * (2*sin(x)+1) * (log(x)-1)^2 * (3-exp(x))&lt;/code&gt;.
What is the derivative of a program that introduces as many non-trivial let-expressions as possbile?
For example what&#x27;s the derivative of the following program?
&lt;/p&gt;
&lt;code class=&quot;block&quot; style=&quot;margin:-10px 0&quot;&gt;
&lt;pre&gt;let v1  = cos(x)   in&lt;/pre&gt;
&lt;pre&gt;let v2  = sin(x)   in&lt;/pre&gt;
&lt;pre&gt;let v3  = 2 * v2   in&lt;/pre&gt;
&lt;pre&gt;let v4  = v3 + 1   in&lt;/pre&gt;
&lt;pre&gt;let v5  = log(x)   in&lt;/pre&gt;
&lt;pre&gt;let v6  = v5 - 1   in&lt;/pre&gt;
&lt;pre&gt;let v7  = v6^2     in&lt;/pre&gt;
&lt;pre&gt;let v8  = exp(x)   in&lt;/pre&gt;
&lt;pre&gt;let v9  = 3 - v8   in&lt;/pre&gt;
&lt;pre&gt;let v10 = v1 * v4  in&lt;/pre&gt;
&lt;pre&gt;let v11 = v7 * v9  in&lt;/pre&gt;
&lt;pre&gt;v10 * v11&lt;/pre&gt;
&lt;/code&gt;
&lt;p&gt;
I invite you to check that indeed this program (which can be seen as a compiled-version) is equivalent to the original expression.
I also invite you to take its derivative by hand.
In case you&#x27;re lazy, here&#x27;s the result using the same code transformation that I&#x27;ve naively implemented in Haskell:
&lt;/p&gt;
&lt;code class=&quot;block&quot; style=&quot;margin:-10px 0&quot;&gt;
&lt;pre&gt;let v1  = cos(x)   in    let v1&#x27;  = -1 * 1 * sin(x)      in&lt;/pre&gt;
&lt;pre&gt;let v2  = sin(x)   in    let v2&#x27;  = 1 * cos(x)           in&lt;/pre&gt;
&lt;pre&gt;let v3  = 2 * v2   in    let v3&#x27;  = 2 * v2&#x27; + 0 * v2     in&lt;/pre&gt;
&lt;pre&gt;let v4  = v3 + 1   in    let v4&#x27;  = v3&#x27; + 0              in&lt;/pre&gt;
&lt;pre&gt;let v5  = log(x)   in    let v5&#x27;  = 1 * x^-1             in&lt;/pre&gt;
&lt;pre&gt;let v6  = v5 - 1   in    let v6&#x27;  = v5&#x27; - 0              in&lt;/pre&gt;
&lt;pre&gt;let v7  = v6^2     in    let v7&#x27;  = 2 * v6&#x27; * v6^1       in&lt;/pre&gt;
&lt;pre&gt;let v8  = exp(x)   in    let v8&#x27;  = 1 * exp(x)           in&lt;/pre&gt;
&lt;pre&gt;let v9  = 3 - v8   in    let v9&#x27;  = 0 - v8&#x27;              in&lt;/pre&gt;
&lt;pre&gt;let v10 = v1 * v4  in    let v10&#x27; = v1 * v4&#x27; + v1&#x27; * v4  in&lt;/pre&gt;
&lt;pre&gt;let v11 = v7 * v9  in    let v11&#x27; = v7 * v9&#x27; + v7&#x27; * v9  in&lt;/pre&gt;
&lt;pre&gt;v10 * v11&#x27; + v10&#x27; * v11&lt;/pre&gt;
&lt;/code&gt;
&lt;p&gt;
Look carefully at what this new code does: for every simple let-expression, we have another simple-ish let-expression that computes its derivative.
The body of the let-expressions is also simple.
The complexity of evaluating it is similar to 2 or 3 calls of the original program.
So the claim that symbolic derivation produces a derivative that is not linear in the program&#x27;s size is bogus.
But that&#x27;s if we transform our code into a representation with as many let-expressions as possible.
And that is precisely where automatic differentiation starts at!
&lt;/p&gt;
&lt;p&gt;
There are two gateways to automatic differentiation.
The first is an interpretation of the exercise described above in the programming domain that is well expressed in the abstract of Wengert&#x27;s 1964 paper introduced forward-mode AD:
&quot;The technique permits the computation of numerical values of derivatives without developing analytical expressions for the derivatives.
The key to the method is the decomposition of the given function, by the introduction of intermediate variables, into a series of elementary functional steps.&quot;
Another way of expressing it can be found in Baydin, Pearlmutter, Radul, and Siskind&#x27;s survey:
&quot;When we are concerned with the accurate numerical evaluation of derivatives and not so much with their actual symbolic form, it is in principle possible to significantly simplify computations by storing only the values of intermediate sub-expressions in memory.
[...] This [...] idea forms the basis of AD and provides an account of its simplest form:
&lt;em&gt;apply symbolic differentiation at the elementary operation level and keep intermediate numerical results, in lockstep with the evaluation of the main function.&lt;/em&gt;&quot;
&lt;/p&gt;
&lt;p&gt;
The second gateway is a mathematical re-interpretation of the two quotes above:
Fundamentally, every program is a composition of basic functions (like adding, multiplying, exponentiating, etc...) whose derivatives are known a-priori.
So a program boils down to a representation of the sort:
$$ P = f_1(f_2(f_3(\cdots f_r(x_1, \cdots, x_n)\cdots))) $$
whose derivative can be taken using the chain rule (in its simplest form):
$$ \frac{\text{d}}{\text{d}x} f(g(x)) = f&#x27;(g(x)) \cdot g&#x27;(x) $$
The &quot;chain rule applied to elementary functions&quot; is the other gateway to AD.
&lt;/p&gt;
&lt;p&gt;
It&#x27;s always a good idea to see many examples, so now and in the next section we&#x27;ll see how to take the derivative of this new function:
$$ f(x_1, x_2, x_3) = \frac{log(x_1)}{x_3}\left(sin\left(\frac{log(x_1)}{x_3}\right)+e^{x_3}\cdot x_2 \cdot sin(x_1)\right) $$
One way this function can be &quot;compiled&quot; to a sequence of elementary function applications is like so:
$$\begin{align*}
v_1 &amp;= log(x_1) \\
v_2 &amp;= \frac{v_1}{x_3} \\
v_3 &amp;= sin(v_2) \\
v_4 &amp;= e^{x_3} \\
v_5 &amp;= sin(x_1) \\
v_6 &amp;= x_2 \cdot v_5 \\
v_7 &amp;= v_4 \cdot v_6 \\
v_8 &amp;= v_3 + v_7 \\
v_9 &amp;= v_2 \cdot v_8 \\
f &amp;= v_9
\end{align*}$$
&lt;/p&gt;
&lt;p&gt;
If we are interested in computing $\frac{\partial f}{\partial x_1}$, we derive each identity line-by-line with respect to $x_1$, for example, $\dot{v_1} = \frac{1}{x_1}$, and $\dot{v_2} = \frac{1}{x_3}\cdot \dot{v_1}$ (where we make use of $\dot{v_1}$ which was just computed).
If we are interested in computing $\frac{\partial f}{\partial x_2}$ we will have to perform the same derivative again with respect to $x_2$.
Ultimately we are computing $n$ different programs for each input variable, so computing the derivative of $f: \mathbb{R}^{1,000,000} \to \mathbb{R}$ requires generating a million other programs.
To avoid doing that, we use a trick.
We differentiate with respect to some direction $s$ and treat our input variables as intermediary variables.
In other words, we assume we are given $\dot{x_i}=\frac{\partial x_i}{\partial s}$ as inputs.
If we want to compute the derivative with respect to $x_1$ then, it&#x27;s enough to set $\dot{x_1} = 1$ and every other $\dot{x_i} = 0$.
&lt;/p&gt;
&lt;p&gt;
Deriving one variable at a time, whence the &quot;forward-mode&quot; part of the name, produces the following sequence whose last variable will hold the value of the derivative in the direction $(\dot{x_1}, \dot{x_2}, \dot{x_3})$ at the point $(x_1, x_2, x_3)$:
$$\begin{align*}
\dot{v_1} &amp;= \frac{\dot{x_1}}{x_1} \\
\dot{v_2} &amp;= \frac{1}{x_3} \dot{v_1} - \frac{\dot{x_3}}{x_3^2} \\
\dot{v_3} &amp;= \dot{x_2} cos(x_2) \\
\dot{v_4} &amp;= \dot{x_3} e^{x_3} \\
\dot{v_5} &amp;= \dot{x_1} cos(x_1) \\
\dot{v_6} &amp;= x_2 \cdot \dot{v_5} + \dot{x_2} \cdot v_5 \\
\dot{v_7} &amp;= v_4 \cdot \dot{v_6} + \dot{v_4} \cdot v_6 \\
\dot{v_8} &amp;= \dot{v_3} + \dot{v_7} \\
\dot{v_9} &amp;= v_2 \cdot \dot{v_8} + \dot{v_2} \cdot v_8 \\
\dot{f}   &amp;= \dot{v_9}
\end{align*} $$
&lt;/p&gt;
&lt;p&gt;
Just as with all other methods, if we are interested in all derivatives of $f: \mathbb{R}^n \to \mathbb{R}^m$ then we must evaluate the derivative-program $n$ times; once for each input.
&lt;/p&gt;
&lt;br&gt;
&lt;h2&gt;Reverse-mode Automatic Differentiation&lt;/h2&gt;
&lt;p&gt;
The only sensible gateway to reverse-mode AD that I have found is the chain rule (which I glanced over in the previous section).
How did forward-mode use the chain rule?
Let&#x27;s look at how a few $\dot{v_i}$s were computed: (keeping in mind that we are differentiating with respect to some direction $s$, so we only know $x_1,x_2,x_3,\dot{x_1},\dot{x_2},\dot{x_3}$, and all the intermediate $v_i$s:
$$ \begin{align*}
\dot{v_1} &amp;\overset{def}= \frac{\partial v_1}{\partial s} \\
&amp;= \frac{\partial v_1}{\partial x_1}\frac{\partial x_1}{\partial s} \\
&amp;= \frac{1}{x_1} \dot{x_1} \\
\dot{v_2} &amp;\overset{def}= \frac{\partial v_2}{\partial s} \\
&amp;= \frac{\partial v_2}{\partial v_1}\frac{\partial v_1}{\partial s} + \frac{\partial v_2}{\partial x_3}\frac{\partial x_3}{\partial s} \\
&amp;= \frac{1}{x_3} \dot{v_1} - \frac{v_1}{x_3^2}\dot{x_3} \\
\dot{v_8} &amp;\overset{def}= \frac{\partial v_8}{\partial s} \\
&amp;= \frac{\partial v_8}{\partial v_3}\frac{\partial v_3}{\partial s} + \frac{\partial v_8}{\partial v_7}{\partial v_7}{\partial s} \\
&amp;= 1 \dot{v_3} + 1 \dot{v_7}
\end{align*} $$
The essential observation is that in every application of the chain rule, we have fixed the denominator $\partial s$ and expanded the numerator.
In other words, we define $\dot{y} \overset{def}= \frac{\partial y}{\partial s}$ where $s$ is fixed and attempt to express every $\dot{y}$ in terms of other $\dot{z}$s.
That is, to compute $\dot{v_i}$ we ask ourselves the question, which variables $v_j$ should we use to do $\frac{\partial v_i}{\partial v_j}\cdot\dot{v_j}$?
The answer is those variables that appear in the definition of $v_i$.
&lt;/p&gt;
&lt;p&gt;
What happens if we fix the numerator instead?
In other words, to compute $\overline{y}\overset{def}=\frac{\partial f}{\partial y}$ where $f$ is the fixed output variable, we ask ourselves, what are the variables $v_j$s needed to use to do $\overline{v_j}\frac{\partial v_j}{\partial v_i}$?
Firstly notice that we removed the direction vector $s$.
After all, it was introduced as an optimization trick.
Moreover, what we are interested in is the derivative $\frac{\partial f}{\partial x_i}$.
The answer is those variables where $v_j$ that includes $v_i$ in their definition.
&lt;/p&gt;
&lt;p&gt;
Now let&#x27;s apply this new trick (fixing the numerator) to the intermediary variables $v_i$.
We will use the adjoint notation, which is the notation introduced in the earlier paragraph $\overline{v_i} \overset{def}= \frac{\partial f}{\partial v_i}$.
Using this notation, the answer we are after becomes $\overline{x_1}, \overline{x_2}, \overline{x_3}$.
The first thing to observe is that $\overline{f}=1$.
In the forward-mode, we knew $\dot{x_1},\dot{x_2},\dot{x_3}$, so we naturally had to go from top-down.
Here we only know $\overline{f}$, so we have no choice but to go bottom-up.
&lt;/p&gt;
$$\begin{align*}
\overline{v_9} &amp;= \frac{\partial f}{\partial v_9}  = 1, \\
\overline{v_8} &amp;= \frac{\partial f}{\partial v_9} = \frac{\partial f}{\partial v_9} \cdot \frac{\partial v_9}{\partial v_8} = \overline{v_9} \cdot v_2,\\
\overline{v_7} &amp;= \frac{\partial f}{\partial v_7} = \frac{\partial f}{\partial v_8} \cdot \frac{\partial v_8}{\partial v_7} = \overline{v_8} \cdot 1,\\
\overline{v_6} &amp;= \frac{\partial f}{\partial v_6} = \frac{\partial f}{\partial v_7} \cdot \frac{\partial v_7}{\partial v_6} = \overline{v_7} \cdot v_4,\\
\vdots\\
\overline{v_2} &amp;= \frac{\partial f}{\partial v_2} \\
&amp;= \frac{\partial f}{\partial v_9}\frac{\partial v_9}{\partial v_2} + \frac{\partial f}{\partial v_3}\frac{\partial v_3}{\partial v_2} \\
&amp;= \overline{v_9}\cdot v_8 + \overline{v_3} \cdot cos(v_2)
\end{align*}$$
&lt;p&gt;
As mentioned earlier, the equation of $\overline{v_i}$ includes those variables that include in their definition $v_i$.
Hence why we use both $\overline{v_9}$ and $\overline{v_3}$ when computing the adjoint $v_2$ .
In practice, when implementing this algorithm, we build a dependency graph whose nodes are the intermediary values, the inputs, and the outputs.
In this graph, $v_i$ is connected to $v_j$ if $v_j$ includes $v_i$ in its definition.
Computing the derivative amounts to traversing this graph forwards to compute the values $v_i$, then traversing it backward to propagate the adjoints.
This is precisely the back-propagation algorithm used in training neural networks.
&lt;/p&gt;
&lt;p&gt;For our running example, the graph looks like this:&lt;br&gt;
&lt;img src=&quot;./depgraph.png&quot; height=&quot;300px&quot; style=&quot;display:block&quot;&gt;
&lt;/p&gt;
&lt;p&gt;
To formalize a little our graph-oriented algorithm from the previous paragraph, let&#x27;s introduce some definitions.
Let $f_v: \mathbb{R}^r \to \mathbb{R}$ be the function that vertex $v$ computes, and let $\partial_1 f_v, \cdots, \partial_r f_v$ be its partial derivatives that are statically known.
Let $I_v$ be the vector of the vertices with an outgoing edge to $v$.
Let $O_v$ be the set of vertices that $v$ has an outgoing edge.
And finally let $i(v_1, v_2)$ be the index that $v_1$ is connected to $v_2$ on.
For example, $f_{v_2}(x_1, x_2) = \frac{x_1}{x_2}$, $\partial_1 f_{v_2} = \frac{1}{x_2}$, $\partial_2 f_{v_2} = -\frac{x_1}{x_2^2}$.
And $I_{v_2} = [v_1, v_3]$, here the order matters, since $f_{v_2}(I_{v_2})$ should be the value of $v_2$.
And $O_{v_2} = \{v_3, v_9\}$, and $i(v_1, v_2) = 1$, and $i(v_3, v_2) = 2$.
Then:
$$ \overline{x} = \sum_{v \in O_x} \overline{v} \cdot \partial_{i(x,v)}f_v\left(I_v\right) $$
&lt;/p&gt;
&lt;p&gt;
And finally, for completeness, here are the adjoints for our running example:
$$ \begin{align*}
\overline{f}   &amp;= 1 \\
\overline{v_9} &amp;= \overline{y} \\
\overline{v_8} &amp;= \overline{v_9} v_2 \\
\overline{v_7} &amp;= \overline{v_8} \\
\overline{v_6} &amp;= \overline{v_7} v_4 \\
\overline{v_5} &amp;= \overline{v_6} x_2 \\
\overline{v_4} &amp;= \overline{v_7} v_4 \\
\overline{v_3} &amp;= \overline{v_8} \\
\overline{v_2} &amp;= \overline{v_3} cos(v_2) + \overline{v_9} v_8 \\
\overline{v_1} &amp;= \overline{v_2} \frac{1}{x_3} \\
\overline{x_3} &amp;= \overline{v_4} e^{x_3} - \overline{v_2} \frac{v_1}{x_3^2} \\
\overline{x_2} &amp;= \overline{v_6} v_5 \\
\overline{x_1} &amp;= \overline{v_1} \frac{1}{x_1} + \overline{v_5} cos(x_1) \\
\end{align*} $$
&lt;/p&gt;
&lt;p&gt;
This is all!
One last observation is that in a single backward pass of $f$ we have managed to compute &lt;u&gt;all&lt;/u&gt; its partial derivatives.
Which explains why in a neural network setting reverse-mode AD is exclusively used.
&lt;/p&gt;
&lt;p&gt;
To deal with $f: \mathbb{R}^n \to \mathbb{R}^m$ (since in our example $m=1$), we will have to compute $m$ different programs for each output.
We can of course reuse the same trick of introducing a direction $s$ and setting $\overline{y_i} = \frac{\partial s}{\partial y_i}$.
To compute all $\frac{\partial y_1}{\partial x_i}$ we just set $\overline{y_1} = 1$ and every other $\overline{y_i} = 0$.
&lt;/p&gt;
&lt;p&gt;
So, when should we use each method?
If we are differentiating $f: \mathbb{R}^n \to \mathbb{R}^m$, and $n \leq m$ then the numerical method is the simplest to implement, while the forward-mode AD is the fastest.
And if $n &gt; m$ then reverse-mode AD is the fastest.
&lt;/p&gt;</description>
<link>https://blog.grgz.me/posts/on-computing-derivatives.html</link>
<guid isPermaLink="false">https://blog.grgz.me/posts/on-computing-derivatives.html</guid>
<pubDate>Wed, 18 Aug 2021</pubDate>
</item>

<item>
<title>A Case for For Loops</title>
<description>&lt;style&gt;
blockquote { border-left: 5px solid rgba(0, 0, 0, 0.2); margin: 20px 0; padding-left: 5rem; }
code.in { padding: 0; background: transparent; border: 0; }&lt;/style&gt;&lt;p&gt;
I do not like for loops.
I think for loops should not be the first tool developers reach for when they wish to loop.
If you have the chance to use &lt;code&gt;map&lt;/code&gt;, &lt;code&gt;filter&lt;/code&gt;, or &lt;code&gt;reduce&lt;/code&gt;,
and if your host language is capable of &lt;a href=&quot;https://github.com/frenchy64/stream-fusion&quot; target=&quot;_blank&quot;&gt;fusing&lt;/a&gt; them,
then it&#x27;s always&lt;sup&gt;[source?]&lt;/sup&gt; more readable to sequence them.&lt;/p&gt;&lt;p&gt;
But I think I found a case where for loops really are the most elegant solution.&lt;/p&gt;&lt;p&gt;
To illustrate this scenario imagine we were asked to find the prime numbers in a list of the first &lt;em&gt;n&lt;/em&gt; fibonacci numbers.
Next, we were asked to find the square numbers in the same list of &lt;em&gt;n&lt;/em&gt; fibonacci numbers.
In fact we were asked by some fibonacci-obsessed mathematician;
in other words we will be computing fibonacci numbers a lot.
So it&#x27;s sensible to imagine some function &lt;code&gt;int[] firstNFibonacci(int n)&lt;/code&gt; defined somewhere.&lt;/p&gt;&lt;p&gt;
However, this fibonacci-crazed odd-ball is of course interested in rare properties of fibonacci numbers;
which means that, of the &lt;em&gt;n&lt;/em&gt; numbers computed, hardly any will remain.
So it&#x27;s a waste of time (and mostly space) to construct a list of size &lt;em&gt;n&lt;/em&gt; and to loop over it once to populate it with fibonacci numbers, then loop over it again to keep the interesting ones.&lt;/p&gt;&lt;p&gt;
It&#x27;s obviously better if &lt;code&gt;firstNFibonacci&lt;/code&gt; can yield the number once it was computed to the filtering logic before carrying on computing the second.
For the sake of generality I will assume your host language does not have a &lt;code&gt;yield&lt;/code&gt; keyword (nor a synonym).
So we&#x27;ll have to simulate yielding.
The way I choose to do it is to include the state of the computation as an argument (so the function can carry on where it left off),
and to include the next state in the output of the function (so the caller can chain these next states and make progress).&lt;/p&gt;
Here is an example:&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;type state = (int, int, int);&lt;/pre&gt;
&lt;pre&gt; &lt;/pre&gt;
&lt;pre&gt;(int, state) firstNFibonacci(int n, state s) {&lt;/pre&gt;
&lt;pre&gt;    int found = s[0], a = s[1], b = s[2];&lt;/pre&gt;
&lt;pre&gt;    return found &amp;lt; n&lt;/pre&gt;
&lt;pre&gt;         ? (a+b, (found+1, b, a+b))&lt;/pre&gt;
&lt;pre&gt;         : (-1, s); // -1 indicates end of computation&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
The question now is, how do we use this iterator correctly?
Here are three ways of finding the prime fibonacci numbers.
I will let you judge which is &lt;strong&gt;completely&lt;/strong&gt; correct.&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;state s = (0, 0, 1); // (none found, first fib., second fib.)&lt;/pre&gt;
&lt;pre&gt;int n = 1000;&lt;/pre&gt;
&lt;pre&gt;var result = firstNFibonacci(n, s);&lt;/pre&gt;
&lt;pre&gt;while (result[0] &amp;gt; -1) {&lt;/pre&gt;
&lt;pre&gt;    if (is_prime(result[0])) print(result[0]);&lt;/pre&gt;
&lt;pre&gt;    result = firstNFibonacci(n, result[1]);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;state s = (0, 0, 1); // (none found, first fib., second fib.)&lt;/pre&gt;
&lt;pre&gt;int n = 1000;&lt;/pre&gt;
&lt;pre&gt;var result, value;&lt;/pre&gt;
&lt;pre&gt;do {&lt;/pre&gt;
&lt;pre&gt;    result = firstNFibonacci(n, s);&lt;/pre&gt;
&lt;pre&gt;    value = result[0];&lt;/pre&gt;
&lt;pre&gt;    s = result[1];&lt;/pre&gt;
&lt;pre&gt;    if (is_prime(value)) print(value);&lt;/pre&gt;
&lt;pre&gt;} while (value &amp;gt; -1);&lt;/pre&gt;&lt;/code&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;state s = (0, 0, 1); // (none found, first fib., second fib.)&lt;/pre&gt;
&lt;pre&gt;int n = 1000;&lt;/pre&gt;
&lt;pre&gt;var result, value;&lt;/pre&gt;
&lt;pre&gt;while (true) {&lt;/pre&gt;
&lt;pre&gt;    result = firstNFibonacci(n, s);&lt;/pre&gt;
&lt;pre&gt;    value = result[0];&lt;/pre&gt;
&lt;pre&gt;    s = result[1];&lt;/pre&gt;
&lt;pre&gt;    if (is_prime(value)) print(value);&lt;/pre&gt;
&lt;pre&gt;    if (value &amp;gt; -1)      break;&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
What happens when &lt;code&gt;n = 0&lt;/code&gt;?
Will the first number always be considered?
Will the last number always be considered?
Will it halt?
The (do)while loops above invite the reader to ask these questions.
Questions whose answers are not obvious and therefore require a context switch in the head of the reader.
(In fact the last two versions are not completely correct)&lt;/p&gt;
Now consider the for loop version&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;int n = 1000;&lt;/pre&gt;
&lt;pre&gt; &lt;/pre&gt;
&lt;pre&gt;for ( var result = firstNFibonacci(n, (0, 0, 1))&lt;/pre&gt;
&lt;pre&gt;    ; result[0] &amp;gt; -1&lt;/pre&gt;
&lt;pre&gt;    ; result = firstNFibonacci(n, result[1]))&lt;/pre&gt;
&lt;pre&gt;{    &lt;/pre&gt;
&lt;pre&gt;    var value = result[0];&lt;/pre&gt;
&lt;pre&gt;    if (is_prime(value)) print(value);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
I consider this version elegant because it fits with the semantics of for loops perfectly.
The first component is an initialization step,
the second is a termination condition,
and the third is the means of making progress.&lt;/p&gt;&lt;p&gt;
In conclusion, like gotos, there seems to be sensible use cases for for loops.
However I still believe that most of the time, for loops are not the tool for the job.
This investigation made me wonder if this is the reason why languages like Java adopted the same &lt;code&gt;for&lt;/code&gt;
keyword for iterators instead of introducing a synonym.
But that is a question for the historians.&lt;/p&gt;</description>
<link>https://blog.grgz.me/posts/a-case-for-for-loops.html</link>
<guid isPermaLink="false">https://blog.grgz.me/posts/a-case-for-for-loops.html</guid>
<pubDate>Sun, 20 Jun 2021</pubDate>
</item>

<item>
<title>C: Fork as a knife</title>
<description>&lt;style&gt;
blockquote { border-left: 5px solid rgba(0, 0, 0, 0.2); margin: 20px 0; padding-left: 5rem; }
code.in { padding: 0; background: transparent; border: 0; }&lt;/style&gt;&lt;p&gt;
Did you know that C&#x27;s &lt;code&gt;int fork()&lt;/code&gt; can fail?
I didn&#x27;t until I read
&lt;a href=&quot;https://rachelbythebay.com/w/2020/12/06/forked/&quot; target=&quot;_blank&quot;&gt;retvals, terrible teaching, and admitting we have a problem&lt;/a&gt;.
First thing I did afterwards was type in my trusty terminal &lt;code class=&quot;in&quot;&gt;man fork&lt;/code&gt;
and summon my machine&#x27;s inner librarian.
Here&#x27;s what this &lt;a href=&quot;https://www.commandlinux.com/man-page/man3/fork.3am.html&quot; target=&quot;_blank&quot;&gt;man page&lt;/a&gt;,
the one installed on my machine, had to say about &lt;code class=&quot;in&quot;&gt;fork()&lt;/code&gt;:
&lt;blockquote&gt;
This function creates a new process. The return value is the zero in the
child and the process-id number of the child in the parent, or -1 upon
error. In the latter case, &lt;code class=&quot;in&quot;&gt;ERRNO&lt;/code&gt; indicates the problem.
&lt;/blockquote&gt;&lt;/p&gt;
Cool, cool... Scrolling down to some examples I find:&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;@load &amp;quot;fork&amp;quot;&lt;/pre&gt;
&lt;pre&gt;...&lt;/pre&gt;
&lt;pre&gt;if ((pid = fork()) == 0)&lt;/pre&gt;
&lt;pre&gt;    print &amp;quot;hello from the child&amp;quot;&lt;/pre&gt;
&lt;pre&gt;else&lt;/pre&gt;
&lt;pre&gt;    print &amp;quot;hello from the parent&amp;quot;&lt;/pre&gt;&lt;/code&gt;
Paraphrasing Rachelbythebay&#x27;s blog post:
WTF?! Where&#x27;s the &lt;code&gt;else if (pid &lt; 0)&lt;/code&gt;?
Why isn&#x27;t anyone writing it?
The blog post concludes:&lt;ol&gt;&lt;li&gt;
We&#x27;re not including it in our examples, so those who are learning
from our examples won&#x27;t know exist, and,&lt;/li&gt;&lt;li&gt;
the (arguably) worse reason of all: laziness combined with
a lack of creativity; the classical reason why a programmer won&#x27;t do
something: &quot;it makes my code messy&quot;.&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;
Anyways, messy-code is not a valid excuse, it never was and it never will be.
Any code can always be &quot;un-messified&quot; with a little bit of creativity.
At worse it can be hid behind a function call;
&lt;code&gt;else handle_fork_fail()&lt;/code&gt;
won&#x27;t ruin the zen energy of any code if you ask me.
Why couldn&#x27;t the man page example have been like this?&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;@load &amp;quot;fork&amp;quot;&lt;/pre&gt;
&lt;pre&gt;...&lt;/pre&gt;
&lt;pre&gt;if ((pid = fork()) == 0)&lt;/pre&gt;
&lt;pre&gt;    print &amp;quot;hello from the child&amp;quot;&lt;/pre&gt;
&lt;pre&gt;else if (pid &amp;gt; 0)&lt;/pre&gt;
&lt;pre&gt;    print &amp;quot;hello from the parent&amp;quot;&lt;/pre&gt;
&lt;pre&gt;else&lt;/pre&gt;
&lt;pre&gt;    ...&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
As example-writers we must always be aware that we will be imitated often,
and especially by those who know least.
And we must always be aware that our code will likely be copy-pasted pretty
much everywhere (example: your next car&#x27;s firmware).&lt;/p&gt;&lt;p&gt;
Rachelbythebay&#x27;s blog post points to, what I believe is, the fundamental issue.
It&#x27;s not in the examples as much as it&#x27;s in &lt;code class=&quot;in&quot;&gt;fork()&lt;/code&gt; itself.
Luckily the blog puts it better than I could, here:
&lt;a target=&quot;_blank&quot; href=&quot;https://rachelbythebay.com/w/2011/07/15/ui/&quot;&gt;if too many users are wrong, it&#x27;s probably your fault&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;
Now here&#x27;s an anecdote.
When I arrived in the french part of Switzerland I was already speaking the official French,
&lt;em&gt;le fran&amp;ccedil;ais Parisien&lt;/em&gt; for the last fifteen years of my life.
First day there what do you do?
You go buy some food and the stuff the airport ruined.
Normal.
I get to the cashier and I heard a number I had never heard before.
You should know that in official French, numbers like 99 are literally pronounced &quot;four twenties ten nine&quot; (&lt;em&gt;quatre-vingt-dix-neuf&lt;/em&gt; 4*20+10+9=99).
What I heard was a new word, something like &quot;nine-ty nine&quot; (&lt;em&gt;&quot;nenate&quot; neuf&lt;/em&gt;), the Swiss got creative, and it blew my mind!
&lt;/p&gt;&lt;p&gt;
Coming back to &lt;code class=&quot;in&quot;&gt;fork()&lt;/code&gt;,
we are complicating our lives when we use ad-hoc return values,
and explicitly encoding statuses as integers isn&#x27;t helping,
at least hide them behind a &lt;code class=&quot;in&quot;&gt;typedef&lt;/code&gt; or a &lt;code class=&quot;in&quot;&gt;#define&lt;/code&gt;, have some shame.
Try it with me, say this out loud: &quot;if the new process is zero&quot;, sounds funky, no?&lt;/p&gt;&lt;p&gt;
If you want to surrender to the status-quo and be pragmatic, here&#x27;s a &lt;code class=&quot;in&quot;&gt;fork()&lt;/code&gt; example for you.&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;#include &amp;lt;stdio.h&amp;gt;&lt;/pre&gt;
&lt;pre&gt;#include &amp;lt;unistd.h&amp;gt;&lt;/pre&gt;
&lt;pre&gt;#include &amp;lt;errno.h&amp;gt;&lt;/pre&gt;
&lt;pre&gt;#include &amp;lt;string.h&amp;gt;&lt;/pre&gt;
&lt;pre&gt;  &lt;/pre&gt;
&lt;pre&gt;int _g_last_pid_value;&lt;/pre&gt;
&lt;pre&gt;int (*old_fork)() = fork;&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;#define last_fork_in_child     if (_g_last_pid_value == 0)&lt;/pre&gt;
&lt;pre&gt;#define last_fork_in_parent    if (_g_last_pid_value &amp;gt; 0)&lt;/pre&gt;
&lt;pre&gt;#define last_fork_error        if (_g_last_pid_value &amp;lt; 0)&lt;/pre&gt;
&lt;pre&gt;#define fork()                 (_g_last_pid_value = old_fork())&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;int main() {&lt;/pre&gt;
&lt;pre&gt;   int pid = fork();&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;   last_fork_in_child     printf(&amp;quot;hello from the child\n&amp;quot;);&lt;/pre&gt;
&lt;pre&gt;   last_fork_in_parent    printf(&amp;quot;hello from the parent (child=%d)\n&amp;quot;, pid);&lt;/pre&gt;
&lt;pre&gt;   last_fork_error        fprintf(stderr, &amp;quot;error %d\n%s\n&amp;quot;, errno, strerror(errno));&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;   return 0;&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
But, if you want to do better, ask yourself:
What are you telling your user?
Are you telling them &quot;hey buddy, don&#x27;t forget about the error case, no biggie if you forget, but please try to remember it&quot;,
or are you saying &quot;listen pal, that&#x27;s not gonna work if you won&#x27;t tell me what to do if it fails&quot;?&lt;/p&gt;&lt;p&gt;
If you want to absolutely force the user to provide an error handler then more sophisticated macros will be required.
My go-to strategy is a type-driven approach,
this way if an handler isn&#x27;t provided the compiler will always let me know (I don&#x27;t have to wait till the runtime).
I implemented a proof-of-concept in D (the full code is at the end),
here&#x27;s an example illustrating my fork&#x27;s interface:&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;MyFork.with_child_handler({&lt;/pre&gt;
&lt;pre&gt;            writeln(&amp;quot;Hello from the child&amp;quot;);&lt;/pre&gt;
&lt;pre&gt;      })&lt;/pre&gt;
&lt;pre&gt;      .with_parent_handler((int pid) {&lt;/pre&gt;
&lt;pre&gt;            writefln(&amp;quot;Hello from the parent (child=%d)&amp;quot;, pid);&lt;/pre&gt;
&lt;pre&gt;      })&lt;/pre&gt;
&lt;pre&gt;      .with_error_handler({&lt;/pre&gt;
&lt;pre&gt;            writeln(&amp;quot;An error occurred&amp;quot;);&lt;/pre&gt;
&lt;pre&gt;      })&lt;/pre&gt;
&lt;pre&gt;      .run();&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
The handlers can be provided in any order,
and exactly one handler must be provided,
providing two will produce a compile error.
The actual forking is done when &lt;code class=&quot;in&quot;&gt;run()&lt;/code&gt; is executed.
Basically there are, eight phantom types (represented by mixed-in structs):&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;struct MyFork {&lt;/pre&gt;
&lt;pre&gt;    MyForkWithChild with_child_handler(ChildHandler handler);&lt;/pre&gt;
&lt;pre&gt;    MyForkWithParent with_parent_handler(ParentHandler handler);&lt;/pre&gt;
&lt;pre&gt;    MyForkWithError with_error_handler(ErrorHandler handler);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;...&lt;/pre&gt;
&lt;pre&gt;struct MyForkWithParent {&lt;/pre&gt;
&lt;pre&gt;    private ParentHandler parent_handler;&lt;/pre&gt;
&lt;pre&gt;    MyForkWithChildParent with_child_handler(ChildHandler handler);&lt;/pre&gt;
&lt;pre&gt;    MyForkWithParentError with_error_handler(ErrorHandler handler);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;...&lt;/pre&gt;
&lt;pre&gt;struct MyForkWithChildParentError {&lt;/pre&gt;
&lt;pre&gt;    private ChildHandler child_handler;&lt;/pre&gt;
&lt;pre&gt;    private ParentHandler parent_handler;&lt;/pre&gt;
&lt;pre&gt;    private ErrorHandler error_handler;&lt;/pre&gt;
&lt;pre&gt;    public void run() {&lt;/pre&gt;
&lt;pre&gt;         int pid = fork();&lt;/pre&gt;
&lt;pre&gt;         if (pid == 0) child_handler();&lt;/pre&gt;
&lt;pre&gt;         else if (pid &amp;gt; 0) parent_handler();&lt;/pre&gt;
&lt;pre&gt;         else error_handler();&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
To reiterate, my point is: messy code has never been a valid excuse, and never will be.
Besides sequencing &lt;code&gt;.with_..._handler&lt;/code&gt;s we could use named arguments.
Or we could use fancier macros.
Or we could simulate the whole thing with function calls like the following example does.
There are a million ways to tidy up your code &lt;strong&gt;and&lt;/strong&gt; do error handling.&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;int (*old_fork)() = fork;&lt;/pre&gt;
&lt;pre&gt;void fork(void (*child)(), void (*parent)(int), void (*error)()) {&lt;/pre&gt;
&lt;pre&gt;    int pid = old_fork();&lt;/pre&gt;
&lt;pre&gt;    if (pid == 0) child();&lt;/pre&gt;
&lt;pre&gt;    else if (pid &amp;gt; 0) parent(pid);&lt;/pre&gt;
&lt;pre&gt;    else error();&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
For the interested here is the complete compilable/executable source code of the D code mentioned above.
The eight phantom types are not hand-written (you think I&#x27;m insane?)
they are generated at compile-time by D&#x27;s mixins and compile-time-function-execution (C++ template magic allows you to do that too).
You could try this code by copy-pasting it in
&lt;a href=&quot;https://run.dlang.io&quot; targte=&quot;_blank&quot;&gt;https://run.dlang.io&lt;/a&gt;.
The implementation of the macros and templates and co. may be complicated,
but the interface ought to be as simple as possible and should encode our requirements correctly (preaching &lt;em&gt;The Right Thing&lt;/em&gt;).
If we wanted to force the user to provide the handlers in a specific order then we would not need eight structs.
Similarly, if we wanted to allow the user to override the handler (by calling &lt;code class=&quot;in&quot;&gt;with_child_handler&lt;/code&gt; many times for example) then we would not need eight structs.
Eight is the number of possible states we could be in (states representing which handlers were provided).
The struct that has all three handlers is the only struct with a &lt;code class=&quot;in&quot;&gt;run()&lt;/code&gt; function.
If we wanted to make the parent handler optional then all structs with a child handler and an error handler (two of them) will have a copy of &lt;code class=&quot;in&quot;&gt;run()&lt;/code&gt;.&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;import std.stdio;&lt;/pre&gt;
&lt;pre&gt;  &lt;/pre&gt;
&lt;pre&gt;mixin template HasChildHandler() {&lt;/pre&gt;
&lt;pre&gt;    private void delegate() child_handler;&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;mixin template HasParentHandler() {&lt;/pre&gt;
&lt;pre&gt;    private void delegate(int) parent_handler;&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;mixin template HasErrorHandler() {&lt;/pre&gt;
&lt;pre&gt;    private void delegate() error_handler;&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;  &lt;/pre&gt;
&lt;pre&gt;  &lt;/pre&gt;
&lt;pre&gt;mixin template ProvideHandlerSetter(T, DG, string field) {&lt;/pre&gt;
&lt;pre&gt;    mixin(`T with_` ~ field ~ `_handler(DG dg) {&lt;/pre&gt;
&lt;pre&gt;        auto value = T();&lt;/pre&gt;
&lt;pre&gt;        value.` ~ field ~ `_handler = dg;&lt;/pre&gt;
&lt;pre&gt;        static if (__traits(compiles, this.child_handler)&lt;/pre&gt;
&lt;pre&gt;                &amp;amp;&amp;amp; __traits(compiles, value.child_handler))&lt;/pre&gt;
&lt;pre&gt;            value.child_handler = this.child_handler;&lt;/pre&gt;
&lt;pre&gt;        static if (__traits(compiles, this.parent_handler)&lt;/pre&gt;
&lt;pre&gt;                &amp;amp;&amp;amp; __traits(compiles, value.parent_handler))&lt;/pre&gt;
&lt;pre&gt;            value.parent_handler = this.parent_handler;&lt;/pre&gt;
&lt;pre&gt;        static if (__traits(compiles, this.error_handler)&lt;/pre&gt;
&lt;pre&gt;                &amp;amp;&amp;amp; __traits(compiles, value.error_handler))&lt;/pre&gt;
&lt;pre&gt;            value.error_handler = this.error_handler;&lt;/pre&gt;
&lt;pre&gt;        return value;&lt;/pre&gt;
&lt;pre&gt;    }`);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt; &lt;/pre&gt;
&lt;pre&gt; &lt;/pre&gt;
&lt;pre&gt;mixin template ProvideChildHandlerSetter(T) {&lt;/pre&gt;
&lt;pre&gt;    mixin ProvideHandlerSetter!(T, void delegate(), &amp;quot;child&amp;quot;);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;mixin template ProvideParentHandlerSetter(T) {&lt;/pre&gt;
&lt;pre&gt;    mixin ProvideHandlerSetter!(T, void delegate(int), &amp;quot;parent&amp;quot;);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;mixin template ProvideErrorHandlerSetter(T) {&lt;/pre&gt;
&lt;pre&gt;    mixin ProvideHandlerSetter!(T, void delegate(), &amp;quot;error&amp;quot;);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt; &lt;/pre&gt;
&lt;pre&gt; &lt;/pre&gt;
&lt;pre&gt;mixin({&lt;/pre&gt;
&lt;pre&gt;    string structName(bool child, bool parent, bool error) {&lt;/pre&gt;
&lt;pre&gt;        string name = &amp;quot;MyFork&amp;quot; ~ (child || parent || error ? &amp;quot;With&amp;quot; : &amp;quot;&amp;quot;);&lt;/pre&gt;
&lt;pre&gt;        if (child) name ~= &amp;quot;Child&amp;quot;;&lt;/pre&gt;
&lt;pre&gt;        if (parent) name ~= &amp;quot;Parent&amp;quot;;&lt;/pre&gt;
&lt;pre&gt;        if (error) name ~= &amp;quot;Error&amp;quot;;&lt;/pre&gt;
&lt;pre&gt;        return name;&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;    string result = &amp;quot;&amp;quot;;&lt;/pre&gt;
&lt;pre&gt;    for (int i=0; i&amp;lt;8; i++) {&lt;/pre&gt;
&lt;pre&gt;        bool child = (i &amp;amp; 0b001) == 1;&lt;/pre&gt;
&lt;pre&gt;        bool parent = ((i &amp;amp; 0b010) &amp;gt;&amp;gt; 1) == 1;&lt;/pre&gt;
&lt;pre&gt;        bool error = ((i &amp;amp; 0b100) &amp;gt;&amp;gt; 2) == 1;&lt;/pre&gt;
&lt;pre&gt;        result ~= &amp;quot;struct &amp;quot; ~ structName(child, parent, error) ~ &amp;quot; {&amp;quot;;&lt;/pre&gt;
&lt;pre&gt;        result ~= (child ? &amp;quot;mixin HasChildHandler&amp;quot; : &amp;quot;mixin ProvideChildHandlerSetter!&amp;quot; ~ structName(true, parent, error)) ~ &amp;quot;;&amp;quot;;&lt;/pre&gt;
&lt;pre&gt;        result ~= (parent ? &amp;quot;mixin HasParentHandler&amp;quot; : &amp;quot;mixin ProvideParentHandlerSetter!&amp;quot; ~ structName(child, true, error)) ~ &amp;quot;;&amp;quot;;&lt;/pre&gt;
&lt;pre&gt;        result ~= (error ? &amp;quot;mixin HasErrorHandler&amp;quot; : &amp;quot;mixin ProvideErrorHandlerSetter!&amp;quot; ~ structName(child, parent, true)) ~ &amp;quot;;&amp;quot;;&lt;/pre&gt;
&lt;pre&gt;        if (child &amp;amp;&amp;amp; parent &amp;amp;&amp;amp; error) {&lt;/pre&gt;
&lt;pre&gt;            result ~= q{void run() {&lt;/pre&gt;
&lt;pre&gt;                import core.sys.posix.unistd : fork, pid_t;&lt;/pre&gt;
&lt;pre&gt;                pid_t pid = fork();&lt;/pre&gt;
&lt;pre&gt;                if (pid == 0) child_handler();&lt;/pre&gt;
&lt;pre&gt;                else if (pid &amp;gt; 0) parent_handler(pid);&lt;/pre&gt;
&lt;pre&gt;                else error_handler();&lt;/pre&gt;
&lt;pre&gt;            }};&lt;/pre&gt;
&lt;pre&gt;        }&lt;/pre&gt;
&lt;pre&gt;        result ~= &amp;quot;}&amp;quot;;&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;    return result;&lt;/pre&gt;
&lt;pre&gt;}());&lt;/pre&gt;
&lt;pre&gt; &lt;/pre&gt;
&lt;pre&gt;     &lt;/pre&gt;
&lt;pre&gt;void main() {&lt;/pre&gt;
&lt;pre&gt;    MyFork()&lt;/pre&gt;
&lt;pre&gt;        .with_error_handler({&lt;/pre&gt;
&lt;pre&gt;            &amp;quot;ERROR&amp;quot;.writeln;&lt;/pre&gt;
&lt;pre&gt;         })&lt;/pre&gt;
&lt;pre&gt;        .with_child_handler({&lt;/pre&gt;
&lt;pre&gt;            &amp;quot;Hello from the child&amp;quot;.writeln;&lt;/pre&gt;
&lt;pre&gt;         })&lt;/pre&gt;
&lt;pre&gt;        .with_parent_handler((child_pid) {&lt;/pre&gt;
&lt;pre&gt;            &amp;quot;Hello from the parent (child=%d)&amp;quot;.writefln(child_pid);&lt;/pre&gt;
&lt;pre&gt;         })&lt;/pre&gt;
&lt;pre&gt;        .run();&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code class=&quot;block&quot;&gt;</description>
<link>https://blog.grgz.me/posts/fork-as-a-knife.html</link>
<guid isPermaLink="false">https://blog.grgz.me/posts/fork-as-a-knife.html</guid>
<pubDate>Thu, 10 Dec 2020</pubDate>
</item>

<item>
<title>Translation Of and Notes On Simone Weil&#x27;s Letter to &lt;em&gt;Cahiers Du Sud&lt;/em&gt;
on the Responsibilities of Literature.</title>
<description>&lt;style&gt;
p { font-family: serif; }
em &gt; em { font-style: normal; }
hr { width: 33%; border: 0; border-bottom: 1px solid #ccc; }
a.footnote { background: transparent; border: 0; }
hr.footnotes { margin-bottom: 50px; }
hr.footnotes + ol li { margin-bottom: 20px; }
sup { font-size: 55%; }&lt;/style&gt;&lt;p&gt;&lt;em&gt;
Written in 1941 and published in 1951 in &lt;em&gt;Cahiers du Sud&lt;/em&gt;, a literary
journal based in Marseilles, this letter is Simone Weil&#x27;s response to the
journal&#x27;s editor-in-chief L&amp;eacute;on-Gabriel Gros who contributed two
chronicles, the first in October 1940 and the second in March 1941, that evoke
the responsibility of writers. Gros presents two theses in his two
contributions: The first thesis is the official thesis, that of the Vichy
government, that blames writers for the fall of France. The second is
that of the &lt;em&gt;Zone Libre&lt;/em&gt; that wish writers would adopt a more moral
stance to help France.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;
Throughout the translation I underlined some sentences. These sentences I believe
are either key points in Weil&#x27;s argument, or are one of her assumptions, beliefs,
or observations.
Similarly the footnotes present are also entirely my own and represent my notes and
reflections about the text.
The original letter has neither footnotes nor underlines.&lt;/em&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;
About this translation: this translation is entirely my own. I have tried
to preserve the structure of the sentences and Weil&#x27;s choice of words,
therefore some sentences may sound clunky. Throughout the letter Weil uses
the expression &lt;em&gt;le bon et le mal&lt;/em&gt; which could either mean &quot;the good
and the bad&quot;, or  &quot;the good and the evil&quot;. I have chosen to use the word
bad always instead of evil as to avoid any extremization. In one
instance where Weil uses &lt;em&gt;opposition du bien et du mal&lt;/em&gt; I have chosen
to translate it as &quot;good vs. evil&quot; as opposed to the more literal &quot;opposition
of the good and the bad&quot;.&lt;br&gt;&lt;/em&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;
Very brief summary: Writers have responsibilities (paragraph 2). And literature&#x27;s
been losing value, but has not lost its prestige which adds responsibility
to the writers (paragraph 3). But there&#x27;s more (paragraph 4). Because
the writers have always had access and knowledge to values (paragraph 5).
But we have to act quickly before movements like Dadaism and Surrealism become
the norm (paragraph 6), just look at the words they, and those before them,
have used (paragraph 7). Now, the contemporaries show signs of lack of values
(paragraph 8). So let&#x27;s go back to owning values (paragraph 9) by looking
inside (paragraph 10).&lt;/em&gt;&lt;/p&gt;
&lt;hr&gt;&lt;p&gt;
While reading Gros&#x27;&lt;a href=&quot;#footnote-1-text&quot; id=&quot;footnote-1-ref&quot; class=&quot;footnote&quot;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; allusion to the controversy surrounding the
responsibility of writers, I was not able to resist going back to this
question and defend a point of view contrary to the journal&#x27;s,
contrary to that of almost all who are sympathetic to me, and resembling
in form, by bad luck, that of people for whom I have no sympathy.&lt;/p&gt;&lt;p&gt;
&lt;u&gt;I believe in the responsibility of the writers of that era that just
passed&lt;/u&gt; towards the misfortune of our time. By that I do not only mean the
defeat of France; the misfortune goes back a long way.
It goes around the whole world, that is in Europe, in America, and in
the other continents, for as long as Western influence has penetrated
there&lt;a href=&quot;#footnote-2-text&quot; id=&quot;footnote-2-ref&quot; class=&quot;footnote&quot;&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;
It is true, just as Mauriac&lt;a href=&quot;#footnote-3-text&quot; id=&quot;footnote-3-ref&quot; class=&quot;footnote&quot;&gt;&lt;sup&gt;3&lt;/sup&gt;&lt;/a&gt; remarked, that the best contemporary
books are hardly ever read.
But the responsibility of the writers cannot be measured by the number
of books sold.
Because &lt;u&gt;the prestige of literature is immense&lt;/u&gt;.
We can verify this if we consider the efforts done in the
past by some political groups to insure the names of popular writers for
demagogic goals.
For those who even the name of some popular writer is unknown to, do not
experience any less the prestige of that literature they are unaware of.
We have never read more than we are reading today.
&lt;u&gt;We do not read books, but we read mediocre and bad periodicals&lt;/u&gt;; these
periodicals are everywhere, in the villages, in the suburbs, and now, due
to the effect of our time&#x27;s literary customs, between the worse of these
periodicals and the best of our writers there are no ruptures of continuity.
This fact, which is known or rather confusedly felt by the public, adorns
in their eyes the most ignoble advertising firms with all the prestige
of high literature.
&lt;u&gt;There was, throughout the previous years, an incredible baseness&lt;/u&gt;, such as
some sentimental consultations accorded by some known writers.
With no doubt all doesn&#x27;t fall like so; a lot was needed.
But those who fell like so were not disavowed nor pushed-back by others;
they did not lose any consideration from their peers&#x27; milieu.
This ease of literary manners, &lt;u&gt;this tolerance of the baseness gives to
our most eminent writers, a responsibility in the demoralisation&lt;/u&gt; of any
farm-girl who never left her village and who never heard their names&lt;a href=&quot;#footnote-4-text&quot; id=&quot;footnote-4-ref&quot; class=&quot;footnote&quot;&gt;&lt;sup&gt;4&lt;/sup&gt;&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;
But writers have a more direct responsibility.&lt;/p&gt;&lt;p&gt;
&lt;u&gt;The essential character of the first half of the 20&lt;sup&gt;th&lt;/sup&gt; century
is the weakening and the near collapse of the notion of value&lt;/u&gt;.
It is one of the rare phenomena that seem to be, for as long as we know,
really new in the history of humanity.
It could be, of course, the case that this happened before through periods
whose memory faded due to forgetfulness, as it could be later the case for
our time.
This phenomenon manifested itself in many domains foreign to literature,
even in everything.
The substitution for quantity of quality in the industrial production,
the discredit that fell on qualified work among the workers, the
substitution for the diploma of the culture as the goal of studies among
the studious youth&lt;a href=&quot;#footnote-5-text&quot; id=&quot;footnote-5-ref&quot; class=&quot;footnote&quot;&gt;&lt;sup&gt;5&lt;/sup&gt;&lt;/a&gt; are some of these manifestations.
Even science does not hold the same criteria for value ever since the
abandonment of classical science&lt;a href=&quot;#footnote-6-text&quot; id=&quot;footnote-6-ref&quot; class=&quot;footnote&quot;&gt;&lt;sup&gt;6&lt;/sup&gt;&lt;/a&gt;.
But writers were &lt;em&gt;par excellence&lt;/em&gt;, the guardians of the lost
treasure&lt;a href=&quot;#footnote-7-text&quot; id=&quot;footnote-7-ref&quot; class=&quot;footnote&quot;&gt;&lt;sup&gt;7&lt;/sup&gt;&lt;/a&gt;, and some drew vanity from that loss.&lt;/p&gt;&lt;p&gt;
Dadaism, and Surrealism are extreme cases.
They expressed the drunkenness of a total license, the drunkenness where
the soul dives when, rejecting any consideration for any value, it delivers
itself to the immediate.
&lt;u&gt;The good is the pole to which is necessary oriented the human spirit&lt;/u&gt;,
not only in action, but in all efforts, including the effort of pure
intelligence.
The surrealists erected as a model disoriented thinking; they chose
as supreme value the complete absence of values&lt;a href=&quot;#footnote-8-text&quot; id=&quot;footnote-8-ref&quot; class=&quot;footnote&quot;&gt;&lt;sup&gt;8&lt;/sup&gt;&lt;/a&gt;.
The license has always intoxicated men, and is the reason why, all
along history cities were sacked.
But the sacking of cities didn&#x27;t always have a literary equivalent.
Surrealism, as such, is an equivalent.&lt;/p&gt;&lt;p&gt;
&lt;u&gt;The other writers of the same period and the previous one did not go as
far, but almost all - three or four excluded - are more or less affected
by the same lack, the lack of any sense of value&lt;/u&gt;.
Some words such as spontaneity, sincerity, gratuity, richness,
enrichment, words that imply an indifference almost entire to the
oppositions of values, started appearing more frequently under their
pens than words that relate to the good and the bad.
In fact this last species of words has degraded, especially those that
are related to the good, as Val&amp;eacute;ry&lt;a href=&quot;#footnote-9-text&quot; id=&quot;footnote-9-ref&quot; class=&quot;footnote&quot;&gt;&lt;sup&gt;9&lt;/sup&gt;&lt;/a&gt; remarked some years ago.
Words such as virtue, nobility, honour, honesty, and generosity either
became almost impossible to pronounce or held a bastardised meaning; &lt;u&gt;the
language doesn&#x27;t provide anymore any resource to legitimately praise the
character of a human&lt;/u&gt;.
It provides a little bit more, but hardly any to praise the spirit; even
the word spirit itself, the words of intelligence, intelligent and
others similar have also been degraded.
The destiny of words portrays sensibly the progressive collapse of the
sense of value, and though this destiny does not depend on the writers,
we cannot prevent making them particularly responsible, since words are
part of their business.&lt;/p&gt;&lt;p&gt;
We have lately praised a lot, and righteously, the book of Bergson&lt;a href=&quot;#footnote-10-text&quot; id=&quot;footnote-10-ref&quot; class=&quot;footnote&quot;&gt;&lt;sup&gt;10&lt;/sup&gt;&lt;/a&gt;; we
have talked a lot about the influence this work had on the thoughts and
the literature of our time.
However, in the center of the philosophy that guides his first three books
lies a notion essentially foreign to any account of value, maybe even
foreign to any account of life.
Not surprisingly in vain some willed this philosophy to be foundations to
Catholicism, which in fact did not need any, since its own are much older.
The work of Proust&lt;a href=&quot;#footnote-11-text&quot; id=&quot;footnote-11-ref&quot; class=&quot;footnote&quot;&gt;&lt;sup&gt;11&lt;/sup&gt;&lt;/a&gt; is full of analyses that try to describe the state of
disoriented souls; the good only appears in rare moments, or as a
consequence of either memory, or beauty, eternity lets itself be sensed
throughout Time.
We could make analogous remarks on many writers before and certainly
after 1914.
In a general manner the literature of the 20&lt;sup&gt;th&lt;/sup&gt; century is
essentially psychological.
And psychology consists of describing the state of souls in laying them
all out on the same plane without discriminating for values, &lt;u&gt;as if the
good and the bad are exterior to them&lt;/u&gt;, and &lt;u&gt;as if the effort towards the
good could be absent at any moment during the thought process of any human&lt;/u&gt;&lt;a href=&quot;#footnote-12-text&quot; id=&quot;footnote-12-ref&quot; class=&quot;footnote&quot;&gt;&lt;sup&gt;12&lt;/sup&gt;&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;
The writers are not to be professors of morals, but they are to express the
human condition. Since &lt;u&gt;nothing is as essential to human life, for every
human and at every instant, as the good and the bad&lt;/u&gt;.
When literature becomes in part indifferent to the problem of good
&lt;em&gt;vs.&lt;/em&gt; evil, it betrays its function and cannot begin to claim
excellence&lt;a href=&quot;#footnote-13-text&quot; id=&quot;footnote-13-ref&quot; class=&quot;footnote&quot;&gt;&lt;sup&gt;13&lt;/sup&gt;&lt;/a&gt;.
Racine made fun of Jansenists in his youth, but he stopped making fun of
them while writing &lt;em&gt;Ph&amp;egrave;dre&lt;/em&gt;, and &lt;em&gt;Ph&amp;egrave;dre&lt;/em&gt; is
his masterpiece.
From that point of view it is not true that there is a continuity in
french literature.
It is not true that Rimbaud and his successors (putting aside some
passages from A Season In Hell) follow the footsteps of Villon&lt;a href=&quot;#footnote-14-text&quot; id=&quot;footnote-14-ref&quot; class=&quot;footnote&quot;&gt;&lt;sup&gt;14&lt;/sup&gt;&lt;/a&gt;.
Why does it matter that Villon has stolen?
The act of stealing became, on its part, probably an effect of
necessity, or probably a sin, but it was not an adventure nor a free
act.
The feeling of the good and the bad impregnate all his verses, just as
he is impregnated in all works that are not foreign to human destiny&lt;a href=&quot;#footnote-15-text&quot; id=&quot;footnote-15-ref&quot; class=&quot;footnote&quot;&gt;&lt;sup&gt;15&lt;/sup&gt;&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;
Certainly, there are things more foreign still to the good and the bad
than amorality, and it&#x27;s a certain morality.
Those who blame now the popular writers are worth infinitely less&lt;a href=&quot;#footnote-16-text&quot; id=&quot;footnote-16-ref&quot; class=&quot;footnote&quot;&gt;&lt;sup&gt;16&lt;/sup&gt;&lt;/a&gt;,
and the &quot;redress&quot; that some would like to impose will be much
worse than the state of things we&#x27;re pretending to remedy.
If the current sufferings never lead to a redress, it will certainly not
happen because of slogans, but through the silence and the solitude of
morality, through the penalties, the misery, the terrors, and in the
most intimate place in each spirit.&lt;/p&gt;
&lt;hr&gt;&lt;p&gt;&lt;em&gt;
Note on the conclusion: Simone Weil is not being a professor of moral in
this letter, she is not teaching us or giving us a moral idea.
She is not trying to grade (by blaming) other writers, and seems to be
vehemently opposed to that idea. Instead what we see is a communication
of an observation by Simone Weil, she&#x27;s pointing something out;
she&#x27;s expressing a human condition.
Her observation is: if any redress or improvement needs to be done
then it will never come from another person, nor a group, nor their ideas,
nor their slogans. The only source of redress needs to come from within
every person, &quot;in the silence and the moral solitude [...] and in the
most intimate place in each spirit&quot;. She&#x27;s inviting us to dig deep within.&lt;/em&gt;&lt;/p&gt;
&lt;hr class=&quot;footnotes&quot;&gt;&lt;ol&gt;&lt;li&gt;&lt;span id=&quot;footnote-1-text&quot; /&gt;&lt;/li&gt;&lt;/ol&gt;
L&amp;eacute;on-Gabriel Gros (1905-1985) was the editor-in-chief of
&lt;em&gt;Cahiers du Sud&lt;/em&gt; who contributed two chronicles about the responsibility
of writers. Read also the introduction of this translation.
&lt;a href=&quot;#footnote-1-ref&quot;&gt;[back]&lt;/a&gt;&lt;li&gt;&lt;span id=&quot;footnote-2-text&quot; /&gt;&lt;/li&gt;
On the surface this may look like an Americo-Eurocentric position, but one must
keep in mind that Simone Weil read the Mahabharata and knew Sanskrit, so she is
very well aware of the rest of the world.&lt;br&gt;
In my opinion, in this sentence she only means that Western thinking is a
fundamental part of this misfortune, she doesn&#x27;t seem to find that misfortune
in the East.
&lt;a href=&quot;#footnote-2-ref&quot;&gt;[back]&lt;/a&gt;&lt;li&gt;&lt;span id=&quot;footnote-3-text&quot; /&gt;&lt;/li&gt;
Fran&amp;ccedil;ois Charles Mauriac (1885-1970) was a writer, journalist, member of the
&lt;em&gt;Acad&amp;eacute;mie Fran&amp;ccedil;aise&lt;/em&gt;, and Nobel Literature prize laureate.
&lt;a href=&quot;#footnote-3-ref&quot;&gt;[back]&lt;/a&gt;&lt;li&gt;&lt;span id=&quot;footnote-4-text&quot; /&gt;&lt;/li&gt;
So we can conclude that it is the responsibility of &lt;em&gt;eminent&lt;/em&gt; writers
to seek out the readers that do not know them. In other words, to be promoted
from a writer to an eminent writer it is one&#x27;s job to advertise oneself and give
as broad an audience as possible to one&#x27;s writings.
&lt;a href=&quot;#footnote-4-ref&quot;&gt;[back]&lt;/a&gt;&lt;li&gt;&lt;span id=&quot;footnote-5-text&quot; /&gt;&lt;/li&gt;
These are supposed to be arguments for the collapse of values. It is true that
these examples represent the collapse of the &lt;em&gt;old&lt;/em&gt; values, but I
do not think it is fair to describe these as only a collapse. To me these
represent a shift, a change, a substitution as she says, of values. So people
are not losing their values, they are just changing them.
&lt;a href=&quot;#footnote-5-ref&quot;&gt;[back]&lt;/a&gt;&lt;li&gt;&lt;span id=&quot;footnote-6-text&quot; /&gt;&lt;/li&gt;
I do not know what Weil means by classical science. The best guess I can provide
is that she means natural philosophy by classical science, i.e. science as it
was up to the late 19&lt;sup&gt;th&lt;/sup&gt; century before the rise of modern science.
&lt;a href=&quot;#footnote-6-ref&quot;&gt;[back]&lt;/a&gt;&lt;li&gt;&lt;span id=&quot;footnote-7-text&quot; /&gt;&lt;/li&gt;
Imagine you were locked up underground during a nuclear explosion. You go back
up to the world and realize the only survivors are a handful of children.
Will you not feel responsible towards their education? Will you not tell them
the stories of old, or teach them what it is to be human?&lt;br&gt;
Similarly, I imagine Weil would believe that it is the responsibility of religious
hermits and recluses to go back to society and share the revelations they
receive in the wild.
&lt;a href=&quot;#footnote-7-ref&quot;&gt;[back]&lt;/a&gt;&lt;li&gt;&lt;span id=&quot;footnote-8-text&quot; /&gt;&lt;/li&gt;
The Dadaists and the Surrealists have explicitly adopted the antithesis of
Simone Weil, so they are &quot;the enemy&quot;, it is not surprising to see that paragraph
end the way it does.
&lt;a href=&quot;#footnote-8-ref&quot;&gt;[back]&lt;/a&gt;&lt;li&gt;&lt;span id=&quot;footnote-9-text&quot; /&gt;&lt;/li&gt;
Ambroise Paul Toussaint Jules Val&amp;eacute;ry (1871-1945) was a writer and philosopher.
He was nominated to the Nobel Literature prize 12 times.
&lt;a href=&quot;#footnote-9-ref&quot;&gt;[back]&lt;/a&gt;&lt;li&gt;&lt;span id=&quot;footnote-10-text&quot; /&gt;&lt;/li&gt;
Henri Bergson (1859-1941) was a philosopher. I am not knowledgeable enough to infer
the exact ideas that offend Weil.
&lt;a href=&quot;#footnote-10-ref&quot;&gt;[back]&lt;/a&gt;&lt;li&gt;&lt;span id=&quot;footnote-11-text&quot; /&gt;&lt;/li&gt;
The work Weil alludes to is Marcel Proust&#x27;s (1871-1922) In Search of Lost Time
(1913-1927, earlier title is: Remembrance of Things Past).
&lt;a href=&quot;#footnote-11-ref&quot;&gt;[back]&lt;/a&gt;&lt;li&gt;&lt;span id=&quot;footnote-12-text&quot; /&gt;&lt;/li&gt;
I suppose we can conclude that for Simone Weil the good and the bad, ethics,
and morals are never entirely exterior to anyone.&lt;br&gt;
We could also infer that, for Weil, psychology (as she interpreted it, or as
the standard interpretation of the time was) is a futile project.
&lt;a href=&quot;#footnote-12-ref&quot;&gt;[back]&lt;/a&gt;&lt;li&gt;&lt;span id=&quot;footnote-13-text&quot; /&gt;&lt;/li&gt;
Therefore literature is &lt;em&gt;primarily&lt;/em&gt; about the good &lt;em&gt;vs.&lt;/em&gt; the evil.
Its function is to tell moral stories about human lives.
&lt;a href=&quot;#footnote-13-ref&quot;&gt;[back]&lt;/a&gt;&lt;li&gt;&lt;span id=&quot;footnote-14-text&quot; /&gt;&lt;/li&gt;
Fran&amp;ccedil;ois Villon (1431-1463) is the best known French medieval poet. His
(short) life was shrouded in mystery and crime.&lt;br&gt;
In June 1455 he committed his first crime: killing Philippe Chermoye, a priest who
attacked him first (or so were the priest&#x27;s last words) after a brawl started.
Since self-defense was not a legal excuse at the time Villon had to suffer
banishment from Paris, his place of birth.&lt;br&gt;
The following January Villon received two pardons from King Charles VII, one for
&lt;em&gt;Fran&amp;ccedil;ois des Loges, aka Villon&lt;/em&gt;, and the other for &lt;em&gt;Fran&amp;ccedil;ois
de Montcorbier&lt;/em&gt;, &lt;em&gt;de Loges&lt;/em&gt; and &lt;em&gt;de Montcorbier&lt;/em&gt; appear both
in his official documents. He used the last name &lt;em&gt;Villon&lt;/em&gt; to refer to
himself in his writings. Villon is the last name of his foster father.&lt;br&gt;
The following December Villon participated in robbing the chapel of &lt;em&gt;Coll&amp;egrave;ge
de Navarre&lt;/em&gt; which went unnoticed for some six-months. It is said that Villon
fled Paris shortly after committing the crime. Anyways, in November 1462 Villon was
arrested for an unrelated crime. During his arrest the &lt;em&gt;Coll&amp;egrave;ge de Navarre&lt;/em&gt;
theft was revived and he was sentenced to death, which was later wavered to
banishment in January 1943.&lt;br&gt;
Nothing is known of his whereabouts after January 1943 and it is assumed he died
soon after being banished.&lt;br&gt;
The question that follows in the letter refers to the theft of the chapel.
&lt;a href=&quot;#footnote-14-ref&quot;&gt;[back]&lt;/a&gt;&lt;li&gt;&lt;span id=&quot;footnote-15-text&quot; /&gt;&lt;/li&gt;
Contrast this with the way Weil describes Proust&#x27;s In Search of Lost Time.
&lt;a href=&quot;#footnote-15-ref&quot;&gt;[back]&lt;/a&gt;&lt;li&gt;&lt;span id=&quot;footnote-16-text&quot; /&gt;&lt;/li&gt;
I think this sentence is very nuanced. On the surface it may seem that Weil is,
herself, blaming writers such as the Dadaists and the Surrealists in paragraph 6.
So she must be making a distinction between popular writers (&lt;em&gt;&amp;eacute;crivains
c&amp;eacute;l&amp;egrave;bre&lt;/em&gt;) and eminent writers (&lt;em&gt;les &amp;eacute;crivains les
plus &amp;eacute;minants&lt;/em&gt; in paragraph 3).&lt;br&gt;
The only (arguably) popular writers she criticises in the letter are Bergson, Proust,
and Rimbaud. She never blamed any of these five writers for
the loss of values (even if they personally, or their work, lacked values),
she only refers to them as exhibiting the symptoms of loss of values.
At worse she blames them for &lt;em&gt;unknowingly&lt;/em&gt; spreading the loss of values.
&lt;a href=&quot;#footnote-16-ref&quot;&gt;[back]&lt;/a&gt;</description>
<link>https://blog.grgz.me/posts/responsibilities-of-literature.html</link>
<guid isPermaLink="false">https://blog.grgz.me/posts/responsibilities-of-literature.html</guid>
<pubDate>Sat, 05 Dec 2020</pubDate>
</item>

<item>
<title>Upon Reading a Friend&#x27;s Message about the Awesomeness of the Kosaraju Algorithm</title>
<description>&lt;style&gt;
.poetry { counter-reset: poetry; max-width: 500px; margin: auto; margin-left: 100px; }
.poetry ol { padding: 0; margin: 0; padding-left: 20pt; }
.poetry li { list-style: none; counter-increment: poetry; text-indent: -20pt; margin-right: 30px; }
.poetry .empty-line { margin-bottom: 30pt; }
.poetry li:nth-child(5n):after { content: counter(poetry); display: inline-block; float: right; margin-right: -30px; font-size: 10px; }&lt;/style&gt;
&lt;div class=&quot;poetry&quot;&gt;&lt;ol&gt;&lt;li&gt;Let us say you reader work as a match-maker&lt;/li&gt;&lt;li&gt;And a client complain&#x27;d about a deal-breaker.&lt;/li&gt;&lt;li&gt;&quot;She dated a dear friend before&quot; was what he said,&lt;/li&gt;&lt;li&gt;&quot;I&#x27;d find it most abhor if we had shared a bed.&lt;/li&gt;&lt;li&gt;Not known to my social circle make sure she be,&lt;/li&gt;&lt;li&gt;Or by god, this bad-buck business I&#x27;ll rate shabby.&quot;
&lt;div class=&#x27;empty-line&#x27;&gt;&lt;/div&gt;&lt;/li&gt;&lt;li&gt;A problem like this one dear ol&#x27; Kosaraju&lt;/li&gt;&lt;li&gt;Tried to solve. But was it more than what he could chew?&lt;/li&gt;&lt;li&gt;Fear not, for foresight sleekly set him out to find&lt;/li&gt;&lt;li&gt;An algorithm so neat; a one-of-a-kind.&lt;/li&gt;&lt;li&gt;One that runs linearly in time and in space,&lt;/li&gt;&lt;li&gt;Designed neatly to be speedy and full of grace.
&lt;div class=&#x27;empty-line&#x27;&gt;&lt;/div&gt;&lt;/li&gt;&lt;li&gt;You must interpret first people as a network&lt;/li&gt;&lt;li&gt;Where Bob connects to Alice if he was a jerk,&lt;/li&gt;&lt;li&gt;or a lover, or simply in acknowledgement.&lt;/li&gt;&lt;li&gt;Then comsume one strongly connected component&lt;/li&gt;&lt;li&gt;That clearly does not include your careful client&lt;/li&gt;&lt;li&gt;And pick potentials from that pool to be compliant.
&lt;div class=&#x27;empty-line&#x27;&gt;&lt;/div&gt;&lt;/li&gt;&lt;li&gt;But how do you go about finding a strongly&lt;/li&gt;&lt;li&gt;Connected component from a graph so quickly?&lt;/li&gt;&lt;li&gt;Precisely that process Kosaraju and kin&lt;/li&gt;&lt;li&gt;Published the year after nineteen seventy sev&#x27;n.
&lt;div class=&#x27;empty-line&#x27;&gt;&lt;/div&gt;&lt;/li&gt;&lt;li&gt;Let list L from holding elements be acquit,&lt;/li&gt;&lt;li&gt;First step is to set all vertices to-visit.&lt;/li&gt;&lt;li&gt;Then one by one through the vertices you should loop&lt;/li&gt;&lt;li&gt;And view each as visited, and its neighbors group&lt;/li&gt;&lt;li&gt;To recurse on them after in L they&#x27;d instill&lt;/li&gt;&lt;li&gt;If the vertex was marked to-visit, else nil.&lt;/li&gt;&lt;li&gt;When pushing the neighbors be certain to prepend&lt;/li&gt;&lt;li&gt;Cause the next step will crucially on it depend:&lt;/li&gt;&lt;li&gt;To go in twine in the L-defined-order &#x27;long&lt;/li&gt;&lt;li&gt;The vertices and assign each itself belong.&lt;/li&gt;&lt;li&gt;Where assignment is defined being twixt two nodes&lt;/li&gt;&lt;li&gt;For former in the latter&#x27;s assignment it abodes&lt;/li&gt;&lt;li&gt;And its neighbors&#x27; assignment&#x27;s nest in the latter&lt;/li&gt;&lt;li&gt;If the former is assigned, else nil&#x27;s the matter.
&lt;div class=&#x27;empty-line&#x27;&gt;&lt;/div&gt;&lt;/li&gt;&lt;li&gt;For your match-making mess mister reader rummage&lt;/li&gt;&lt;li&gt;Through those client-unassigned to avoid damage.&lt;/li&gt;&lt;/ol&gt;
&lt;/div&gt;</description>
<link>https://blog.grgz.me/posts/kosaraju_poem.html</link>
<guid isPermaLink="false">https://blog.grgz.me/posts/kosaraju_poem.html</guid>
<pubDate>Sun, 08 Mar 2020</pubDate>
</item>

<item>
<title>Recursion Elimination &amp;mdash; Or how to make pretty code ugly</title>
<description>&lt;h2 id=&quot;sec-1&quot;&gt;Introduction&lt;/h2&gt;&lt;p&gt;
Recursive code is the epitome of beautiful (read elegant, pretty, concise...) code, but is the bane of performance.
A classic example is the Fibonacci function, here&#x27;s the slow yet elegant recursive version:&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;int fibonacci(uint n) {&lt;/pre&gt;
&lt;pre&gt;    return n &amp;lt; 2 ? 1 : fibonacci(n-1) + fibonacci(n-2);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
And here is the fast yet unenlightening iterative version:&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;int fibonacci(int n) {&lt;/pre&gt;
&lt;pre&gt;    int current = 1; int next = 1; int temp;&lt;/pre&gt;
&lt;pre&gt;    while (n &amp;gt;= 2) {&lt;/pre&gt;
&lt;pre&gt;        temp = current + next;&lt;/pre&gt;
&lt;pre&gt;        current = next;&lt;/pre&gt;
&lt;pre&gt;        next = temp;&lt;/pre&gt;
&lt;pre&gt;        n--;&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;    return next;&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
The other day I stumbled upon James Kopell&#x27;s blog post (and video presentation) &lt;a href=&quot;http://www.pathsensitive.com/2019/07/the-best-refactoring-youve-never-heard.html&quot; target=&quot;_blank&quot;&gt;The best refactoring you&#x27;ve never heard of&lt;/a&gt; in which he presents a framework to transform recursive functions into iterative ones.
What&#x27;s the catch?
Firstly, the transformation is hard to automate.
Secondly, the resulting code&#x27;s running time is identical to the recursive one&#x27;s.
So forget about transforming the recursive &lt;em&gt;&amp;Theta;(&amp;phi;&lt;sup&gt;n&lt;/sup&gt;)&lt;/em&gt; Fibonacci into the iterative &lt;em&gt;&amp;Theta;(n)&lt;/em&gt; code by applying the transformation mindlessly.
And finally, the transformed code is just really ugly...
Regardless, I think this transformation could be helpful.&lt;/p&gt;&lt;p&gt;
In this blog post I&#x27;ll guide you through the steps to transform a few complicated recursive functions into iterative ones.
In the process I hope to present the motivation behind this transformation, and to go deeper in the explanations of the components that make it up.
To the curious, here&#x27;s an example taken from Kopell&#x27;s post that showcases the transformation:&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;// RECURSIVE VERSION&lt;/pre&gt;
&lt;pre&gt;void printTree(Tree* tree) {&lt;/pre&gt;
&lt;pre&gt;    if (tree != null) {&lt;/pre&gt;
&lt;pre&gt;        printTree(tree.left);&lt;/pre&gt;
&lt;pre&gt;        print(tree.node);&lt;/pre&gt;
&lt;pre&gt;        printTree(tree.right);&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;// ITERATIVE VERSION&lt;/pre&gt;
&lt;pre&gt;class Cont {&lt;/pre&gt;
&lt;pre&gt;    Tree tree;&lt;/pre&gt;
&lt;pre&gt;    Cont next;&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt; &lt;/pre&gt;
&lt;pre&gt;void printTree(Tree tree, Cont cont) {&lt;/pre&gt;
&lt;pre&gt;    while (true) {&lt;/pre&gt;
&lt;pre&gt;        if (tree != null) {&lt;/pre&gt;
&lt;pre&gt;            cont = new Cont(tree, cont);&lt;/pre&gt;
&lt;pre&gt;            tree = tree.left;&lt;/pre&gt;
&lt;pre&gt;        } else {&lt;/pre&gt;
&lt;pre&gt;            if (cont != null) {&lt;/pre&gt;
&lt;pre&gt;                print(cont.tree.node);&lt;/pre&gt;
&lt;pre&gt;                tree = cont.tree.right;&lt;/pre&gt;
&lt;pre&gt;                cont = cont.next;&lt;/pre&gt;
&lt;pre&gt;            } else return;&lt;/pre&gt;
&lt;pre&gt;        }&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;h2 id=&quot;sec-2&quot;&gt;Recursive code that is easy to rewrite&lt;/h2&gt;&lt;p&gt;
Tail-recursive functions, i.e. functions whose last instruction is a recursive one, can be easily transformed into iterative code.
Consider the following code that prints a linked list.
We can transform it into iterative code by following these instructions:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;Wrapping the body of the function with a &lt;code&gt;while (true) { ... }&lt;/code&gt;,&lt;/li&gt;&lt;li&gt;adding a &lt;code&gt;break;&lt;/code&gt; (or a &lt;code&gt;return&lt;/code&gt;) in the branches that contain no recursive calls,&lt;/li&gt;&lt;li&gt;and replacing the recursive call with a re-assignment of the function&#x27;s arguments (beware that the order of assignment may be important!).&lt;/li&gt;&lt;/ol&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;// RECURSIVE&lt;/pre&gt;
&lt;pre&gt;void printList(LinkedList list) {&lt;/pre&gt;
&lt;pre&gt;    if (list == null) {&lt;/pre&gt;
&lt;pre&gt;        print(&amp;quot;()&amp;quot;);&lt;/pre&gt;
&lt;pre&gt;    } else {&lt;/pre&gt;
&lt;pre&gt;        print(list.data + &amp;quot; -&amp;gt; &amp;quot;);&lt;/pre&gt;
&lt;pre&gt;        printList(list.next);&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;// ITERATIVE AFTER DOING TAIL CALL OPTIMIZATION&lt;/pre&gt;
&lt;pre&gt;void printList(LinkedList list) {&lt;/pre&gt;
&lt;pre&gt;    while (true) {&lt;/pre&gt;
&lt;pre&gt;        if (list == null) {&lt;/pre&gt;
&lt;pre&gt;            print(&amp;quot;()&amp;quot;);&lt;/pre&gt;
&lt;pre&gt;            break;&lt;/pre&gt;
&lt;pre&gt;        } else {&lt;/pre&gt;
&lt;pre&gt;            print(list.data + &amp;quot; -&amp;gt; &amp;quot;);&lt;/pre&gt;
&lt;pre&gt;            list = list.next;&lt;/pre&gt;
&lt;pre&gt;        }&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
For some functions that operate on the recursive call, e.g. factorial, we can use accumulators to transform the function into a tail-recursive one.
Here&#x27;s the factorial example:&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;// RECURSIVE&lt;/pre&gt;
&lt;pre&gt;int factorial(int n, int acc = 1) {&lt;/pre&gt;
&lt;pre&gt;    if (n &amp;lt; 2)&lt;/pre&gt;
&lt;pre&gt;        return acc;&lt;/pre&gt;
&lt;pre&gt;    return factorial(n-1, acc*n);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;// ITERATIVE&lt;/pre&gt;
&lt;pre&gt;int factorial(int n) {&lt;/pre&gt;
&lt;pre&gt;    int acc = 1;&lt;/pre&gt;
&lt;pre&gt;    while (true) {&lt;/pre&gt;
&lt;pre&gt;        if (n &amp;lt; 2)&lt;/pre&gt;
&lt;pre&gt;            return acc;&lt;/pre&gt;
&lt;pre&gt;        acc = acc * n;   // the order of assignment is important here!&lt;/pre&gt;
&lt;pre&gt;        n = n - 1;&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;h2 id=&quot;sec-3&quot;&gt;Quest for a general algorithm&lt;/h2&gt;&lt;h3 id=&quot;sec-3.1&quot;&gt;Hand wavy description&lt;/h3&gt;&lt;p&gt;
The steps described here are the same ones presented in Kopell&#x27;s presentation.
To give value to my presentation and not regurgitate Kopell&#x27;s I have tried to motivate the same steps from a different perspective.&lt;/p&gt;&lt;p&gt;
How can we rewrite any recursive function iteratively?
One approach is to see if this problem reduces to the simple case, i.e. we ask ourselves, can we rewrite any recursive function in a tail-recursive way?
It&#x27;s not clear how to accomplish that, let&#x27;s see why.
Consider the recursive &lt;code&gt;printTree&lt;/code&gt; code, the code after &lt;code&gt;printTree(tree.left)&lt;/code&gt; (lines 5-6) is code that needs to &lt;em&gt;continue&lt;/em&gt; to evaluate.
We can&#x27;t just stop after the first recursive call, and the second recursive call prevents us from using the accumulator trick.
The key insight is to recognize that lines 5 and 6 are the &lt;em&gt;continuation&lt;/em&gt; of the first recursive call (i.e. what is left to be done).
Rewriting the code in &lt;a href=&quot;https://en.wikipedia.org/wiki/Continuation-passing_style&quot; target=&quot;_blank&quot;&gt;continuation-passing style&lt;/a&gt; (CPS) will abstract the remaining recursive calls into the continuation.
At this stage we end up with a function with a single (albeit complicated) function call.
This function call will be none other than the first recursive call.
Now, our function is tail recursive that is passing around closures (the continuations).
Alas these closures carry around an environment of their own, so we still can&#x27;t do tail-call optimization.
The second and last missing piece of the puzzle is &lt;a href=&quot;https://en.wikipedia.org/wiki/Defunctionalization&quot; target=&quot;_blank&quot;&gt;Defunctionalization&lt;/a&gt;.
This trick allows us to encode higher-order functions in terms of data.
Putting everything together: encoding the continuations transforms the code into a recursive function (a couple actually) that we can apply TCO to.&lt;/p&gt;&lt;p&gt;The transformation, which I dub &lt;em&gt;Recursion Elimination&lt;/em&gt;, consists of four stages.&lt;/p&gt;&lt;ol&gt;&lt;li&gt;Rewriting in continuation-passing style (CPS)&lt;/li&gt;&lt;li&gt;Defunctionalizing&lt;/li&gt;&lt;li&gt;Inlining&lt;/li&gt;&lt;li&gt;Doing tail-call optimization (TCO)&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;The last step, tail-call optimization, may need to be done twice: before and after inlining.&lt;/p&gt;&lt;h3 id=&quot;sec-3.2&quot;&gt;Are these steps tractable for more complicated code?&lt;/h3&gt;&lt;p&gt;
Sure &lt;code&gt;printTree&lt;/code&gt; is a cute example, but I wonder if the transformation would be humanly tractable to apply to more complicated recursive code.
So I set about rewriting &lt;a href=&quot;https://www.youtube.com/watch?v=OyfBQmvr2Hc&quot; target=&quot;_blank&quot;&gt;The Most Beautiful Program Ever Written&lt;/a&gt; (&lt;strong&gt;spoiler:&lt;/strong&gt; it&#x27;s a lisp interpreter) in an iterative way.
The resulting code, far from being called the ugliest program ever written, sure is cryptic and doubtlessly unmanageable.
Transforming it was a challenge at first and so I&#x27;ve definitely learned from it.
Furthermore the result was up to &lt;em&gt;24% faster&lt;/em&gt; than the recursive version, and it never segfaults (in practice)!
I also noticed that with enough practice this sort of transformation could be mindlessly done quickly by hand.&lt;/p&gt;&lt;p&gt;
&lt;em&gt;Disclaimer&lt;/em&gt;: I didn&#x27;t write a lisp interpreter but rather a lambda calculus evaluator.
The language that we will implement will be very tiny.
It consists of variables, abstractions (aka functions), and [function] applications.
The only hard coded function that we will support is &lt;code&gt;print&lt;/code&gt; that prints to stdout whatever it is given and returns it as its value.
The interpreter is written in the &lt;a href=&quot;https://dlang.org&quot; target=&quot;_blank&quot;&gt;D programming language&lt;/a&gt;, and all code samples from here on will be in that language.
D is similar to C/C++, however here&#x27;s a few things that you might&#x27;ve not known:&lt;ol&gt;&lt;li&gt;Function arguments can have default values.&lt;/li&gt;&lt;li&gt;Besides &lt;code&gt;func(val)&lt;/code&gt; for calling functions, it&#x27;s also possible to write &lt;code&gt;val.func()&lt;/code&gt; or &lt;code&gt;val.func&lt;/code&gt;.
In general &lt;code&gt;func(val, ...)&lt;/code&gt; can be rewritten as &lt;code&gt;val.func(...)&lt;/code&gt;.
Empty parenthesis can be omitted.&lt;/li&gt;&lt;li&gt;Closures, or functions with context, are called delegates.
The type of a delegate is &lt;code&gt;R delegate(T0, T1, ...)&lt;/code&gt; where &lt;code&gt;R&lt;/code&gt; is the return type, and &lt;code&gt;T0, T1, ...&lt;/code&gt; are the argument types.&lt;/li&gt;&lt;li&gt;Structs can be stored in the heap by doing &lt;code&gt;new StructName(...)&lt;/code&gt; which returns a pointer to this struct, or on the stack by doing &lt;code&gt;StructName(...)&lt;/code&gt;&lt;/li&gt;&lt;li&gt;D has a garbage collector.&lt;/li&gt;&lt;/ol&gt;&lt;/p&gt;&lt;h2 id=&quot;sec-4&quot;&gt;Interim &amp;mdash; Case study: Lambda calculus evaluator&lt;/h2&gt;&lt;p&gt;The program that we will transform is the following:&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;enum TType { VAR, APP, ABS };&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;struct Term {&lt;/pre&gt;
&lt;pre&gt;    TType type;&lt;/pre&gt;
&lt;pre&gt;    string a;       // a is either the variable name, or the function&amp;#x27;s only parameter&lt;/pre&gt;
&lt;pre&gt;    Term* t1;       // t1 is the body of the function, or the left term in an application&lt;/pre&gt;
&lt;pre&gt;    Term* t2;       // t2 is the right term in an application&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;alias Env = Term*[string];  // a hashmap whose keys are strings and values are Term*&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;Term* dup(Term* t) {&lt;/pre&gt;
&lt;pre&gt;    if (t == null) return null;&lt;/pre&gt;
&lt;pre&gt;    return new Term(t.type, t.a, dup(t.t1), dup(t.t2));&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;Term* beta(Term* term, string var, Term* val) {&lt;/pre&gt;
&lt;pre&gt;    if (term == null) return term;&lt;/pre&gt;
&lt;pre&gt;    final switch (term.type) {&lt;/pre&gt;
&lt;pre&gt;        case TType.VAR:&lt;/pre&gt;
&lt;pre&gt;            return term.a == var ? val : term;&lt;/pre&gt;
&lt;pre&gt;        case TType.ABS:&lt;/pre&gt;
&lt;pre&gt;            if (term.a == var) return term;&lt;/pre&gt;
&lt;pre&gt;            term.t1 = beta(term.t1, var, val);&lt;/pre&gt;
&lt;pre&gt;            return term;&lt;/pre&gt;
&lt;pre&gt;        case TType.APP:&lt;/pre&gt;
&lt;pre&gt;            term.t1 = beta(term.t1, var, val);&lt;/pre&gt;
&lt;pre&gt;            term.t2 = beta(term.t2, var, val);&lt;/pre&gt;
&lt;pre&gt;            return term;&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;Term* eval(Term* term, Env env, void delegate(Term*, int) interfunc, int depth = 0) {&lt;/pre&gt;
&lt;pre&gt;    interfunc(term, depth);&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;    final switch (term.type) {&lt;/pre&gt;
&lt;pre&gt;        case TType.VAR:&lt;/pre&gt;
&lt;pre&gt;            if (term.a == &amp;quot;print&amp;quot;) {&lt;/pre&gt;
&lt;pre&gt;                return term;&lt;/pre&gt;
&lt;pre&gt;            } else if ((term.a in env) !is null) {&lt;/pre&gt;
&lt;pre&gt;                return eval(dup(env[term.a]), env, interfunc, depth);&lt;/pre&gt;
&lt;pre&gt;            } else assert(false, &amp;quot;Unbound variable &amp;quot; ~ term.a);&lt;/pre&gt;
&lt;pre&gt;        &lt;/pre&gt;
&lt;pre&gt;        case TType.APP:&lt;/pre&gt;
&lt;pre&gt;            if (term.t1.type == TType.ABS) {&lt;/pre&gt;
&lt;pre&gt;                term.t1.t1 = beta(term.t1.t1, term.t1.a, dup(term.t2));&lt;/pre&gt;
&lt;pre&gt;                return eval(term.t1.t1, env, interfunc, depth);&lt;/pre&gt;
&lt;pre&gt;            } else {&lt;/pre&gt;
&lt;pre&gt;                if (term.t1.type == TType.VAR &amp;amp;&amp;amp; term.t1.a == &amp;quot;print&amp;quot;) {&lt;/pre&gt;
&lt;pre&gt;                    writefln(&amp;quot;[print] %s&amp;quot;, term.t2.toString);&lt;/pre&gt;
&lt;pre&gt;                    return eval(term.t2, env, interfunc, depth-1);&lt;/pre&gt;
&lt;pre&gt;                }&lt;/pre&gt;
&lt;pre&gt;                term.t1 = eval(term.t1, env, interfunc, depth+1);&lt;/pre&gt;
&lt;pre&gt;                term.t2 = eval(term.t2, env, interfunc, depth+1);&lt;/pre&gt;
&lt;pre&gt;                return eval(term, env, interfunc, depth);&lt;/pre&gt;
&lt;pre&gt;            }&lt;/pre&gt;
&lt;pre&gt;        &lt;/pre&gt;
&lt;pre&gt;        case TType.ABS:&lt;/pre&gt;
&lt;pre&gt;            return term;&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
Three functions are omitted since they are not relevant to this blog post.
They are: the parsing function, the &lt;code&gt;string toString(Term* t)&lt;/code&gt; function that displays a term, and the main function that runs the whole show.
You can find these in &lt;a href=&quot;https://github.com/geezee/typeless/tree/13f629e9039a3af0ef10673ad06bdf521fca1ef4&quot; target=&quot;_blank&quot;&gt;typeless.git&lt;/a&gt; (there&#x27;s a REPL to play around with!).&lt;/p&gt;&lt;p&gt;There are three recursive functions that we will rewrite iteratively:&lt;ol&gt;&lt;li&gt;&lt;code&gt;Term* dup(Term* t)&lt;/code&gt; creates a deep copy of a term.&lt;/li&gt;&lt;li&gt;&lt;code&gt;Term* beta(Term* t, string var, Term* val)&lt;/code&gt; replaces all the occurrences of the variable &lt;code&gt;var&lt;/code&gt; by the value &lt;code&gt;val&lt;/code&gt;.
For example &lt;code&gt;beta(parse(&quot;((lambda x x) x) x&quot;), &quot;x&quot;, parse(&quot;y&quot;))&lt;/code&gt; produces &lt;code&gt;((lambda x x) y) y&lt;/code&gt;.
Notice the outer &lt;code&gt;x&lt;/code&gt;s were replaced and the one in the lambda is not (since it&#x27;s shadowed by the lambda&#x27;s argument).&lt;/li&gt;&lt;li&gt;&lt;code&gt;Term* eval(Term* term, Env env, ...)&lt;/code&gt; reduces the given term until it&#x27;s a value (i.e. not possible to reduce it any further).
A variable is reduced by looking up its value in the environment.
If the variable is not defined (i.e. not present in the environment) then execution halts with an error message.&lt;br&gt;
The remaining two arguments, &lt;code&gt;interfun&lt;/code&gt; and &lt;code&gt;depth&lt;/code&gt; are for debugging purposes.
Between every reduction a call to &lt;code&gt;interfunc&lt;/code&gt; happens.
The arguments to it are the current term and the depth of the reduction.
I use this function to pretty-print the evaluation as it is happening, and to count the total number of reductions.&lt;/li&gt;&lt;/ol&gt;
I figured these functions are complicated enough to test the applicability of &lt;em&gt;Recursion Elimination&lt;/em&gt;.&lt;/p&gt;&lt;h2 id=&quot;sec-5&quot;&gt;Continuation-passing style (CPS)&lt;/h2&gt;&lt;h3 id=&quot;sec-5.1&quot;&gt;Motivation&lt;/h3&gt;&lt;p&gt;&lt;strong&gt;Very briefly&lt;/strong&gt; Code written in CPS is code that explicitly defines what it does after every instruction.&lt;/p&gt;&lt;p&gt;
Let&#x27;s examine our opening statement again: &quot;Recursive code is the epitome of beautiful code&quot;.
If we consider &quot;complete&quot; code (self-descriptive) as criteria for beauty then our recursive Fibonacci example is surprisingly not beautiful.
Consider this small variation&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;int fibonacci(int n) {&lt;/pre&gt;
&lt;pre&gt;    writef(&amp;quot;n=%d; &amp;quot;, n);&lt;/pre&gt;
&lt;pre&gt;    return n &amp;lt; 2 ? 1 : fibonacci(n-1) + fibonacci(n-2);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
What will we read on the console if we call &lt;code&gt;fibonacci(3)&lt;/code&gt;?
Without knowing much about D we can&#x27;t know whether we&#x27;ll see &lt;code&gt;n=3; n=1; n=2;&lt;/code&gt;, or &lt;code&gt;n=3; n=2; n=1;&lt;/code&gt;, or an infinite stream of numbers.
The semantics of this function depend on the order of evaluation of &lt;code&gt;fibonacci(n-1) + fibonacci(n-2)&lt;/code&gt;; i.e. which side of &lt;code&gt;+&lt;/code&gt; is evaluated first.
And it also depends on whether the branches of the ternary operator &lt;code&gt;x ? y : z&lt;/code&gt; are all evaluated first (hence the infinite stream of numbers) or not.
Compiling this code with &lt;code&gt;gcc&lt;/code&gt; will produce undefined behavior.
On the other hand compiling this code with GNU ELisp where the &lt;a href=&quot;https://gnu.org/software/emacs/manual/html_node/elisp/Function-Forms.html&quot; target=&quot;_blank&quot;&gt;order of evaluation&lt;/a&gt; is specified we know the output will be &lt;code&gt;n=3; n=1; n=2;&lt;/code&gt;.
Hence we cannot attest to the completeness of this recursive function as its semantics depend on the host language.&lt;/p&gt;&lt;p&gt;A trivial fix is to rewrite the code with assignments like so:&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;int fibonacci(int n) {&lt;/pre&gt;
&lt;pre&gt;    writefln(&amp;quot;computing fibonacci %d&amp;quot;, n);&lt;/pre&gt;
&lt;pre&gt;    if (n &amp;lt; 2) return 1;&lt;/pre&gt;
&lt;pre&gt;    int left = fibonacci(n-1);&lt;/pre&gt;
&lt;pre&gt;    int right = fibonacci(n-2);&lt;/pre&gt;
&lt;pre&gt;    return left + right;&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
But who&#x27;s to say the compiler (or a successor programmer) won&#x27;t shuffle the order?
As motivated in the outline above we really should transform everything into a single instruction since order of evaluation cannot be ambiguous when there&#x27;s only one instruction to be evaluated.
We know that after executing &lt;code&gt;fibonacci(n-1)&lt;/code&gt; we have to call the function&lt;br&gt;
&lt;code&gt;(int left) { int right = fibonacci(n-2); return left + right; }&lt;/code&gt; with &lt;code&gt;left&lt;/code&gt; being whatever the first computation produced.
To achieve this we will rewrite &lt;code&gt;fibonacci&lt;/code&gt; in &lt;a href=&quot;https://en.wikipedia.org/wiki/Continuation-passing_style&quot; target=&quot;_blank&quot;&gt;continuation-passing style&lt;/a&gt; like so:&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;int fibonacci(int n, int delegate(int) continutaion) {&lt;/pre&gt;
&lt;pre&gt;    writefln(&amp;quot;computing fibonacci %d&amp;quot;, n);&lt;/pre&gt;
&lt;pre&gt;    if (n &amp;lt; 2) return continuation(1);&lt;/pre&gt;
&lt;pre&gt;    return fibonacci(n-1, (int left) {&lt;/pre&gt;
&lt;pre&gt;        return fibonacci(n-2, (int right) {&lt;/pre&gt;
&lt;pre&gt;            return continuation(left + right);&lt;/pre&gt;
&lt;pre&gt;        });&lt;/pre&gt;
&lt;pre&gt;    });&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
Continuations are very useful, their usage spans many more applications.
Continuations allow you to explicitly specify the control flow.
A language equipped with continuations can use them to simulate try/catch, return, loops, and even &quot;time-traveling&quot;.
I recommend reading &lt;a href=&quot;http://matt.might.net/articles/programming-with-continuations--exceptions-backtracking-search-threads-generators-coroutines/&quot; target=&quot;_blank&quot;&gt;Continuations by example: Exceptions, time-traveling search, generators, threads, and coroutines&lt;/a&gt; by Matt Might.
Or you can watch William Byrd&#x27;s excellent video tutorial &lt;a href=&quot;https://www.youtube.com/watch?v=2GfFlfToBCo&quot; target=&quot;_blank&quot;&gt;Intro to continuations, call/cc, and CPS&lt;/a&gt;.&lt;/p&gt;&lt;h3 id=&quot;sec-5.2&quot;&gt;High-level algorithm for CPS-ing a recursive function&lt;/h3&gt;&lt;ol&gt;&lt;li&gt;Add an extra argument &lt;code&gt;cont&lt;/code&gt; to your function.&lt;/li&gt;&lt;li&gt;In all branches where there are no recursive calls, replace &lt;code&gt;return value;&lt;/code&gt; with &lt;code&gt;return cont(value);&lt;/code&gt;.&lt;/li&gt;&lt;li&gt;In all branches where there are recursive calls, add &lt;code&gt;cont&lt;/code&gt; as a parameter to the &lt;em&gt;last&lt;/em&gt; recursive call.&lt;/li&gt;&lt;li&gt;Wrap the instructions that follow every recursive call in a function.
This function will be the extra parameter to the recursive call.&lt;/li&gt;&lt;/ol&gt;&lt;h3 id=&quot;sec-5.3&quot;&gt;CPS-ing dup, beta, and eval&lt;/h3&gt;&lt;p&gt;There is not much to be said about this step of the transformation here, so here&#x27;s the transformed code:&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;Term* dupCPS(Term* t, Term* delegate(Term*) cont) {&lt;/pre&gt;
&lt;pre&gt;    if (t == null) return cont(null);&lt;/pre&gt;
&lt;pre&gt;    return dupCPS(t.t1, (Term* ans1) {&lt;/pre&gt;
&lt;pre&gt;        return dupCPS(t.t2, (Term* ans2) {&lt;/pre&gt;
&lt;pre&gt;            return cont(new Term(t.type, t.a, ans1, ans2));&lt;/pre&gt;
&lt;pre&gt;        });&lt;/pre&gt;
&lt;pre&gt;    });&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;Term* betaCPS(Term* term, string var, Term* val,&lt;/pre&gt;
&lt;pre&gt;              Term* delegate(Term*) cont = (Term* t) { return t; }) {&lt;/pre&gt;
&lt;pre&gt;    if (term == null) return cont(null);&lt;/pre&gt;
&lt;pre&gt;    if (term.type == TType.VAR) {&lt;/pre&gt;
&lt;pre&gt;        return cont(term.a == var ? val : term);&lt;/pre&gt;
&lt;pre&gt;    } else if (term.type == TType.ABS) {&lt;/pre&gt;
&lt;pre&gt;        if (term.a == var) return cont(term);&lt;/pre&gt;
&lt;pre&gt;        return betaCPS(term.t1, var, val, (Term* ans) {&lt;/pre&gt;
&lt;pre&gt;            term.t1 = ans;&lt;/pre&gt;
&lt;pre&gt;            return cont(term);&lt;/pre&gt;
&lt;pre&gt;        });&lt;/pre&gt;
&lt;pre&gt;    } else {&lt;/pre&gt;
&lt;pre&gt;        return betaCPS(term.t1, var, val, (Term* ans) {&lt;/pre&gt;
&lt;pre&gt;            term.t1 = ans;&lt;/pre&gt;
&lt;pre&gt;            return betaCPS(term.t2, var, val, (Term* ans) {&lt;/pre&gt;
&lt;pre&gt;                term.t2 = ans;&lt;/pre&gt;
&lt;pre&gt;                return cont(term);&lt;/pre&gt;
&lt;pre&gt;            });&lt;/pre&gt;
&lt;pre&gt;        });&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;Term* evalCPS(Term* term, Env env, void delegate(Term*, int) interfunc, int depth = 0,&lt;/pre&gt;
&lt;pre&gt;              Term* delegate(Term*) cont = (Term* t) { return t; }) {&lt;/pre&gt;
&lt;pre&gt;    interfunc(term, depth);&lt;/pre&gt;
&lt;pre&gt;    &lt;/pre&gt;
&lt;pre&gt;    if (term.type == TType.VAR) {&lt;/pre&gt;
&lt;pre&gt;        if (term.a == &amp;quot;print&amp;quot;) {&lt;/pre&gt;
&lt;pre&gt;            return cont(term);&lt;/pre&gt;
&lt;pre&gt;        } else if ((term.a in env) !is null) {&lt;/pre&gt;
&lt;pre&gt;            return evalCPS(env[term.a].dup, env, interfunc, depth, cont);&lt;/pre&gt;
&lt;pre&gt;        } else assert(false, &amp;quot;Unbounded variable &amp;quot; ~ term.a);&lt;/pre&gt;
&lt;pre&gt;    } else if (term.type == TType.APP) {&lt;/pre&gt;
&lt;pre&gt;        if (term.t1.type == TType.ABS) {&lt;/pre&gt;
&lt;pre&gt;            term.t1.t1 = betaCPS(term.t1.t1, term.t1.a, term.t2.dup);&lt;/pre&gt;
&lt;pre&gt;            return evalCPS(term.t1.t1, env, interfunc, depth, cont);&lt;/pre&gt;
&lt;pre&gt;        } else {&lt;/pre&gt;
&lt;pre&gt;            if (term.t1.type == TType.VAR &amp;amp;&amp;amp; term.t1.a == &amp;quot;print&amp;quot;) {&lt;/pre&gt;
&lt;pre&gt;                writefln(&amp;quot;[print] &amp;quot;, term.t2.toString);&lt;/pre&gt;
&lt;pre&gt;                return evalCPS(term.t2, env, interfunc, depth-1, cont);&lt;/pre&gt;
&lt;pre&gt;            }&lt;/pre&gt;
&lt;pre&gt;            return evalCPS(term.t1, env, interfunc, depth+1, (Term* ans) {&lt;/pre&gt;
&lt;pre&gt;                term.t1 = ans;&lt;/pre&gt;
&lt;pre&gt;                return evalCPS(term.t2, env, interfunc, depth+1, (Term* ans) {&lt;/pre&gt;
&lt;pre&gt;                    term.t2 = ans;&lt;/pre&gt;
&lt;pre&gt;                    return evalCPS(term, env, interfunc, depth, cont);&lt;/pre&gt;
&lt;pre&gt;                });&lt;/pre&gt;
&lt;pre&gt;            });&lt;/pre&gt;
&lt;pre&gt;        }&lt;/pre&gt;
&lt;pre&gt;    } else {&lt;/pre&gt;
&lt;pre&gt;        return cont(term);&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;h2 id=&quot;sec-6&quot;&gt;Defunctionalization&lt;/h2&gt;&lt;h3 id=&quot;sec-6.1&quot;&gt;Motivation&lt;/h3&gt;&lt;p&gt;&lt;strong&gt;Very briefly&lt;/strong&gt; Defunctionalizing some code is roughly equivalent to writing a tiny interpreter for that code in the host language.&lt;/p&gt;&lt;p&gt;
John C. Reynolds introduced defunctionalization in 1972 in his paper &lt;a href=&quot;https://surface.syr.edu/cgi/viewcontent.cgi?article=1012&amp;context=lcsmith_other&quot; target=&quot;_blank&quot;&gt;Definitional interpreters for higher-order programming languages &lt;sup&gt;[PDF]&lt;/sup&gt;&lt;/a&gt; to address these issues:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;Eliminating higher-order functions from interpreters.
Interpreters free of higher-order functions can be implemented using low-level languages (e.g. C) that do not support them.
(side-note: C supports function pointers which allow you to pass and return functions, but it does not support closures.)&lt;/li&gt;&lt;li&gt;Making the order of evaluation in the interpreter explicit.
This issue was discussed in detail in the section about CPS.
But I suppose you agree with me that making the semantics of a language dependent on the semantics of the interpreter&#x27;s host language is a horrible idea.&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;CPS solves the second issue, and defunctionalization solves the first.
Briefly, the idea is to pass descriptions of functions (which is data) rather than closures.
If &lt;em&gt;f&lt;/em&gt; is a function, then all applications &lt;em&gt;f(x&lt;sub&gt;1&lt;/sub&gt;, ..., x&lt;sub&gt;n&lt;/sub&gt;)&lt;/em&gt; are replaced by &lt;em&gt;apply(descriptionOfF, x&lt;sub&gt;1&lt;/sub&gt;, ..., x&lt;sub&gt;n&lt;/sub&gt;)&lt;/em&gt;.
Consider the following program which contains only one higher-order function, &lt;code&gt;map&lt;/code&gt;:&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;int[] map(int[] list, int delegate(int) mapper) {&lt;/pre&gt;
&lt;pre&gt;    if (list.length == 0) return [];&lt;/pre&gt;
&lt;pre&gt;    else                  return [ mapper(list[0]) ] ~ map(list[1..$], mapper);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;auto someNumbers(int maxN, int parg1 = 2, int parg2 = 3) {&lt;/pre&gt;
&lt;pre&gt;    return range(1, maxN).map(x =&amp;gt; pow(parg1, x))&lt;/pre&gt;
&lt;pre&gt;                         .map(x =&amp;gt; pow(parg2, x))&lt;/pre&gt;
&lt;pre&gt;                         .map(x =&amp;gt; x+1);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
To begin with, we collect all the functions that are passed to &lt;code&gt;map&lt;/code&gt;.
In this case they are &lt;code&gt;x =&gt; pow(parg1, x)&lt;/code&gt;, &lt;code&gt;x =&gt; pow(parg2, x)&lt;/code&gt;, and &lt;code&gt;x =&gt; x+1&lt;/code&gt;.
Next, we identify all the free variables inside these closures, i.e. all the variables that assume their value from some parent scope.
These are &lt;code&gt;parg1&lt;/code&gt; and &lt;code&gt;parg2&lt;/code&gt; in the above example.
Finally, we create a data structure that holds all these free variables and a label to differentiate the closures.
For the code above, we create an int label that will tell us whether we should exponentiate, or increment.
Since &lt;code&gt;parg1&lt;/code&gt; and &lt;code&gt;parg2&lt;/code&gt; are never used in the same closure we can save some space and use a single field to encode them instead of two.&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;struct HOFunc { // Datastructure describing all lambdas passed to the higher-order function `map`&lt;/pre&gt;
&lt;pre&gt;    int behavior;   // 0 means &amp;quot;do x+1&amp;quot;, 1 means &amp;quot;do pow(powArg,x)&amp;quot;&lt;/pre&gt;
&lt;pre&gt;    int powArg;     // the first argument to pow&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;int apply(int arg, HOFunc func) {&lt;/pre&gt;
&lt;pre&gt;    if (func.behavior == 1) return pow(func.powArg, arg);&lt;/pre&gt;
&lt;pre&gt;    if (func.behavior == 0) return arg + 1;&lt;/pre&gt;
&lt;pre&gt;    assert(false, &amp;quot;Unknown function description &amp;quot;, func);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;We must then rewrite &lt;code&gt;map&lt;/code&gt; and &lt;code&gt;someNumbers&lt;/code&gt; to use &lt;code&gt;apply&lt;/code&gt; and &lt;code&gt;HOFunc&lt;/code&gt;.
All calls to the arg-functions will be replaced by calls to &lt;code&gt;apply&lt;/code&gt;,
and all introductions of arg-functions will be replaced by &lt;code&gt;HOFunc&lt;/code&gt; data that describes said function.
Here&#x27;s how we would rewrite those two functions:&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;int[] map(int[] list, HOFunc mapper) {&lt;/pre&gt;
&lt;pre&gt;    if (list.length == 0) return [];&lt;/pre&gt;
&lt;pre&gt;    else                  return [ apply(list[0], mapper) ] ~ map(list[1..$], mapper);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;auto someNumbers(int maxN, int parg1 = 2, int parg2 = 3) {&lt;/pre&gt;
&lt;pre&gt;    return range(1, maxN).map(HOFunc(1, parg1))&lt;/pre&gt;
&lt;pre&gt;                         .map(HOFunc(1, parg2))&lt;/pre&gt;
&lt;pre&gt;                         .map(HOFunc(0, 0));    // 2nd arg is useless, can be anything&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;h3 id=&quot;sec-6.2&quot;&gt;How is this relevant?&lt;/h3&gt;&lt;p&gt;
Look again at &lt;code&gt;dupCPS&lt;/code&gt;, &lt;code&gt;betaCPS&lt;/code&gt;, and &lt;code&gt;evalCPS&lt;/code&gt;.
You&#x27;ll see that these are higher-order functions that take the continuation (a function) as their final argument.
Once we defunctionalize all three functions we&#x27;ll end up with code that doesn&#x27;t use any higher-order functions,
and all three functions (six in reality if we count the apply functions) will be tail-recursive.&lt;/p&gt;&lt;h3 id=&quot;sec-6.3&quot;&gt;High-level algorithm for defunctionalizing a function&lt;/h3&gt;&lt;ol&gt;&lt;li&gt;Locate all the higher-order functions in your code; i.e. functions that take functions as arguments, or return functions.&lt;/li&gt;&lt;li&gt;For every higher order function:&lt;ol&gt;&lt;li&gt;Locate all the functions that are passed to/returned from this function.&lt;/li&gt;&lt;li&gt;Find all the functions&#x27; free variables.&lt;/li&gt;&lt;li&gt;Create a struct that holds all these free variables.
Add a label that acts as identification for every function.&lt;/li&gt;&lt;li&gt;Replace all applications to these functions by calls to the special apply function.&lt;/li&gt;&lt;li&gt;Replace all the function introductions with a value from the struct.&lt;/li&gt;&lt;/ol&gt;&lt;/li&gt;&lt;/ol&gt;&lt;h3 id=&quot;sec-6.4&quot;&gt;Defunctionalizing dup, beta, and eval&lt;/h3&gt;&lt;p&gt;
Instead of introducing one giant &lt;code&gt;apply&lt;/code&gt; function and one giant &lt;code&gt;HOFunc&lt;/code&gt; struct we will introduce one of each for each of the three higher-order functions.&lt;/p&gt;&lt;p&gt;Let&#x27;s start with &lt;code&gt;dupCPS&lt;/code&gt;.
There are only two closures in the whole program that are fed to &lt;code&gt;dupCPS&lt;/code&gt; and these are the ones in its body.
The free variables of both these closures are &lt;code&gt;Term* t&lt;/code&gt;, &lt;code&gt;Term* ans1&lt;/code&gt;, and &lt;code&gt;Term* delegate(Term*) cont&lt;/code&gt;.
From here on we will rename all continuations in the set of free variables to &lt;code&gt;next&lt;/code&gt;.&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;struct DupCont {&lt;/pre&gt;
&lt;pre&gt;    bool inner;         // false is outer closure (line 3), true is inner closure (line 4)&lt;/pre&gt;
&lt;pre&gt;    Term* term;         // the Term t&lt;/pre&gt;
&lt;pre&gt;    Term* ans1;&lt;/pre&gt;
&lt;pre&gt;    DupCont* next;      // the next continuation&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;Term* applyDup(Term* ans, DupCont* cont) {&lt;/pre&gt;
&lt;pre&gt;    if (cont == null) return ans;&lt;/pre&gt;
&lt;pre&gt;    if (cont.inner) {&lt;/pre&gt;
&lt;pre&gt;        Term* t = new Term(cont.term.type, cont.term.a, cont.ans1, ans);&lt;/pre&gt;
&lt;pre&gt;        return applyDup(t, cont.next);&lt;/pre&gt;
&lt;pre&gt;    } else {&lt;/pre&gt;
&lt;pre&gt;        return dupDefun(cont.term.t2, new DupCont(true, cont.term, ans, cont.next));&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;Term* dupDefun(Term* t, DupCont* cont = null) {&lt;/pre&gt;
&lt;pre&gt;    if (t == null) return applyDup(t, cont);&lt;/pre&gt;
&lt;pre&gt;    return dupDefun(t.t1, new DupCont(false, t, null, cont));&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
The same procedure can be applied to &lt;code&gt;betaCPS&lt;/code&gt; to get &lt;code&gt;betaDefun&lt;/code&gt;.
This time, we notice that the parameters &lt;code&gt;var&lt;/code&gt; and &lt;code&gt;val&lt;/code&gt; are constant and will be redundant in the struct.
So instead we pass them to &lt;code&gt;applyBeta&lt;/code&gt;.
Moreover, there&#x27;s no label to indicate which closure we&#x27;re executing, we use the &lt;code&gt;type&lt;/code&gt; to distinguish them since there&#x27;s only one closure used for a given type.&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;struct BetaCont {&lt;/pre&gt;
&lt;pre&gt;    TType type;         // technically redundant, we could use term.type instead&lt;/pre&gt;
&lt;pre&gt;    int argNum;         // 0 means we&amp;#x27;re working with term.t1, 1 means term.t2&lt;/pre&gt;
&lt;pre&gt;    Term* term;&lt;/pre&gt;
&lt;pre&gt;    BetaCont* next;&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;Term* applyBeta(Term* ans, string var, Term* val, BetaCont* cont) { // var, val in here because they never change&lt;/pre&gt;
&lt;pre&gt;    if (cont == null) return ans;&lt;/pre&gt;
&lt;pre&gt;    switch (cont.type) {&lt;/pre&gt;
&lt;pre&gt;        case TType.ABS:&lt;/pre&gt;
&lt;pre&gt;            cont.term.t1 = ans;&lt;/pre&gt;
&lt;pre&gt;            return applyBeta(cont.term, var, val, cont.next);&lt;/pre&gt;
&lt;pre&gt;        case TType.APP:&lt;/pre&gt;
&lt;pre&gt;            if (cont.argNum == 1) {&lt;/pre&gt;
&lt;pre&gt;                cont.term.t1 = ans;&lt;/pre&gt;
&lt;pre&gt;                return betaDefun(cont.term.t2, var, val, new BetaCont(cont.type, 2, cont.term, cont.next));&lt;/pre&gt;
&lt;pre&gt;            } else {&lt;/pre&gt;
&lt;pre&gt;                cont.term.t2 = ans;&lt;/pre&gt;
&lt;pre&gt;                return applyBeta(cont.term, var, val, cont.next);&lt;/pre&gt;
&lt;pre&gt;            }&lt;/pre&gt;
&lt;pre&gt;        default: applyBeta(ans, var, val, cont.next);&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;Term* betaDefun(Term* term, string var, Term* val, BetaCont* cont = null) {&lt;/pre&gt;
&lt;pre&gt;    if (term == null) return applyBeta(term, var, val, cont);&lt;/pre&gt;
&lt;pre&gt;    final switch (term.type) {&lt;/pre&gt;
&lt;pre&gt;        case TType.VAR:&lt;/pre&gt;
&lt;pre&gt;            return applyBeta(term.a == var ? val : term, var, val, cont);&lt;/pre&gt;
&lt;pre&gt;        case TType.ABS:&lt;/pre&gt;
&lt;pre&gt;            if (term.a == var) return applyBeta(term, var, val, cont);&lt;/pre&gt;
&lt;pre&gt;            else return betaDefun(term.t1, var, val, new BetaCont(TType.ABS, 0, term, cont));&lt;/pre&gt;
&lt;pre&gt;        case TType.APP:&lt;/pre&gt;
&lt;pre&gt;            return betaDefun(term.t1, var, val, new BetaCont(TType.APP, 1, term, cont));&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
&lt;code&gt;evalCPS&lt;/code&gt; only has two closures passed to it, one at line 51, and the other at line 53.
It should be noted that we are not interested in defunctionalizing the &lt;code&gt;interfunc&lt;/code&gt; argument away.
There&#x27;s nothing special about this code that hasn&#x27;t been said before, so here is the defunctionalization of &lt;code&gt;evalCPS&lt;/code&gt; for the sake of completeness.&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;struct EvalCont {&lt;/pre&gt;
&lt;pre&gt;    Term* term;&lt;/pre&gt;
&lt;pre&gt;    bool inner;     // true is closure at line 53, and false is closure at line 51&lt;/pre&gt;
&lt;pre&gt;    int depth;&lt;/pre&gt;
&lt;pre&gt;    EvalCont* next;&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;Term* applyEval(Term* ans, Env env, void delegate(Term*, int) interfunc, EvalCont* cont) {&lt;/pre&gt;
&lt;pre&gt;    if (cont == null) return ans;&lt;/pre&gt;
&lt;pre&gt;    if (cont.inner) {&lt;/pre&gt;
&lt;pre&gt;        cont.term.t2 = ans;&lt;/pre&gt;
&lt;pre&gt;        return evalDefun(cont.term, env, interfunc, cont.depth+1, cont.next);&lt;/pre&gt;
&lt;pre&gt;    } else {&lt;/pre&gt;
&lt;pre&gt;        cont.term.t1 = ans;&lt;/pre&gt;
&lt;pre&gt;        return evalDefun(cont.term.t2, env, interfunc, cont.depth,&lt;/pre&gt;
&lt;pre&gt;                         new EvalCont(cont.term, true, cont.depth, cont.next));&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;pre&gt;Term* evalDefun(Term* term, Env env, void delegate(Term*, int) interfunc,&lt;/pre&gt;
&lt;pre&gt;                int depth = 0, EvalCont* cont = null) {&lt;/pre&gt;
&lt;pre&gt;    interfunc(term, depth);&lt;/pre&gt;
&lt;pre&gt;    if (term.type == TType.VAR) {&lt;/pre&gt;
&lt;pre&gt;        if (term.a == &amp;quot;print&amp;quot;)&lt;/pre&gt;
&lt;pre&gt;            return applyEval(term, env, interfunc, cont);&lt;/pre&gt;
&lt;pre&gt;        else if ((term.a in env) !is null)&lt;/pre&gt;
&lt;pre&gt;            return evalDefun(dupDefun(env[term.a]), env, interfunc, depth, cont);&lt;/pre&gt;
&lt;pre&gt;        else assert(false, &amp;quot;Unbounded variable &amp;quot; ~ term.a);&lt;/pre&gt;
&lt;pre&gt;    } else if (term.type == TType.APP) {&lt;/pre&gt;
&lt;pre&gt;        if (term.t1.type == TType.ABS) {&lt;/pre&gt;
&lt;pre&gt;            term.t1.t1 = betaDefun(term.t1.t1, term.t1.a, dupDefun(term.t2));&lt;/pre&gt;
&lt;pre&gt;            return evalDefun(term.t1.t1, env, interfunc, depth-1, cont);&lt;/pre&gt;
&lt;pre&gt;        }&lt;/pre&gt;
&lt;pre&gt;        if (term.t1.type == TType.VAR &amp;amp;&amp;amp; term.t1.a == &amp;quot;print&amp;quot;) {&lt;/pre&gt;
&lt;pre&gt;            writefln(&amp;quot;[print] %s&amp;quot;, term.t2.toString);&lt;/pre&gt;
&lt;pre&gt;            return evalDefun(term.t2, env, interfunc, depth-1, cont);&lt;/pre&gt;
&lt;pre&gt;        }&lt;/pre&gt;
&lt;pre&gt;        return evalDefun(term.t1, env, interfunc, depth+1,&lt;/pre&gt;
&lt;pre&gt;                         new EvalCont(term, false, depth, cont));&lt;/pre&gt;
&lt;pre&gt;    } else return applyEval(term, env, interfunc, cont);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;p&gt;
There is something really interesting worth pointing out.
Take a look at &lt;code&gt;DupCont&lt;/code&gt;, &lt;code&gt;BetaCont&lt;/code&gt;, and &lt;code&gt;EvalCont&lt;/code&gt;.
All three look like a linked list.
In fact all three are a special linked list; a stack.
We knew all along (but never mentioned it) that we ought to be manipulating a stack at some point since we are simulating recursive calls.
And here is where the stack arises in our code.&lt;/p&gt;&lt;h2 id=&quot;sec-7&quot;&gt;Inlining &amp; Tail-call Optimization&lt;/h2&gt;&lt;p&gt;Now if you carefully look at the six functions:
&lt;code&gt;applyDup&lt;/code&gt; &amp; &lt;code&gt;dupDefun&lt;/code&gt;,
&lt;code&gt;applyBeta&lt;/code&gt; &amp; &lt;code&gt;betaDefun&lt;/code&gt;,
and &lt;code&gt;applyEval&lt;/code&gt; &amp; &lt;code&gt;evalDefun&lt;/code&gt;,
you will notice that every couple of functions (as grouped previously) are mutually-recursive, and most importantly tail recursive!
To complete our transformation we just need to inline the special &lt;code&gt;apply&lt;/code&gt; functions and do TCO on every couple.&lt;/p&gt;&lt;p&gt;
I grouped the inline and TCO steps together since in some cases, as is in &lt;code&gt;applyBeta&lt;/code&gt; and &lt;code&gt;applyDup&lt;/code&gt;, one must do TCO on the apply function first before inlining.
So some functions will require three steps: do TCO on apply, inline apply with the function, and finally do TCO on the whole function.&lt;/p&gt;&lt;p&gt;I have already explained how to do TCO in &lt;a href=&quot;#sec-2&quot;&gt;section 2&lt;/a&gt;, so I won&#x27;t repeat myself.
Again, for the sake of completeness here are the three functions with inlining and TCO applied to them:&lt;/p&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;Term* dupOpt(Term* t, DupCont* cont = null) {&lt;/pre&gt;
&lt;pre&gt;    while (true) {&lt;/pre&gt;
&lt;pre&gt;        if (t == null) {&lt;/pre&gt;
&lt;pre&gt;            Term* ans = t;&lt;/pre&gt;
&lt;pre&gt;            DupCont* acont = cont;&lt;/pre&gt;
&lt;pre&gt;            while (true) {&lt;/pre&gt;
&lt;pre&gt;                if (acont == null) return ans;&lt;/pre&gt;
&lt;pre&gt;                if (acont.inner) {&lt;/pre&gt;
&lt;pre&gt;                    ans = new Term(acont.term.type, acont.term.a, acont.ans1, ans);&lt;/pre&gt;
&lt;pre&gt;                    acont = acont.next;&lt;/pre&gt;
&lt;pre&gt;                } else {&lt;/pre&gt;
&lt;pre&gt;                    t = acont.term.t2;&lt;/pre&gt;
&lt;pre&gt;                    cont = new DupCont(acont.term, true, ans, acont.next);&lt;/pre&gt;
&lt;pre&gt;                    break;&lt;/pre&gt;
&lt;pre&gt;                }&lt;/pre&gt;
&lt;pre&gt;            }&lt;/pre&gt;
&lt;pre&gt;        } else {&lt;/pre&gt;
&lt;pre&gt;            cont = new DupCont(t, false, null, cont);&lt;/pre&gt;
&lt;pre&gt;            t = t.t1;&lt;/pre&gt;
&lt;pre&gt;        }&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;Term* betaOpt(Term* term, string var, Term* val, BetaCont* cont = null) {&lt;/pre&gt;
&lt;pre&gt;    Term* ans;&lt;/pre&gt;
&lt;pre&gt;    BetaCont* acont;&lt;/pre&gt;
&lt;pre&gt;    do {&lt;/pre&gt;
&lt;pre&gt;        bool computeAns = false;&lt;/pre&gt;
&lt;pre&gt;        if (term == null) {&lt;/pre&gt;
&lt;pre&gt;            computeAns = true;&lt;/pre&gt;
&lt;pre&gt;            ans = term; acont = cont;&lt;/pre&gt;
&lt;pre&gt;        } else if (term.type == TType.VAR) {&lt;/pre&gt;
&lt;pre&gt;            computeAns = true;&lt;/pre&gt;
&lt;pre&gt;            ans = term.a == var ? val : term; acont = cont;&lt;/pre&gt;
&lt;pre&gt;        } else if (term.type == TType.ABS) {&lt;/pre&gt;
&lt;pre&gt;            if (term.a == var) {&lt;/pre&gt;
&lt;pre&gt;                computeAns = true;&lt;/pre&gt;
&lt;pre&gt;                ans = term; acont = cont;&lt;/pre&gt;
&lt;pre&gt;            } else {&lt;/pre&gt;
&lt;pre&gt;                cont = new BetaCont(TType.ABS, 0, term, cont);&lt;/pre&gt;
&lt;pre&gt;                term = term.t1;&lt;/pre&gt;
&lt;pre&gt;            }&lt;/pre&gt;
&lt;pre&gt;        } else {&lt;/pre&gt;
&lt;pre&gt;            cont = new BetaCont(TType.APP, 1, term, cont);&lt;/pre&gt;
&lt;pre&gt;            term = term.t1;&lt;/pre&gt;
&lt;pre&gt;        }&lt;/pre&gt;
&lt;pre&gt;        if (computeAns) {&lt;/pre&gt;
&lt;pre&gt;            while(true) {&lt;/pre&gt;
&lt;pre&gt;                if (acont == null) return ans;&lt;/pre&gt;
&lt;pre&gt;                if (acont.type == TType.ABS) {&lt;/pre&gt;
&lt;pre&gt;                        acont.term.t1 = ans;&lt;/pre&gt;
&lt;pre&gt;                        ans = acont.term;&lt;/pre&gt;
&lt;pre&gt;                        acont = acont.next;&lt;/pre&gt;
&lt;pre&gt;                } else if (acont.type == TType.APP) {&lt;/pre&gt;
&lt;pre&gt;                    if (acont.argNum == 1) {&lt;/pre&gt;
&lt;pre&gt;                        acont.term.t1 = ans;&lt;/pre&gt;
&lt;pre&gt;                        term = acont.term.t2;&lt;/pre&gt;
&lt;pre&gt;                        cont = new BetaCont(acont.type, 2, acont.term, acont.next);&lt;/pre&gt;
&lt;pre&gt;                        break;&lt;/pre&gt;
&lt;pre&gt;                    } else {&lt;/pre&gt;
&lt;pre&gt;                        acont.term.t2 = ans;&lt;/pre&gt;
&lt;pre&gt;                        ans = acont.term;&lt;/pre&gt;
&lt;pre&gt;                        acont = acont.next;&lt;/pre&gt;
&lt;pre&gt;                    }&lt;/pre&gt;
&lt;pre&gt;                } else {&lt;/pre&gt;
&lt;pre&gt;                    acont = acont.next;&lt;/pre&gt;
&lt;pre&gt;                }&lt;/pre&gt;
&lt;pre&gt;            }&lt;/pre&gt;
&lt;pre&gt;        }&lt;/pre&gt;
&lt;pre&gt;    } while (true);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;code class=&quot;block&quot;&gt;
&lt;pre&gt;Term* evalOpt(alias beta, alias dup)&lt;/pre&gt;
&lt;pre&gt;             (Term* term, Env env, void delegate(Term*, int) interfunc, int depth = 0, EvalCont* cont = null) {&lt;/pre&gt;
&lt;pre&gt;    Term* ans;&lt;/pre&gt;
&lt;pre&gt;    EvalCont* acont;&lt;/pre&gt;
&lt;pre&gt;    do {&lt;/pre&gt;
&lt;pre&gt;        interfunc(term, depth);&lt;/pre&gt;
&lt;pre&gt;        int computeAns = false;&lt;/pre&gt;
&lt;pre&gt;        if (term.type == TType.VAR) {&lt;/pre&gt;
&lt;pre&gt;            if (term.a == &amp;quot;print&amp;quot;) {&lt;/pre&gt;
&lt;pre&gt;                computeAns = true;&lt;/pre&gt;
&lt;pre&gt;                ans = term; acont = cont;&lt;/pre&gt;
&lt;pre&gt;            } else if ((term.a in env) !is null) {&lt;/pre&gt;
&lt;pre&gt;                term = dup(env[term.a]);&lt;/pre&gt;
&lt;pre&gt;            } else assert(false, &amp;quot;Unbounded variable &amp;quot; ~ term.a);&lt;/pre&gt;
&lt;pre&gt;        } else if (term.type == TType.APP) {&lt;/pre&gt;
&lt;pre&gt;            if (term.t1.type == TType.ABS) {&lt;/pre&gt;
&lt;pre&gt;                term.t1.t1 = beta(term.t1.t1, term.t1.a, dup(term.t2));&lt;/pre&gt;
&lt;pre&gt;                term = term.t1.t1;&lt;/pre&gt;
&lt;pre&gt;                depth--;&lt;/pre&gt;
&lt;pre&gt;            } else if (term.t1.type == TType.VAR &amp;amp;&amp;amp; term.t1.a == &amp;quot;print&amp;quot;) {&lt;/pre&gt;
&lt;pre&gt;                writefln(&amp;quot;[print] %s&amp;quot;, term.t2.toString);&lt;/pre&gt;
&lt;pre&gt;                term = term.t2;&lt;/pre&gt;
&lt;pre&gt;                depth--;&lt;/pre&gt;
&lt;pre&gt;            } else {&lt;/pre&gt;
&lt;pre&gt;                cont = new EvalCont(term, false, depth, cont);&lt;/pre&gt;
&lt;pre&gt;                term = term.t1;&lt;/pre&gt;
&lt;pre&gt;                depth++;&lt;/pre&gt;
&lt;pre&gt;            }&lt;/pre&gt;
&lt;pre&gt;        } else {&lt;/pre&gt;
&lt;pre&gt;            computeAns = true;&lt;/pre&gt;
&lt;pre&gt;            ans = term; acont = cont;&lt;/pre&gt;
&lt;pre&gt;        }&lt;/pre&gt;
&lt;pre&gt;        if (computeAns) {&lt;/pre&gt;
&lt;pre&gt;            if (acont == null) return ans;&lt;/pre&gt;
&lt;pre&gt;            if (acont.inner) {&lt;/pre&gt;
&lt;pre&gt;                acont.term.t2 = ans;&lt;/pre&gt;
&lt;pre&gt;                term = acont.term;&lt;/pre&gt;
&lt;pre&gt;                depth = acont.depth+1;&lt;/pre&gt;
&lt;pre&gt;                cont = acont.next;&lt;/pre&gt;
&lt;pre&gt;            } else {&lt;/pre&gt;
&lt;pre&gt;                acont.term.t1 = ans;&lt;/pre&gt;
&lt;pre&gt;                term = acont.term.t2;&lt;/pre&gt;
&lt;pre&gt;                depth = acont.depth;&lt;/pre&gt;
&lt;pre&gt;                cont = new EvalCont(acont.term, true, acont.depth, acont.next);&lt;/pre&gt;
&lt;pre&gt;            }&lt;/pre&gt;
&lt;pre&gt;        }&lt;/pre&gt;
&lt;pre&gt;    } while (true);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;&lt;/code&gt;&lt;h2 id=&quot;sec-8&quot;&gt;Some Tangible Results&lt;/h2&gt;&lt;p&gt;With the help of &lt;a href=&quot;https://en.wikipedia.org/wiki/Church_encoding&quot; target=&quot;_blank&quot;&gt;Church encoding&lt;/a&gt; to encode numbers and booleans I wrote a program that computes the fibonacci numbers (it&#x27;s &lt;code&gt;stdlib.lc&lt;/code&gt; in &lt;a href=&quot;https://github.com/geezee/typeless/tree/13f629e9039a3af0ef10673ad06bdf521fca1ef4&quot; target=&quot;_blank&quot;&gt;typeless.git&lt;/a&gt;).
The table below displays 30 results, each for a different &lt;em&gt;n&lt;/em&gt; (the input) and level of optimization.
For a given run, if a function&#x27;s cell contains the check mark &amp;#x2713; then the transformed (i.e. iterative) version of that function was used.
The results are grouped by &lt;em&gt;n&lt;/em&gt; and the fastest result is in bold.
I benchmarked the code on my slow notebook whose brain is an &lt;a href=&quot;https://ark.intel.com/content/www/us/en/ark/products/93361/intel-atom-x5-x8350-processor-2m-cache-up-to-1-92-ghz.html&quot; target=&quot;_blank&quot;&gt; Intel Atom x5-Z8350 processor (1.9GHz / 2M cache)&lt;/a&gt; with 1.8 GB RAM.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Number of reductions&lt;/th&gt;
&lt;th&gt;&lt;code&gt;eval&lt;/code&gt;&lt;/th&gt;
&lt;th&gt;&lt;code&gt;beta&lt;/code&gt;&lt;/th&gt;
&lt;th&gt;&lt;code&gt;dup&lt;/code&gt;&lt;/th&gt;
&lt;th&gt;Total (sec)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt; &lt;td rowspan=&quot;8&quot;&gt;150,992&lt;br&gt;fibonacci(8)&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;strong&gt;0.358&lt;/strong&gt;&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;0.415&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;0.373&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;0.768&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;0.413&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;0.849&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;0.791&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;0.847&lt;/td&gt; &lt;/tr&gt;
&lt;tr class=&quot;thick-top&quot;&gt; &lt;td rowspan=&quot;8&quot;&gt;4,710,572&lt;br&gt;fibonacci(15)&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;14.41&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;strong&gt;12.92 (+11.5%)&lt;/strong&gt;&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;14.22&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;30.34&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;13.31&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;27.86&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;32.34&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;28.14&lt;/td&gt; &lt;/tr&gt;
&lt;tr class=&quot;thick-top&quot;&gt; &lt;td rowspan=&quot;6&quot;&gt;12,354,971&lt;br&gt;fibonacci(17)&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;45.33&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;41.61&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;39.9&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;85.33&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;strong&gt;37.32 (+21.5%)&lt;/strong&gt;&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;78.73&lt;/td&gt; &lt;/tr&gt;
&lt;tr class=&quot;thick-top&quot;&gt; &lt;td rowspan=&quot;4&quot;&gt;20,000,475&lt;br&gt;fibonacci(18)&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;Segfault (@ 67.69)&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;Segfault (@ 67.01)&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;63.45&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;strong&gt;62.2&lt;/strong&gt;&lt;/td&gt; &lt;/tr&gt;
&lt;tr class=&quot;thick-top&quot;&gt; &lt;td rowspan=&quot;2&quot;&gt;52,389,823&lt;br&gt;fibonacci(20)&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;strong&gt;162.34&lt;/strong&gt;&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;174.28&lt;/td&gt; &lt;/tr&gt;
&lt;tr class=&quot;thick-top&quot;&gt; &lt;td rowspan=&quot;2&quot;&gt;221,990,915&lt;br&gt;fibonacci(23)&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;strong&gt;693.21&lt;/strong&gt;&lt;/td&gt; &lt;/tr&gt;
&lt;tr&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&amp;#x2713;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;705.99&lt;/td&gt; &lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;p&gt;
Before running these benchmarks I&#x27;ve profiled the interpreter.
Briefly, the function that is called the most is &lt;code&gt;dup&lt;/code&gt;, 4.3 times more than &lt;code&gt;beta&lt;/code&gt; which is called 2.5 times more than &lt;code&gt;eval&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;
As expected the code that uses all recursive versions eventually segfaults, which is basically an indication that we ran out stack space.
What may be surprising is that using &lt;code&gt;dupOpt&lt;/code&gt; instead of &lt;code&gt;dup&lt;/code&gt; actually slows things down, by a lot!
Keep in mind that accessing data on the heap is slower than on the stack, &lt;code&gt;dup&lt;/code&gt; is already a memory intensive operation, &lt;code&gt;dupOpt&lt;/code&gt; will be even more memory intensive, which I guess is the reason behind the slow-down.&lt;/p&gt;&lt;p&gt;
However what I am incapable of explaining is why eventually, for really large &lt;em&gt;n&lt;/em&gt;, using both &lt;code&gt;evalOpt&lt;/code&gt; and &lt;code&gt;betaOpt&lt;/code&gt; (version A) is slower than using &lt;code&gt;eval&lt;/code&gt; and &lt;code&gt;betaOpt&lt;/code&gt; (version B).
My guess is that memory becomes too fragmented after too many pushes/pops on the &lt;code&gt;EvalCont&lt;/code&gt; and &lt;code&gt;BetaCont&lt;/code&gt; linked lists.
I conjecture that eventually B will segfault for some large &lt;em&gt;n&lt;/em&gt;.
However, I tried running B on a macbook that is on average five times faster than my notebook with &lt;em&gt;n=28&lt;/em&gt; taking some 2.4 billion operations.
B did not segfault and it ran significantly faster than A.&lt;/p&gt;&lt;p&gt;
In conclusion, we should keep the recursive &lt;code&gt;eval&lt;/code&gt; and &lt;code&gt;dup&lt;/code&gt; and use the iterative &lt;code&gt;betaOpt&lt;/code&gt; instead of &lt;code&gt;beta&lt;/code&gt;.
So beware of overtrusting the &quot;iterative code is quicker than recursive code&quot; idiom since that wasn&#x27;t the case for 2/3 of our functions!
The lesson drawn from this experiment was: As always, first benchmark and then decide.&lt;/p&gt;</description>
<link>https://blog.grgz.me/posts/recursion_elimination.html</link>
<guid isPermaLink="false">https://blog.grgz.me/posts/recursion_elimination.html</guid>
<pubDate>Sun, 18 Aug 2019</pubDate>
</item>
  </channel>
</rss>
