<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
    <title>Davis</title>
    <link rel="self" type="application/atom+xml" href="https://thedav.is/atom.xml"/>
    <link rel="alternate" type="text/html" href="https://thedav.is"/>
    <generator uri="https://www.getzola.org/">Zola</generator>
    <updated>2021-01-14T12:15:00-05:00</updated>
    <id>https://thedav.is/atom.xml</id>
    <entry xml:lang="en">
        <title>Crafting Semantics 2: Basic Features</title>
        <published>2021-01-14T12:15:00-05:00</published>
        <updated>2021-01-14T12:15:00-05:00</updated>
        
        <author>
          <name>
            
              Unknown
            
          </name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://thedav.is/post/crafting-semantics-2/"/>
        <id>https://thedav.is/post/crafting-semantics-2/</id>
        
        <content type="html" xml:base="https://thedav.is/post/crafting-semantics-2/">&lt;p&gt;This series of posts revolves around creating operational semantics of the Scheme programming language from the ground up, starting with the lambda calculus.&lt;&#x2F;p&gt;
&lt;p&gt;If you have not read the introductory post, you can find it &lt;a href=&quot;https:&#x2F;&#x2F;thedav.is&#x2F;post&#x2F;crafting-semantics-0&#x2F;&quot;&gt;here&lt;&#x2F;a&gt;, and see the index of this series &lt;a href=&quot;&#x2F;tags&#x2F;crafting-semantics&#x2F;&quot;&gt;here&lt;&#x2F;a&gt;.&lt;&#x2F;p&gt;
&lt;h1 id=&quot;intro&quot;&gt;Intro&lt;&#x2F;h1&gt;
&lt;p&gt;Hi! Welcome! Today, we will be extending the CESK machine from the &lt;a href=&quot;https:&#x2F;&#x2F;thedav.is&#x2F;post&#x2F;crafting-semantics-1&#x2F;&quot;&gt;previous post&lt;&#x2F;a&gt;, adding some simple features that will make our language more usable. In particular, we will implement numbers and conditionals. To accomplish that, we will be partitioning the machine into 2 different types of states. This will make future extensions to our language much simpler.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;recap&quot;&gt;Recap&lt;&#x2F;h2&gt;
&lt;p&gt;Let&#x27;s look at the machine that we have so far. These transition functions serve as the basis for the famous call-by-value lambda-calculus. If you don&#x27;t remember the domains, I will reproduce them soon, when we create our new machine.&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;(x , \rho , \sigma , \kappa) \leadsto (v , \rho_\lambda , \sigma , \kappa) \\
\begin{aligned}
\text{where } \sigma(\rho(x)) &amp;= (v , \rho_\lambda) \\
\end{aligned}&lt;&#x2F;script&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;((e_f \; e_a) , \rho , \sigma , \kappa) \leadsto (e_f , \rho , \sigma , \kappa&#x27;) \\
\begin{aligned}
\text{where } \kappa&#x27; &amp;\triangleq \textbf{arg}(e_a , \rho , \kappa) \\
\end{aligned}&lt;&#x2F;script&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;(lam , \rho , \sigma , \textbf{arg}(e_a , \rho&#x27; , \kappa))
\leadsto (e_a , \rho&#x27; , \sigma , \textbf{fn}(lam , \rho , \kappa)) \\&lt;&#x2F;script&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;(lam , \rho , \sigma , \textbf{fn}(lam&#x27; , \rho&#x27; , \kappa))
\leadsto (e , \rho&#x27;&#x27; , \sigma&#x27; , \kappa) \\
\begin{aligned}
\text{where } lam&#x27; &amp;= (λ \; (x) \; e) \\
			  a &amp;\triangleq alloc(\sigma) \\
			  \rho&#x27;&#x27; &amp;\triangleq \rho&#x27;[x \mapsto a] \\
			  \sigma&#x27; &amp;\triangleq \sigma[a \mapsto (lam , \rho)]
\end{aligned}&lt;&#x2F;script&gt;
&lt;h2 id=&quot;roadblock&quot;&gt;Roadblock&lt;&#x2F;h2&gt;
&lt;p&gt;The main issue with this machine is that it is very &#x27;lambda-centric&#x27;. For example, if you pay close attention in the last post, closure creation is actually deeply embedded into the semantics. When a variable is evaluated it finds the closure and sets it to the current environment. We want a machine that is more ... &#x27;value independent&#x27;&lt;&#x2F;p&gt;
&lt;p&gt;If we wanted to have values that are less syntactically visible, like &lt;a href=&quot;https:&#x2F;&#x2F;thedav.is&#x2F;post&#x2F;continuations-as-return&#x2F;&quot;&gt;first-class continuations&lt;&#x2F;a&gt;, adding them to the current machine would overcomplicate our transitions. Instead, we will partition the machine into &#x27;eval&#x27; and &#x27;apply&#x27; states. Eval states are for &lt;em&gt;evaluating&lt;&#x2F;em&gt; syntax to get a value. Apply states are for &lt;em&gt;applying&lt;&#x2F;em&gt; the value into the current Kontinuation.&lt;&#x2F;p&gt;
&lt;h1 id=&quot;the-next-machine&quot;&gt;The Next Machine&lt;&#x2F;h1&gt;
&lt;p&gt;Our machine is very similar to the previous machine, with a few additions to the syntactic and semantic domains. I will point out the differences, so don&#x27;t worry about cross-referencing the last post!&lt;&#x2F;p&gt;
&lt;h2 id=&quot;syntax-domains&quot;&gt;Syntax Domains&lt;&#x2F;h2&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\begin{aligned}
% expressions
e \in \textsf{Exp} &amp;::= \text{\ae}  \\
				   &amp;| \; (\texttt{if} \; e \; e \; e) \\
                   &amp;| \; (e\;e) \\
\text{\ae} \in \textsf{AExp}
	&amp;::= x \;|\; lam \;|\; n \;|\; b \\
% variables
x \in \textsf{Var} &amp;\triangleq \text{The set of variables} \\
% lambdas
lam \in \textsf{Lam} &amp;::= (λ \; (x) \; e) \\
n \in \mathbb{Z} &amp;\triangleq \text{The set of integers } \\
b \in \textsf{Bool} &amp;::= \texttt{\#t} \;|\; \texttt{\#f}
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;The main chunk of change revolves around the new &lt;code&gt;æ&lt;&#x2F;code&gt; domain. Through this, we have partitioned the syntax into expressions that are complex, and require further evaluation, and &#x27;atomic expressions&#x27;, which are as small as they need to be, in order to become real values.&lt;&#x2F;p&gt;
&lt;p&gt;The set of atomic expressions include lambdas and variables, as before, and introducing integers and booleans. I also added an &lt;code&gt;if&lt;&#x2F;code&gt; complex-expression, which we will implement today.&lt;&#x2F;p&gt;
&lt;p&gt;Also, quick note, booleans in Scheme are &lt;code&gt;#t&lt;&#x2F;code&gt; for true, and &lt;code&gt;#f&lt;&#x2F;code&gt; for false. Just wanted to be clear on that!&lt;&#x2F;p&gt;
&lt;h2 id=&quot;semantic-domains&quot;&gt;Semantic Domains&lt;&#x2F;h2&gt;
&lt;p&gt;The semantic domains are also mostly the same, but with some additions to accommodate this partition between &#x27;eval&#x27; and &#x27;apply&#x27; states.&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\begin{aligned}
% Machine
\varsigma \in \Sigma &amp;\triangleq
			E\langle \textit{Eval} \rangle
			+ A\langle \textit{Apply} \rangle \\
\textit{Eval} &amp;\triangleq \textsf{Exp} \times \textit{Env} \times \textit{Store} \times \textit{Kont} \\
\textit{Apply} &amp;\triangleq \textit{Val} \times \textit{Env} \times \textit{Store} \times \textit{Kont} \\
% Env
\rho \in \textit{Env} &amp;\triangleq \textsf{Var} \rightarrow \textsf{Addr} \\
% Store
\sigma \in \textit{Store} &amp;\triangleq \textsf{Addr} \rightarrow \textsf{Val} \\
% Address
a \in \textit{Addr} &amp;\triangleq \mathbb{N} \\
% Value
v \in \textit{Val} &amp;\triangleq \textit{Clo}
					+ \mathbb{Z} + \textsf{Bool} \\
% Closures
clo \in \textit{Clo} &amp;\triangleq \textsf{Lam} \times \textit{Env} \\
% Continuation
\kappa \in \textit{Kont} &amp;::= \textbf{mt} \\
						&amp; | \; \textbf{cond}(e , e , \rho , \kappa) \\
						&amp; | \; \textbf{arg}(e, \rho, \kappa) \\
						&amp; | \; \textbf{fn}(v, \kappa) \\
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;The changes here were to the states, the values, and the continuations. The change to the states is the most jarring, now we can have 2 different types of sub-states. I added to the values domain, because now we have numbers and booleans! Exciting!&lt;&#x2F;p&gt;
&lt;p&gt;We also needed a continuation type for the conditional. When is it appropriate to add a continuation type? In this machine, you have two things to look at for guidance during computation. First and foremost is the Control. When our machine starts evaluating the syntax &lt;code&gt;(if cond then else)&lt;&#x2F;code&gt;, we will place &lt;code&gt;cond&lt;&#x2F;code&gt; into the control, and place a continuation &lt;code&gt;cond(then, else, ρ, κ)&lt;&#x2F;code&gt; at the top of our Kontinuation stack. After the control is evaluated to a value, we need to look to the Kontinuation for the next steps. For that, we use a continuation.&lt;&#x2F;p&gt;
&lt;p&gt;So, whenever you are adding syntax that needs some state, so the machine knows what to do after the initial control is evaluated, you probably want a new continuation frame type.&lt;&#x2F;p&gt;
&lt;p&gt;Having 2 types of states will make writing out machine rules really easy, I promise! Now, we will have rules for evaluating the control (syntax), and for what to do after its a value (through the continuation)! It is a nice give and take relationship between the states that I really enjoy from this style of machine.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;atomic-evaluation-and-other-functions&quot;&gt;Atomic Evaluation And Other Functions&lt;&#x2F;h2&gt;
&lt;p&gt;Last before we get to the new transition rules, we need to define an &#x27;atomic evaluation&#x27; function. This function is the bridge from &#x27;eval&#x27; states into &#x27;Apply&#x27; states. When we see a &lt;code&gt;4&lt;&#x2F;code&gt; in our program, it is syntax, because its in the program text. We need to turn that syntax-&lt;code&gt;4&lt;&#x2F;code&gt; into a value-&lt;code&gt;4&lt;&#x2F;code&gt;.&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\mathcal{A} : \textit{Eval} \rightarrow \textit{Val} \\
\begin{aligned}
\mathcal{A}(\langle n , \_ , \_ , \_ \rangle) &amp;\triangleq n \\
\mathcal{A}(\langle b , \_ , \_ , \_ \rangle) &amp;\triangleq b \\
\mathcal{A}(\langle x , \rho , \sigma , \_ \rangle) &amp;\triangleq \sigma(\rho(x)) \\
\mathcal{A}(\langle lam , \rho , \_ , \_ \rangle) &amp;\triangleq (lam, \rho) \\
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;This function turns syntax into values! It is straightforward in the number&#x2F;bool case, and reminiscent of the machine of the last post for the other two cases.&lt;&#x2F;p&gt;
&lt;p&gt;We use this function when the control is &#x27;atomically evaluable&#x27;, meaning we can determine its value immediately. For variables, we just need to look its value up, and for lambdas, we pair it with the current environment to form a closure. The other, &#x27;complex&#x27;, expressions need a little more work done on them before they can be atomically evaluated.&lt;&#x2F;p&gt;
&lt;p&gt;I will also reproduce the other useful functions from the last post, for posterity:&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;inj : \textsf{Exp} \rightarrow \Sigma \\
inj(e) \triangleq E\langle e , \varnothing , \varnothing , \textbf{mt} \rangle \\
\; \\
alloc : \textit{Store} \rightarrow \textit{Addr} \\
alloc(\sigma) \triangleq |\sigma|&lt;&#x2F;script&gt;
&lt;h1 id=&quot;transitions&quot;&gt;Transitions&lt;&#x2F;h1&gt;
&lt;p&gt;Now that we have all of the supporting infrastructure, we can make the transition rules! We are going to start with all of the &#x27;eval&#x27; rules, and then do the &#x27;apply&#x27; rules.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;eval-rules&quot;&gt;Eval Rules&lt;&#x2F;h2&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;E \langle \text{\ae} , \rho , \sigma , \kappa \rangle
\leadsto
A \langle v , \rho , \sigma , \kappa \rangle \\
\begin{aligned}
\text{where }
v &amp;\triangleq \mathcal{A}(\varsigma)
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;As a refresher, you can read this rule as follows:&lt;&#x2F;p&gt;
&lt;blockquote&gt;
&lt;p&gt;If the current state is an Eval state, and our control is atomically evaluable, then return the following Apply state, where v is defined by using the atomic-eval function on the input state.&lt;&#x2F;p&gt;
&lt;&#x2F;blockquote&gt;
&lt;p&gt;This rule is quite simple! If the current control is an atomically evaluable expression, use our fancy-A evaluation function to make a value of it. This rule covers when the control is a number, boolean, lambda, or variable, what a multitasker!&lt;&#x2F;p&gt;
&lt;p&gt;As I said before, this transition rule is the bridge from eval to apply states. We will  make transition rules for apply states later, but for now, lets continue evaluating syntax!&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;E \langle (\texttt{if} \; e_c \; e_t \; e_f) , \rho , \sigma , \kappa \rangle
\leadsto
E \langle e_c , \rho , \sigma , \kappa&#x27; \rangle \\
\begin{aligned}
\text{where }
\kappa&#x27; &amp;\triangleq \textbf{cond}(e_t , e_f , \rho , \kappa)
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;This is the first half of the rules required to support conditionals. When we encounter an &lt;code&gt;if&lt;&#x2F;code&gt; expression, we transition to start evaluating the condition. And later, once the condition is evaluated, we will check for a continuation and see the &lt;code&gt;cond&lt;&#x2F;code&gt; frame, and go from there! Stay tuned for the riveting conclusion to &lt;del&gt;this anime&lt;&#x2F;del&gt; interpreting conditionals.&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;E \langle (e_f \; e_0) , \rho , \sigma , \kappa \rangle
\leadsto
E \langle e_f , \rho , \sigma , \kappa&#x27; \rangle \\
\begin{aligned}
\text{where }
\kappa&#x27; &amp;\triangleq \textbf{arg}(e_0 , \rho , \kappa)
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;This rule is remarkably similar to the last post&#x27;s rule, which is great! I&#x27;m not trying to overcomplicate this stuff, so I hope that things don&#x27;t get needlessly crazy. Although, small spoiler for the next post, I will be implementing multi-arg functions, so this will change slightly! Sorry for making you think that this rule would never ever change!&lt;&#x2F;p&gt;
&lt;p&gt;We have now covered 100% of the syntax that can be found in our little language! But, there is a little more to do. Lets transition apply states!&lt;&#x2F;p&gt;
&lt;h2 id=&quot;apply-rules&quot;&gt;Apply Rules&lt;&#x2F;h2&gt;
&lt;p&gt;As I alluded to before, there are 2 things that the machine uses to right itself, the control and the continuation. The Eval states are for checking the control, and the apply states are for checking the continuation. We have exhausted control, and now we must exhaust all types of continuations!&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;A \langle v , \rho , \sigma , \kappa \rangle
\leadsto
E \langle e_f , \rho_{\kappa} , \sigma , \kappa&#x27; \rangle \\
\begin{aligned}
\text{where }
\kappa &amp;= \textbf{cond}(e_f , e_f , \rho_{\kappa} , \kappa&#x27;) \\
v &amp;= \texttt{\#f}
\end{aligned} \\
A \langle v , \rho , \sigma , \kappa \rangle
\leadsto
E \langle e_t , \rho_{\kappa} , \sigma , \kappa&#x27; \rangle \\
\begin{aligned}
\text{where }
\kappa &amp;= \textbf{cond}(e_t , e_f , \rho_{\kappa} , \kappa&#x27;) \\
v &amp;\;≠ \texttt{\#f}
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;These are the final rules for dealing with conditionals. We refer to the value (which is the value of the condition) and check if it is equal to false. If so, we take the false branch. We &#x27;take it&#x27; by just setting that branch to the control of the next state. It &lt;em&gt;is&lt;&#x2F;em&gt; that easy! The opposite goes for &lt;code&gt;true&lt;&#x2F;code&gt;, if the value in the condition is simply &#x27;not false&#x27;, then we take the true branch.&lt;&#x2F;p&gt;
&lt;p&gt;(Aside: At the time of writing, it seems the rendering for ≠ is broken, but the false branch should have &lt;code&gt;v ≠ #f&lt;&#x2F;code&gt;)&lt;&#x2F;p&gt;
&lt;p&gt;Note the semantics here! Many languages have many different ideas of &#x27;falsy&#x27; and &#x27;truthy&#x27;. Python has a whole overridable &lt;code&gt;__bool__&lt;&#x2F;code&gt; function, and I don&#x27;t want to get &lt;em&gt;near&lt;&#x2F;em&gt; what JavaScript does. Scheme is simple. The only &#x27;falsy&#x27; value is false. Everything else is truthy. Everything. Simple!&lt;&#x2F;p&gt;
&lt;p&gt;Its also important to &#x27;reset&#x27; the environment. During the course of evaluating the condition, the environment may have changed. We don&#x27;t want to use that environment while taking one of the resultant branches, which is why we stored the original environment in the continuation.&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;A \langle v , \rho , \sigma , \kappa \rangle
\leadsto
E \langle e , \rho_{\kappa} , \sigma , \kappa&#x27;&#x27; \rangle \\
\begin{aligned}
\text{where }
\kappa &amp;= \textbf{arg}(e , \rho_{\kappa} , \kappa&#x27;) \\
\kappa&#x27;&#x27; &amp;\triangleq \textbf{fn}(v , \kappa&#x27;)
\end{aligned} \\
%
A \langle v , \rho , \sigma , \kappa \rangle
\leadsto
E \langle e_b , \rho_{\lambda}&#x27; , \sigma&#x27; , \kappa&#x27; \rangle \\
\begin{aligned}
\text{where }
\kappa &amp;= \textbf{fn}(((\lambda \; (x) \; e_b) , \rho_{\lambda}) , \kappa&#x27;) \\
a &amp;\triangleq alloc(\sigma) \\
\rho_{\lambda}&#x27; &amp;\triangleq \rho_{\lambda}[x \mapsto a] \\
\sigma&#x27; &amp;\triangleq \sigma[a \mapsto v]
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;These two rules are all we need to interpret our function calling syntax. In the first rule, we have finished evaluating the &#x27;function&#x27; half of the two expressions, and move to evaluate the argument. Then in the next rule, we have completely evaluated both the function and the argument, and we call the function! These rules are also exceedingly similar to the rules from the previous post, they should not surprise.&lt;&#x2F;p&gt;
&lt;p&gt;I like to add this final rule, just to explicitly say &#x27;this is the end&#x27;:&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;A \langle \varsigma \rangle \leadsto A \langle \varsigma \rangle \\
\begin{aligned}
\text{where }
\kappa &amp;= \textbf{mt}
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;Of course, this rule is vacuous, as without it, we would simply reach a stuck state in the same circumstance, and say &#x27;thats all folks&#x27;. This way though, you can feel a little safer, having a slight distinction between &#x27;stuck&#x27; and &#x27;nothing left to do&#x27;.&lt;&#x2F;p&gt;
&lt;h1 id=&quot;example&quot;&gt;Example&lt;&#x2F;h1&gt;
&lt;p&gt;Lets evaluate a simple program utilizing our new features!&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;e_0 = ((λ \; (x) \; x) \;\; (\texttt{if} \; \texttt{\#f} \; 3 \; 12)) \\
\varsigma_0 = inj(e_0) = E\langle e_0 , \varnothing , \varnothing , \textbf{mt}\rangle \\
\varsigma_n = step(\varsigma_{n-1}) \\
\;\\
%
\varsigma_1 = E\langle (λ \; (x) \; x) , \varnothing , \varnothing  ,
				\textbf{arg}((\texttt{if} \; \texttt{\#f} \; 3 \; 12) ,
								\varnothing , \textbf{mt}) \rangle \\
\varsigma_2 = A\langle
				((λ \; (x) \; x) , \varnothing) , \varnothing , \varnothing ,
				\textbf{arg}((\texttt{if} \; \texttt{\#f} \; 3 \; 12) ,
								\varnothing , \textbf{mt})
				\rangle \\
\varsigma_3 = E\langle
				(\texttt{if} \; \texttt{\#f} \; 3 \; 12) , \varnothing , \varnothing ,
				\textbf{fn}(((λ \; (x) \; x) , \varnothing) , \textbf{mt})
				\rangle \\
\varsigma_4 = E\langle
				\texttt{\#f} , \varnothing , \varnothing ,
				\textbf{cond}(3 , 12 , \varnothing , \textbf{fn}(((λ \; (x) \; x) , \varnothing) , \textbf{mt}))
				\rangle \\
\varsigma_5 = A\langle
				\texttt{\#f} , \varnothing , \varnothing ,
				\textbf{cond}(3 , 12 , \varnothing , \textbf{fn}(((λ \; (x) \; x) , \varnothing) , \textbf{mt}))
				\rangle \\
\varsigma_6 = E\langle
				12 , \varnothing , \varnothing ,
				\textbf{fn}(((λ \; (x) \; x) , \varnothing) , \textbf{mt})
				\rangle \\
\varsigma_7 = A\langle
				12 , \varnothing , \varnothing ,
				\textbf{fn}(((λ \; (x) \; x) , \varnothing) , \textbf{mt})
				\rangle \\
\varsigma_8 = E\langle
				x , \{x : 0 \} , \{ 0 : 12 \} , \textbf{mt}
				\rangle \\
\varsigma_9 = A\langle
				12 , \{x : 0 \} , \{ 0 : 12 \} , \textbf{mt}
				\rangle&lt;&#x2F;script&gt;
&lt;p&gt;This example clearly shows the interchange between Eval and Apply states. You evaluate until you apply, and then you evaluate, and so on, until you reach a stuck or finished point (a fixpoint).&lt;&#x2F;p&gt;
&lt;h1 id=&quot;conclusion&quot;&gt;Conclusion&lt;&#x2F;h1&gt;
&lt;p&gt;So in only these few short minutes we have added some quality-of-life features to our language, making it much more usable! The semantics grew a little in breadth and depth, but is now much more capable of supporting more advanced features.&lt;&#x2F;p&gt;
&lt;p&gt;This post will serve as a general template for this series. We take the machine we have, decide what to add, and then add it. Further than that, the addition of features is similarly patterned. You add syntax, then make sure the semantic domains support the syntax (i.e. the Val and Kont domains), and finally add transitions.&lt;&#x2F;p&gt;
&lt;p&gt;By utilizing this method, adding new features is simple. Also by utilizing this method, I can churn out blog posts until the sun dies! Just kidding, I have better things to do than eternally add features until we accidentally formalize Perl.&lt;&#x2F;p&gt;
&lt;p&gt;In the next post, I will be adding multi-arg functions, and a couple of other useful features. I hope to see you there!&lt;&#x2F;p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Crafting Semantics 1: Lambda Calculus</title>
        <published>2021-01-06T12:15:00-05:00</published>
        <updated>2021-01-06T12:15:00-05:00</updated>
        
        <author>
          <name>
            
              Unknown
            
          </name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://thedav.is/post/crafting-semantics-1/"/>
        <id>https://thedav.is/post/crafting-semantics-1/</id>
        
        <content type="html" xml:base="https://thedav.is/post/crafting-semantics-1/">&lt;p&gt;This series of posts revolves around creating operational semantics of the Scheme programming language from the ground up, starting with the lambda calculus.&lt;&#x2F;p&gt;
&lt;p&gt;If you have not read the introductory post, you can find it &lt;a href=&quot;https:&#x2F;&#x2F;thedav.is&#x2F;post&#x2F;crafting-semantics-0&#x2F;&quot;&gt;here&lt;&#x2F;a&gt;, and see the index of this series &lt;a href=&quot;&#x2F;tags&#x2F;crafting-semantics&#x2F;&quot;&gt;here&lt;&#x2F;a&gt;.&lt;&#x2F;p&gt;
&lt;h1 id=&quot;intro&quot;&gt;Intro&lt;&#x2F;h1&gt;
&lt;p&gt;Hi, in this post we will be implementing a CESK Abstract Machine for the lambda calculus (or simply &#x27;λ&#x27;). First, we need to define all of what an &#x27;abstract machine&#x27; is, what semantics are, and the syntax we will be using. So this post may be a bit long. Future posts are likely to be shorter!&lt;&#x2F;p&gt;
&lt;p&gt;If you know all of the intro stuff already, but dont know how to define semantics for the lambda calculus, feel free to skip to &lt;a href=&quot;https:&#x2F;&#x2F;thedav.is&#x2F;post&#x2F;crafting-semantics-1&#x2F;#the-machine&quot;&gt;here&lt;&#x2F;a&gt;&lt;&#x2F;p&gt;
&lt;h1 id=&quot;cesk&quot;&gt;CESK&lt;&#x2F;h1&gt;
&lt;p&gt;The type of abstract machine we will be creating is called &#x27;CESK&#x27;. It stands for &lt;strong&gt;C&lt;&#x2F;strong&gt;ontrol, &lt;strong&gt;Environment&lt;&#x2F;strong&gt;, &lt;strong&gt;Store&lt;&#x2F;strong&gt;, and &lt;strong&gt;Kontinuation&lt;&#x2F;strong&gt; (C was already taken). For a language as simple as the λ-calculus, we dont need all of this machinery, but as we build features for this machine into a real scheme, it will be nice to have the extra features provided by the Store and Kontinuation pieces.&lt;&#x2F;p&gt;
&lt;p&gt;The control of a machine is the current instruction that is being evaluated. For the λ-calculus, this will simply be the syntax. For a more complex machine, like the JVM, this could be the bytecodes and an index into the current instruction. For a CPU, it may be an instruction pointer and the binary program text. When you hear the word &#x27;control flow&#x27; it is referring to this component.&lt;&#x2F;p&gt;
&lt;p&gt;The environment is the set of variables that can be referenced. We will use a simple key-value mapping (dict, hash, etc.) to represent our environment. The keys of the mapping will be the variable names, and the value will be the address of where to find that variables value.&lt;&#x2F;p&gt;
&lt;p&gt;The store is where values are actually held. If you have an address, you can access the store to get its corresponding value. We again use a key-value mapping, from address to value.&lt;&#x2F;p&gt;
&lt;p&gt;The kontinuation is what happens &#x27;next&#x27;, after we finish evaluating an expression. We will use a special continuation frame object to track this. In many languages, this kind of thing is called a &#x27;
&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;en.wikipedia.org&amp;#x2F;wiki&amp;#x2F;Call_stack&quot; target=&quot;_blank&quot;&gt;call-stack↪&lt;&#x2F;a&gt;
&#x27;. When a function is called, the &#x27;stack&#x27; is added to with the current function. In the future, We will augment it to track more things, such as conditionals, let bindings, and variable mutation.&lt;&#x2F;p&gt;
&lt;p&gt;It is used to represent a fine grained call-stack. But instead of only keeping track of function calls, it tracks many other things, such as conditionals and let bindings.&lt;&#x2F;p&gt;
&lt;h1 id=&quot;the-l-of-computer-science&quot;&gt;The λ of Computer Science&lt;&#x2F;h1&gt;
&lt;p&gt;λ, spelled &#x27;lambda&#x27; in english, is a greek letter which is ubiquitous in the computing sciences. It refers to computation itself.&lt;&#x2F;p&gt;
&lt;p&gt;The lambda calculus is a very simple language. Created before modern computers, its goal was to express logic formally. Now, we can use it as a basis for a small and simple programming language. Its 
&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;en.wikipedia.org&amp;#x2F;wiki&amp;#x2F;Lambda_calculus&quot; target=&quot;_blank&quot;&gt;Wikipedia Page↪&lt;&#x2F;a&gt;
 is chock-full of great stuff, but I will give it a quick introduction.&lt;&#x2F;p&gt;
&lt;p&gt;The lambda calculus has 3 forms&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\begin{aligned}
% expressions
e &amp;::= x  \\
  &amp; | \; (e\;e) \\
  &amp; | \; (\lambda \; (x) \; e) \\
x &amp;::= \; \text{some variable} \\
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;This syntax means, an expression (we are just calling it &lt;code&gt;e&lt;&#x2F;code&gt;) can be three things. It could be some variable, that we are calling &lt;code&gt;x&lt;&#x2F;code&gt;. It could also be an &#x27;application&#x27; with 2 expressions in it. Finally, It may be an &#x27;abstraction&#x27; that takes some variable and some expression.&lt;&#x2F;p&gt;
&lt;p&gt;Both &lt;code&gt;e&lt;&#x2F;code&gt; and &lt;code&gt;x&lt;&#x2F;code&gt; are what are called &#x27;metavariables&#x27;, meaning they are variables to be used in the grammar, and will be replaced in a real text. An example λ-calculus program may be:&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;((\lambda \; (q) \; (\lambda \; (b) \; q)) \; (\lambda \; (\text{blerp}) \; \text{WORD}))&lt;&#x2F;script&gt;
&lt;p&gt;This is a program! At this moment, it doesnt do anything, beacuse we have not given it any &lt;em&gt;semantics&lt;&#x2F;em&gt;! Semantics are what give program text meaning. Maybe in my semantics, I will say, &quot;If a program looks like &lt;code&gt;((λ (q) (λ (b) q)) (λ (z) z))&lt;&#x2F;code&gt;, then format the Hard Drive!&quot;. I would not say thats a very moral semantics, and it places a weird dependency on something called a &#x27;hard&#x27;... &#x27;drive&#x27;... but it&#x27;s a semantics!&lt;&#x2F;p&gt;
&lt;p&gt;Given a reasonable (and standard, time honored) semantics, these three can perform any computation. We will implement semantics for the lambda calculus in this post, and add on to it in the future to make an actually useful language.&lt;&#x2F;p&gt;
&lt;p&gt;So lets get started!&lt;&#x2F;p&gt;
&lt;h1 id=&quot;the-machine&quot;&gt;The Machine&lt;&#x2F;h1&gt;
&lt;p&gt;First, we need to define our &lt;em&gt;domains&lt;&#x2F;em&gt;. These are the things that we actually use to implement our machines. A simple domain that you may be familiar with is the set of Integers. starting at 0, you can go forward by 1, or backwards by 1, to infinity (and negative infinity). Our domains include &#x27;syntactic domains&#x27;, which are domains seen in the progrm text, and &#x27;semantic domains&#x27;, for determining meaning.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;syntax&quot;&gt;Syntax&lt;&#x2F;h2&gt;
&lt;p&gt;The syntactic domain is our grammar from above, but lets expand on it a bit for our sake. We will also be using a more mathy notation, in addition to the 
&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;en.wikipedia.org&amp;#x2F;wiki&amp;#x2F;Backus–Naur_form&quot; target=&quot;_blank&quot;&gt;BNF↪&lt;&#x2F;a&gt;
 above.&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\begin{aligned}
% expressions
e \in \textsf{Exp} &amp;::= x  \\
                   &amp;| \; (e\;e) \\
                   &amp;| \; lam \\
% variables
x \in \textsf{Var} &amp;\triangleq \text{The set of variables} \\
% lambdas
lam \in \textsf{Lam} &amp;::= (λ \; (x) \; e) \\
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;To read this notation, you need to take a look at the three parts. First, is the name of the metavariable. For the first line, the metavariable is &lt;code&gt;e&lt;&#x2F;code&gt;. When you see &lt;code&gt;e&lt;&#x2F;code&gt; in use, it is referring to this domain. Next is the name of the domain. Third, you have the definition. I use BNF style or &#x27;definitional equality&#x27; by my own choice. the &lt;code&gt;∈&lt;&#x2F;code&gt; symbol means &#x27;in&#x27;, or &#x27;is a member of domain&#x27;. So the first line reads, &quot;&lt;code&gt;e&lt;&#x2F;code&gt; is a member of the domain &#x27;Exp&#x27;, which is defined as these three productions&quot;.&lt;&#x2F;p&gt;
&lt;p&gt;There are 3 domains here, expressions, variables, and lambdas. These are the same as above, but now we have the name of the sets used, instead of just the metavariable names. If we see any &lt;code&gt;e&lt;&#x2F;code&gt;, then it is in the &lt;code&gt;Exp&lt;&#x2F;code&gt; domain. The same goes for &lt;code&gt;x&lt;&#x2F;code&gt; and &lt;code&gt;Var&lt;&#x2F;code&gt;. We may see multiple &lt;code&gt;e&lt;&#x2F;code&gt; metavariables used, but in this context, they can be filled in with different values. Later, when we are writing the semantics, we will differentiate metavariables of the same domain with subscripts or tick-marks.&lt;&#x2F;p&gt;
&lt;p&gt;I also factored the lambda &#x27;production&#x27; in the grammar into its own domain. This will be helpful in the semantic domain definitions.&lt;&#x2F;p&gt;
&lt;p&gt;The equal sign with the delta-triangle over it just means &#x27;is defined as&#x27;. In Computer Science and Math, &lt;code&gt;=&lt;&#x2F;code&gt; may mean &#x27;is the same as&#x27; or &#x27;is defined as&#x27;, so we use the Δ to differentiate the two.&lt;&#x2F;p&gt;
&lt;p&gt;Sometimes &lt;code&gt;::=&lt;&#x2F;code&gt; is used, and sometimes our &lt;code&gt;=&lt;&#x2F;code&gt; with &lt;code&gt;Δ&lt;&#x2F;code&gt; is used, why? Because using notation in this way is helpful. There arent strict rules here, and I found it useful to use BNF style for some domains, and definitional-equality for others. If you dont like it, you could perhaps give each production in the BNF grammar its own domain, and use a &#x27;
&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;en.wikipedia.org&amp;#x2F;wiki&amp;#x2F;Tagged_union&quot; target=&quot;_blank&quot;&gt;sum type↪&lt;&#x2F;a&gt;
&#x27; to define everything in terms of definitional equality.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;semantics&quot;&gt;Semantics&lt;&#x2F;h2&gt;
&lt;p&gt;The semantic domains include the definitions for the machine parts themselves. Exciting!&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\begin{aligned}
% Machine
\varsigma \in \Sigma &amp;\triangleq \textsf{Exp} \times \textit{Env} \\
					 &amp; \times \textit{Store} \times \textit{Kont} \\
% Env
\rho \in \textit{Env} &amp;\triangleq \textsf{Var} \rightarrow \textsf{Addr} \\
% Store
\sigma \in \textit{Store} &amp;\triangleq \textsf{Addr} \rightarrow \textsf{Val} \\
% Address
a \in \textit{Addr} &amp;\triangleq \mathbb{N} \\
% Value
v \in \textit{Val} &amp;\triangleq \textit{Clo} \\
% Closures
clo \in \textit{Clo} &amp;\triangleq \textsf{Lam} \times \textit{Env} \\
% Continuation
\kappa \in \textit{Kont} &amp;::= \textbf{mt} \\
						&amp; | \; \textbf{arg}(e, \rho, \kappa) \\
						&amp; | \; \textbf{fn}(v, \rho, \kappa) \\
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;So there are a lot of pieces here! Lets go through them! Dont worry if they dont make perfect sense just yet, it will make more sense when they are used in context in the next section.&lt;&#x2F;p&gt;
&lt;p&gt;First, the state definition itself. We have 4 components as previously defined. We use a &#x27;
&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;en.wikipedia.org&amp;#x2F;wiki&amp;#x2F;Product_type&quot; target=&quot;_blank&quot;&gt;product type↪&lt;&#x2F;a&gt;
&#x27; to say &#x27;One of each&#x27;. The domain is called Σ, or &#x27;sigma&#x27; (uppercase). When we only have one state, (much as we would have one number in the domain of &#x27;Integer&#x27;), we use ς, or &#x27;varsigma&#x27; (i dont understand ancient greek enough to get why its called that). To form a state, you take one of each of the constituent parts. Our machine takes a state as input, and returns a state.&lt;&#x2F;p&gt;
&lt;p&gt;Next, we need to define the environment and store. In computer science jargon, a map is simply a &#x27;partial function&#x27; from the input to the output. For the environment, the function takes a &lt;code&gt;Var&lt;&#x2F;code&gt;, and returns its &lt;code&gt;Addr&lt;&#x2F;code&gt;. The same is true of the store, which takes the address, and returns the value that it points to. The store isn&#x27;t particularly useful in this machine, but when we implement things like mutation, it will be good to have around.&lt;&#x2F;p&gt;
&lt;p&gt;Third, the address and value sets. In this simple machine, addresses will be very simple, we will use numbers to define them (the set with the fancy &lt;code&gt;N&lt;&#x2F;code&gt; is integers starting at 0 and going up to infinity).&lt;&#x2F;p&gt;
&lt;p&gt;Values in this machine are &#x27;
&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;en.wikipedia.org&amp;#x2F;wiki&amp;#x2F;Closure_(computer_programming)&quot; target=&quot;_blank&quot;&gt;closures↪&lt;&#x2F;a&gt;
&#x27;. Closures are a key part of higher order languages, such as Scheme, and are defined as a syntactic function (in our case the abstraction form), and an environment. In more advanced machines, values will be able to take on many different types, including numbers, strings, even continuations!&lt;&#x2F;p&gt;
&lt;p&gt;Finally, our definition of continuations. If you look closely, its a kind of linked list, meaning that a continuation has another continuation attached to it, until you get to the &lt;code&gt;mt&lt;&#x2F;code&gt; continuation, the end. Other than &lt;code&gt;mt&lt;&#x2F;code&gt;, there are two important &#x27;continuation frame&#x27; types. The &lt;code&gt;arg&lt;&#x2F;code&gt; continuation means that after we finish the current computation, we must evaluate the argument to the application. The &lt;code&gt;fn&lt;&#x2F;code&gt; frame tells us that after the current computation, we need to execute the function with the argument.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;injection-and-allocation&quot;&gt;Injection And Allocation&lt;&#x2F;h2&gt;
&lt;p&gt;As I mentioned earlier, our machine takes a state and returns a state, so how do we know what the &#x27;first&#x27; state is? To determine that, we create an &#x27;injection function&#x27;. This takes the program text as input, and returns the initial machine state that will evaluate it. Ours is quite simple:&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;inj : \textsf{Exp} \rightarrow \Sigma \\
inj(e) \triangleq (e , \emptyset , \emptyset , \textbf{mt}) \\&lt;&#x2F;script&gt;
&lt;p&gt;The top line is the type of the function &lt;code&gt;inj&lt;&#x2F;code&gt;, which states that it is a function that takes an expression, and returns a state. The next line is the definition, you will see that it takes an &lt;code&gt;e&lt;&#x2F;code&gt;, and returns a state, with the &lt;code&gt;e&lt;&#x2F;code&gt; as the control, empty sets for the environment and store, meaning that there are no mappings. the starting continuation is &#x27;mt&#x27;, meaning that there is nothing left to do after it is encountered.&lt;&#x2F;p&gt;
&lt;p&gt;We also need a way to make an address. A good allocator gives us an unused address, so that we dont step on any other variables toes. Lets define a simple alloc here:&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;alloc : \textit{Store} \rightarrow \textit{Addr} \\
alloc(\sigma) \triangleq |\sigma| \\&lt;&#x2F;script&gt;
&lt;p&gt;We define alloc as simply, &#x27;the amount of items in the store&#x27;. If the store is empty, the address return will be &lt;code&gt;0&lt;&#x2F;code&gt;, if there are 12 items, the address will be &lt;code&gt;12&lt;&#x2F;code&gt;. As long as we never implement garbage collection, this is guaranteed to always give us a clean, unused address!&lt;&#x2F;p&gt;
&lt;p&gt;The starting state is used to create the next state, and the state after that, until we reach the end of the program (or infinite loop! Thanks halting problem!). This is called a &#x27;state machine&#x27;. If you took a few computer science courses, you may be familiar with &#x27;finite state machines&#x27;. A programming language can be thought of as an &#x27;infinite state machine&#x27;, because we have &lt;em&gt;no idea&lt;&#x2F;em&gt; if it will end! Exciting! Mysterious!&lt;&#x2F;p&gt;
&lt;h1 id=&quot;transitions&quot;&gt;Transitions&lt;&#x2F;h1&gt;
&lt;p&gt;The machine we will be making is based off of a multitude of &#x27;state transition functions&#x27;, that say &quot;if the state looks like this, do that&quot;. When you combine all of these functions, you get a working machine, or what a lay-prorammer may call an &#x27;interpreter&#x27;!&lt;&#x2F;p&gt;
&lt;p&gt;So, without further ado, lets write out some state transition functions! We begin with something simple, variable lookup:&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;(x , \rho , \sigma , \kappa) \leadsto (lam , \rho_\lambda , \sigma , \kappa) \\
\begin{aligned}
\text{where } \sigma(\rho(x)) &amp;= (lam , \rho_\lambda) \\
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;We have finally defined our first semantic! If our control is some variable, then we need to look it up in the environment and store. If we find that they lead to a closure (a lambda and an environment), then we use them in the resulting state. I use the funky arrow cause I think it looks funny. I call it &#x27;drunk arrow&#x27;. You can read it as &#x27;leads to&#x27;.&lt;&#x2F;p&gt;
&lt;p&gt;Note that I used a regular &lt;code&gt;=&lt;&#x2F;code&gt; and i said &#x27;if we find&#x27; above. In the &#x27;where&#x27; clause, I am not stating what the variable lookup will be, but making a query. Luckily, the only thing that our store can hold at the moment is a closure, so its likely that the query succeeds.&lt;&#x2F;p&gt;
&lt;p&gt;But there is also the case that the variable does not exist. If the variable is not found, then this transition function does not go into effect. We call such a state a &#x27;stuck state&#x27;, there is no usable transition, so the state never changes. This can mean that we are &#x27;done&#x27;, and that there is no more computation left, or it could indicate some error. You could of course implement some semantic such as:&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;(x , \rho , \sigma , \kappa) \leadsto \text{ERROR-STATE} \\
\begin{aligned}
\text{where } \rho(x) &amp;= \text{NO-ENTRY-FOUND} \\
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;But then we would have to add error types to the state definition, and a lot more transitions to describe errors. Thats no fun, so I will leave boring stuff like that to &#x27;real&#x27; interpreter writers. Let&#x27;s just assume all programs given to our machine are &#x27;good&#x27; and dont get into any bad stuck states.&lt;&#x2F;p&gt;
&lt;p&gt;So if our machine consists only of the one semantic, it will never be used, because our environment and store are never added to, so no variable will ever be found. Let&#x27;s add some more semantics to alleviate that issue.&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;((e_f \; e_a) , \rho , \sigma , \kappa) \leadsto (e_f , \rho , \sigma , \kappa&#x27;) \\
\begin{aligned}
\text{where } \kappa&#x27; &amp;\triangleq \textbf{arg}(e_a , \rho , \kappa) \\
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;Now we can evaluate an &#x27;application&#x27; form. This is when well-defined semantics are really important. In our machine, we evaluate the first expression before the second. We are giving an explicit order of evaluation here. Why is the order of evaluation important? In more complex languages with mutable state, you can have undefined behavior if the order of evaluation is undefined. I will leave further research as an exercise to the esteemed reader.&lt;&#x2F;p&gt;
&lt;p&gt;We also change the continuation in the resultant state. The new continuation contains the second expression of the application, and the environment in which to evaluate the expression. It also contains the old continuation, so we can know what to do after we finish evaluating the current control.&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;(lam , \rho , \sigma , \textbf{arg}(e_a , \rho&#x27; , \kappa))
\leadsto (e_a , \rho&#x27; , \sigma , \textbf{fn}(lam , \rho , \kappa)) \\&lt;&#x2F;script&gt;
&lt;p&gt;This input state is more complex than the prior. If we have a value for the control (in our case, the control is a lambda), and if the current continuation is an &lt;code&gt;arg&lt;&#x2F;code&gt; frame, then we transition as shown. Wht this transition &#x27;means&#x27;, is that we are finished evaluating the left side of the application, and are now going to evaluate the right side.&lt;&#x2F;p&gt;
&lt;p&gt;Also pay attention to the environments, and what goes where. For the resulting state, we use the env found in the continuation, but in the resulting continuation, we use the environment given in the state. This is because the closure we are creating by pairing the lambda (control) requires the env it was found in.  But when we evaluate the right side of the application (e&lt;sub&gt;a&lt;&#x2F;sub&gt;
), we need to use the same environment that we originally used when evaluating the left side.&lt;&#x2F;p&gt;
&lt;p&gt;Take a little bit to think on that. The fact that we need to use the same environment for both elements of the application, and why the env that gets paired with the lambda is the one that it is.&lt;&#x2F;p&gt;
&lt;p&gt;After you understand that, lets finish this out with the final transition function for today.&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;(lam , \rho , \sigma , \textbf{fn}(lam&#x27; , \rho&#x27; , \kappa))
\leadsto (e , \rho&#x27;&#x27; , \sigma&#x27; , \kappa) \\
\begin{aligned}
\text{where } lam&#x27; &amp;= (λ \; (x) \; e) \\
			  a &amp;\triangleq alloc(\sigma) \\
			  \rho&#x27;&#x27; &amp;\triangleq \rho&#x27;[x \mapsto a] \\
			  \sigma&#x27; &amp;\triangleq \sigma[a \mapsto (lam , \rho)]
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;At this point, we have a lambda as the control, and a &lt;code&gt;fn&lt;&#x2F;code&gt; continuation frame. It is officially time to apply the application! The first part of the continuation frame is the function, and the current control is the argument. So we place the functions body as the new control, and add its argument (paired with the environment it was found in to form a closure) to the env&#x2F;store.&lt;&#x2F;p&gt;
&lt;p&gt;This is the most complex function in this machine. Make sure to internalize that in this machine, the only value is the closure. So, when we see a lambda, we have reached a value (when combined with an env). There 
&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;en.wikipedia.org&amp;#x2F;wiki&amp;#x2F;Church_encoding&quot; target=&quot;_blank&quot;&gt;are ways↪&lt;&#x2F;a&gt;
 to ues closures to represent common datatypes such as numbers, or lists. These ways are how lambda calculus continues to be used as the basis for minimalistic languages such as scheme. But it makes programs hard to read, so we add integers anyways!&lt;&#x2F;p&gt;
&lt;h1 id=&quot;the-completed-machine&quot;&gt;The Completed Machine&lt;&#x2F;h1&gt;
&lt;p&gt;And just like that, we have the 4 transition functions that define a standard &#x27;call-by-value&#x27; lambda calculus. Lets put them together for posterity:&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;(x , \rho , \sigma , \kappa) \leadsto (v , \rho_\lambda , \sigma , \kappa) \\
\begin{aligned}
\text{where } \sigma(\rho(x)) &amp;= (v , \rho_\lambda) \\
\end{aligned}&lt;&#x2F;script&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;((e_f \; e_a) , \rho , \sigma , \kappa) \leadsto (e_f , \rho , \sigma , \kappa&#x27;) \\
\begin{aligned}
\text{where } \kappa&#x27; &amp;\triangleq \textbf{arg}(e_a , \rho , \kappa) \\
\end{aligned}&lt;&#x2F;script&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;(lam , \rho , \sigma , \textbf{arg}(e_a , \rho&#x27; , \kappa))
\leadsto (e_a , \rho&#x27; , \sigma , \textbf{fn}(lam , \rho , \kappa)) \\&lt;&#x2F;script&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;(lam , \rho , \sigma , \textbf{fn}(lam&#x27; , \rho&#x27; , \kappa))
\leadsto (e , \rho&#x27;&#x27; , \sigma&#x27; , \kappa) \\
\begin{aligned}
\text{where } lam&#x27; &amp;= (λ \; (x) \; e) \\
			  a &amp;\triangleq alloc(\sigma) \\
			  \rho&#x27;&#x27; &amp;\triangleq \rho&#x27;[x \mapsto a] \\
			  \sigma&#x27; &amp;\triangleq \sigma[a \mapsto (lam , \rho)]
\end{aligned}&lt;&#x2F;script&gt;
&lt;p&gt;The machine works by combining each of these into one big function, much like the 
&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;en.wikipedia.org&amp;#x2F;wiki&amp;#x2F;Piecewise&quot; target=&quot;_blank&quot;&gt;piece-wise function↪&lt;&#x2F;a&gt;
 you learned in math class. Lets give this function the name &lt;code&gt;step&lt;&#x2F;code&gt;.&lt;&#x2F;p&gt;
&lt;h1 id=&quot;an-example-run&quot;&gt;An Example Run&lt;&#x2F;h1&gt;
&lt;p&gt;To evaluate a function, we continuously execute our transition functions until we reach a stuck-state. That final state is the return value of our program.&lt;&#x2F;p&gt;
&lt;p&gt;Lets take our example from before, and run it by hand.&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;e_0 = ((\lambda \; (q) \; (\lambda \; (b) \; q)) \; (\lambda \; (\text{blerp}) \; \text{WORD})) \\
\varsigma_0 = inj(e_0) = (e_0 , \emptyset , \emptyset , \textbf{mt}) \\
\varsigma_n = step(\varsigma_{n-1}) \\
\;\\
%
\varsigma_1 = ((\lambda \; (q) \; (\lambda \; (b) \; q)) , \emptyset , \emptyset , \textbf{arg}((\lambda \; (\text{blerp}) \; \text{WORD}) , \emptyset , \textbf{mt})) \\
%
\varsigma_2 = ((\lambda \; (\text{blerp}) \; \text{WORD}) , \emptyset , \emptyset , \textbf{fn}((\lambda \; (q) \; (\lambda \; (b) \; q)) , \emptyset , \textbf{mt})) \\
%
\varsigma_3 = ((\lambda \; (b) \; q) , \{q : 0\} , \{0 : (\lambda \; (\text{blerp}) \; \text{WORD})\} , \textbf{mt}) \\&lt;&#x2F;script&gt;
&lt;p&gt;ς&lt;sub&gt;3&lt;&#x2F;sub&gt;
 is the final state, if we run &lt;code&gt;step&lt;&#x2F;code&gt; again, no applicable input is found. Try to write the steps out more explicitly on some paper, and see for yourself that this is the final state.&lt;&#x2F;p&gt;
&lt;p&gt;The key insight to understand that  ς&lt;sub&gt;3&lt;&#x2F;sub&gt;
 is the final state is that we are at an &#x27;atomic&#x27; value with an empty continuation. Atomic in this case means we can&#x27;t break it down further, like we could a variable or and application form.&lt;&#x2F;p&gt;
&lt;h1 id=&quot;whats-next&quot;&gt;Whats next&lt;&#x2F;h1&gt;
&lt;p&gt;Well, we have a turing complete language, what&#x27;s the point in doing anything else? Language features to make this machine usable?? Fine! Stay tuned and next time we will implement &#x27;useful&#x27; things, like numbers, and &lt;code&gt;if&lt;&#x2F;code&gt;. I promise that it will be shorter than this post.&lt;&#x2F;p&gt;
&lt;p&gt;See you next time!&lt;&#x2F;p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Crafting Semantics 0: Introduction</title>
        <published>2021-01-05T12:15:00-05:00</published>
        <updated>2021-01-05T12:15:00-05:00</updated>
        
        <author>
          <name>
            
              Unknown
            
          </name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://thedav.is/post/crafting-semantics-0/"/>
        <id>https://thedav.is/post/crafting-semantics-0/</id>
        
        <content type="html" xml:base="https://thedav.is/post/crafting-semantics-0/">&lt;h1 id=&quot;introduction&quot;&gt;Introduction&lt;&#x2F;h1&gt;
&lt;p&gt;Hi, this is the first post on a series about creating semantics for a programming language. We will be using Scheme as a reference point, and slowly building more and more features for it.&lt;&#x2F;p&gt;
&lt;p&gt;We will be using &#x27;&lt;em&gt;computer science notation&lt;&#x2F;em&gt;&#x27; (specifically an operational semantics) for every post. We won&#x27;t be implementing these semantics in a &#x27;real&#x27; programming language, but you could quite easily if you wanted to.&lt;&#x2F;p&gt;
&lt;p&gt;If you want to get started in Programming Language Theory, and want to understand how to define a programming language formally, this is the series for you! If you want to understand abstract machines better, this is the series for you!&lt;&#x2F;p&gt;
&lt;h1 id=&quot;what-does-all-of-this-mean&quot;&gt;What does all of this mean?&lt;&#x2F;h1&gt;
&lt;p&gt;We will be building a programming language! But instead of writing a parser, interpreter, compiler, etc. for it, we will simply define it mathematically. When you have a rigorously defined semantics, it should be quite easy to make a &#x27;real&#x27; interpreter out of it.&lt;&#x2F;p&gt;
&lt;p&gt;For a mostly &#x27;finished&#x27; product, I have semantics for many forms of Scheme &lt;a href=&quot;https:&#x2F;&#x2F;github.com&#x2F;sinistersnare&#x2F;aams&#x2F;blob&#x2F;master&#x2F;latex&#x2F;formalism.pdf&quot;&gt;here in a Git repository&lt;&#x2F;a&gt;. Also included in that repo are implementations in Racket and Rust. We may or may not deviate from it as I see fit, but that will be what the semantics will look like. If this series goes far enough, I may delve into the abstract semantics section of that document, and talk about static analysis!&lt;&#x2F;p&gt;
&lt;h1 id=&quot;semantics&quot;&gt;Semantics&lt;&#x2F;h1&gt;
&lt;p&gt;The semantics of a language are how its syntax is interpreted by a reader (either human or machine). Like many things in Programming Language Theory, we have stolen this term from the field of linguistics (thanks!). Computer scientists use semantics to study programming languages. You can learn more about them in my &lt;a href=&quot;https:&#x2F;&#x2F;thedav.is&#x2F;post&#x2F;abstract-machines&#x2F;&quot;&gt;&#x27;Abstract Machines&#x27; post&lt;&#x2F;a&gt;.&lt;&#x2F;p&gt;
&lt;h1 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;&#x2F;h1&gt;
&lt;p&gt;There will be no &#x27;programming&#x27; in this series, only notation. I will try to explain all notation as it is first used.&lt;&#x2F;p&gt;
&lt;p&gt;All I ask is that you are interested in the topic at hand!&lt;&#x2F;p&gt;
&lt;h1 id=&quot;let-s-begin&quot;&gt;Let&#x27;s begin!&lt;&#x2F;h1&gt;
&lt;p&gt;We will start after that post, with a CESK machine based on the lambda calculus. See &lt;a href=&quot;https:&#x2F;&#x2F;thedav.is&#x2F;post&#x2F;crafting-semantics-1&#x2F;&quot;&gt;The next post&lt;&#x2F;a&gt; for the exciting start to this series!&lt;&#x2F;p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Continuations as First Class Return</title>
        <published>2020-11-30T12:15:00-05:00</published>
        <updated>2020-11-30T12:15:00-05:00</updated>
        
        <author>
          <name>
            
              Unknown
            
          </name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://thedav.is/post/continuations-as-return/"/>
        <id>https://thedav.is/post/continuations-as-return/</id>
        
        <content type="html" xml:base="https://thedav.is/post/continuations-as-return/">&lt;p&gt;This post can serve as an extra-light introduction to continuations.
If you have not heard of, or are confused by continuations,
this post may be for you!&lt;&#x2F;p&gt;
&lt;p&gt;This will be the first post of a series on continuations.
We start with a short introduction to the idea of first-class control.
In the future, I may introduce topics like &lt;code&gt;dynamic-wind&lt;&#x2F;code&gt;, or maybe just more interesting uses of continuations, like ambiguous functions.
I eventually want to get to the downsides of these undelimited continuations, and then introduce
delimited continuations. If none of that made sense, awesome! Enjoy!&lt;&#x2F;p&gt;
&lt;h1 id=&quot;first-class&quot;&gt;First Class&lt;&#x2F;h1&gt;
&lt;p&gt;You may be familiar with the concept of first class functions. Where you can use functions as regular-old values, and treat them like anything else in a language.&lt;&#x2F;p&gt;
&lt;pre data-lang=&quot;python&quot; style=&quot;background-color:#282a36;color:#f8f8f2;&quot; class=&quot;language-python &quot;&gt;&lt;code class=&quot;language-python&quot; data-lang=&quot;python&quot;&gt;&lt;span style=&quot;font-style:italic;color:#ff79c6;&quot;&gt;def &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;foo&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;a&lt;&#x2F;span&gt;&lt;span&gt;):
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;...
&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ff79c6;&quot;&gt;def &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;bar&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;b&lt;&#x2F;span&gt;&lt;span&gt;):
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;...
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;...
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;if &lt;&#x2F;span&gt;&lt;span&gt;x &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;&amp;lt; &lt;&#x2F;span&gt;&lt;span&gt;y:
&lt;&#x2F;span&gt;&lt;span&gt;    which &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span&gt;foo
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;else&lt;&#x2F;span&gt;&lt;span&gt;:
&lt;&#x2F;span&gt;&lt;span&gt;    which &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span&gt;bar
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;value &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;which&lt;&#x2F;span&gt;&lt;span&gt;(x)
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;p&gt;Here we decide which function to use based on some condition. We can also have functions take functions as arguments.&lt;&#x2F;p&gt;
&lt;pre data-lang=&quot;python&quot; style=&quot;background-color:#282a36;color:#f8f8f2;&quot; class=&quot;language-python &quot;&gt;&lt;code class=&quot;language-python&quot; data-lang=&quot;python&quot;&gt;&lt;span style=&quot;font-style:italic;color:#ff79c6;&quot;&gt;def &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;add1&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;x&lt;&#x2F;span&gt;&lt;span&gt;):
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;return &lt;&#x2F;span&gt;&lt;span&gt;x &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;+ &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;1
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;better &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#8be9fd;&quot;&gt;map&lt;&#x2F;span&gt;&lt;span&gt;(add1, [&lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;1&lt;&#x2F;span&gt;&lt;span&gt;,&lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;2&lt;&#x2F;span&gt;&lt;span&gt;,&lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;3&lt;&#x2F;span&gt;&lt;span&gt;,&lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;4&lt;&#x2F;span&gt;&lt;span&gt;])
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;# better == [2,3,4,5]
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;p&gt;Functions are just like any other value in many modern languages. They are at the same status as integers, or strings.
This is really nice, and programmers have decided that this is overall a nice-to-have feature.&lt;&#x2F;p&gt;
&lt;p&gt;So, lets go further! Let&#x27;s make more things first-class.&lt;&#x2F;p&gt;
&lt;h1 id=&quot;return&quot;&gt;Return&lt;&#x2F;h1&gt;
&lt;p&gt;What does it mean to have a first class return? It means promoting an important control-flow primitive into something that programmers have power over.
By having a first class return, we turn the idea of returning into a value that can be passed around, same as an integer, or a function.&lt;&#x2F;p&gt;
&lt;p&gt;Lets pretend our language no longer has a return statement, and we can only return by using first-class return values. Lets have &lt;code&gt;return&lt;&#x2F;code&gt; be the
final argument to any function.&lt;&#x2F;p&gt;
&lt;pre data-lang=&quot;python&quot; style=&quot;background-color:#282a36;color:#f8f8f2;&quot; class=&quot;language-python &quot;&gt;&lt;code class=&quot;language-python&quot; data-lang=&quot;python&quot;&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;# We call the return argument `exit`
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;# in the main function.
&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ff79c6;&quot;&gt;def &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;main&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;exit&lt;&#x2F;span&gt;&lt;span&gt;):
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;compute&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;12&lt;&#x2F;span&gt;&lt;span&gt;, exit)
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ff79c6;&quot;&gt;def &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;compute&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;x&lt;&#x2F;span&gt;&lt;span&gt;, &lt;&#x2F;span&gt;&lt;span style=&quot;background-color:#ff79c6;color:#f8f8f0;&quot;&gt;return&lt;&#x2F;span&gt;&lt;span&gt;):
&lt;&#x2F;span&gt;&lt;span&gt;    y &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span&gt;x &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;&#x2F; &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;3
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;return&lt;&#x2F;span&gt;&lt;span&gt;(y)
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;p&gt;In the &lt;code&gt;main&lt;&#x2F;code&gt; function, we are given a value that we named &lt;code&gt;exit&lt;&#x2F;code&gt; instead of &lt;code&gt;return&lt;&#x2F;code&gt;. Of course, these are variables so we can call them whatever
we want. This &lt;code&gt;exit&lt;&#x2F;code&gt; argument, when called, will take you to the exited state of the program, when given a return value. Much like how
in C we can return an integer at the end of the &lt;code&gt;main&lt;&#x2F;code&gt; procedure, and the caller of the C program can use that value however it wants.&lt;&#x2F;p&gt;
&lt;p&gt;The &lt;code&gt;compute&lt;&#x2F;code&gt; function is almost identical to one in a current programming language. The difference is that we have &lt;code&gt;return&lt;&#x2F;code&gt; as an argument now,
a value. We call the &lt;code&gt;return&lt;&#x2F;code&gt; argument like a function, &lt;em&gt;&lt;strong&gt;but they are different&lt;&#x2F;strong&gt;&lt;&#x2F;em&gt;. these values do not go back eventually like a function would.
When we call &lt;code&gt;y = foo(x)&lt;&#x2F;code&gt;, eventually &lt;code&gt;foo&lt;&#x2F;code&gt; will return and &lt;code&gt;y&lt;&#x2F;code&gt; will be filled with some value. But in these special &lt;code&gt;return&lt;&#x2F;code&gt; things,
we alter the &#x27;control&#x27; of the program to somewhere else.&lt;&#x2F;p&gt;
&lt;p&gt;Lets call these values &lt;code&gt;continuations&lt;&#x2F;code&gt;. As in, where to &#x27;continue&#x27; to by calling it.&lt;&#x2F;p&gt;
&lt;p&gt;A great thing about having continuations is that they can be passed around like any value, so we can return from some deeply nested function easily if need be.&lt;&#x2F;p&gt;
&lt;p&gt;However, right now, the only actual continuation value we have seen is the &lt;code&gt;exit&lt;&#x2F;code&gt; continuation, that is provided as a way to quit the program. We have been passing it around, but, how do we get any continuation?
If I want to call &lt;code&gt;var = foo(42, ???)&lt;&#x2F;code&gt; How do I get a continuation that will return and then fill in &lt;code&gt;var&lt;&#x2F;code&gt;?
Lets use an operator called &lt;code&gt;cc&lt;&#x2F;code&gt;, the &#x27;current continuation&#x27;:&lt;&#x2F;p&gt;
&lt;pre data-lang=&quot;python&quot; style=&quot;background-color:#282a36;color:#f8f8f2;&quot; class=&quot;language-python &quot;&gt;&lt;code class=&quot;language-python&quot; data-lang=&quot;python&quot;&gt;&lt;span style=&quot;font-style:italic;color:#ff79c6;&quot;&gt;def &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;compute&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;x&lt;&#x2F;span&gt;&lt;span&gt;, &lt;&#x2F;span&gt;&lt;span style=&quot;background-color:#ff79c6;color:#f8f8f0;&quot;&gt;return&lt;&#x2F;span&gt;&lt;span&gt;):
&lt;&#x2F;span&gt;&lt;span&gt;    y &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span&gt;x &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;&#x2F; &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;3
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;return&lt;&#x2F;span&gt;&lt;span&gt;(y)
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ff79c6;&quot;&gt;def &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;main&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;exit&lt;&#x2F;span&gt;&lt;span&gt;):
&lt;&#x2F;span&gt;&lt;span&gt;    y &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;compute&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;12&lt;&#x2F;span&gt;&lt;span&gt;, cc)
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#8be9fd;&quot;&gt;print&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;color:#f1fa8c;&quot;&gt;&amp;quot;Got: &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;{y}&lt;&#x2F;span&gt;&lt;span style=&quot;color:#f1fa8c;&quot;&gt;&amp;quot;&lt;&#x2F;span&gt;&lt;span&gt;, cc)
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;exit&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;9001&lt;&#x2F;span&gt;&lt;span&gt;)
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;p&gt;This &lt;code&gt;cc&lt;&#x2F;code&gt; operator reckons what the current computation is, and creates a continuation for that. In our line &lt;code&gt;y = compute(12, cc)&lt;&#x2F;code&gt;, &lt;code&gt;cc&lt;&#x2F;code&gt; knows that after
the function ends, it is going to place the returned value into the variable &lt;code&gt;y&lt;&#x2F;code&gt;. The &lt;code&gt;cc&lt;&#x2F;code&gt; in the call to &lt;code&gt;print&lt;&#x2F;code&gt; is used so that the program
will simply continue running, as no variable is assigned anywhere. Then we use the &lt;code&gt;exit&lt;&#x2F;code&gt; continuation to end the program with a nice and big number.&lt;&#x2F;p&gt;
&lt;p&gt;With the &lt;code&gt;cc&lt;&#x2F;code&gt; operator, we can now fulfill our goal of &#x27;early return&#x27; semantics.&lt;&#x2F;p&gt;
&lt;pre data-lang=&quot;python&quot; style=&quot;background-color:#282a36;color:#f8f8f2;&quot; class=&quot;language-python &quot;&gt;&lt;code class=&quot;language-python&quot; data-lang=&quot;python&quot;&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;# In the world where this program exists,
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;# 73 is a _VERY BAD NUMBER_, dont trust it.
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;# We must make sure all input does not contain 73.
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;# If an illegal number is found, we bail
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;# out to `bad_return` with an error message
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;# Otherwise, we return to `good_return`
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;# with the value.
&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ff79c6;&quot;&gt;def &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;sanitize&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;x&lt;&#x2F;span&gt;&lt;span&gt;, &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;bad_return&lt;&#x2F;span&gt;&lt;span&gt;, &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;good_return&lt;&#x2F;span&gt;&lt;span&gt;):
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;if &lt;&#x2F;span&gt;&lt;span&gt;x &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;- &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;1 &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;== &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;72&lt;&#x2F;span&gt;&lt;span&gt;:
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;bad_return&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;color:#f1fa8c;&quot;&gt;&amp;quot;NO EVIL ALLOWED HERE&amp;quot;&lt;&#x2F;span&gt;&lt;span&gt;)
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;else&lt;&#x2F;span&gt;&lt;span&gt;:
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;good_return&lt;&#x2F;span&gt;&lt;span&gt;(x)
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ff79c6;&quot;&gt;def &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;get_value_from_world&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;background-color:#ff79c6;color:#f8f8f0;&quot;&gt;return&lt;&#x2F;span&gt;&lt;span&gt;):
&lt;&#x2F;span&gt;&lt;span&gt;    value &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;get_maybe_dangerous_input&lt;&#x2F;span&gt;&lt;span&gt;(cc)
&lt;&#x2F;span&gt;&lt;span&gt;    good &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;sanitize&lt;&#x2F;span&gt;&lt;span&gt;(value, &lt;&#x2F;span&gt;&lt;span style=&quot;background-color:#ff79c6;color:#f8f8f0;&quot;&gt;return&lt;&#x2F;span&gt;&lt;span&gt;, cc&lt;&#x2F;span&gt;&lt;span style=&quot;background-color:#ff79c6;color:#f8f8f0;&quot;&gt;)&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;return&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;color:#f1fa8c;&quot;&gt;&amp;quot;Got good value &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;{good}&lt;&#x2F;span&gt;&lt;span style=&quot;color:#f1fa8c;&quot;&gt;!&amp;quot;&lt;&#x2F;span&gt;&lt;span&gt;)
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ff79c6;&quot;&gt;def &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;main&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;exit&lt;&#x2F;span&gt;&lt;span&gt;):
&lt;&#x2F;span&gt;&lt;span&gt;    important_val &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;get_value_from_world&lt;&#x2F;span&gt;&lt;span&gt;(cc)
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;prin&lt;&#x2F;span&gt;&lt;span&gt;(important_val, cc)
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;exit&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;color:#f1fa8c;&quot;&gt;&amp;quot;nothing bad going on here&amp;quot;&lt;&#x2F;span&gt;&lt;span&gt;)
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;p&gt;Here, we are able to exit out of our computation if we find ourselves in a tricky situation.
Normally, we may accomplish this through an exception-based system. You would have a convoluted
try-catch system just to watch for a single error-case... good luck getting through code review!
But now, we have the power to bail out without having an extra system!&lt;&#x2F;p&gt;
&lt;h1 id=&quot;conclusion&quot;&gt;Conclusion&lt;&#x2F;h1&gt;
&lt;p&gt;Continuations are really powerful, and still under active research!
Having first-class control is really cool. They are basically a &lt;code&gt;goto&lt;&#x2F;code&gt;,
but more computer-sciencey.&lt;&#x2F;p&gt;
&lt;p&gt;Current research on continuations includes making them safer and more efficient.
Perhaps in the future, &lt;code&gt;return&lt;&#x2F;code&gt; statements will simply be a syntactic sugar
for an implicit argument given to functions. That way, you can take multiple
return points as arguments, and then decide where you want to go next,&lt;&#x2F;p&gt;
&lt;p&gt;If this blog post interested you, but didnt have enough info, stay tuned!&lt;&#x2F;p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Abstract Machines: Interpreters for Computer Scientists</title>
        <published>2020-11-09T12:15:00-05:00</published>
        <updated>2020-11-09T12:15:00-05:00</updated>
        
        <author>
          <name>
            
              Unknown
            
          </name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://thedav.is/post/abstract-machines/"/>
        <id>https://thedav.is/post/abstract-machines/</id>
        
        <content type="html" xml:base="https://thedav.is/post/abstract-machines/">&lt;h1 id=&quot;introduction&quot;&gt;Introduction&lt;&#x2F;h1&gt;
&lt;p&gt;So im a PhD student now, so I need to write about cool computer science things!
As part of my learnings, I have been writing a bunch of &#x27;Abstract Machines&#x27;.
I think of them as how computer scientists do programming languages research without computers.
I mean, they have to use &lt;em&gt;something&lt;&#x2F;em&gt; to write their super complex papers.&lt;&#x2F;p&gt;
&lt;blockquote&gt;
&lt;p&gt;&quot;Computer Science is no more about computers than astronomy is about telescopes&quot;&lt;&#x2F;p&gt;
&lt;ul&gt;
&lt;li&gt;Edsger Dijkstra&lt;&#x2F;li&gt;
&lt;&#x2F;ul&gt;
&lt;&#x2F;blockquote&gt;
&lt;p&gt;We love computers, but they are merely a tool of computing. The real study
of computation can be done without them, and the theories of how programming
languages function is not excluded from that. So how do computer scientists
study interpreters without a computer? The theory of
abstract machines is one of the more popular ways.&lt;&#x2F;p&gt;
&lt;h1 id=&quot;how-to-compute&quot;&gt;How to Compute&lt;&#x2F;h1&gt;
&lt;p&gt;What does it mean to compute something? Humans are pretty good at just looking at things
and formulating an answer. For example, a person does not use a sorting algorithm when matching
socks after their laundry is finished. But computers can&#x27;t just intuit a solution. They are given
precise instructions on what to do to accomplish something. So how can we model that,
and use it to inform the science behind computation?&lt;&#x2F;p&gt;
&lt;p&gt;&#x27;Abstract Machines&#x27; were created to model real computation strategies. These are functions that take program states, and return some value. Program states can be composed of many different things. The simplest abstract machines simply use the current point that the program is at. Others include a mapping of variables to values, so we can keep state around. We will describe such machines, and what kind of languages they can describe.&lt;&#x2F;p&gt;
&lt;p&gt;These machines, in practice, are interpreters. They are called &#x27;abstract&#x27; because the theory on them is not specific to any exact language. You can make an abstract machine for whatever you could want: Lisp, Java bytecode, RISC-V assembly language...&lt;&#x2F;p&gt;
&lt;h1 id=&quot;digression-operational-semantics&quot;&gt;Digression: Operational Semantics&lt;&#x2F;h1&gt;
&lt;p&gt;Operational Semantics are how we can write semantics of a language
using pen and paper. Using a simple syntax, we can get the idea of
&#x27;if the syntax looks like this, it can be evaluated into this&#x27;.&lt;&#x2F;p&gt;
&lt;p&gt;The idea of semantics is separate from execution of a program. Semantics describe what something &#x27;means&#x27;, based on how it looks. Here are two different kinds of &#x27;operational semantics&#x27;, big-step and small-step.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;big-step&quot;&gt;Big Step&lt;&#x2F;h2&gt;
&lt;p&gt;Big step evaluations have the type &lt;code&gt;State -&amp;gt; Value&lt;&#x2F;code&gt;,
meaning that you give them a state, and it will tell you which value
it exactly evaluates to. These are nice and simple generally, because they
give you the values in a single step.&lt;&#x2F;p&gt;
&lt;p&gt;To use a small example expression, &lt;code&gt;if cond then e_true else e_false&lt;&#x2F;code&gt;
there are two rules that will be used.&lt;&#x2F;p&gt;
&lt;ol&gt;
&lt;li&gt;If cond evaluates to &lt;code&gt;true&lt;&#x2F;code&gt;, then the result is what &lt;code&gt;e_true&lt;&#x2F;code&gt; evaluates to.&lt;&#x2F;li&gt;
&lt;li&gt;If cond evaluates to &lt;code&gt;false&lt;&#x2F;code&gt;, then the result is what &lt;code&gt;e_false&lt;&#x2F;code&gt; evaluates to.&lt;&#x2F;li&gt;
&lt;&#x2F;ol&gt;
&lt;p&gt;These rules assume that we have some way to fully evaluate whatever &lt;code&gt;cond&lt;&#x2F;code&gt; is. But whatever that way is is unimportant to the rule of evaluating &lt;code&gt;if&lt;&#x2F;code&gt; statements. This separation is very important for operational semantics. We can write small rules for specific parts of the language, all of which get composed together into a fully formalized machine.&lt;&#x2F;p&gt;
&lt;p&gt;I like using big step when thinking exactly about what expressions &lt;em&gt;do&lt;&#x2F;em&gt;.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;small-step&quot;&gt;Small Step&lt;&#x2F;h2&gt;
&lt;p&gt;Small step semantics have the type &lt;code&gt;State -&amp;gt; State&lt;&#x2F;code&gt;. They will
show you what to do step by step to evaluate a term. They work iteratively,
explicitly, to show how a given state is computed.&lt;&#x2F;p&gt;
&lt;p&gt;For example, if the term is &lt;code&gt;if cond then e_true else e_false&lt;&#x2F;code&gt;,
There will be a few different rules.&lt;&#x2F;p&gt;
&lt;ol&gt;
&lt;li&gt;If cond is an atomic value, and that value is &lt;code&gt;true&lt;&#x2F;code&gt;, the resulting state is &lt;code&gt;e_true&lt;&#x2F;code&gt;.&lt;&#x2F;li&gt;
&lt;li&gt;If cond is an atomic value, and that value is &lt;code&gt;false&lt;&#x2F;code&gt;, the resulting state is &lt;code&gt;e_false&lt;&#x2F;code&gt;.&lt;&#x2F;li&gt;
&lt;li&gt;If cond is not an atomic value, then evaluate it to &lt;code&gt;cond&#x27;&lt;&#x2F;code&gt; , and return &lt;code&gt;if cond&#x27; then e_true else e_false&lt;&#x2F;code&gt;.&lt;&#x2F;li&gt;
&lt;&#x2F;ol&gt;
&lt;p&gt;An atomic value is a value that can not be broken up any more. This means a datatype, not a complex expression. In these simple machines, the only atomic datatype is a number. Don&#x27;t tell computer scientists about quarks, they may go insane.&lt;&#x2F;p&gt;
&lt;p&gt;By going from a state to a next state, small step mechanics more closely follow
how our computers work. They dont evaluate to values directly, they just... keep going.&lt;&#x2F;p&gt;
&lt;p&gt;This may confuse a new reader, if it keeps going, how do we know its done? Big step rules
directly result in a value, full stop. How do we know a state in small step semantics is the one with the value? We use what is called a &#x27;fixpoint&#x27;, or more simply, we evaluate until there isnt a meaningful change in the state after running. If we evaluate a math expression enough times,
it will decompose into a single number, upon which evaluation will lead to itself. That means there is no more work to be done, and evaluation stops.&lt;&#x2F;p&gt;
&lt;p&gt;The same is true in a language like &lt;code&gt;C&lt;&#x2F;code&gt;, after the final instruction in &lt;code&gt;main&lt;&#x2F;code&gt;, if we try to evaluate any more, nothing will happen, theres nothing left to do. That is a fixpoint.&lt;&#x2F;p&gt;
&lt;p&gt;Small step semantics are a bit more precise in my opinion, and they are much easier to translate
to &lt;em&gt;real&lt;&#x2F;em&gt; interpreters. But it is very useful to understand both styles, they have different uses. Using small steps, we can also more closely trace how an expression is evaluated.&lt;&#x2F;p&gt;
&lt;h1 id=&quot;a-simple-abstract-machine-c&quot;&gt;A Simple Abstract Machine - C&lt;&#x2F;h1&gt;
&lt;p&gt;I dont mean the the C language, especially because I would not use simple to describe it!
C in this case stands for &#x27;control&#x27;. You may remember things like &#x27;if&#x27; are called &#x27;control flow
operators&#x27;. Control is the currently running &#x27;thing&#x27; in your program. The &lt;code&gt;if&lt;&#x2F;code&gt; operator, is a way to change the control based on a condition. This machine will be called
the C machine because you only need control to represent the state of the entire program.&lt;&#x2F;p&gt;
&lt;p&gt;C machines are not capable of much, only simple rewriting of expresions, because they dont have any information other than the program&#x27;s control itself to go off of.
One kind of language we can formalize with a C machine is that of mathematical expressions.&lt;&#x2F;p&gt;
&lt;p&gt;Here is a big-step semantics of type &lt;script type=&quot;math&#x2F;tex&quot;&gt;MathExp \Downarrow Number&lt;&#x2F;script&gt;
 (takes a math expression and returns a number). This means that the control we choose to use is a math expression. The result of evaluating a math expression is a number, of course, so thats the value.&lt;&#x2F;p&gt;
&lt;p&gt;&lt;script type=&quot;math&#x2F;tex&quot;&gt;Addition:&lt;&#x2F;script&gt;

&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\frac{e_1 \Downarrow n_1 \;,\; e_2 \Downarrow n_2 \;,\; n_1+n_2 = n }
     {e_1+e_2 \Downarrow n}&lt;&#x2F;script&gt;
&lt;&#x2F;p&gt;
&lt;p&gt;This rule shows how to add expressions to end up with a number. You can understand it by reading the half under the bar as &#x27;this is what we start and end with&#x27; and the half above the bar as &#x27;these must be true to use these semantics&#x27;. You read &lt;script type=&quot;math&#x2F;tex&quot;&gt;\Downarrow&lt;&#x2F;script&gt;
 as &#x27;evalutes to&#x27;.&lt;&#x2F;p&gt;
&lt;p&gt;You can read this rule like so:&lt;&#x2F;p&gt;
&lt;ol&gt;
&lt;li&gt;If we have some control that looks like &lt;script type=&quot;math&#x2F;tex&quot;&gt;e_1 + e_2&lt;&#x2F;script&gt;
 (this is from the bottom left, before the arrow)&lt;&#x2F;li&gt;
&lt;li&gt;if &lt;script type=&quot;math&#x2F;tex&quot;&gt;e_1&lt;&#x2F;script&gt;
 evaluates to some number &lt;script type=&quot;math&#x2F;tex&quot;&gt;n_1&lt;&#x2F;script&gt;
 (the first expression above the bar),&lt;&#x2F;li&gt;
&lt;li&gt;if &lt;script type=&quot;math&#x2F;tex&quot;&gt;e_2&lt;&#x2F;script&gt;
 evaluates to some number &lt;script type=&quot;math&#x2F;tex&quot;&gt;n_2&lt;&#x2F;script&gt;
 (the second expression above the bar),&lt;&#x2F;li&gt;
&lt;li&gt;if &lt;script type=&quot;math&#x2F;tex&quot;&gt;n_1&lt;&#x2F;script&gt;
 added to &lt;script type=&quot;math&#x2F;tex&quot;&gt;n_2&lt;&#x2F;script&gt;
 is equal to some number &lt;script type=&quot;math&#x2F;tex&quot;&gt;n&lt;&#x2F;script&gt;
 (the third expression above the bar).&lt;&#x2F;li&gt;
&lt;li&gt;THEN we know that the expression in step 1 evaluates to &lt;script type=&quot;math&#x2F;tex&quot;&gt;n&lt;&#x2F;script&gt;
.&lt;&#x2F;li&gt;
&lt;&#x2F;ol&gt;
&lt;p&gt;This may seem a bit backwards, we implement adding by adding? Well, the key is that expressions are complex, they can be composed of other expressions or just values. These rules show how to do math on expressions by first evaluating them to values. Then once they are values, it is quite easy to do math operations on them.&lt;&#x2F;p&gt;
&lt;p&gt;Note the distinction between the arrow &lt;script type=&quot;math&#x2F;tex&quot;&gt;\Downarrow&lt;&#x2F;script&gt;
 and &lt;script type=&quot;math&#x2F;tex&quot;&gt;=&lt;&#x2F;script&gt;
 here. &lt;script type=&quot;math&#x2F;tex&quot;&gt;\Downarrow&lt;&#x2F;script&gt;
 is saying &quot;left evaluates to right by virtue of applying this machine&#x27;s rules.&quot; and &lt;script type=&quot;math&#x2F;tex&quot;&gt;=&lt;&#x2F;script&gt;
 is saying &quot;you can substitute left for right&quot;.&lt;&#x2F;p&gt;
&lt;p&gt;Authors of semantics like these love to use different looking arrow symbols, they all mean the same thing. Usually in big step they use a cool down-facing arrow like &lt;script type=&quot;math&#x2F;tex&quot;&gt;\Downarrow&lt;&#x2F;script&gt;
. In small step they will use a more boring arrow like &lt;script type=&quot;math&#x2F;tex&quot;&gt;\rightarrow&lt;&#x2F;script&gt;
.&lt;&#x2F;p&gt;
&lt;h3 id=&quot;example&quot;&gt;Example&lt;&#x2F;h3&gt;
&lt;p&gt;Lets evaluate a simple math expression to show how you can use these rules to prove that expressions are evaluated correctly using a machines rules.&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\frac{\frac{7 \Downarrow 7 \; 3 \Downarrow 3 \; 7 + 3 = 10}{7 + 3 \Downarrow 10}  \scriptsize{\mathbf{Addition}} \;\;\; \frac{}{4 \Downarrow 4} \;\;\; 10 + 4 = 14}
     {7+3+4 \Downarrow 14} \scriptsize{\mathbf{Addition}}&lt;&#x2F;script&gt;
&lt;p&gt;Here, at the first, bottom most level, &lt;script type=&quot;math&#x2F;tex&quot;&gt;e_1 = 7 + 3&lt;&#x2F;script&gt;
 and &lt;script type=&quot;math&#x2F;tex&quot;&gt;e_2 = 4&lt;&#x2F;script&gt;
. Then we need to prove that &lt;code&gt;7 + 3 = 10&lt;&#x2F;code&gt;, and we do that with another application of the addition rule! We could have chosen &lt;code&gt;3 + 4&lt;&#x2F;code&gt; to be be &lt;script type=&quot;math&#x2F;tex&quot;&gt;e_2&lt;&#x2F;script&gt;
, but it doesnt matter for addition, and we leave issues like that to a parser. I noted each level with the rule that was used to evaluate it. It is generally showed like this, but I usually dont show them. I only have so much horizontal space on this webpage!&lt;&#x2F;p&gt;
&lt;p&gt;To evaluate simple mathematical expressions, we only need a control for the state. C machines are only capable of evaluating simple programs. What if we want to add a simple programming construct like variables? For that, we need a place to store them. And so, the CE machine is born!&lt;&#x2F;p&gt;
&lt;h1 id=&quot;environments-with-the-ce-machine&quot;&gt;Environments with the CE machine.&lt;&#x2F;h1&gt;
&lt;p&gt;To evaluate variables, we need to be able to keep track of what value they hold at a given program point. in a C machine, if we are given &lt;code&gt;a + 2&lt;&#x2F;code&gt;, we have no way of know what &lt;code&gt;a&lt;&#x2F;code&gt; is, because its not a number, and we can only deal with syntax as we see it. But if we gave a machine both &lt;code&gt;a + 2&lt;&#x2F;code&gt;, the control, and a mapping &lt;code&gt;{a : 4}&lt;&#x2F;code&gt;, an environment, we can evaluate the expression to 6!&lt;&#x2F;p&gt;
&lt;p&gt;So, a big-step CE machine doesnt just have &lt;code&gt;MathExp&lt;&#x2F;code&gt; (C) for state anymore, we need an &lt;code&gt;Env&lt;&#x2F;code&gt; (E) to accompany it! The function is now of type &lt;script type=&quot;math&#x2F;tex&quot;&gt;(MathExp \times Env) \Downarrow Number&lt;&#x2F;script&gt;
. This means that our machine will take 2 arguments, a math expression and an environment, and it will return a computed number.&lt;&#x2F;p&gt;
&lt;p&gt;&lt;script type=&quot;math&#x2F;tex&quot;&gt;Var-Lookup:&lt;&#x2F;script&gt;

&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\frac{\rho[var] = n}
     {(var, \rho) \Downarrow n}&lt;&#x2F;script&gt;
&lt;&#x2F;p&gt;
&lt;p&gt;This simply states that if the expression is a variable, not an artithmetic expression,
the value it returns is what the environment says it is. We use the greek
letter rho (&#x27;ρ&#x27;) (not the letter &#x27;p&#x27;) to represent the environment. This is what is used
in the literature, and its always best to follow along with norms to avoid confusion! For the history on why they used &lt;script type=&quot;math&#x2F;tex&quot;&gt;\rho&lt;&#x2F;script&gt;
 for this task, you will have to ask someone smarter than me.&lt;&#x2F;p&gt;
&lt;p&gt;We dont have variable binding yet, but you can imagine an expression like:
&lt;code&gt;m*c*c&lt;&#x2F;code&gt; with an environment &lt;code&gt;{m : 12 c : 299792458}&lt;&#x2F;code&gt;, which will return some number for us.
We have made a calculator with predefined constants! We can put pi in there,
or tau if you are a lunatic...&lt;&#x2F;p&gt;
&lt;h1 id=&quot;real-looking-programs&quot;&gt;Real Looking Programs&lt;&#x2F;h1&gt;
&lt;p&gt;Wow, it seems like we can do a lot with just a control and an environment. We could further extend this to things like variable assignment (again, these are big-step semantics):&lt;&#x2F;p&gt;
&lt;p&gt;&lt;script type=&quot;math&#x2F;tex&quot;&gt;\mathbf{Assignment:}&lt;&#x2F;script&gt;

&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\frac{e_1 \Downarrow n_2 \;,\; \rho_2 = (\rho + \{var : n_2\}) \;,\; (e_2, \rho_2) \Downarrow n}
     {(var := e_1 \;\text{in}\; e_2 \;,\; \rho) \Downarrow n}&lt;&#x2F;script&gt;
&lt;&#x2F;p&gt;
&lt;p&gt;This tells us that when we assign a variable, it will be available in the next expression.&lt;&#x2F;p&gt;
&lt;p&gt;It seems that these two components of a state are enough to be wildly dangerous with. Soon enough, your semantics will be modeling a real language, with conditions, and inequalities, oh my! But, there are two big problems that you may face.&lt;&#x2F;p&gt;
&lt;p&gt;First, your big step semantics may limit you. Their stringent requirements that their sub-expressions be terminating can cause issues in a turing-complete environment. And a small-step semantics can provide more granularity of control. For that reason, we will be using small-step semantics from now on.&lt;&#x2F;p&gt;
&lt;p&gt;Also, as your language gets more and more complicated, the constructs of control and environment may be overburdened with responsibility. What can we do to simplify our understanding of these machines?&lt;&#x2F;p&gt;
&lt;h1 id=&quot;what-next-kontinuations-cek&quot;&gt;What next? Kontinuations! CEK&lt;&#x2F;h1&gt;
&lt;p&gt;One way to alleviate the burden is to add a new construct to our machines: The continuation.
A continuation is a way of showing &#x27;future work&#x27; to be done. For example, when we implement
our assignment operation, we can delegate the work of executing the second expression to the
continuation:&lt;&#x2F;p&gt;
&lt;p&gt;&lt;script type=&quot;math&#x2F;tex&quot;&gt;\footnotesize{\mathbf{Assign-Exp}}:&lt;&#x2F;script&gt;

&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\footnotesize{
\frac{}
     {(v := e_1 \;\text{in}\; e_2 , \rho , \kappa)
     \rightarrow (e_1 , \rho , \text{assign}(v, e_2, \kappa))}
}&lt;&#x2F;script&gt;
&lt;&#x2F;p&gt;
&lt;p&gt;&lt;script type=&quot;math&#x2F;tex&quot;&gt;\footnotesize{\mathbf{Assign-Kont}}:&lt;&#x2F;script&gt;

&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\frac{e \text{ is atomic} , \rho_2 = (\rho + \{v : \text{e} \})}
     {(e , \rho , \text{assign}(v, e_2 , k_{next} ))
        \rightarrow (e_2 , \rho_2 , k_{next})}&lt;&#x2F;script&gt;
&lt;&#x2F;p&gt;
&lt;p&gt;There is quite a bit more to unpack here!&lt;&#x2F;p&gt;
&lt;p&gt;First, we switched to a small step semantics. Instead of returning a fully evaluated value as before, we now return states. Big step semantics are nice for simple programs, but when things get more complex, we want finer-grained control, so we switch to small-step.&lt;&#x2F;p&gt;
&lt;p&gt;Next, our state has a third argument. Our type signature is now &lt;script type=&quot;math&#x2F;tex&quot;&gt;(C, E, K) \rightarrow (C, E, K)&lt;&#x2F;script&gt;
. The third argument is a continuation, it is
useful in small step semantics, so we can focus on evaluating expressions. When we are done, we know what to do next.&lt;&#x2F;p&gt;
&lt;p&gt;Finaly, The above semantics show that when we see an assignment expression, we simply return the &lt;script type=&quot;math&#x2F;tex&quot;&gt;e_1&lt;&#x2F;script&gt;
 expression as the control for the next state. The key is that we save a new &#x27;continuation frame&#x27; along with that control. This signifies that after that expression is fully evaluated, we continue by assigning it to a variable, and then execute the expression &lt;script type=&quot;math&#x2F;tex&quot;&gt;e_2&lt;&#x2F;script&gt;
.&lt;&#x2F;p&gt;
&lt;p&gt;Another notable thing is that, inside of that &#x27;assign&#x27; continuation frame, we store the old continuation. This recursive format is necessary when nesting complex expressions. Let&#x27;s use an example with nested assignment expressions, with the recursive nature of the continuations being our life-jacket.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;example-1&quot;&gt;Example&lt;&#x2F;h2&gt;
&lt;p&gt;If we had some expression:&lt;&#x2F;p&gt;
&lt;p&gt;&lt;code&gt;x := 4 in (x + 1)&lt;&#x2F;code&gt;, we would start with the &lt;code&gt;assign-exp&lt;&#x2F;code&gt; rule,
which simply gives us a new state, it doesnt directly evaluate anything to a base value.
The new state says that we need to evaluate &lt;code&gt;4&lt;&#x2F;code&gt; with the same environment as before,
but we change the continuation, to store the values in the we need to use after the &lt;code&gt;4&lt;&#x2F;code&gt; is
fully evaluated (which it is, but we cant see that far ahead! One small step at a time!).
After the &lt;code&gt;assign-exp&lt;&#x2F;code&gt; a state that looks like &lt;code&gt;(4 , env , assign(...))&lt;&#x2F;code&gt; is returned.
We immediately see that the &lt;code&gt;assign-kont&lt;&#x2F;code&gt; rule can be applied, as the control is a number,
and we have an &lt;code&gt;assign&lt;&#x2F;code&gt; continuation in the &lt;code&gt;K&lt;&#x2F;code&gt; position. So by applying that,
a state &lt;code&gt;(x + 1, env2 , old_kont)&lt;&#x2F;code&gt; is given to us, and with &lt;code&gt;x&lt;&#x2F;code&gt; in the environment mapped to &lt;code&gt;4&lt;&#x2F;code&gt;.&lt;&#x2F;p&gt;
&lt;p&gt;What is &lt;code&gt;old_kont&lt;&#x2F;code&gt; in this example? As you see from the &lt;code&gt;assign-exp&lt;&#x2F;code&gt; rule, one of the main things
that a continuation does is store the previous one, like a linked-list. Continuations are the
&#x27;rest of the program&#x27;, so after the current continuation is used, we do what the old continuation was.&lt;&#x2F;p&gt;
&lt;p&gt;For example, an program that looks like:&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;x := (y := (z := 3 \;\text{in}\; z) \;\text{in}\; (y + y)) \;\text{in}\; x&lt;&#x2F;script&gt;
&lt;p&gt;Here is what the states will look like over the course of 3 applications of &lt;code&gt;assign-exp&lt;&#x2F;code&gt;:&lt;&#x2F;p&gt;
&lt;pre style=&quot;background-color:#282a36;color:#f8f8f2;&quot;&gt;&lt;code&gt;&lt;span&gt;(x := (y := (z := 3 in z) in (y + y)) in x , {} , NONE)
&lt;&#x2F;span&gt;&lt;span&gt;-&amp;gt; ((y := (z := 3 in z) in (y + y)) , {} , assign(x , x , NONE))
&lt;&#x2F;span&gt;&lt;span&gt;-&amp;gt; ((z := 3 in z) , {} , assign(y , y + y , assign(x , x , NONE)))
&lt;&#x2F;span&gt;&lt;span&gt;-&amp;gt; (3 , {} , assign(z , z , assign(y , y + y , assign(x , x , NONE))))
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;p&gt;Then if we apply &lt;code&gt;assign-kont&lt;&#x2F;code&gt; a couple times, with omitted &lt;code&gt;addition&lt;&#x2F;code&gt; and &lt;code&gt;var-lookup&lt;&#x2F;code&gt; rules:&lt;&#x2F;p&gt;
&lt;pre style=&quot;background-color:#282a36;color:#f8f8f2;&quot;&gt;&lt;code&gt;&lt;span&gt;-&amp;gt; (z , {z : 3} , assign(y , y + y , assign(x , x , NONE)))
&lt;&#x2F;span&gt;&lt;span&gt;-&amp;gt; (3 , {z : 3} , assign(y , y + y , assign(x , x , NONE)))
&lt;&#x2F;span&gt;&lt;span&gt;-&amp;gt; (y + y , {z : 3 , y : 3} , assign(x , x , NONE))
&lt;&#x2F;span&gt;&lt;span&gt;...
&lt;&#x2F;span&gt;&lt;span&gt;-&amp;gt; (6 , {z : 3 , y : 3} , assign(x , x , NONE))
&lt;&#x2F;span&gt;&lt;span&gt;-&amp;gt; (x , {z : 3 , y : 3 , x : 6} , NONE)
&lt;&#x2F;span&gt;&lt;span&gt;-&amp;gt; (6 , {z : 3 , y : 3 , x : 6} , NONE)
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;h3 id=&quot;interlude-injection&quot;&gt;Interlude: Injection&lt;&#x2F;h3&gt;
&lt;p&gt;Note above that there is an &#x27;initial&#x27; state that we use when we start evaluating an expression. We wrap the expression with an empty environment (&#x27;{}&#x27;), and an &#x27;empty&#x27; contination (&#x27;NONE&#x27;). This is usually done with whats called an &lt;em&gt;injection function&lt;&#x2F;em&gt;:&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;inject(e) = (e \;,\; \{\} \;,\; \text{NONE})&lt;&#x2F;script&gt;
&lt;p&gt;This gives us the initial state from an expression. The initial state can of course be changed to your needs. adding initial environment values or constants, for example.&lt;&#x2F;p&gt;
&lt;h3 id=&quot;back-to-the-example&quot;&gt;Back To The Example&lt;&#x2F;h3&gt;
&lt;p&gt;We started with a NONE continuation, meaning have nothing to do next (end of program!).
We then slowly build up continuations. &lt;em&gt;Continuations are turned to for guidance once control is atomic&lt;&#x2F;em&gt;. Atomic here means that it cant be broken down any more (computer scientists dont have quarks yet). Once we evaluate a continuation, the cycle continues, evaluate the control until it is atomic again. Eventually (if your program terminates!), we will be faced with an atomic control, and a NONE continuation. This means that we have finished evaluation, as there is nothing left to do! That is known as a fixpoint, which is a term taken from math meaning, if we run it another step, nothing will change: &lt;code&gt;f(x)&lt;&#x2F;code&gt; evaluated to &lt;code&gt;x&lt;&#x2F;code&gt;.&lt;&#x2F;p&gt;
&lt;p&gt;This is a good example of the differences between small and big step evalaution models. Small step is a scalpel, where big is a cudgel. They may be more effective than the other, depending on what youre doing.&lt;&#x2F;p&gt;
&lt;h1 id=&quot;other-continuation-types&quot;&gt;Other Continuation Types&lt;&#x2F;h1&gt;
&lt;p&gt;We have demonstrated two different continuation types, &quot;NONE&quot;, and &quot;ASSIGN&quot;.
One signifies the end of computation, and one tells us how to add variables to the environment.
What if we want to add a conditional to our language? It is very easy with our language!&lt;&#x2F;p&gt;
&lt;p&gt;Lets compute this text:&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\text{if}\; c \;\text{then}\; t \;\text{else}\; f&lt;&#x2F;script&gt;
&lt;p&gt;This will evaluate &lt;code&gt;c&lt;&#x2F;code&gt;, and once a value is computed, it checks its value. If the value is &lt;code&gt;0&lt;&#x2F;code&gt;, it will take the &lt;code&gt;else&lt;&#x2F;code&gt; branch, otherwise it will take the &lt;code&gt;then&lt;&#x2F;code&gt; branch. If we had a more complex language with booleans, we could use those. Or really, we could do almost anything! Make your own language, make it weird!&lt;&#x2F;p&gt;
&lt;p&gt;&lt;script type=&quot;math&#x2F;tex&quot;&gt;\text{if-exp}:&lt;&#x2F;script&gt;

&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\frac{}
     {((\text{if}\; c \;\text{then}\; t \;\text{else}\; f) \;,\; \rho , \kappa)
     \rightarrow (c , \rho , \text{ifk}(t , f , \kappa))}&lt;&#x2F;script&gt;
&lt;&#x2F;p&gt;
&lt;p&gt;&lt;script type=&quot;math&#x2F;tex&quot;&gt;\text{if-kont-t}:&lt;&#x2F;script&gt;

&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\frac{v \text{ is atomic} , v \;\text{!=}\; 0}
     {(v , \rho , \text{ifk}(t , f , \kappa_{next}))
     \rightarrow (t , \rho , \kappa_{next})}&lt;&#x2F;script&gt;
&lt;&#x2F;p&gt;
&lt;p&gt;&lt;script type=&quot;math&#x2F;tex&quot;&gt;\text{if-kont-f}:&lt;&#x2F;script&gt;

&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\frac{v \text{ is atomic} , v = 0}
     {(v , \rho , \text{ifk}(t , f , \kappa_{next}))
     \rightarrow (f , \rho , \kappa_{next})}&lt;&#x2F;script&gt;
&lt;&#x2F;p&gt;
&lt;p&gt;Here, when it is time to check the continuation for guidance, we will next evaluate
one of the branches from the &lt;code&gt;ifk&lt;&#x2F;code&gt; continuation &#x27;frame&#x27; based on the controls value.&lt;&#x2F;p&gt;
&lt;p&gt;The idea of small step + continuation can be very similar to big-step. this CEK machine
is basically saying &#x27;evaluate this to a value, then do something else&#x27;. Big-step says
that but in a slightly more compact way, involving more inference rules on the top half of the
big bar.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;another-example&quot;&gt;Another Example&lt;&#x2F;h2&gt;
&lt;p&gt;Lets do another simple example of continuations, just to hammer them in!&lt;&#x2F;p&gt;
&lt;p&gt;We will show that:
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\scriptsize{
\frac{}
     {(x := (\text{if} \; (1 + 1) \; \text{then} \;7\; \text{else} \;12) \; \text{in} \; x \;,\; \{\} \;,\; NONE)
        \rightarrow (7, \{\}, NONE)}
}&lt;&#x2F;script&gt;
&lt;&#x2F;p&gt;
&lt;pre style=&quot;background-color:#282a36;color:#f8f8f2;&quot;&gt;&lt;code&gt;&lt;span&gt;(x := (if (1 + 1) then 7 else 12) , {} , NONE)
&lt;&#x2F;span&gt;&lt;span&gt;-&amp;gt; (if (1 + 1) then 7 else 12 , {} , assign(x, x, NONE))
&lt;&#x2F;span&gt;&lt;span&gt;-&amp;gt; ((1 + 1) , {} , ifk(7, 12, assign(x, x, NONE)))
&lt;&#x2F;span&gt;&lt;span&gt;-&amp;gt; (2 , {} , ifk(7, 12, assign(x, x, NONE)))
&lt;&#x2F;span&gt;&lt;span&gt;-&amp;gt; (7 , {} , assign(x, x, NONE))
&lt;&#x2F;span&gt;&lt;span&gt;-&amp;gt; (x , {x : 7} , NONE)
&lt;&#x2F;span&gt;&lt;span&gt;-&amp;gt; (7 , {} , NONE)
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;h3 id=&quot;fun-insight&quot;&gt;Fun Insight!&lt;&#x2F;h3&gt;
&lt;p&gt;If you have been paying close attention to the continuations, they kind of act like a fine-grained &lt;em&gt;stack&lt;&#x2F;em&gt;. Traditional stacks are at the level of funtions. You call a function, and a stack-frame is pushed. After a &lt;code&gt;return&lt;&#x2F;code&gt; is issued (in our case, reaching an atomic value), that frame is popped. The idea with continuations here is very similar, but at the level of instructions (like conditionals, assignments, etc.), not just functions.&lt;&#x2F;p&gt;
&lt;p&gt;I didnt want to get into the weeds of &lt;em&gt;real progrmaming&lt;&#x2F;em&gt; in this post, but if that helps you understand more, great! If not, dont fret! But think on the recursive nature of continuations, it can really give shed new light on how to model computation!&lt;&#x2F;p&gt;
&lt;p&gt;In practice, recursive continnuations can be made efficient by using tail-call eliminations, but thats a subject for a whole &#x27;nother post!&lt;&#x2F;p&gt;
&lt;h1 id=&quot;the-big-idea&quot;&gt;The Big Idea&lt;&#x2F;h1&gt;
&lt;p&gt;The abstract machines are the C, CE, and CEK &lt;em&gt;ideas&lt;&#x2F;em&gt; that we have talked about.
They are the types of state used when implementing an abstract machine. The resulting
machine, however, is a &lt;em&gt;concrete interpreter&lt;&#x2F;em&gt; for your programming language.&lt;&#x2F;p&gt;
&lt;p&gt;So what is wih all this trouble? Creating a tiny interpreter is easy! Using abstract machines
offers us a way to build new features incrementally, and concisely.&lt;&#x2F;p&gt;
&lt;p&gt;These Abstract Machines provide a way to form an independent interpreter for your language,
that doesnt necessarily depend on the runtime of your host language. Also, using
operational semantics can help you to formalize how your language evalautes, and be sure that your implementation is correct!&lt;&#x2F;p&gt;
&lt;p&gt;But more than all of that, this is how computer scientists can model real languages. To accomodate that, other components can be added to the state, such as a &#x27;store&#x27;, for modeling the heap. A CESK machine changes the environment to be a mapping from variables to &#x27;addresses&#x27;, and the store becomes a mapping from addresses to the values. This is helpful for modeling mutation, and has implications in computability when doing static program analysis.&lt;&#x2F;p&gt;
&lt;h1 id=&quot;the-future&quot;&gt;The Future&lt;&#x2F;h1&gt;
&lt;p&gt;Adding even more complex language features is a necessity for formalizing a real language. One key feature is of exception handling: try-catch and the like. A solution used for advanced control flow such as try-catch is to bring continuations to first-class status. Continuations are very powerful constructs, and can be used to implement exception handling schemes. I am writing another post on what continuations &lt;em&gt;are&lt;&#x2F;em&gt;, becuase they are very poorly known in the world outside of programming panguages research.&lt;&#x2F;p&gt;
&lt;p&gt;Abstract Machines can themselves be abstracted, to form interpreters that are non-deterministic. These interpreters can be used to see what possible states a program can reach. Using this information, static analyses of programs can be conducted, meaning optimizations, warnings, etc.. The ideas of abstract AMs is still new, and a topic of current research.&lt;&#x2F;p&gt;
&lt;h1 id=&quot;conclusion&quot;&gt;Conclusion&lt;&#x2F;h1&gt;
&lt;p&gt;Abstract Machines are a way to formally define computation for terms. When mapped to &#x27;the real world&#x27; that means an interpreter for your programming language. They are a wonderful way of explicitly showing how programs are executed, and computation is performed.&lt;&#x2F;p&gt;
&lt;h1 id=&quot;appendix&quot;&gt;Appendix&lt;&#x2F;h1&gt;
&lt;script type=&quot;math&#x2F;tex&quot;&gt;&lt;&#x2F;script&gt;
&lt;p&gt;&lt;script type=&quot;math&#x2F;tex&quot;&gt;\rho:&lt;&#x2F;script&gt;
 &#x27;rho&#x27;, is an environment, used to map variables to values.&lt;&#x2F;p&gt;
&lt;p&gt;&lt;script type=&quot;math&#x2F;tex&quot;&gt;\kappa:&lt;&#x2F;script&gt;
 &#x27;kappa&#x27;, is a continuation, which represents the rest of the program. We consult this after the current control is fully evaluated.&lt;&#x2F;p&gt;
&lt;p&gt;&lt;script type=&quot;math&#x2F;tex&quot;&gt;\Sigma:&lt;&#x2F;script&gt;
 &#x27;Sigma&#x27; (uppercase). Although not used in this post, this character often is used to represent the &lt;code&gt;State&lt;&#x2F;code&gt; type of the machine.&lt;&#x2F;p&gt;
&lt;p&gt;&lt;script type=&quot;math&#x2F;tex&quot;&gt;\varsigma:&lt;&#x2F;script&gt;
 &#x27;sigma&#x27; (lowercase in &#x27;final word position&#x27;). This is known as &#x27;varsigma&#x27;. You may find this used as an instance of a state. A small step machine goes from some state to a next state, so we can codify that as&lt;&#x2F;p&gt;
&lt;script type=&quot;math&#x2F;tex;mode=display&quot;&gt;\varsigma_i \rightarrow \varsigma_{i+1}&lt;&#x2F;script&gt;
&lt;p&gt;&lt;script type=&quot;math&#x2F;tex&quot;&gt;\sigma:&lt;&#x2F;script&gt;
 &#x27;sigma&#x27; (lowercase). Although not used in this post, this character is used to represent the &lt;code&gt;store&lt;&#x2F;code&gt; component of a machine. If we would have made a CESK machine,  then the S would be this.&lt;&#x2F;p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>The Robson Tree Traversal (DRAFT)</title>
        <published>2019-12-05T08:10:44-05:00</published>
        <updated>2019-12-05T08:10:44-05:00</updated>
        
        <author>
          <name>
            
              Unknown
            
          </name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://thedav.is/post/robson-traversal/"/>
        <id>https://thedav.is/post/robson-traversal/</id>
        
        <content type="html" xml:base="https://thedav.is/post/robson-traversal/">&lt;h1 id=&quot;this-is-a-draft&quot;&gt;THIS IS A DRAFT&lt;&#x2F;h1&gt;
&lt;p&gt;Hiya, this is a draft! Probably never going to finish it at this rate.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;todo&quot;&gt;TODO&lt;&#x2F;h2&gt;
&lt;ul&gt;
&lt;li&gt;prune images that aren&#x27;t needed.&lt;&#x2F;li&gt;
&lt;li&gt;Add pictures of tree&#x27;s being traversed!!!&lt;&#x2F;li&gt;
&lt;li&gt;StackOverflow posts:
&lt;ul&gt;
&lt;li&gt;https:&#x2F;&#x2F;stackoverflow.com&#x2F;questions&#x2F;31323283&#x2F;incomplete-traversal-using-link-inversion-of-binary-tree&lt;&#x2F;li&gt;
&lt;li&gt;https:&#x2F;&#x2F;stackoverflow.com&#x2F;questions&#x2F;22288074&#x2F;robson-tree-traversal-algorithm&lt;&#x2F;li&gt;
&lt;&#x2F;ul&gt;
&lt;&#x2F;li&gt;
&lt;&#x2F;ul&gt;
&lt;h1 id=&quot;introduction&quot;&gt;Introduction&lt;&#x2F;h1&gt;
&lt;p&gt;In this post, we will discuss a novel tree traversal algorithm.
The standard traversal method operates with a &lt;em&gt;linear&lt;&#x2F;em&gt; spatial cost.
The Robson traversal counters with a cool &lt;em&gt;&lt;strong&gt;constant&lt;&#x2F;strong&gt;&lt;&#x2F;em&gt; space!&lt;&#x2F;p&gt;
&lt;p&gt;The final code is on 
&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;github.com&amp;#x2F;sinistersnare&amp;#x2F;robson&quot; target=&quot;_blank&quot;&gt;github↪&lt;&#x2F;a&gt;
,
but I encourage you to read this post!
The table of contents may help for people that may want to skip a bit :)&lt;&#x2F;p&gt;
&lt;h1 id=&quot;table-of-contents&quot;&gt;Table of Contents&lt;&#x2F;h1&gt;
&lt;p&gt;TODO&lt;&#x2F;p&gt;
&lt;h1 id=&quot;the-famous-tree&quot;&gt;The Famous Tree&lt;&#x2F;h1&gt;
&lt;p&gt;The tree is an incredibly important data structure.
A great learning tool for beginning computer scientists, starting to understand the science.
Trees are also used throughout the real-world.
File systems use 
&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;en.wikipedia.org&amp;#x2F;wiki&amp;#x2F;B-tree&quot; target=&quot;_blank&quot;&gt;B-trees↪&lt;&#x2F;a&gt;
 to

&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;github.com&amp;#x2F;postgres&amp;#x2F;postgres&amp;#x2F;tree&amp;#x2F;master&amp;#x2F;src&amp;#x2F;backend&amp;#x2F;access&amp;#x2F;nbtree&quot; target=&quot;_blank&quot;&gt;store their data↪&lt;&#x2F;a&gt;
. Text editors use

&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;en.wikipedia.org&amp;#x2F;wiki&amp;#x2F;Rope_(data_structure)&quot; target=&quot;_blank&quot;&gt;ropes↪&lt;&#x2F;a&gt;
 to

&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;github.com&amp;#x2F;google&amp;#x2F;xi-editor&amp;#x2F;tree&amp;#x2F;master&amp;#x2F;rust&amp;#x2F;rope&quot; target=&quot;_blank&quot;&gt;organize their text↪&lt;&#x2F;a&gt;
.
Trees power the world, inside and outside of computers.
We will be using a simple binary tree for this post.&lt;&#x2F;p&gt;
&lt;p&gt;Here is a common binary tree definition. We will be using C for the whole of this post:&lt;&#x2F;p&gt;
&lt;pre data-lang=&quot;c&quot; style=&quot;background-color:#282a36;color:#f8f8f2;&quot; class=&quot;language-c &quot;&gt;&lt;code class=&quot;language-c&quot; data-lang=&quot;c&quot;&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* We will use this type definition later. *&#x2F;
&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;typedef void &lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt;VisitFunc)(Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt;);
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;typedef struct&lt;&#x2F;span&gt;&lt;span&gt; Tree &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;int&lt;&#x2F;span&gt;&lt;span&gt; data;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;struct&lt;&#x2F;span&gt;&lt;span&gt; Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; left;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;struct&lt;&#x2F;span&gt;&lt;span&gt; Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; right;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;} &lt;&#x2F;span&gt;&lt;span&gt;Tree;
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;p&gt;We can use the tree like so:&lt;&#x2F;p&gt;
&lt;pre data-lang=&quot;c&quot; style=&quot;background-color:#282a36;color:#f8f8f2;&quot; class=&quot;language-c &quot;&gt;&lt;code class=&quot;language-c&quot; data-lang=&quot;c&quot;&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;int &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;main&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;void&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;    Tree root, root_left;
&lt;&#x2F;span&gt;&lt;span&gt;    root_left&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;.&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;data &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;0&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;    root_left&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;.&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;left &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;    root_left&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;.&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;right &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;    root&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;.&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;data &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;1&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;    root&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;.&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;left &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &amp;amp;&lt;&#x2F;span&gt;&lt;span&gt;root_left;
&lt;&#x2F;span&gt;&lt;span&gt;    root&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;.&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;right &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;p&gt;We will  specifically be using

&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;en.wikipedia.org&amp;#x2F;wiki&amp;#x2F;Binary_search_tree&quot; target=&quot;_blank&quot;&gt;Binary Search Trees↪&lt;&#x2F;a&gt;
,
so that way in-order traversal works.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;how-do-we-traverse-a-tree&quot;&gt;How Do We Traverse a tree?&lt;&#x2F;h2&gt;
&lt;p&gt;Traversing a tree means accessing each node&#x27;s data in the whole tree.
This is obviously a critically important function of a tree,
we should be able to access all elements if we need to.&lt;&#x2F;p&gt;
&lt;p&gt;Luckily, traversing a tree is super easy!&lt;&#x2F;p&gt;
&lt;pre data-lang=&quot;c&quot; style=&quot;background-color:#282a36;color:#f8f8f2;&quot; class=&quot;language-c &quot;&gt;&lt;code class=&quot;language-c&quot; data-lang=&quot;c&quot;&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;void &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;traverse&lt;&#x2F;span&gt;&lt;span&gt;(Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;* &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;cur&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;if &lt;&#x2F;span&gt;&lt;span&gt;(cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;== &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;return&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;pre_visit&lt;&#x2F;span&gt;&lt;span&gt;(cur); &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* pre-order traversal *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;traverse&lt;&#x2F;span&gt;&lt;span&gt;(cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;left);
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;in_visit&lt;&#x2F;span&gt;&lt;span&gt;(cur); &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* in-order traversal *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;traverse&lt;&#x2F;span&gt;&lt;span&gt;(cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;right);
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;post_visit&lt;&#x2F;span&gt;&lt;span&gt;(cur); &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* post-order traversal *&#x2F;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;p&gt;This algorithm is universally taught in beginning CS courses at universities.
It gets the job done, but I think we can do better.&lt;&#x2F;p&gt;
&lt;p&gt;Tree traversals can be adapted for use in memory management.
Many garbage collectors represent their memory pool using tree-like structures,
and when they are marking live memory, they traverse that tree.&lt;&#x2F;p&gt;
&lt;p&gt;Pre-order traversal always visits a parent before its child. This is very useful
when you want to copy a tree, maintaining its order. In-order is mostly used for
sorted trees, as it will visit nodes in order! A node will be visited in post-order
only after its children have been visited. This means that post-order is best used
for tasks such as deleting the tree, freeing its memory without dangling pointers left over.
If we made &lt;code&gt;free&lt;&#x2F;code&gt; our pre-visit function, then we would never be able to traverse right children!&lt;&#x2F;p&gt;
&lt;h1 id=&quot;why-is-the-standard-method-bad&quot;&gt;Why is the &#x27;standard&#x27; method bad?&lt;&#x2F;h1&gt;
&lt;p&gt;To get into how algorithms are rated against eachother, we need to talk about &quot;Big-O notation&quot;,
and that is a little bit out of scope for this already long blog-post, so...
Take an algorithms course I guess? I&#x27;ll give a quick paragraph.&lt;&#x2F;p&gt;
&lt;p&gt;Big-O uses a polynomial to describe how the function performs with relation to input size.
If we are talking about speed, an &lt;code&gt;O(n)&lt;&#x2F;code&gt; function will perform linearly with regards to input.
An &lt;code&gt;O(1)&lt;&#x2F;code&gt; function will always perform the same no matter how big the input gets. You should try
to avoid &lt;code&gt;O(n!)&lt;&#x2F;code&gt; functions, too... These functions are used for &#x27;time&#x27; and &#x27;space&#x27;. If you
are interested in this stuff, please check out

&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;en.wikipedia.org&amp;#x2F;wiki&amp;#x2F;Introduction_to_Algorithms&quot; target=&quot;_blank&quot;&gt;CLRS↪&lt;&#x2F;a&gt;

chapter 3 for more information, or ask me to write a post on it!&lt;&#x2F;p&gt;
&lt;p&gt;The &#x27;standard&#x27; traversal method is as efficient as possible, time-wise.
We need to traverse all &lt;code&gt;n&lt;&#x2F;code&gt;-nodes of a tree, and the algorithm has &lt;code&gt;O(n)&lt;&#x2F;code&gt;
run-time complexity. You cant get any better than that!&lt;&#x2F;p&gt;
&lt;p&gt;A reader may think that you also cant get better space-wise.
The algorithm is like 4 lines long, how can we get better than that!?
Well, if you paid attention in (or had taken an) algorithms class,
you would know that stack space counts! Even though this algorithm
looks small and perfect, it uses up a whole stack-frame each time the algorithm recurses!
If you turn this recursive code into an iterative, explicit-stack based, solution,
you would see that you need some memory for each level, and in the worst-case,
we need &lt;code&gt;O(n)&lt;&#x2F;code&gt; memory!&lt;&#x2F;p&gt;
&lt;p&gt;You may be saying now, &quot;O(n) is not that bad! It seems as good as it can get!&quot;
Well I say no! We can do better! I say we can do it in &lt;em&gt;&lt;strong&gt;constant O(1) time&lt;&#x2F;strong&gt;&lt;&#x2F;em&gt;!&lt;&#x2F;p&gt;
&lt;p&gt;That means we can do it using the same amount of memory, no matter how big the tree gets!&lt;&#x2F;p&gt;
&lt;p&gt;Let&#x27;s do it!&lt;&#x2F;p&gt;
&lt;h2 id=&quot;how-can-we-do-better-than-that&quot;&gt;How can we do better than that!?!?!&lt;&#x2F;h2&gt;
&lt;p&gt;Here is the thing about trees: they can be quite wasteful!&lt;&#x2F;p&gt;
&lt;p&gt;Let&#x27;s look at a tree-structure:&lt;&#x2F;p&gt;
&lt;div class=&quot;img-tpl&quot;&gt;
    &lt;img src=&quot;wasteful.png&quot; alt=&quot;TODO-SORRY!&quot;&gt;
&lt;&#x2F;div&gt;
&lt;p&gt;You see, the leaf-nodes have 2 pointers that are just &lt;em&gt;&lt;strong&gt;null&lt;&#x2F;strong&gt;&lt;&#x2F;em&gt;!
What a waste! Thats so much space we are wasting! For any given tree of &lt;code&gt;n&lt;&#x2F;code&gt; nodes,
there will be &lt;code&gt;n + 1&lt;&#x2F;code&gt; null pointers.&lt;&#x2F;p&gt;
&lt;p&gt;Here is the theory. We use that freely-available space for our traversal.
That way, we use as little extra memory as possible!&lt;&#x2F;p&gt;
&lt;p&gt;That is how we are going to get to our solution, but first we need to understand some preliminary concepts.&lt;&#x2F;p&gt;
&lt;h1 id=&quot;stackless-traversals&quot;&gt;Stackless Traversals&lt;&#x2F;h1&gt;
&lt;p&gt;As mentioned in the introductory sections, the standard tree traversal requries a stack to traverse the tree.
This is becuase we need to &#x27;pop&#x27; back up the tree once we reach a leaf. Using a stack is super easy to understand,
and it makes for a clean algorithm.&lt;&#x2F;p&gt;
&lt;p&gt;explain stack for a minute here or in the big-O section. Chef says, at least explain a &#x27;pop&#x27;.&lt;&#x2F;p&gt;
&lt;p&gt;In 1968, Donald Knuth asked the computer science community if there existed a method for computing
tree traversals without a stack, while also leaving the tree unmodified. Lets discuss some methods for
doing just that, ending in the Robson traversal.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;the-link-inversion-model&quot;&gt;The Link-Inversion Model&lt;&#x2F;h2&gt;
&lt;p&gt;Link Inversion is a key ingredient to our final algorithm. Link-Inversion is a process where we
use a marker-bit on each node to tell if we should continue to traverse up, or traverse rightward
when going up a tree.&lt;&#x2F;p&gt;
&lt;p&gt;This method is stackless, like in the threaded tree, and solves Knuth&#x27;s question.
It does not solve our dilemma though, we need O(1) worst-case space complexity!
Lets talk about how and why it works, which will lead us to Robson.&lt;&#x2F;p&gt;
&lt;pre data-lang=&quot;c&quot; style=&quot;background-color:#282a36;color:#f8f8f2;&quot; class=&quot;language-c &quot;&gt;&lt;code class=&quot;language-c&quot; data-lang=&quot;c&quot;&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;typedef struct&lt;&#x2F;span&gt;&lt;span&gt; Tree &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;int&lt;&#x2F;span&gt;&lt;span&gt; data;
&lt;&#x2F;span&gt;&lt;span&gt;    Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; left;
&lt;&#x2F;span&gt;&lt;span&gt;    Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; right;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;bool&lt;&#x2F;span&gt;&lt;span&gt; went_right;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;} &lt;&#x2F;span&gt;&lt;span&gt;Tree;
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;void &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;link_inversion&lt;&#x2F;span&gt;&lt;span&gt;(Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;* &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;cur&lt;&#x2F;span&gt;&lt;span&gt;, VisitFunc &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;pre_order&lt;&#x2F;span&gt;&lt;span&gt;,
&lt;&#x2F;span&gt;&lt;span&gt;                               VisitFunc &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;in_order&lt;&#x2F;span&gt;&lt;span&gt;,
&lt;&#x2F;span&gt;&lt;span&gt;                               VisitFunc &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;post_order&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;    Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; prev &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;    Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; old_prev;
&lt;&#x2F;span&gt;&lt;span&gt;    Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; old_prev_left;
&lt;&#x2F;span&gt;&lt;span&gt;    Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; old_cur;
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;if &lt;&#x2F;span&gt;&lt;span&gt;(cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;== &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;return&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;do &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* 1) Descend leftward as much as possible. *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;while &lt;&#x2F;span&gt;&lt;span&gt;(cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;!= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;            &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;pre_order&lt;&#x2F;span&gt;&lt;span&gt;(cur);
&lt;&#x2F;span&gt;&lt;span&gt;            cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;went_right &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;false&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;            old_cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; cur;
&lt;&#x2F;span&gt;&lt;span&gt;            cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; old_cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;left;
&lt;&#x2F;span&gt;&lt;span&gt;            old_cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;left &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; prev;
&lt;&#x2F;span&gt;&lt;span&gt;            prev &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; old_cur;
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* 2) ascend from right as much as we can. *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;while &lt;&#x2F;span&gt;&lt;span&gt;(prev &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;!= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;&amp;amp;&amp;amp;&lt;&#x2F;span&gt;&lt;span&gt; prev&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;went_right) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;            old_prev &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; prev;
&lt;&#x2F;span&gt;&lt;span&gt;            prev &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; prev&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;right;
&lt;&#x2F;span&gt;&lt;span&gt;            old_prev&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;right &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; cur;
&lt;&#x2F;span&gt;&lt;span&gt;            cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; old_prev;
&lt;&#x2F;span&gt;&lt;span&gt;            &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;post_order&lt;&#x2F;span&gt;&lt;span&gt;(cur);
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* 3)
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;            If prev is null after coming back up from the right,
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;                it means that we have finished traversal,
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;                so head back to the while-condition and get outta here!
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;            Else, we will do an exchange here,
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;                swap to right child of parent. *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;if &lt;&#x2F;span&gt;&lt;span&gt;(prev &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;!= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;            &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* Switch from the left side of prev to the right
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;               Also, mark prev as went_right so we know to traverse
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;               upwards using right pointer. *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;            &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;in_order&lt;&#x2F;span&gt;&lt;span&gt;(prev);
&lt;&#x2F;span&gt;&lt;span&gt;            old_prev_left &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; prev&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;left;
&lt;&#x2F;span&gt;&lt;span&gt;            prev&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;went_right &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;true&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;            prev&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;left &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; cur;
&lt;&#x2F;span&gt;&lt;span&gt;            cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; prev&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;right;
&lt;&#x2F;span&gt;&lt;span&gt;            prev&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;right &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; old_prev_left;
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;} &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;while &lt;&#x2F;span&gt;&lt;span&gt;(prev &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;!= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;);
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;p&gt;The core algorithm is in the name, we must invert the links. As we push down the tree,
we invert the links so that way the child points to the parent, and we can walk up the tree
the same way we walked down. As we go up, we need to un-invert the links so that way the tree
is back as it started. The marker bit is used so that when we go back up, we know if we are
ascending from the left or from the right.&lt;&#x2F;p&gt;
&lt;p&gt;Lets talk about each of these steps.&lt;&#x2F;p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;We must start by traversing leftwards as much as possible.
Keeping pointers to the current and previously visited nodes.
As we traverse, we invert the links. That means that cur-&amp;gt;left will be changed to point to the parent.&lt;&#x2F;p&gt;
&lt;&#x2F;li&gt;
&lt;li&gt;
&lt;p&gt;Next may not make sense, so if it doesnt make perfect sense, come to it after step 3.
Here, we are done with this subtree, so we want to get to the subtree&#x27;s root.
We do this by ascending from the right until we get to the root of the traversed part of the tree.
This ensures the tree is in a state that step 3 can deal with.&lt;&#x2F;p&gt;
&lt;&#x2F;li&gt;
&lt;li&gt;
&lt;p&gt;Thirdly, we do an exchange. Here, we are assuredly in a left child, thanks to step 2.
We can safely traverse to the parents right child and
forget completely about the previous subtree forever!
This exchange marks a completion of the left subtree of the new root,
now we must traverse the right subtree of the new root. Back to step 1!&lt;&#x2F;p&gt;
&lt;&#x2F;li&gt;
&lt;&#x2F;ol&gt;
&lt;p&gt;Here, we are skipping some of the technicalities, like what is &lt;code&gt;went_right&lt;&#x2F;code&gt; for?
It is so that we know when we get to the end of the subtree in step 2.
Hopefully, I will elucidate why its necessary with pictures very soon.
After I elucidate that, I will later explain why it&#x27;s not necessary (hint: Robson!).&lt;&#x2F;p&gt;
&lt;h3 id=&quot;walk-through&quot;&gt;Walk-through&lt;&#x2F;h3&gt;
&lt;p&gt;The algorithm is weird, but I think it&#x27;ll help by showing it!&lt;&#x2F;p&gt;
&lt;div class=&quot;img-tpl&quot;&gt;
    &lt;img src=&quot;inversion01.png&quot; alt=&quot;TODO-SORRY!&quot;&gt;
&lt;&#x2F;div&gt;
&lt;p&gt;Here, the tree has been traversed almost completely down the side.
Each time we step downwards, we invert the links to point to the parent.
The next step will be to venture into the NULL left-child from the current point.&lt;&#x2F;p&gt;
&lt;p&gt;This image has not even finished the first run of step 1 from above yet, so lets continue.&lt;&#x2F;p&gt;
&lt;div class=&quot;img-tpl&quot;&gt;
    &lt;img src=&quot;inversion02.png&quot; alt=&quot;TODO-SORRY!&quot;&gt;
&lt;&#x2F;div&gt;
&lt;p&gt;Okay, we have successfully finished part 1 of the algorithm: &#x27;go leftward a lot&#x27;!
Now step 2 does not apply, &lt;code&gt;went_right&lt;&#x2F;code&gt; has been set for exactly 0 nodes at this point in execution.
We swiftly move to step 3! Here, we perform an exchange.
We have finished traversing the left child of the current subtree (the leaf), and now we must traverse the left.
We do some swaps and end up here:&lt;&#x2F;p&gt;
&lt;div class=&quot;img-tpl&quot;&gt;
    &lt;img src=&quot;inversion03.png&quot; alt=&quot;TODO-SORRY!&quot;&gt;
&lt;&#x2F;div&gt;
&lt;p&gt;Okay, the exchange succeeded! We are back at step 1, because &lt;code&gt;prev != NULL&lt;&#x2F;code&gt;.
Lets ignore the red circle for just a moment and execute step 1.
Done! Did you see it? Nothing!
Of course, &lt;code&gt;cur == NULL&lt;&#x2F;code&gt;, so step 1 is not run. Time for step 2! We must go up until we reach the root!
We run this until &lt;code&gt;prev-&amp;gt;went_right == false&lt;&#x2F;code&gt;, in this case one time.
Running this step means we are prepared to forget about the current subtree.
Step 3 will exchange once more, getting us to the parents right child:&lt;&#x2F;p&gt;
&lt;div class=&quot;img-tpl&quot;&gt;
    &lt;img src=&quot;inversion04.png&quot; alt=&quot;TODO-SORRY!&quot;&gt;
&lt;&#x2F;div&gt;
&lt;p&gt;If you are keen, you may have noticed that this is a strikingly similar image to the first one in the series.
The only difference is the red marker in the &lt;code&gt;prev&lt;&#x2F;code&gt; node. If you apply the operations I have listed since the
start of this subsection, you can fully traverse this tree. Making enough images to illustrate all of that
is an exercise left to the reader.&lt;&#x2F;p&gt;
&lt;p&gt;Link inversion is relatively complex when compared to the standard method, but definitely more fun!&lt;&#x2F;p&gt;
&lt;h3 id=&quot;warning&quot;&gt;Warning&lt;&#x2F;h3&gt;
&lt;p&gt;This algorithm is &lt;em&gt;dangerous&lt;&#x2F;em&gt;! If you attempt to modify the tree while it is being
traversed, pointers will be a complete mess! Make sure this algorithm completes before altering the
tree any more!&lt;&#x2F;p&gt;
&lt;h3 id=&quot;analysis&quot;&gt;Analysis&lt;&#x2F;h3&gt;
&lt;ul&gt;
&lt;li&gt;Space-Complexity: &lt;code&gt;O(n)&lt;&#x2F;code&gt;
&lt;ul&gt;
&lt;li&gt;This is because each tree node needs a marker, so linear cost.&lt;&#x2F;li&gt;
&lt;&#x2F;ul&gt;
&lt;&#x2F;li&gt;
&lt;li&gt;Time complexity: &lt;code&gt;O(n)&lt;&#x2F;code&gt;&lt;&#x2F;li&gt;
&lt;&#x2F;ul&gt;
&lt;p&gt;We still have not yet improved on the algorithmic cost of the standard depth-first search.
We have been doing quite well on solving Knuth&#x27;s challenge, but thats only a minor goal!
Lets get to the real thing now, the Robson traversal.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;the-threaded-tree&quot;&gt;The Threaded Tree&lt;&#x2F;h2&gt;
&lt;p&gt;J. H. Morris presented the threaded tree in 1979, and it involves using those wasteful null nodes
at the ends of the tree. However, you will see it does not solve all of our problems.&lt;&#x2F;p&gt;
&lt;p&gt;Threaded trees have two bits, one for each direction, telling whether the pointer is a thread.
If the left pointer is a thread (&lt;code&gt;cur-&amp;gt;left_thread&lt;&#x2F;code&gt;), then &lt;code&gt;cur-&amp;gt;left&lt;&#x2F;code&gt; points to the in-order
predecessor. The same is true for &lt;code&gt;cur-&amp;gt;right_thread&lt;&#x2F;code&gt; pointing to the in-order successor.
Following threads is a constant operation to the predecessor&#x2F;successor, which speeds up in-order
traversals.&lt;&#x2F;p&gt;
&lt;pre data-lang=&quot;c&quot; style=&quot;background-color:#282a36;color:#f8f8f2;&quot; class=&quot;language-c &quot;&gt;&lt;code class=&quot;language-c&quot; data-lang=&quot;c&quot;&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;typedef struct&lt;&#x2F;span&gt;&lt;span&gt; Tree &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;int&lt;&#x2F;span&gt;&lt;span&gt; data;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;struct&lt;&#x2F;span&gt;&lt;span&gt; Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; left;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;struct&lt;&#x2F;span&gt;&lt;span&gt; Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; right;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;bool&lt;&#x2F;span&gt;&lt;span&gt; left_thread;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;bool&lt;&#x2F;span&gt;&lt;span&gt; right_thread;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;} &lt;&#x2F;span&gt;&lt;span&gt;Tree;
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* Takes the root of the tree (we call it cur for readability in the function itself) *&#x2F;
&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;void &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;threaded_traversal&lt;&#x2F;span&gt;&lt;span&gt;(Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;* &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;cur&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* Go all the way down to the smallest number in the tree. *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;while &lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;!&lt;&#x2F;span&gt;&lt;span&gt;cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;is_thread) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;        cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;left;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* Now all we have to do is go rightwards until the end! *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;while &lt;&#x2F;span&gt;&lt;span&gt;(cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;!= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;inorder_visit&lt;&#x2F;span&gt;&lt;span&gt;(cur);
&lt;&#x2F;span&gt;&lt;span&gt;        cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;tree_successor&lt;&#x2F;span&gt;&lt;span&gt;(cur);
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* Returns a successor to any given node, `node`.*&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;* &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;tree_successor&lt;&#x2F;span&gt;&lt;span&gt;(Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;* &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;node&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;    Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; cur;
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* fast path! *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;if &lt;&#x2F;span&gt;&lt;span&gt;(node&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;right_thread) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;return&lt;&#x2F;span&gt;&lt;span&gt; node&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;right;
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* else return leftmost child of right subtree! *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;    cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; node&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;right;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;while &lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;!&lt;&#x2F;span&gt;&lt;span&gt;cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;left_thread) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;        cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;left;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;return&lt;&#x2F;span&gt;&lt;span&gt; cur;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;p&gt;This &lt;code&gt;Tree&lt;&#x2F;code&gt; struct includes a boolean field to tell whether the current tree node has an in-order thread.
When we search for the in-order successor to the current node, and find that it is a thread, we take the
right node to get the immediate successor! This is always a single operation, AKA O(1) time!&lt;&#x2F;p&gt;
&lt;p&gt;You note, of course, that to support this method, we need to add a boolean field for each and every node in the tree!
This means we are stuck with a linear space cost for this traversal.&lt;&#x2F;p&gt;
&lt;p&gt;Threaded trees are super cool, and I would love for people to know them. Luckily, there is a great

&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;en.wikipedia.org&amp;#x2F;wiki&amp;#x2F;Threaded_binary_tree&quot; target=&quot;_blank&quot;&gt;Wikipedia page↪&lt;&#x2F;a&gt;
 on the subject. If there was not, I would definitely write more.&lt;&#x2F;p&gt;
&lt;p&gt;I won&#x27;t do a full walkthrough of the threaded traversal, but here is an image of a threaded tree:&lt;&#x2F;p&gt;
&lt;div class=&quot;img-tpl&quot;&gt;
    &lt;img src=&quot;threaded01.png&quot; alt=&quot;TODO-SORRY!&quot;&gt;
&lt;&#x2F;div&gt;
&lt;p&gt;To start, go to the leftmost node, which is the minimum of an inorder traversal.
To find the successor, if the right pointer is a thread, follow it, and that is the successor.
If it is not, take it, and then go left as much as possible, that is the next node in-order.&lt;&#x2F;p&gt;
&lt;h3 id=&quot;analysis-1&quot;&gt;Analysis&lt;&#x2F;h3&gt;
&lt;ul&gt;
&lt;li&gt;Space-Complexity: &lt;code&gt;O(n)&lt;&#x2F;code&gt;
&lt;ul&gt;
&lt;li&gt;This is because each tree node needs 2 markers, so linear cost&lt;&#x2F;li&gt;
&lt;&#x2F;ul&gt;
&lt;&#x2F;li&gt;
&lt;li&gt;Time complexity: &lt;code&gt;O(n)&lt;&#x2F;code&gt;&lt;&#x2F;li&gt;
&lt;li&gt;Time complexity for finding a single successor: &lt;em&gt;Amortized&lt;&#x2F;em&gt; &lt;code&gt;O(1)&lt;&#x2F;code&gt;!
&lt;ul&gt;
&lt;li&gt;Ask for that algorithmic analysis post if you want me to explain this!&lt;&#x2F;li&gt;
&lt;&#x2F;ul&gt;
&lt;&#x2F;li&gt;
&lt;&#x2F;ul&gt;
&lt;p&gt;So we have found a cool algorithm that makes use of those dumb null pointers at the fringes of
the tree. It does not seem like we gain much, though, as it still comes at a linear spatial cost.
If you want amortized constant successor finding, then this is a great algorithm for you!&lt;&#x2F;p&gt;
&lt;h2 id=&quot;the-robson-tree-traversal&quot;&gt;The Robson Tree Traversal&lt;&#x2F;h2&gt;
&lt;p&gt;Here we are! The Robson Tree Traversal is a method for traversing trees in linear time, and in &lt;em&gt;&lt;strong&gt;constant space&lt;&#x2F;strong&gt;&lt;&#x2F;em&gt;.&lt;&#x2F;p&gt;
&lt;p&gt;Robson learns from the threaded and link-inversion models. By using the leaf-pointers as pseudo marker-bits,
we create an awesome tree-traversal.&lt;&#x2F;p&gt;
&lt;p&gt;The downside of the threaded-tree was that it is linear-space.
Yet, it successfully used those null pointers that we lamented of their waste.
The downside of the link-inversion model is that it is worst-case linear-space.
We had to add an extra bit of memory to each node.
Robson solves both problems by playing to the strength&#x27;s of both!&lt;&#x2F;p&gt;
&lt;h3 id=&quot;the-algorithm&quot;&gt;The Algorithm&lt;&#x2F;h3&gt;
&lt;p&gt;Lets start by talking about the memory usage. We need a few bytes of memory for this to work,
here is what we will be using those bytes for:&lt;&#x2F;p&gt;
&lt;ul&gt;
&lt;li&gt;a &lt;code&gt;cur&lt;&#x2F;code&gt; pointer. This will be the current node that we are algorithmizing.&lt;&#x2F;li&gt;
&lt;li&gt;a &lt;code&gt;parent&lt;&#x2F;code&gt; pointer. Fairly self explanatory, we need to know the parent of the current node at any given time.
This does not need to be part of the data structure, we will just update our single pointer as the algorithm runs.&lt;&#x2F;li&gt;
&lt;li&gt;a pointer we call &lt;code&gt;available&lt;&#x2F;code&gt;. This will be used to point to a node that we can use in our &#x27;leaf-stack&#x27;,
that I will describe later.&lt;&#x2F;li&gt;
&lt;li&gt;A pointer called &lt;code&gt;top&lt;&#x2F;code&gt;. This will be the top of the aforementioned and still mysterious leaf-stack.&lt;&#x2F;li&gt;
&lt;li&gt;a temporary pointer used for exchanging nodes similarly to link-inversion.&lt;&#x2F;li&gt;
&lt;li&gt;a bool used to keep some state regarding how we have been traversing the tree.&lt;&#x2F;li&gt;
&lt;&#x2F;ul&gt;
&lt;p&gt;These variables are kept in the function, and other than them, the only memory needed is the tree itself!
Unlike the other algorithms mentioned in this post, this tree is completely basic. There are no changes
to the underlying data structure from what you learn in CS102. Now, lets move to the algorithm itself.
The core algorithm is split into two parts: pushing down the tree, and finding the next subtree.&lt;&#x2F;p&gt;
&lt;p&gt;First, we push down the tree while inverting the pointers, a la link-inversion.
We go down the tree not until we hit the left-most node, like in link-inversion,
but when we hit a fully fledged leaf. The inversions themselves are a bit different than in link-inversion.
There are a few couple to consider:&lt;&#x2F;p&gt;
&lt;ol&gt;
&lt;li&gt;There is a left child. Here, we follow the the left child.
The left pointer is set to the parent of the current node, and the right is unaltered.
This follows link-inversion, nothing to change here.&lt;&#x2F;li&gt;
&lt;li&gt;There is no left child, but there is a right child. Here we do the same as case 1, but
we set the current right pointer to the parent. This is very important, we leave the left child&#x27;s
pointer alone as null. When we go back up the tree, we will see that the parent&#x27;s left is null,
and know that we are ascending via the right tree. This is important in preserving the tree&#x27;s structure.&lt;&#x2F;li&gt;
&lt;li&gt;There are no children (as in cur is a leaf). This is the start of the interesting stuff!
Robson uses the leaf nodes as a sort of pseudo-stack. The leaf-stack tells us where to ascend from when
we dont know if we are ascending from left or right. Here, we simply will track the leaf as &#x27;available&#x27;.
Wow! We are at a leaf! That means it&#x27;s time to go up!&lt;&#x2F;li&gt;
&lt;&#x2F;ol&gt;
&lt;p&gt;Lets discuss these states with pictures! If someone wants to write an interactive javascript demo of this,
be my guest!&lt;&#x2F;p&gt;
&lt;p&gt;Going up the tree, we have 4 cases, some mundane, and some interesting!&lt;&#x2F;p&gt;
&lt;ol&gt;
&lt;li&gt;The parent&#x27;s right pointer is null. Here, we must be ascending from the left. We un-invert the
pointers, as in link-inversion. No funny business yet!&lt;&#x2F;li&gt;
&lt;li&gt;The parent&#x27;s left pointer is null. This is a mirror of the previous case, so ascend using
the right pointers instead of the left.&lt;&#x2F;li&gt;
&lt;li&gt;Now, the tree has both pointers, how do we know if we are ascending from the left or right?
Here we are getting a bit interesting! We are at an &#x27;exchange point&#x27;, where we do not know
if we should ascend from the left or from the right. Lets move out of this list
and talk about the leaf stack, and its relation to exchange points.&lt;&#x2F;li&gt;
&lt;&#x2F;ol&gt;
&lt;h4 id=&quot;the-leaf-stack&quot;&gt;The Leaf Stack&lt;&#x2F;h4&gt;
&lt;p&gt;The leaf stack is not a real stack, but a linked list, composed of tree leaves.
The &lt;code&gt;right&lt;&#x2F;code&gt; pointer of each leaf&#x2F;stack-element points to an &#x27;exchange point&#x27;.
Each left pointer points to the next element of the list&#x2F;stack.
We call it a stack because we only access the top element, and therefore it is treated as a stack.
Also, its a cheeky &#x27;im not touching you&#x27; to Knuth&#x27;s challenge. Anyways, these exchange points are used
to tell if we are ascending from the left or right. Lets get back into the cases!&lt;&#x2F;p&gt;
&lt;p&gt;The &lt;code&gt;available&lt;&#x2F;code&gt; pointer&#x27;s destiny is to be the new head of the leaf-stack.
Before we add it to the stack though, we must find an exchange point.
I&#x27;ll leave the answer for not immediately adding it to the stack as an exercise to the reader.
Once we find an exchange point we will set &lt;code&gt;available&lt;&#x2F;code&gt; to the head of the leaf-stack.&lt;&#x2F;p&gt;
&lt;p&gt;Okay! Now lets get back to finding the next subtree to traverse!&lt;&#x2F;p&gt;
&lt;p&gt;TODO: does this last sentence need more reasons&#x2F;usage?
I feel like people will get caught up on what an exchange point is,
and lose grasp of the section.&lt;&#x2F;p&gt;
&lt;!-- TODO: make this `ol` a shortcode so markdown can render inside of it. --&gt;
&lt;!-- Have to re-start the ol from before. --&gt;
&lt;ol start=&quot;3&quot; class=&quot;numbered&quot;&gt;
    &lt;li&gt;
        Back at the old #3, we were discussing what to do when the parent has both children.
        Let&#x27;s discuss the more difficult and more fun case here. When `top` is null,
        or when `top-&gt;right` does not point to the parent, we know we are ascending from the left.
        This is what we refer to as the exchange point, where the leaf stack first comes into play!
        We will use `available` now and then go down the right subtree. We set `available-&gt;right` to
        the parent, `available-&gt;left` to `top`, and then `top` to `available`. Woohoo, its a linked list!
        After these shenanigans, there are more shenanigans! We can not fix the pointers as in
        link inversion, as `parent-&gt;left` is currently pointing to `parent`&#x27;s parent!
        What we will do is set `parent-&gt;right` to `cur`, and `cur` to `parent-&gt;right`!
        It looks funky when you draw it out, but it works! Now we are on an un-traversed
        section of the tree, so we can resume the go-down part of the algorithm!
        In the next case, we will make use of the leaf stack!
    &lt;&#x2F;li&gt;
    &lt;li&gt;
        Okay! In this final case, we are pushing up the tree, and find that `parent == top-&gt;right`!
        This tells us we are on ascending from the right, and have thus completed the left and right side&#x27;s
        of this subtree! Congratulations! Now, we &#x27;pop&#x27; off of the  leaf-stack, and fix the pointers.
        Remember how the parents right pointer is pointing to the left child? Yeah, now we re-set that!
        We set `parent` (the root of the subtree), to `cur` and continue pushing up the stack using the rules
        I just laid out!
    &lt;&#x2F;li&gt;
&lt;&#x2F;ol&gt;
&lt;p&gt;The algorithm really isnt that hard, but when you look at the tree mid-algorithm, it can be really funky.
Pointers just completely out of place, but still kind of beautiful in a way!
Oh yeah, another reminder to not edit the tree while running this algorithm!
The tree is &lt;em&gt;&lt;strong&gt;not&lt;&#x2F;strong&gt;&lt;&#x2F;em&gt; in a safe, workable, state during these traversals!&lt;&#x2F;p&gt;
&lt;h3 id=&quot;analysis-2&quot;&gt;Analysis&lt;&#x2F;h3&gt;
&lt;p&gt;Amazing.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;&#x2F;h2&gt;
&lt;p&gt;Ending Text!&lt;&#x2F;p&gt;
&lt;h3 id=&quot;p-s&quot;&gt;P.S.&lt;&#x2F;h3&gt;
&lt;p&gt;On x86 systems at least, the least-significant bit of a pointer will always be 0, so you could theoretically store
anything there, as long as you swap it for 0 when you need to actually use the pointer. So maybe
as another way to do this stuff, you can just use one of the pointers&#x27; low bits as the follow pointer
in link inversion. However, that would be really ugly to code, and then I would have had less to write about :(&lt;&#x2F;p&gt;

&lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;stackoverflow.com&amp;#x2F;questions&amp;#x2F;19991506&amp;#x2F;how-portable-is-using-the-low-bit-of-a-pointer-as-a-flag&quot; target=&quot;_blank&quot;&gt;relevant discussion↪&lt;&#x2F;a&gt;
&lt;h3 id=&quot;when-not-to-use-robson&quot;&gt;When not to use robson&lt;&#x2F;h3&gt;
&lt;p&gt;Robson only works on binary trees i think(!)&lt;&#x2F;p&gt;
&lt;p&gt;if you need to stop the algorithm at any time the tree will be in a terrible state,
you need to run the algorithm completely before doing anything else with the tree.&lt;&#x2F;p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Fancy Tree Traversals</title>
        <published>2019-01-02T10:10:44-05:00</published>
        <updated>2019-01-02T10:10:44-05:00</updated>
        
        <author>
          <name>
            
              Unknown
            
          </name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://thedav.is/post/fancy-tree-traversals/"/>
        <id>https://thedav.is/post/fancy-tree-traversals/</id>
        
        <content type="html" xml:base="https://thedav.is/post/fancy-tree-traversals/">&lt;h1 id=&quot;introduction&quot;&gt;Introduction&lt;&#x2F;h1&gt;
&lt;p&gt;In this post, we will discuss a couple of novel methods for traversing trees.
The threaded tree offers amortized constant access to the successor of a tree-node.
The link-inversion traversal offers a stackless traversal of binary trees.&lt;&#x2F;p&gt;
&lt;p&gt;The final code is in &lt;a href=&quot;https:&#x2F;&#x2F;github.com&#x2F;sinistersnare&#x2F;robson&quot;&gt;this repository&lt;&#x2F;a&gt;.
Please read on for some history, and some novel algorithms you may have never heard of!&lt;&#x2F;p&gt;
&lt;h1 id=&quot;the-famous-tree&quot;&gt;The Famous Tree&lt;&#x2F;h1&gt;
&lt;p&gt;The tree is an incredibly important data structure.
A great learning tool for beginning computer scientists, starting to understand the science.
Trees are also used throughout the real-world.
File systems use &lt;a href=&quot;https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;B-tree&quot;&gt;B-trees&lt;&#x2F;a&gt;
to &lt;a href=&quot;https:&#x2F;&#x2F;github.com&#x2F;postgres&#x2F;postgres&#x2F;tree&#x2F;master&#x2F;src&#x2F;backend&#x2F;access&#x2F;nbtree&quot;&gt;store their data&lt;&#x2F;a&gt;.
Text editors use &lt;a href=&quot;https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Rope_(data_structure)&quot;&gt;ropes&lt;&#x2F;a&gt;
to &lt;a href=&quot;https:&#x2F;&#x2F;github.com&#x2F;google&#x2F;xi-editor&#x2F;tree&#x2F;master&#x2F;rust&#x2F;rope&quot;&gt;organize their text&lt;&#x2F;a&gt;.
Trees power the world, inside and outside of computers.
We will be using a simple binary tree for this post.&lt;&#x2F;p&gt;
&lt;p&gt;Here is a common binary tree definition. We will be using C for the whole of this post:&lt;&#x2F;p&gt;
&lt;pre data-lang=&quot;c&quot; style=&quot;background-color:#282a36;color:#f8f8f2;&quot; class=&quot;language-c &quot;&gt;&lt;code class=&quot;language-c&quot; data-lang=&quot;c&quot;&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* We will use this type definition later. *&#x2F;
&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;typedef void &lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt;VisitFunc)(Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt;);
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;typedef struct&lt;&#x2F;span&gt;&lt;span&gt; Tree &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;int&lt;&#x2F;span&gt;&lt;span&gt; data;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;struct&lt;&#x2F;span&gt;&lt;span&gt; Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; left;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;struct&lt;&#x2F;span&gt;&lt;span&gt; Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; right;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;} &lt;&#x2F;span&gt;&lt;span&gt;Tree;
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;p&gt;We can create the tree like so:&lt;&#x2F;p&gt;
&lt;pre data-lang=&quot;c&quot; style=&quot;background-color:#282a36;color:#f8f8f2;&quot; class=&quot;language-c &quot;&gt;&lt;code class=&quot;language-c&quot; data-lang=&quot;c&quot;&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;int &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;main&lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;void&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;    Tree root, root_left;
&lt;&#x2F;span&gt;&lt;span&gt;    root_left&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;.&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;data &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;0&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;    root_left&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;.&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;left &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;    root_left&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;.&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;right &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;    root&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;.&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;data &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;1&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;    root&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;.&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;left &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &amp;amp;&lt;&#x2F;span&gt;&lt;span&gt;root_left;
&lt;&#x2F;span&gt;&lt;span&gt;    root&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;.&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;right &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;h2 id=&quot;how-do-we-traverse-a-tree&quot;&gt;How Do We Traverse a tree?&lt;&#x2F;h2&gt;
&lt;p&gt;Traversing a tree is accessing each node&#x27;s data in the whole tree.
This is obviously a critically important function of a tree,
we should be able to access all elements if we need to.&lt;&#x2F;p&gt;
&lt;p&gt;Luckily, traversing a tree is super easy!&lt;&#x2F;p&gt;
&lt;pre data-lang=&quot;c&quot; style=&quot;background-color:#282a36;color:#f8f8f2;&quot; class=&quot;language-c &quot;&gt;&lt;code class=&quot;language-c&quot; data-lang=&quot;c&quot;&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;void &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;traverse&lt;&#x2F;span&gt;&lt;span&gt;(Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;* &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;cur&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;if &lt;&#x2F;span&gt;&lt;span&gt;(cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;== &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;return&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;pre_visit&lt;&#x2F;span&gt;&lt;span&gt;(cur); &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* pre-order traversal *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;traverse&lt;&#x2F;span&gt;&lt;span&gt;(cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;left);
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;in_visit&lt;&#x2F;span&gt;&lt;span&gt;(cur); &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* in-order traversal *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;traverse&lt;&#x2F;span&gt;&lt;span&gt;(cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;right);
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;post_visit&lt;&#x2F;span&gt;&lt;span&gt;(cur); &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* post-order traversal *&#x2F;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;p&gt;Pre-order traversal always visits a parent before its child. This is very useful when you want to copy a tree, maintaining its order. In-order is mostly used for sorted trees, as it will visit nodes in order! A node will be visited in post-order only after its children have been visited. This means that post-order is best used for tasks such as deleting the tree, freeing its memory without dangling pointers left over. If we made &lt;code&gt;free&lt;&#x2F;code&gt; our pre-visit function, then we would never be able to traverse right children!&lt;&#x2F;p&gt;
&lt;p&gt;This algorithm is universally taught in beginning CS courses at universities.
It gets the job done, and yet here we are, trying to complicate things!&lt;&#x2F;p&gt;
&lt;h1 id=&quot;stackless-traversals&quot;&gt;Stackless Traversals&lt;&#x2F;h1&gt;
&lt;p&gt;When we use that standard traversal algorithm, we utilize the power of stacks! Stacks are a wonderful and simple datastructure. Imagine first: a &lt;em&gt;stack&lt;&#x2F;em&gt; of plates in your cupboard. You can not pick a plate from the center of that stack, you must go from the top. This Last-In-First-Out ordering is great for traversing trees too! Now, lets imagine the left-edge of the tree to be our plate-stack. As we traverse down, we push nodes onto the stack. When we reach the bottom of the tree, we need a way to get back up. The solution is to simply &#x27;pop&#x27; off the node-stack, and then we are at the &lt;code&gt;second-to-last&lt;&#x2F;code&gt; node!&lt;&#x2F;p&gt;
&lt;p&gt;Next, we go right. Add the right-child of the &lt;code&gt;second-to-last&lt;&#x2F;code&gt; node to the stack. We now have to traverse that sub-tree, the same way as before, all the way to the left, until we reach the bottom. Eventually, after going up and right, and down and left enough, we will have traversed the entire tree. And now we have it, a semi-rigorous explanation of stackful tree traversals!&lt;&#x2F;p&gt;
&lt;p&gt;You can re-write that code in the previous section to use an explicit stack, if you wanted. It is still there, however, implicitly. When a function recurses, it uses a computer&#x27;s internal stack to store information about the current function running. When we go down the tree, we add a &#x27;stack-frame&#x27;, which we use to traverse the tree.&lt;&#x2F;p&gt;
&lt;p&gt;Stacks are amazing! Using a stack grants quite an intuitive model for beginner programmers to grok. For a long time, we only knew how to traverse trees using stacks. It was a sad world though. Punch-cards, no Wikipedia, and Algol... I shudder at the very thought, but I digress. Computer scientists felt this was a silly limitation, and sought to fix that, creating the world we see today through their hatred of stacks.&lt;&#x2F;p&gt;
&lt;p&gt;In 1968, famous computer scientist Donald Knuth gave his community a problem. He wanted an algorithm for traversing trees without using a stack, which does not modify the tree in any way. I will present two algorithms that were not the first, nor the best methods for traversing trees. I like them, though, and feel like they provide some good ideas for computer scientists to learn from.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;the-threaded-tree&quot;&gt;The Threaded Tree&lt;&#x2F;h2&gt;
&lt;p&gt;J.H. Morris presented the threaded tree in 1979. It utilizes the wasteful NULL nodes at the end of trees, for great profit. Using this algorithm will allow us to perform the &lt;code&gt;successor&lt;&#x2F;code&gt; operation of an in-order traversal in &lt;em&gt;amortized constant&lt;&#x2F;em&gt; time.&lt;&#x2F;p&gt;
&lt;p&gt;A Threaded tree has two extra bits of information. One bit informs whether the left pointer is actually a &lt;em&gt;thread&lt;&#x2F;em&gt;, and the other for the right pointer. A thread is &lt;em&gt;not&lt;&#x2F;em&gt; an OS thread, think of it more like a pointer to a seemingly random part of the tree, and not a child. If we follow a thread, what we find is the in-order successor to a node. Here is the code for our Threaded Tree. I will describe the algorithm under the code-block.&lt;&#x2F;p&gt;
&lt;pre data-lang=&quot;c&quot; style=&quot;background-color:#282a36;color:#f8f8f2;&quot; class=&quot;language-c &quot;&gt;&lt;code class=&quot;language-c&quot; data-lang=&quot;c&quot;&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;typedef struct&lt;&#x2F;span&gt;&lt;span&gt; Tree &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;int&lt;&#x2F;span&gt;&lt;span&gt; data;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;struct&lt;&#x2F;span&gt;&lt;span&gt; Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; left;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;struct&lt;&#x2F;span&gt;&lt;span&gt; Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; right;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;bool&lt;&#x2F;span&gt;&lt;span&gt; right_thread;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;} &lt;&#x2F;span&gt;&lt;span&gt;Tree;
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* Takes the root of the tree (we call it cur for readability in the function itself) *&#x2F;
&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;void &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;threaded_traversal&lt;&#x2F;span&gt;&lt;span&gt;(Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;* &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;cur&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* Go all the way down to the smallest number in the tree. *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;while &lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;!&lt;&#x2F;span&gt;&lt;span&gt;cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;is_thread) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;        cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;left;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* Now all we have to do is go rightwards until the end! *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;while &lt;&#x2F;span&gt;&lt;span&gt;(cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;!= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;inorder_visit&lt;&#x2F;span&gt;&lt;span&gt;(cur);
&lt;&#x2F;span&gt;&lt;span&gt;        cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;tree_successor&lt;&#x2F;span&gt;&lt;span&gt;(cur);
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* Returns a successor to any given node, `node`.*&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;* &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;tree_successor&lt;&#x2F;span&gt;&lt;span&gt;(Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;* &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;node&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;    Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; cur;
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* fast path! *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;if &lt;&#x2F;span&gt;&lt;span&gt;(node&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;right_thread) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;return&lt;&#x2F;span&gt;&lt;span&gt; node&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;right;
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* else return leftmost child of right subtree! *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;    cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; node&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;right;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;while &lt;&#x2F;span&gt;&lt;span&gt;(&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;!&lt;&#x2F;span&gt;&lt;span&gt;cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;left) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;        cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;left;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;return&lt;&#x2F;span&gt;&lt;span&gt; cur;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;p&gt;This &lt;code&gt;Tree&lt;&#x2F;code&gt; struct includes a boolean field to tell whether the current tree node has an in-order thread. When we search for the in-order successor to the current node, and find that it is a thread, we take the right node to get the immediate successor! This is always a single operation. If we traverse an entire tree this way, we find that the &lt;code&gt;tree_successor&lt;&#x2F;code&gt; function is running in &lt;em&gt;amortized &lt;code&gt;O(1)&lt;&#x2F;code&gt;&lt;&#x2F;em&gt; speed.&lt;&#x2F;p&gt;
&lt;p&gt;However, to support this method, we must add a boolean field for each and every node in this tree. This means that the spatial cost for this algorithm is linear.&lt;&#x2F;p&gt;
&lt;p&gt;Threaded trees are super cool, and I would love for people to know them. Luckily, there is a great &lt;a href=&quot;https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Threaded_binary_tree&quot;&gt;Wikipedia page&lt;&#x2F;a&gt; on the subject. If there was not, I would definitely write more.&lt;&#x2F;p&gt;
&lt;p&gt;I won&#x27;t do a full walkthrough of the threaded traversal, but here is an image of a threaded tree:&lt;&#x2F;p&gt;
&lt;div class=&quot;img-tpl&quot;&gt;
    &lt;img src=&quot;threaded01.png&quot; alt=&quot;TODO-SORRY!&quot;&gt;
&lt;&#x2F;div&gt;
&lt;p&gt;To start, go to the leftmost node, which is the minimum of an in-order traversal. To find the successor, if the right pointer is a thread, follow it, and that is the successor. If it is not, take it, and then go left as much as possible, that is the next node in-order.&lt;&#x2F;p&gt;
&lt;h3 id=&quot;analysis&quot;&gt;Analysis&lt;&#x2F;h3&gt;
&lt;ul&gt;
&lt;li&gt;Space-Complexity: &lt;code&gt;O(n)&lt;&#x2F;code&gt;
&lt;ul&gt;
&lt;li&gt;This is because each tree node needs 2 markers, so linear cost&lt;&#x2F;li&gt;
&lt;&#x2F;ul&gt;
&lt;&#x2F;li&gt;
&lt;li&gt;Time complexity: &lt;code&gt;O(n)&lt;&#x2F;code&gt;&lt;&#x2F;li&gt;
&lt;li&gt;Time complexity for finding a single successor: &lt;em&gt;Amortized &lt;code&gt;O(1)&lt;&#x2F;code&gt;&lt;&#x2F;em&gt;!&lt;&#x2F;li&gt;
&lt;&#x2F;ul&gt;
&lt;p&gt;So we have found a cool algorithm that makes use of those dumb null pointers at the fringes of the tree. It does not seem like we gain much, though, as it still comes at a linear spatial cost. If you want amortized constant successor finding, then this is a great algorithm for you!&lt;&#x2F;p&gt;
&lt;p&gt;For me, the biggest downside of this algorithm is that it only works for in-order traversals. If you want pre- or post-order traversals, this algorithm is not for you.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;the-link-inversion-model&quot;&gt;The Link-Inversion Model&lt;&#x2F;h2&gt;
&lt;p&gt;Link Inversion is a key ingredient to our final algorithm. Link-Inversion is a process where we use a marker-bit on each node to tell if we should continue to traverse up, or traverse rightward when going up a tree.&lt;&#x2F;p&gt;
&lt;p&gt;This method is stackless, like the threaded tree traversal. The trick is that we jumble the pointers, to thwart hacking attempts. Just kidding! We only seemingly jumble pointers! Also, it is not to thwart hackers, its to show us the way back up the tree!&lt;&#x2F;p&gt;
&lt;pre data-lang=&quot;c&quot; style=&quot;background-color:#282a36;color:#f8f8f2;&quot; class=&quot;language-c &quot;&gt;&lt;code class=&quot;language-c&quot; data-lang=&quot;c&quot;&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;typedef struct&lt;&#x2F;span&gt;&lt;span&gt; Tree &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;int&lt;&#x2F;span&gt;&lt;span&gt; data;
&lt;&#x2F;span&gt;&lt;span&gt;    Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; left;
&lt;&#x2F;span&gt;&lt;span&gt;    Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; right;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;bool&lt;&#x2F;span&gt;&lt;span&gt; went_right;
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;} &lt;&#x2F;span&gt;&lt;span&gt;Tree;
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#8be9fd;&quot;&gt;void &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;link_inversion&lt;&#x2F;span&gt;&lt;span&gt;(Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;* &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;cur&lt;&#x2F;span&gt;&lt;span&gt;, VisitFunc &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;pre_order&lt;&#x2F;span&gt;&lt;span&gt;,
&lt;&#x2F;span&gt;&lt;span&gt;                               VisitFunc &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;in_order&lt;&#x2F;span&gt;&lt;span&gt;,
&lt;&#x2F;span&gt;&lt;span&gt;                               VisitFunc &lt;&#x2F;span&gt;&lt;span style=&quot;font-style:italic;color:#ffb86c;&quot;&gt;post_order&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;    Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; prev &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;    Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; old_prev;
&lt;&#x2F;span&gt;&lt;span&gt;    Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; old_prev_left;
&lt;&#x2F;span&gt;&lt;span&gt;    Tree&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;*&lt;&#x2F;span&gt;&lt;span&gt; old_cur;
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;if &lt;&#x2F;span&gt;&lt;span&gt;(cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;== &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;return&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;do &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* 1) Descend leftward as much as possible. *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;while &lt;&#x2F;span&gt;&lt;span&gt;(cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;!= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;            &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;pre_order&lt;&#x2F;span&gt;&lt;span&gt;(cur);
&lt;&#x2F;span&gt;&lt;span&gt;            cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;went_right &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;false&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;            old_cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; cur;
&lt;&#x2F;span&gt;&lt;span&gt;            cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; old_cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;left;
&lt;&#x2F;span&gt;&lt;span&gt;            old_cur&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;left &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; prev;
&lt;&#x2F;span&gt;&lt;span&gt;            prev &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; old_cur;
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* 2) ascend from right as much as we can. *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;while &lt;&#x2F;span&gt;&lt;span&gt;(prev &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;!= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;&amp;amp;&amp;amp;&lt;&#x2F;span&gt;&lt;span&gt; prev&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;went_right) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;            old_prev &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; prev;
&lt;&#x2F;span&gt;&lt;span&gt;            prev &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; prev&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;right;
&lt;&#x2F;span&gt;&lt;span&gt;            old_prev&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;right &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; cur;
&lt;&#x2F;span&gt;&lt;span&gt;            cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; old_prev;
&lt;&#x2F;span&gt;&lt;span&gt;            &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;post_order&lt;&#x2F;span&gt;&lt;span&gt;(cur);
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;span&gt;
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* 3)
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;            If prev is null after coming back up from the right,
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;                it means that we have finished traversal,
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;                so head back to the while-condition and get outta here!
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;            Else, we will do an exchange here,
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;                swap to right child of parent. *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;if &lt;&#x2F;span&gt;&lt;span&gt;(prev &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;!= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;) &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;{
&lt;&#x2F;span&gt;&lt;span&gt;            &lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;&#x2F;* Switch from the left side of prev to the right
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;               Also, mark prev as went_right so we know to traverse
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#6272a4;&quot;&gt;               upwards using right pointer. *&#x2F;
&lt;&#x2F;span&gt;&lt;span&gt;            &lt;&#x2F;span&gt;&lt;span style=&quot;color:#50fa7b;&quot;&gt;in_order&lt;&#x2F;span&gt;&lt;span&gt;(prev);
&lt;&#x2F;span&gt;&lt;span&gt;            old_prev_left &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; prev&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;left;
&lt;&#x2F;span&gt;&lt;span&gt;            prev&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;went_right &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;true&lt;&#x2F;span&gt;&lt;span&gt;;
&lt;&#x2F;span&gt;&lt;span&gt;            prev&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;left &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; cur;
&lt;&#x2F;span&gt;&lt;span&gt;            cur &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; prev&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;right;
&lt;&#x2F;span&gt;&lt;span&gt;            prev&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;-&amp;gt;&lt;&#x2F;span&gt;&lt;span&gt;right &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;=&lt;&#x2F;span&gt;&lt;span&gt; old_prev_left;
&lt;&#x2F;span&gt;&lt;span&gt;        &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;span&gt;    &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;} &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;while &lt;&#x2F;span&gt;&lt;span&gt;(prev &lt;&#x2F;span&gt;&lt;span style=&quot;color:#ff79c6;&quot;&gt;!= &lt;&#x2F;span&gt;&lt;span style=&quot;color:#bd93f9;&quot;&gt;NULL&lt;&#x2F;span&gt;&lt;span&gt;);
&lt;&#x2F;span&gt;&lt;span style=&quot;color:#ffffff;&quot;&gt;}
&lt;&#x2F;span&gt;&lt;&#x2F;code&gt;&lt;&#x2F;pre&gt;
&lt;p&gt;The core algorithm is in the name, we must invert the links. As we push down the tree,
we invert the links so that way the child points to the parent, and we can walk up the tree
the same way we walked down. As we go up, we need to un-invert the links so that way the tree
is back as it started. The marker bit is used so that when we go back up, we know if we are
ascending from the left or from the right.&lt;&#x2F;p&gt;
&lt;p&gt;Let&#x27;s talk about each of these steps.&lt;&#x2F;p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;We must start by traversing leftwards as much as possible.
Keeping pointers to the current and previously visited nodes.
As we traverse, we invert the links. That means that cur-&amp;gt;left will be changed to point to the parent.&lt;&#x2F;p&gt;
&lt;&#x2F;li&gt;
&lt;li&gt;
&lt;p&gt;Next may not make sense, so if it doesn&#x27;t make perfect sense, come to it after step 3.
Here, we are done with this subtree, so we want to get to the subtree&#x27;s root.
We do this by ascending from the right until we get to the root of the traversed part of the tree.
This ensures the tree is in a state that step 3 can deal with.&lt;&#x2F;p&gt;
&lt;&#x2F;li&gt;
&lt;li&gt;
&lt;p&gt;Thirdly, we do an exchange. Here, we are assuredly in a left child, thanks to step 2.
We can safely traverse to the parents right child and
forget completely about the previous subtree forever!
This exchange marks a completion of the left subtree of the new root,
now we must traverse the right subtree of the new root. Back to step 1!&lt;&#x2F;p&gt;
&lt;&#x2F;li&gt;
&lt;&#x2F;ol&gt;
&lt;p&gt;Here, we are skipping some of the technicalities, like what is &lt;code&gt;went_right&lt;&#x2F;code&gt; for?
It is so that we know when we get to the end of the subtree in step 2.
Hopefully, I will elucidate why its necessary with pictures very soon.
After I elucidate that, I will later explain why it&#x27;s not necessary (hint: Robson!).&lt;&#x2F;p&gt;
&lt;h3 id=&quot;walk-through&quot;&gt;Walk-through&lt;&#x2F;h3&gt;
&lt;p&gt;The algorithm is weird, but I think it&#x27;ll help by showing it!&lt;&#x2F;p&gt;
&lt;div class=&quot;img-tpl&quot;&gt;
    &lt;img src=&quot;inversion01.png&quot; alt=&quot;TODO-SORRY!&quot;&gt;
&lt;&#x2F;div&gt;
&lt;p&gt;Here, the tree has been traversed almost completely down the side.
Each time we step downwards, we invert the links to point to the parent.
The next step will be to venture into the NULL left-child from the current point.&lt;&#x2F;p&gt;
&lt;p&gt;This image has not even finished the first run of step 1 from above yet, so let&#x27;s continue.&lt;&#x2F;p&gt;
&lt;div class=&quot;img-tpl&quot;&gt;
    &lt;img src=&quot;inversion02.png&quot; alt=&quot;TODO-SORRY!&quot;&gt;
&lt;&#x2F;div&gt;
&lt;p&gt;Okay, we have successfully finished part 1 of the algorithm: &#x27;go leftward a lot&#x27;!
Now step 2 does not apply, &lt;code&gt;went_right&lt;&#x2F;code&gt; has been set for exactly 0 nodes at this point in execution.
We swiftly move to step 3! Here, we perform an exchange.
We have finished traversing the left child of the current subtree (the leaf), and now we must traverse the left.
We do some swaps and end up here:&lt;&#x2F;p&gt;
&lt;div class=&quot;img-tpl&quot;&gt;
    &lt;img src=&quot;inversion03.png&quot; alt=&quot;TODO-SORRY!&quot;&gt;
&lt;&#x2F;div&gt;
&lt;p&gt;Okay, the exchange succeeded! We are back at step 1, because &lt;code&gt;prev != NULL&lt;&#x2F;code&gt;.
Let&#x27;s ignore the red circle for just a moment and execute step 1.
Done! Did you see it? Nothing!
Of course, &lt;code&gt;cur == NULL&lt;&#x2F;code&gt;, so step 1 is not run. Time for step 2! We must go up until we reach the root!
We run this until &lt;code&gt;prev-&amp;gt;went_right == false&lt;&#x2F;code&gt;, in this case one time.
Running this step means we are prepared to forget about the current subtree.
Step 3 will exchange once more, getting us to the parents right child:&lt;&#x2F;p&gt;
&lt;div class=&quot;img-tpl&quot;&gt;
    &lt;img src=&quot;inversion04.png&quot; alt=&quot;TODO-SORRY!&quot;&gt;
&lt;&#x2F;div&gt;
&lt;p&gt;If you are keen, you may have noticed that this is a strikingly similar image to the first one in the series.
The only difference is the red marker in the &lt;code&gt;prev&lt;&#x2F;code&gt; node. If you apply the operations I have listed since the
start of this subsection, you can fully traverse this tree. Making enough images to illustrate all of that
is an exercise left to the reader.&lt;&#x2F;p&gt;
&lt;p&gt;Link inversion is relatively complex when compared to the standard method, but definitely more fun!&lt;&#x2F;p&gt;
&lt;h3 id=&quot;warning&quot;&gt;Warning&lt;&#x2F;h3&gt;
&lt;p&gt;This algorithm is &lt;em&gt;dangerous&lt;&#x2F;em&gt;! If you attempt to modify the tree while it is being
traversed, pointers will be a complete mess! Make sure this algorithm completes before altering the
tree anymore!&lt;&#x2F;p&gt;
&lt;h3 id=&quot;analysis-1&quot;&gt;Analysis&lt;&#x2F;h3&gt;
&lt;ul&gt;
&lt;li&gt;Space-Complexity: &lt;code&gt;O(n)&lt;&#x2F;code&gt;
&lt;ul&gt;
&lt;li&gt;This is because each tree node needs a marker, so linear cost.&lt;&#x2F;li&gt;
&lt;&#x2F;ul&gt;
&lt;&#x2F;li&gt;
&lt;li&gt;Time complexity: &lt;code&gt;O(n)&lt;&#x2F;code&gt;&lt;&#x2F;li&gt;
&lt;&#x2F;ul&gt;
&lt;p&gt;We still have not yet improved on the algorithmic cost of the standard depth-first search.
We have been doing quite well on solving Knuth&#x27;s challenge, but thats only a minor goal!
Let&#x27;s get to the real thing now, the Robson traversal.&lt;&#x2F;p&gt;
&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;&#x2F;h2&gt;
&lt;p&gt;The threaded tree is a great structure for in-order traversal. Use it when you need to find the successor to a node lickity-split. The link-inversion method is quite strange, almost alien. However, it is used as the basis for a much cooler algorithm, The Robson Traversal. This post does not cover this traversal, but maybe a future one will.&lt;&#x2F;p&gt;
&lt;p&gt;These algorithms are quite interesting to me. Finding novel ways to do simple tasks can lead to some interesting findings. Even if we re-invent the wheel sometimes, knowing how to make a wheel is important! I hope you find a cool use for these algorithms in the future. They have provided me with quite a bit of help, I would like to think.&lt;&#x2F;p&gt;
&lt;h3 id=&quot;p-s&quot;&gt;P.S.&lt;&#x2F;h3&gt;
&lt;p&gt;I have another blog post in the works, detailing an even cooler tree traversal. This Robson traversal is little known, but traverses trees in &lt;em&gt;&lt;strong&gt;constant space&lt;&#x2F;strong&gt;&lt;&#x2F;em&gt;. Please keep an eye out for this forthcoming blog post.&lt;&#x2F;p&gt;
&lt;p&gt;If you liked this post, and want to see the new one even sooner, shoot me an email or a tweet for encouragement! I hope you learned something great today!&lt;&#x2F;p&gt;
</content>
        
    </entry>
</feed>
