<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="4.3.4">Jekyll</generator><link href="https://www.haoxuany.com/feed.xml" rel="self" type="application/atom+xml"/><link href="https://www.haoxuany.com/" rel="alternate" type="text/html" hreflang="en"/><updated>2026-06-11T00:01:56+00:00</updated><id>https://www.haoxuany.com/feed.xml</id><title type="html">Aaron Yue</title><subtitle>Aaron&apos;s Website </subtitle><entry><title type="html">Johnson Memoized CPS Parser (aka the Agda mixfix parser)</title><link href="https://www.haoxuany.com/blog/johnson/" rel="alternate" type="text/html" title="Johnson Memoized CPS Parser (aka the Agda mixfix parser)"/><published>2026-06-10T00:00:00+00:00</published><updated>2026-06-10T00:00:00+00:00</updated><id>https://www.haoxuany.com/blog/johnson</id><content type="html" xml:base="https://www.haoxuany.com/blog/johnson/"><![CDATA[<blockquote class="block-warning"> <p>This post is under construction.</p> </blockquote> <p>I’m currently pretty stuck on my compiler project, for technical problems related to the modular type classes <a class="citation" href="#DHCK2007">(Dreyer et al., 2007)</a> paper, and how poorly it interacts with the module interpretation of datatype and polymophism in particular. It is a bit of a long story but I had two different elaboration stragies in mind, both of which are deeply problematic for complicated, and different, reasons (perhaps a different blog post/brain dump on a different day, but the crux here is that specifically I’m not compiling exactly Standard ML in the Definition, and dictionary construction actually forces me to be extremely careful about how elaboration works).</p> <p>Nevertheless, I find it useful to just take a break from thinking about it for a while. Maybe come back to the drawing board in a few days and hope that I get a different perspective on this (I doubt it, but we’ll see). So it’s time to look at something completely different (and certainly much more straightforward).</p> <p>For quite a long time, I was somewhat facinated by how Agda does mixfix notation parsing. For those not familiar with Agda, basically you can just define a function like this:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>if_then_else_ : {A : Set} → Bool → A → A → A
if true then x else y = x
if false then x else y = y
</code></pre></div></div> <p>and then the parser will pick it up as a mixfix expression and apply it to subsequent parsing (ex. <code class="language-plaintext highlighter-rouge">if true then 1 else 1</code>), where <code class="language-plaintext highlighter-rouge">_</code> represents a hole an expression should go to. (Note that it sticks to the Haskell convention where the arguments are always curried.)</p> <p>Nowadays many modern languages have notational shorthands like this (on top of my head, Coq, Lean and Isabelle comes to mind). The most sophisticated notation system is probably the one implemented in Coq, but to be honest that implementation is exceptionally complicated and requires the language to have specific conventions (in Gallina’s case, all statements terminated with a <code class="language-plaintext highlighter-rouge">.</code>) to work. Languages like Standard ML (what I’m working on) and Haskell have a much more restricted notation parsing system (“fixity”), which only handles infix operators. That can be accomplished in a very straightforward way through a hand written shift reduce parser, so there’s not much to see there. Since I’m implementing my own compiler as a single person project, I have always wondered if a similar mixfix parsing feature can be added to the language, but it wasn’t too obvious how to do so on top of my head.</p> <p>So time to steal how everyone else does it. The way Agda does it is more akin to what a normal person would do: it does a single round of lexing and parsing first, where these notation expressions are first interpreted as a list of application expression. Then it performs a second round of parsing to handle these mixfix parses. The <a href="https://github.com/agda/agda/blob/master/src/full/Agda/Utils/Parser/MemoisedCPS.hs">internal comments</a> in the code very nicely pointed me to <a class="citation" href="#Johnson1995">(Johnson, 1995)</a>, which I thought was a really cool paper, and is what I’ll explain today.</p> <p>Before this, a huge disclaimer:</p> <blockquote class="block-warning"> <p>I am not computability theorist. Like most people working on languages, I only really care about issues on language design. Issues on grammar design are something I prefer <em>not</em> to think about if possible. As such, my knowledge on computability theory is dated, so read this at your own risk. The results I’m writing about are almost entirely from the Johnson paper, but for reasons which I will sometimes explain, the presentation is different. I will present all this in Standard ML (the original paper presents this in Scheme).</p> </blockquote> <h1 id="top-down-parsing">Top Down Parsing</h1> <p>Like (probably) most computer science students, I am very significantly more well versed in bottom up parsing than top down parsing. This is because bottom up parsers are much more widely used, and there is a reason for this. To see the problems with top down parsing, let us look at an example, of parsing an expression with only natural numbers and addition:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>E ::= n (where n is a natural number) | E + E
</code></pre></div></div> <p>We stick to the convention that uppercase expressions are metavariables/nonterminals and anything else are just terminals/atom/axioms. This syntax is ambiguous, in that an expression <code class="language-plaintext highlighter-rouge">1 + 2 + 3</code> can have two different parses: <code class="language-plaintext highlighter-rouge">(1 + 2) + 3</code> and <code class="language-plaintext highlighter-rouge">1 + (2 + 3)</code>. We shall presume that we want <em>all</em> possible parses.</p> <p>Top down parsing consists of checking whether the string matches some rule for the grammar, and if so, apply it. Do this for all rules (since we want all possible parses). This makes writing the code very simple, since each parsing rule can be very directly modelled as a function. The function takes in a token stream (to simplify, suppose it is a list of strings), and then returns a list of all possible parses, and the rest of the stream that is remaining. Hence, it is not too far-fetched to quickly hack up this piece of code:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>structure Fail = struct
  type stream = string list
  datatype exp =
    ExpNat of int
  | ExpPlus of exp * exp

  type t = stream -&gt; (exp * stream) list
  
  fun parse_single s (f : string -&gt; exp option) =
    case s of
      nil =&gt; nil
    | h :: t =&gt; 
        let
        in
          case f h of
            NONE =&gt; nil
          | SOME v =&gt; [ ( v , t ) ]
        end

  fun bind (a : t) (f : exp -&gt; t) : t =
    fn s =&gt;
      let 
        val parses = List.map (fn (e , s) =&gt; f e s) (a s)
      in 
        List.concat parses
      end

  fun either (l : t list) : t =
    fn s =&gt;
    let
      val parses = List.map (fn f =&gt; f s) l
    in
      List.concat parses
    end

  fun parse_num s = parse_single s 
    (fn v =&gt;
      case Int.fromString v of 
         NONE =&gt; NONE
       | SOME v =&gt; SOME (ExpNat v))

  and parse_plus s =
    bind parse_exp
    (fn e1 =&gt; fn s =&gt;
      case s of
        nil =&gt; nil
      | h :: t =&gt;
          if h = "+"
          then nil
          else 
            bind parse_exp
            (fn e2 =&gt; fn s =&gt; [ (ExpPlus (e1 , e2) , s) ]) 
            t
    ) s

  and parse_exp s =
    either [ parse_num , parse_plus ] s
end
</code></pre></div></div> <p>In this code, <code class="language-plaintext highlighter-rouge">parse_single</code>, <code class="language-plaintext highlighter-rouge">bind</code>, and <code class="language-plaintext highlighter-rouge">either</code> are just simple parser combinators: <code class="language-plaintext highlighter-rouge">parse_single</code> just parses a single token and converts it to an expression, <code class="language-plaintext highlighter-rouge">bind</code> is basically just sequencing (parse <code class="language-plaintext highlighter-rouge">a</code> first, then parse <code class="language-plaintext highlighter-rouge">f</code>), and <code class="language-plaintext highlighter-rouge">either</code> is basically just consider all these possible parsing rules. The implementation of <code class="language-plaintext highlighter-rouge">parse_num</code>, <code class="language-plaintext highlighter-rouge">parse_plus</code>, and <code class="language-plaintext highlighter-rouge">parse_exp</code> are self explanatory then based on exactly what the grammar says).</p> <blockquote class="block-tip"> <p>In the original paper, Johnson calls the functions <code class="language-plaintext highlighter-rouge">parse_single</code>, <code class="language-plaintext highlighter-rouge">bind</code>, <code class="language-plaintext highlighter-rouge">either</code> different names: <code class="language-plaintext highlighter-rouge">terminal</code>, <code class="language-plaintext highlighter-rouge">seq</code>, <code class="language-plaintext highlighter-rouge">alt</code>. The types differ because here we are not just concerned about whether the given token stream has valid parses (perhaps that is more useful in a NLP context?). We care a lot about exactly what syntax tree the parsing ended up producing. Hence we are not at all concerned about “recognizers” in the paper, and the syntax we deal with are all CFGs anyway.</p> </blockquote> <p>The nice part is that this code doesn’t take very long to write from scratch. The bad part is that it doesn’t work (and why many people stick to bottom up parsing). There are two big problems here:</p> <h2 id="left-factoring">Left Factoring</h2> <p>In order to parse <code class="language-plaintext highlighter-rouge">E</code>, I need to try and parse <code class="language-plaintext highlighter-rouge">E + E</code>. But in order to parse <code class="language-plaintext highlighter-rouge">E + E</code>, I need to parse <code class="language-plaintext highlighter-rouge">E</code> first, then <code class="language-plaintext highlighter-rouge">+</code>, then <code class="language-plaintext highlighter-rouge">E</code> again. This procedure does not terminate because the leftmost token refers to a parsing procedure back to itself, which makes no progress here (still at the beginning of the stream). You can simply see in the code that is doesn’t terminate.</p> <p>This is a very significant problem, and generally a strong enough reason to not use top down parsing (at least certainly not so liberally). On top of my head, these are the ways to make it work that I know of:</p> <ol> <li>Just stick with bottom up parsing, which does not have this problem.</li> <li>Use a lookahead parser to determine how many tokens to consume for parsing the subexpression (aka, LL(k))</li> <li>Refactor the syntax, for example, if my syntax has delimiters (say, wrapped in <code class="language-plaintext highlighter-rouge">[</code> <code class="language-plaintext highlighter-rouge">]</code> always), then there is in fact neither parsing ambiguity nor left factoring issues: <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>E ::= n | [ E + E ]
</code></pre></div> </div> <p>This is because just by looking at <code class="language-plaintext highlighter-rouge">[</code> I can uniquely make progress in top down parsing since I know exactly where the subexpression starts and ends.</p> </li> <li>Alternatively, I can refactor the grammar a bit to make this work (aka. “left factoring”), by breaking down which rules should be handled when.</li> </ol> <p>(It just occurred to me when writing that I actually don’t know of a general left factoring algorithm. I just know how to do it with concrete examples. One day remind me to look into it.)</p> <p>In any case, 2, 3, 4, requires you to know the <em>whole</em> syntax ahead of time, which you don’t for mixfix notation parsing, because it is user defined. More importantly, 2, 3, 4, are simply not always possible to do (2 might not have a finite lookahead, 3, 4, can be constrained by what the grammar looks like). Because these are <em>global</em> syntax transformations, modelling them as functions no longer work, because functions are negative types (aka, you cannot break up a function to look at it inside), so you basically end with something more similar to a parser generator with a top down strategy rather than a parser combinator anyway if you pick any of the approaches here.</p> <blockquote class="block-tip"> <p>A note on practicality: the reality is that most parser generators today actually generate code rather than generate internal representations on the fly that can be easily linked to your compiler, so unless your parser generator library supports constructing these rules on the fly, for practical purposes, it’s a no go, at least for mixfix parsing.</p> </blockquote> <h2 id="time-complexity">Time complexity</h2> <p>The other issue is time complexity for a naive approach like this. Suppose this is the grammar that I am parsing:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>T ::= T list
    | T tree
    | int
</code></pre></div></div> <p>(aka the grammar is basically <code class="language-plaintext highlighter-rouge">int</code> postfixed with <code class="language-plaintext highlighter-rouge">list</code> or <code class="language-plaintext highlighter-rouge">tree</code> multiple times.)</p> <p>Top down parsing in fact requires you to guess which rule to use for parsing. If I want to parse something like <code class="language-plaintext highlighter-rouge">int list tree tree tree</code>, what will happen is: I will guess first that my rule is <code class="language-plaintext highlighter-rouge">T list</code>, this requires me to parse <code class="language-plaintext highlighter-rouge">T = int list tree tree</code> first, and then check the next token is <code class="language-plaintext highlighter-rouge">list</code> (which it is not, it is <code class="language-plaintext highlighter-rouge">tree</code>). So my guess here missed. Then I have to guess that my rule is <code class="language-plaintext highlighter-rouge">T tree</code>, which requires me to parse <code class="language-plaintext highlighter-rouge">T = int list tree tree</code> a <em>second</em> time, and then check that the next token is <code class="language-plaintext highlighter-rouge">tree</code>, which worked this time. Given n tokens, <code class="language-plaintext highlighter-rouge">T(n) = c1T(n - 1) + c2T(n - 1) + c3</code>, which solves to <code class="language-plaintext highlighter-rouge">T(n) = O(2 ^ n)</code>, aka exponential time. (Note that because I am actually getting all parses, the actual time complexity is even worse than this.)</p> <p>This issue has a much more straightforward solution: we can always memoize at a location completed parses of <code class="language-plaintext highlighter-rouge">T</code>. When we need it a second time we can just pull it out. That is, assuming that parsing for <code class="language-plaintext highlighter-rouge">T</code> terminates in the first place (aka left factoring).</p> <h1 id="johnson">Johnson</h1> <p>So are parser combinators doomed? When I was much younger in college, I thought that due to left factoring issues, parser combinators are not practical to use in general parsing (not to mention that dealing with left factoring is simply painful, I’m sure anyone who had the displeasure of writing parsers in general can agree).</p> <p>I am glad to see that I am proven wrong by <a class="citation" href="#Johnson1995">(Johnson, 1995)</a>: there is a surprisingly straightforward way of working around both issues at the same time. It involves two very simple tricks that everyone learned in freshman programming class, but used them in a surprising way: CPS and memoization.</p> <p>In short, the idea is:</p> <ul> <li>The parser combinator can be written in continuation passing style, which transforms it into something very similar to a parser table. We send the results to the continuation one at a time. Aka, previously if there are no valid parse results, the continuation will never be called, and if there are multiple parse results, we send them to the continuation one at a time, so the continuation gets called multiple times, etc.</li> <li>Memoization takes care of both left factoring (through a simple termination proof), and time complexity, at the same time.</li> </ul> <h2 id="trick-1-cps-conversion-by-hand">Trick 1: CPS conversion (by hand)</h2> <p>The first step is straightforward: we change the type of the combinator. Now, instead of returning the parse results, we call the provided continuation each time.</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>type t = stream -&gt; ((exp * stream) -&gt; unit) -&gt; unit
</code></pre></div></div> <blockquote class="block-tip"> <p>You might be wondering why I’m using the unit type rather than the void type or <code class="language-plaintext highlighter-rouge">'a</code> here. The reason here is that the function can return if there are no valid parses in the rule. It does not return only if parsing succeeds. See <code class="language-plaintext highlighter-rouge">parse_single</code> below.</p> </blockquote> <p>Then to rewrite the combinators:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fun parse_single (f : string -&gt; exp option) s k =
  case s of
    nil =&gt; ()
  | h :: t =&gt;
      let
      in
        case f h of
          NONE =&gt; ()
        | SOME v =&gt; k ( v , t )
      end

fun bind (a : t) (f : exp -&gt; t) : t =
  fn s =&gt; fn k =&gt;
    a s (fn (exp , s) =&gt; f exp s k)

fun either (l : t list) : t =
  fn s =&gt; fn k =&gt;
  List.app (fn f =&gt; f s k) l
</code></pre></div></div> <p>Which is actually mildly easier to write now, since the type really just tells you everything. However, since we are writing code in CPS form by hand, and the rest of your program <em>probably</em> isn’t in CPS form, we will unfortunately need to use a reference to escape out of CPS form, and also collate all parses sent over.</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fun run (p : t) : stream -&gt; (exp * stream) list =
  fn s =&gt;
  let
    val results = ref []
    val () = p s (fn result =&gt; results := result :: (!results) )
  in
    !results
  end
</code></pre></div></div> <p>So far no problems, but this does not solve the inherent issue of left factoring. This brings us to the next trick.</p> <h2 id="trick-2-memoization">Trick 2: Memoization</h2> <p>So this is the really tricky part of the paper: how do you memoize for this problem? Usually for programs <strong>not</strong> in CPS form, we think of something like:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
functor Memoize (structure A :
  sig 
    type t
    val eq : t -&gt; t -&gt; bool
  end) = struct
    
    local open A in

    fun memo (f : t -&gt; 'a) : t -&gt; 'a =
      let 
        val table = ref []
      in
        fn v =&gt;
          case List.find (fn (x , _) =&gt; A.eq x v) (!table) of
            SOME (_ , res) =&gt; res
          | NONE =&gt;
              let
                val result = f v
              in
                table := (v , result) :: (!table) ;
                result
              end
      end

    end
        
end
</code></pre></div></div> <p>(exactly what it says, if a value exists in the table, look it up and use it directly, otherwise compute the function value and write it to the table, then return. There are obviously different ways of writing this where you can do lookup faster with a better data structure, if say <code class="language-plaintext highlighter-rouge">A.t</code> can also be hashed instead of using a list, etc.)</p> <p>But what about for the CPS converted combinators here? Clearly we shouldn’t be caching the “return value”, since that value gets passed to the continuation, and possibly multiple times.</p> <p>First, we handle the arguments. We determine whether two token streams are the same by comparing “where we are” in the stream, aka the current stream position. We assume that all tokens have unique positions, which can be easily done by just tacking some integer position on the token stream. Hence we can memoize results of subparses by only referring to their positions in the stream (which is nice, since it does not require an equality function on the input token type at all). This is also nice since we are no longer restricted to lists for memoization, as the same trick works for coinductive streams as well.</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>type token = string * int
type stream = token list
</code></pre></div></div> <p>Then what about the results? This is the tricky part. Per <a class="citation" href="#Johnson1995">(Johnson, 1995)</a>, we will also need to maintain a list of continuations that are passed in as well, and call them at the appropriate time. Specifically:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code></code></pre></div></div> <blockquote class="block-warning"> <p>This post is under construction.</p> </blockquote>]]></content><author><name></name></author><category term="programming"/><summary type="html"><![CDATA[magic tricks]]></summary></entry><entry><title type="html">Thoughts on Standard ML</title><link href="https://www.haoxuany.com/blog/experimental-sml/" rel="alternate" type="text/html" title="Thoughts on Standard ML"/><published>2026-01-30T00:00:00+00:00</published><updated>2026-01-30T00:00:00+00:00</updated><id>https://www.haoxuany.com/blog/experimental-sml</id><content type="html" xml:base="https://www.haoxuany.com/blog/experimental-sml/"><![CDATA[<p>So as I am very quickly getting old and washed, people who are close to me might know that I’m in the process of writing my own SML compiler. Much like most one man projects that need to juggle an irrelevant day job and this, it is going extremely slowly. But this post here is to mostly dump my thoughts in case I forget about them one day (which, as you are getting old and washed, happens).</p> <p>The elephant in the room is that there are likely more than 10 different compiler implementation for SML out there, and they are all (annoyingly) different and specializes in most things that you can think of, so why write one more when there are already pretty good implementations out there? (My personal favorite implementations are the New Jersey compiler, SML#, and Rossberg’s HamLet).</p> <p>A few years ago I was working on a similar ML compiler, but decided to scrape it, because I regretted certain implementation strategies that I did. The internal type theory is quite similar to the one in TILT, but for a number of reasons on top of my head it was unsatisfactory for seperate compilation in too many ways. But more importantly, I wanted to fix certain things in the <em>language</em>, from scratch.</p> <p>There are three main goals in my mind:</p> <ol> <li>To fix some of the language to be more consistent with Harper-Stone.</li> <li>To implement dictionary construction for modules.</li> <li>To have a “good enough” implementation of seperate compilation, independent of the module system (aka. unlike OCaml). For example, something similar to <a class="citation" href="#SMCH2006">(Swasey et al., 2006)</a>.</li> </ol> <p>Hence this is a rant about some stuff I don’t like in Standard ML, and on top of my mind, what is the right way to fix it. Of course, I really like the language (as any minimally competent programmer does); I wouldn’t bother to talk about it otherwise.</p> <h1 id="what-is-standard-ml">What is Standard ML?</h1> <p>When I think of Standard ML, there are two well known papers that stand out on top of my head:</p> <ul> <li>Harper-Stone Elaboration <a class="citation" href="#HarperStone2000">(Harper &amp; Stone, 2000)</a></li> <li>The Mechanized Metatheory of Standard ML <a class="citation" href="#LeeCraryHarper2007">(Lee et al., 2007)</a>. The paper doesn’t have complete details because the proof is quite large, so you’d need to look at the Twelf proof.</li> </ul> <p>These papers are also based on the PhD thesis of Dreyer on recursive modules. <a class="citation" href="#Dreyer2005">(Dreyer, 2005)</a></p> <p>If there is one thing I <em>don’t</em> care about, it is the original definition <a class="citation" href="#Defn2nd">(Milner et al., 2019)</a>. The definition is noble in its goals at the time, but pretty problematic in retrospect. It’s not just the tiny things, but overall in methodology on how the language is defined. The wonderful thing about Harper-Stone is that it translates the language into proper objects in type theory, so that it can be actually studied, and type safety (and surprisingly, even parametricity <a class="citation" href="#Crary2017">(Crary, 2017)</a>) can actually be proven. I personally think that this fact alone makes it the canonical view of ML.</p> <p>There’s also this other paper by Sterling-Harper, but quite frankly I don’t understand it after years of trying. <a class="citation" href="#SterlingHarper2021">(Sterling &amp; Harper, 2021)</a></p> <p>Then there’s the Rossberg-Russo-Dreyer F-ing Modules paper <a class="citation" href="#RossbergRussoDreyer2010">(Rossberg et al., 2010)</a>, which basically attempts to elaborate away all modules. Technically there’s nothing wrong with the paper, but I don’t hold this view. I consider modules as proper type theoretic objects. They are basically dependent sums with restrictions.</p> <h1 id="the-well-known-problems">The Well Known Problems</h1> <p>Most people who write any real amount of code probably already know, or seen, many of the problems. An excellent comprehensive list is given in <a href="https://people.mpi-sws.org/~rossberg/papers/Rossberg%20-%20Defects%20in%20the%20Revised%20Definition%20of%20Standard%20ML%20[2013-09-18%20Update].pdf">Rossberg</a>. These issues are largely uncontroversial on their own, but the correct fix on the other hand can be. To list out a few (out of many) that I do plan to address slowly while I’m here anyway:</p> <ul> <li>Parsing bugs, a lot of them. Many shift-reduce conflicts, and some horrific reduce-reduce conflicts in the case of <code class="language-plaintext highlighter-rouge">&lt;match&gt;</code>. These mostly involve changing some of the syntax and is more annoying than it is difficult to fix. I’m personally happy as long as all such conflicts are avoided as much as possible, which generally involves adding a reserved word in expressions, declaration, etc.</li> <li>eqtype needs to die. It is questionable to do equality checks in the first place, but it should absolutely not be in the language.</li> <li>Fixity is very messy in the language. I haven’t decided exactly what to do here yet, as it seems that whatever I end up with will piss somebody off one way or the other regardless.</li> <li>Some stuff could definitely be more general, or nicer. For instance, being able to define extension types that are not <code class="language-plaintext highlighter-rouge">exn</code>. Some syntatic sugar on working with products/records. Having/Being able to define a <code class="language-plaintext highlighter-rouge">void</code> type as an empty datatype. Some syntatic sugar like <code class="language-plaintext highlighter-rouge">M.(e)</code> = <code class="language-plaintext highlighter-rouge">let open M in e end</code> like in OCaml. Removing positional argument syntax in functors. Higher order functors. Cleaning up the syntax for type sharing. The list goes on and on.</li> <li>Having a seperate compilation system that doesn’t depend on modules.</li> </ul> <p>To me, these are mostly the minor annoying problems, and boils down to spending a very long time writing a lot of implementation code. There are, however, two major problems that I want to address, which had been stuck in my head for years ever since and is what I will actually talk about. These two issues have led me to conclude that the right way forward is to ignore backwards compatibilty altogether and start from scratch, because it will require a rethinking of how to structure libraries anyway. I can’t say I have a complete solution in my mind already, so this should be considered a sketch.</p> <h1 id="issue-1-syntatic-patterns-and-datatype">Issue 1: Syntatic Patterns and Datatype</h1> <p>One of my biggest gripes with the language is not being able to define syntatic patterns for a type. Let me explain how I came to this particular conclusion, but you will have to bear with me since this will take a while.</p> <p>In Harper-Stone elaboration, datatypes are just modules. This is a very nice view of datatypes, because it seperates out what datatype is actually doing within the internal language into disparate parts. A datatype is a module with an abstract type, a constructor, and a pattern (or destructor, if you will). For example:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>datatype foo = Foo of int | Bar of string
</code></pre></div></div> <p>is actually (I will make up some concrete syntax for the internal language to make it nicer to read):</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>structure Foo :&gt; sig
  type t (* = mu.(int + string) *)

  val Foo : int -&gt; t
  val Bar : string -&gt; t

  val expose (* pattern for t *) : t -&gt; (int[Tag Foo] + string[Tag Bar])
end = struct ... end
</code></pre></div></div> <p>Basically there is an abstract type <code class="language-plaintext highlighter-rouge">t</code> that is internally implemented with a recursive sum, two constructors (aka just functions), and one pattern/destructor <code class="language-plaintext highlighter-rouge">expose</code> (aka also just a function). The <code class="language-plaintext highlighter-rouge">expose</code> function is applied every time pattern matching happens. (Let’s ignore equality for time being. I’ll get to it when I talk about the next issue.). For example:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>case foo : foo of
| Foo.Foo x =&gt; e1
| Foo.Bar y =&gt; e2
</code></pre></div></div> <p>becomes</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>case[int + string] Foo.expose foo of
| InjFoo v =&gt; (fn x =&gt; e1) v
| InjBar v =&gt; (fn y =&gt; e2) v
</code></pre></div></div> <p>From the Harper-Stone perspective, what struck me when I first read it, is that it is a huge shame there is no way to syntatically express patterns for the type in the concrete language (like <code class="language-plaintext highlighter-rouge">expose</code> here). This turns into certain bizarre artifacts when writing code that happens more often than people think.</p> <p>The most annoying place where this shows up is when people put a <code class="language-plaintext highlighter-rouge">datatype</code> in a signature. I generally avoid putting <code class="language-plaintext highlighter-rouge">datatype</code> in signatures because of what the definition requires. Suppose I am writing, say, a signature for <code class="language-plaintext highlighter-rouge">STACK</code>. At this point, I have to make a decision. The first cut, I can do:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>signature STACK = sig
  datatype 'a t = Empty | Stack of 'a * 'a t

  val push : 'a t -&gt; 'a -&gt; 'a t
  (* and etc. *)
end
</code></pre></div></div> <p>This type is clearly isomorphic with the type of lists, but it isn’t a list. It can be represented as a list, so what I want to be able to write, following Harper-Stone, is:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>structure StackList :&gt; STACK = struct
  type 'a t = 'a list

  val Empty = Nil
  val Cons (h , t) = Stack (h , t)
end
</code></pre></div></div> <p>And now I’m stuck for two reasons: Reason 1) This doesn’t typecheck, because ‘a t needs to be a datatype. Reason 2) I can’t write code in the surface syntax for patterns.</p> <p>Therefore, to deal with these two problems today, what I can do is to change the signature to remove <code class="language-plaintext highlighter-rouge">datatype</code> and use an abstract type, and to have some “view” type for the pattern. For example, the signature needs to be:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>signature STACK = sig
  type 'a t

  val empty : 'a t
  val push : 'a t -&gt; 'a -&gt; 'a t

  datatype 'a view = Empty | Stack of 'a * 'a t
  val elim : 'a t -&gt; 'a view
end
</code></pre></div></div> <p>I found this problematic for two reasons. The first has to do with more complex pattern matching. For instance, if I want to check that some <code class="language-plaintext highlighter-rouge">s : int stack</code> has <code class="language-plaintext highlighter-rouge">1</code> and <code class="language-plaintext highlighter-rouge">2</code> at the top of the stack, what do I do? I want to write:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>case s of
| Stack (1 , Stack (2 , rest)) =&gt; e (* do something *)
</code></pre></div></div> <p>except that because my views are (potentially) lazy, this won’t work, so you’d need to do something like</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>case elim s of
| Stack (1 , s) =&gt;
  case elim s of
  | Stack (2 , rest) =&gt; e
</code></pre></div></div> <p>And at this point, you have effectively <em>become the compiler</em>, compiling everything yourself.</p> <p>The second reason has to do with what this actually looks like in the internal language. Suppose I have some implementation:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>structure S : STACK = sig
  type 'a t = 'a list

  datatype 'a view = Empty | Stack of 'a * 'a t
  fun elim s =
    case s of
    | Nil =&gt; Empty
    | Cons (h , t) =&gt; Stack (h , elim t)
end
</code></pre></div></div> <p>Because <code class="language-plaintext highlighter-rouge">'a view</code> is also a <code class="language-plaintext highlighter-rouge">datatype</code>, the internal language of Harper-Stone looks like</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>structure S : STACK = sig
  structure List = List
  structure View = struct
    type 'a t (* = mu x.fn x =&gt; 1 + 'a * 'a x *)

    val Empty : 'a t
    val Stack : 'a t -&gt; 'a -&gt; 'a t
  end

  open List View

  fun elim s =
    case List.expose s of
    (* ... *)
end
</code></pre></div></div> <p>Aka, this requires a translation to some other type <code class="language-plaintext highlighter-rouge">'a View.t</code>, which is there solely to help people with pattern matching.</p> <p>Arguably, this translation is probably necessary anyway (I have thoughts on optimization, but not very concrete at the moment), but in this form, it will require the compiler to do a pretty difficult analysis to optimize. Also observe that the sole purpose of <code class="language-plaintext highlighter-rouge">'a view</code> is just to help people pattern match. The internal representation <code class="language-plaintext highlighter-rouge">'a View.t</code> is completely irrelevant, because it gets eliminated immediately in pattern matching, and you are essentially just working with recursive sums directly instead of all the <code class="language-plaintext highlighter-rouge">fold</code> and <code class="language-plaintext highlighter-rouge">unfold</code> that needs to happen.</p> <p>I found all this very ugly and unsatisfactory. If you pick the first signature, you get locked into a data representation. If you pick the second signature, you get screwed during pattern matching. So generally people pick the second signature, since at least it is more general.</p> <p>This happens a lot when you need to write types that have multiple representations. And the point of ML module type theory is precisely to allow multiple implementations. For instance, for locally nameless form of the Debruijn representation, trying to do pattern matching can be hell when you need to switch between representations manually. A similar issue is working with streams, where you need to do this kind of fold/unfold constantly.</p> <h2 id="my-idea-for-a-fix">My Idea for A Fix</h2> <p>So there are two questions with writing it the straightforward way. The first question here being, ignoring the pattern matching part, should this typecheck?</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>structure StackList :&gt; sig
  datatype 'a t = Empty | Stack of 'a * 'a t
end = struct
  type 'a t = 'a list

  val Empty = Nil
  val Cons (h , t) = Stack (h , t)

  (* do something about patterns *)
end
</code></pre></div></div> <p>My answer to this is an emphatic <strong>yes</strong>. Of course this should typecheck. Because from the perspective of Harper-Stone, datatypes are <em>just</em> modules, and hence datatype specifications are <em>just</em> signatures. Who cares if you are implementing recursive sums exactly the way the “canonical compiler” dictates! If you have a more efficient representation, it should typecheck by Harper-Stone, and you should be able to replace it with a better one.</p> <p>This means that you can represent booleans with integers or natural numbers with integers. For example, I think this should typecheck:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>structure BoolInt : sig
  datatype t = True | False
end = struct
  type t = int

  val True = 1
  val False = 0

  (* do something about patterns *)
end
structure NatInt : sig
  datatype t = Z | S of t
end = struct
  type t = int

  val Z = 0
  fun S v = v + 1

  (* do something about patterns *)
end
</code></pre></div></div> <p>This is obviously a better natural number implementation than what the definition of Standard ML dictates the signature to be. You can work with natural numbers inductively, but it is also represented internally efficiently. So you get the best of both worlds here.</p> <p>The motivation above brings us to the natural question on what to do about patterns here, and that is not so obvious. My current idea is to basically have a specific pattern construct so that it can be used as elaboration for pattern matching. This idea was basically stolen from Rossberg’s HamLetS (except that conversion only goes one way):</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>structure NatInt : sig
  datatype t = Z | S of t
end = struct
  type t = int

  val Z = 0
  fun S v = v + 1

  pattern t (as t2) Z | S of t = pat
    fun convert (v : t) : t2 =
      case v of
      | 0 =&gt; Z
      | _ =&gt; S (v - 1)
  end
end
</code></pre></div></div> <p>In the pattern declaration, <code class="language-plaintext highlighter-rouge">Z</code> and <code class="language-plaintext highlighter-rouge">S</code> are functions only available within the <code class="language-plaintext highlighter-rouge">pat ... end</code> block, whereas outside the block only the pattern is available for use.</p> <p>Similarly, just as you can view a binary search tree as both a tree and a sorted list, a type can have multiple patterns. I haven’t worked out the details yet but I suspect it can be annoying to elaborate, especially with polymorphism in the type. A nice thing here is that it doesn’t just allow you to write the conversion eagerly, but in the above example it also works on as “as needed” basis for pattern matching, where only the stuff you pattern much gets evaluated, even in complex patterns. Hence,</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>case i : NatInt.t of
| S (S v) =&gt; e
</code></pre></div></div> <p>becomes</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>case convert i of
| S x' =&gt;
  case convert x' of
  | S v =&gt; e (* v here is still an int, internally *)
</code></pre></div></div> <p>whereas if you insist on evaluating stuff eagerly here (I don’t see why you would), you can still do:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  pattern t (as t2) Z | S of t2 = pat
    fun convert (v : t) : t2 =
      case v of
      | 0 =&gt; Z
      | _ =&gt; S (convert (v - 1))
  end
</code></pre></div></div> <p>But more importantly, it “completes” the Harper-Stone interpretation nicely without compromises. This signature:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>sig
  datatype t = Z | S of t
end
</code></pre></div></div> <p>is now syntatic sugar and completely identical to this one:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>sig
  type t

  val Z : t
  val S : t -&gt; t

  pattern t (as t2) of Z | S of t
end
</code></pre></div></div> <p>Similarly, the so-called “GADTs” are just modules, with some special typechecking rules for the typechecker:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>sig
  datatype 'a exp =
  | Int : int -&gt; int exp
  | String : string -&gt; string exp
  | Plus : int exp * int exp -&gt; int exp
end
</code></pre></div></div> <p>is just</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>sig
  type 'a exp

  val Int : int -&gt; int exp
  val String : string -&gt; string exp
  val Plus : int exp * int exp -&gt; int exp

  pattern 'a exp (as 'a exp2) of
    Int : int -&gt; int exp
  | String : string -&gt; string exp
  | Plus : int exp * int exp -&gt; int exp
end
</code></pre></div></div> <p>and can be implemented with a “regular” datatype for all you care:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>struct E : E = struct
  datatype exp =
  | Int of int
  | String of string
  | Plus of exp * exp
  (* etc *)
end
</code></pre></div></div> <p>And everything typechecks and everyone is happy. Probably. (There are still a bunch of corners I haven’t ironed out here yet.)</p> <h1 id="issue-2-the-modular-type-classes-paper">Issue 2: The Modular Type Classes Paper</h1> <p>So there’s this paper <a class="citation" href="#DHCK2007">(Dreyer et al., 2007)</a> that describes the point of view of some modules as type classes, and doing dictionary construction on it. I agree with the paper “in spirit”. This is how most ML programmers think about certain modules with a “most important” type anyway.</p> <p>My main problem with this paper is the implementation, which I don’t agree with. There are two main issues on top of my mind, one is practical and one theoretical. But in either case, the problem is dealing with the actual metatheory of ML rather than the much more simplified case in the paper.</p> <p>On the practical side, the issue with the actual ML language is that it has much more annoying types to deal with, in particular n-ary products and n-ary sums. For example, suppose I want to write a functor for equality, how do I actually do it? If I do:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>functor Eq (structure A : EQ structure B : EQ) : EQ = struct
  type t = A.t * B.t
  fun == ((a, a'), (b, b')) = a === b andalso a' = b'
end
</code></pre></div></div> <p>which really only works for the exact binary product type <code class="language-plaintext highlighter-rouge">A * B</code>, but in ML, you can have n-ary products, and you can have products with labels. You can’t actually write something like:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>functor Eq(structure A : EQ, structure A2 : EQ, ... ) : EQ
</code></pre></div></div> <p>This makes no sense. It breaks everything about functors because you need to have to deal with arbitrary specs, which does not have any type theoretic meaning.</p> <p>A similar issue is with <code class="language-plaintext highlighter-rouge">datatype</code> and labeled products. Once in a while, the label can actually matter, for example, in a “Show” functor that prints out values. If you want to print out a labeled product, you probably will want to print the label as well. So your specification will need to look something more like:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>functor Show(
  val labelA : string
  structure A : SHOW
  val labelB : string
  structure B : SHOW
) : SHOW = struct
  type t = (* what do I put here? *)
  fun show (a , b) = String.concat [{ , labelA , : , show A (* etc *)
end
</code></pre></div></div> <p>It’s also pretty questionable what you’ll need to instantiate this functor by hand.</p> <p>My take on this is: it doesn’t appear to be avoidable, that in general some form of metaprogramming will need to be involved, which is all about looking at the type and constructing programs. I don’t see any other way, especially in the second case. So what <code class="language-plaintext highlighter-rouge">deriving</code> should do is to both be able to derive the exact module for the type given a signature, and also a functor for signature, since that type can be arbitrary. That code will need to live in the compiler rather than be possible to hand write.</p> <p>The next one is a theoretical issue with recursive types. For simple cases of recursive types, it is probably okay. For example:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>datatype foo = Int of int | Foo of foo
</code></pre></div></div> <p>One possible functor we can write for <code class="language-plaintext highlighter-rouge">EQ</code> is probably:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>functor Foo(structure Int : EQ) : EQ = struct
  datatype t = Int of Int.int | Foo of t (* this needs to be not generative *)
  fun == (a , b) =
    case (a , b) of
      (Int i , Int j) =&gt; Int.== (i ,j)
    | (Foo a , Foo b) =&gt; == (a , b)
end
</code></pre></div></div> <p>We can probably agree that this is the right functor, since if we take another specification <code class="language-plaintext highlighter-rouge">structure Foo : EQ</code>, it breaks the interpretation of datatypes being generative (which we’ll need to work around in the internal language), but more importantly, makes this functor impossible to instantiate.</p> <p>What is much worse, however, are mutually recursive types, for example:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>datatype foo = Int of int | Bar of bar
and bar = Foo of foo
</code></pre></div></div> <p>Even if we generate two functors:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>functor FooEq(
  structure Int : EQ
  structure Bar : EQ
) : EQ
functor BarEq(
  structure Foo : EQ
) : EQ
</code></pre></div></div> <p>This is impossible to instantiate either, since they are mutually dependent on either other’s implementation.</p> <p>But let’s take a step back for a moment. Suppose that we give up being able to customize the specific equality used for both <code class="language-plaintext highlighter-rouge">foo</code> and <code class="language-plaintext highlighter-rouge">bar</code>. We are left with:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>functor FooEq(structure Int : EQ) : EQ = struct
  fun == (a , b) =
    case (a , b) of
    | (Bar a, Bar b) =&gt; (* what now ? *)
end
structure BarEq : EQ = struct
  fun == (a , b) =
    case (a , b) of
    | (Foo a, Foo b) =&gt; (* what now ? *)
end
</code></pre></div></div> <p>At this point, both modules depend on each other, and even worse, <code class="language-plaintext highlighter-rouge">BarEq</code>, in a way, implicitly needs to depend on the implementation of integer equality from <code class="language-plaintext highlighter-rouge">FooEq</code> (which of course, makes sense looking at the type). But how to write the code?</p> <p>This can be quite the headache, since if you’re me, you really want to avoid the theory of recursive modules. I found the theory rather painful to handle in so many ways. I have to be honest that I haven’t figured out yet, but on the top of my head, if we ignore potentially a backpatching solution, this will probably also work:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>functor FooBarEq(structure Int : EQ) = struct
  type t = (* ... *)

  fun fooeq (a , b) =
    case (a , b) of
    | (Int a , Int b) =&gt; Int.== (a , b)
    | (Bar a , Bar b) =&gt; bareq (a , b)
  and bareq (a , b) =
    case (a , b) of
    | (Foo a , Foo b) =&gt; fooeq (a , b)

  structure FooEq : EQ = struct
    type t = foo
    val == = fooeq
  end
  structure BarEq : EQ = struct
    type t = bar
    val == = bareq
  end
end
</code></pre></div></div> <p>and then we round it out with</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>functor FooEq(structure Int : EQ) : EQ =
let
  structure E = FooBarEq(structure Int = Int)
in
  E.FooEq
end
functor BarEq(structure Int : EQ) : EQ =
let
  structure E = FooBarEq(structure Int = Int)
in
  E.BarEq
end
</code></pre></div></div> <p>Which is a very convoluted way of avoiding recursive modules by just constructing recursive functions and placing them in the right place.</p> <h1 id="thoughts">Thoughts</h1> <p>Either way, there’s still a long ways to go, but in however many years I actually finish this stuff, it will likely require a rewrite of libraries (which I suspect will need to happen anyway, just by killing <code class="language-plaintext highlighter-rouge">eqtype</code>). So here comes probably another year of no blog updates.</p>]]></content><author><name></name></author><category term="programming"/><summary type="html"><![CDATA[here we go again]]></summary></entry><entry><title type="html">How to Dislike Constructive Mathematics Correctly</title><link href="https://www.haoxuany.com/blog/dislike-constructive-mathematics/" rel="alternate" type="text/html" title="How to Dislike Constructive Mathematics Correctly"/><published>2025-02-22T00:00:00+00:00</published><updated>2025-02-22T00:00:00+00:00</updated><id>https://www.haoxuany.com/blog/dislike-constructive-mathematics</id><content type="html" xml:base="https://www.haoxuany.com/blog/dislike-constructive-mathematics/"><![CDATA[<p>I am going to quickly go over, at a very elementary level, what constructive mathematics is all about. Unlike all the other stuff I plan to blog about, this material is decidedly <em>not</em> technical, and I plan to keep the discussion strictly at a <strong>high school</strong> level. There will be no technical discussion of proofs in type theory or logic, and all proofs are phrased in English in a way that can hopefully be appreciated by everyone, using only basic arithmetic and logic.</p> <p>The main reason I’m writing this is that I finally got annoyed enough by the occassionally bizarre comments by certain mathematicians about why they don’t like constructive mathematics, why the law of excluded middle is critical, and why most of mathematics cannot be done without it. Most of these statements are <strong>false</strong> (here comes the angry mob), and the very point of this post is to do some mythbusting.</p> <p>To make my biases clear: I <em>do</em> believe in constructive mathematics, for reasons related to computer science and type theory. That said, I don’t think that classical mathematics is <em>wrong</em> per se, nor can it ever be, which will be validated in the development below. But in a precise sense, it is <strong>worse</strong>. My main issue is that a number of people dislike constructive mathematics for the <em>wrong reasons</em> due to some fundamental misunderstandings, even in the elementary development below. Clearing that up is the point of this post.</p> <p>If you have any basic knowledge in modern logic, type theory, or programming languages, this post is not for you. Yes, I am aware there are different schools of constructivism, and it is not the point of the post to discuss these finer points. If you have the background, there are no new ideas here and a much more detailed explanation can be found in a good textbook in logic. Reading my explanations would just be preaching to the choir.</p> <p>That said, allow me to quickly quote Andrej Bauer in his <a href="https://www.youtube.com/watch?v=21qPOReu4FI">very excellent talk about constructive mathematics</a> out of context:</p> <blockquote> <p>If you don’t believe me, you can type it into Coq.</p> </blockquote> <p>Which is exactly what we are going to do. We will give two descriptions: one in English (for those who aren’t familiar with type theory), and one in Coq (for those who don’t believe me, and to not so subtly illustrate a specific point later).</p> <h1 id="some-basic-definitions">Some Basic Definitions</h1> <p>We start with some very basic definitions.</p> <blockquote class="block-tip"> <p>Definition: a <strong>proposition</strong> is a statement of some sort.</p> </blockquote> <p>Yes I am aware that this is a bad definition, since there are technically some restrictions on what can be a proposition, but that is besides the point here. We will survive with this for now. Note that this is phrased deliberately to avoid wording it the other (wrong) way.</p> <blockquote class="block-tip"> <p>Definition: A proposition is <strong>true</strong> if there is a proof of it.</p> </blockquote> <p>Again, we don’t explicitly define what a proof is. There are some technical reasons to avoid doing so (Godel’s Incompleteness), and we won’t be concerned about them here.</p> <p>For convenience, we call this definition <strong>Proof of a Truth</strong>, aka to show that a proposition is true, we prove it.</p> <p>This brings us to our first theorem:</p> <blockquote class="block-tip"> <p>Theorem: There are some true propositions.</p> </blockquote> <ul id="true-prop" class="tab" data-tab="c043dff6-ef72-413a-8b55-c1ffb9f759bd" data-name="true-prop"> <li class="active" id="true-prop-english"> <a href="#">English </a> </li> <li id="true-prop-coq"> <a href="#">Coq </a> </li> </ul> <ul class="tab-content" id="c043dff6-ef72-413a-8b55-c1ffb9f759bd" data-name="true-prop"> <li class="active"> <p>Proof: $0 = 0$ is a true proposition. It is true by this proof: we use the von Neumann definition of natural numbers, in which case this is equivalent to the statement that $ \emptyset = \emptyset $, which is true by axioms of set theory about equality of sets.</p> </li> <li> <p>The type theoretic version isn’t nearly as contrived.</p> <div class="language-coq highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">Theorem</span><span class="w"> </span><span class="no">zero_id</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="mi">0</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">0</span><span class="pi">.</span><span class="w">
</span><span class="k">Proof</span><span class="pi">.</span><span class="w"> </span><span class="ne">reflexivity</span><span class="pi">.</span><span class="w"> </span><span class="k">Qed</span><span class="pi">.</span><span class="w">

</span><span class="k">Theorem</span><span class="w"> </span><span class="no">true_p_exists</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="kp">exists</span><span class="w"> </span><span class="no">p</span><span class="p">,</span><span class="w"> </span><span class="no">p</span><span class="pi">.</span><span class="w">
</span><span class="k">Proof</span><span class="pi">.</span><span class="w"> </span><span class="kp">exists</span><span class="w"> </span><span class="p">(</span><span class="mi">0</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">0</span><span class="p">)</span><span class="pi">.</span><span class="w"> </span><span class="kp">apply</span><span class="w"> </span><span class="no">zero_id</span><span class="pi">.</span><span class="w"> </span><span class="k">Qed</span><span class="pi">.</span><span class="w">
</span></code></pre></div></div> </li> </ul> <blockquote class="block-tip"> <p>Definition: A proposition is <strong>false</strong> if assuming that it is true, we can derive a contradiction.</p> </blockquote> <p>This is an important point: the term contradiction is <em>not prohibited</em> in constructive mathematics. A contradiction is simply a proposition that is always false. It is a weirdly common misconception that these proofs are not allowed in constructive mathematics, even though they are decidedly not controversial in any school of constructive mathematics that I know of.</p> <p>For convenience, we call this definition <strong>Proof of a Contradiction</strong>, aka we are proving that a contradiction exist, and therefore the proposition is false by virtue of what is means for something to be false.</p> <blockquote class="block-tip"> <p>Theorem: There are some false propositions.</p> </blockquote> <ul id="false-prop" class="tab" data-tab="34a04134-6551-4d90-8616-0c91c6dc4092" data-name="false-prop"> <li class="active" id="false-prop-english"> <a href="#">English </a> </li> <li id="false-prop-coq"> <a href="#">Coq </a> </li> </ul> <ul class="tab-content" id="34a04134-6551-4d90-8616-0c91c6dc4092" data-name="false-prop"> <li class="active"> <p>Proof: $1 = 0$ is a false proposition. It is false by this proof: suppose that it is true, then we have $f(1) = f(0)$ for any function $f$. Let $f(x) = \emptyset \in x$, thus we know that $\emptyset \in 1$ but $\emptyset \notin 0$, and hence they cannot be equal, contradiction.</p> <p>(Yes I am aware this is contrived, and it is not the only way of proving this.)</p> </li> <li> <p>The type theoretic version isn’t nearly as contrived.</p> <div class="language-coq highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">Definition</span><span class="w"> </span><span class="no">zero_eq_one</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="kr">Prop</span><span class="w"> </span><span class="p">:=</span><span class="w"> </span><span class="mi">0</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">1</span><span class="pi">.</span><span class="w">
</span><span class="k">Theorem</span><span class="w"> </span><span class="no">zero_eq_one_false</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="no">not</span><span class="w"> </span><span class="no">zero_eq_one</span><span class="pi">.</span><span class="w">
</span><span class="k">Proof</span><span class="pi">.</span><span class="w">
  </span><span class="kp">unfold</span><span class="w"> </span><span class="no">not</span><span class="pi">.</span><span class="w"> </span><span class="kp">intros</span><span class="pi">.</span><span class="w">
  </span><span class="kp">inversion</span><span class="w"> </span><span class="no">H</span><span class="pi">.</span><span class="w">
</span><span class="k">Qed</span><span class="pi">.</span><span class="w">

</span><span class="k">Theorem</span><span class="w"> </span><span class="no">false_p_exists</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="kp">exists</span><span class="w"> </span><span class="no">p</span><span class="p">,</span><span class="w"> </span><span class="no">not</span><span class="w"> </span><span class="no">p</span><span class="pi">.</span><span class="w">
</span><span class="k">Proof</span><span class="pi">.</span><span class="w">
  </span><span class="kp">exists</span><span class="w"> </span><span class="no">zero_eq_one</span><span class="pi">.</span><span class="w"> </span><span class="kp">apply</span><span class="w"> </span><span class="no">zero_eq_one_false</span><span class="pi">.</span><span class="w">
</span><span class="k">Qed</span><span class="pi">.</span><span class="w">
</span></code></pre></div></div> </li> </ul> <blockquote class="block-tip"> <p>Theorem: There are some propositions that are either true or false.</p> </blockquote> <ul id="true-false-prop" class="tab" data-tab="3ef554d7-7826-4bc0-a285-55797aaaadb8" data-name="true-false-prop"> <li class="active" id="true-false-prop-english"> <a href="#">English </a> </li> <li id="true-false-prop-coq"> <a href="#">Coq </a> </li> </ul> <ul class="tab-content" id="3ef554d7-7826-4bc0-a285-55797aaaadb8" data-name="true-false-prop"> <li class="active"> <p>Proof: $0 = 1$ is a true proposition, as shown above. Therefore it is either true or false.</p> </li> <li> <div class="language-coq highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">Theorem</span><span class="w"> </span><span class="no">true_or_false_p</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="kp">exists</span><span class="w"> </span><span class="no">p</span><span class="p">,</span><span class="w"> </span><span class="no">p</span><span class="w"> </span><span class="o">\/</span><span class="w"> </span><span class="no">not</span><span class="w"> </span><span class="no">p</span><span class="pi">.</span><span class="w">
</span><span class="k">Proof</span><span class="pi">.</span><span class="w">
  </span><span class="kp">exists</span><span class="w"> </span><span class="p">(</span><span class="mi">0</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">0</span><span class="p">)</span><span class="pi">.</span><span class="w"> </span><span class="no">left</span><span class="pi">.</span><span class="w"> </span><span class="kp">apply</span><span class="w"> </span><span class="no">zero_id</span><span class="pi">.</span><span class="w">
</span><span class="k">Qed</span><span class="pi">.</span><span class="w">
</span></code></pre></div></div> </li> </ul> <blockquote class="block-tip"> <p>Definition: A proposition that is either true or false is called a <strong>decidable proposition</strong> (or sometimes, <strong>boolean proposition</strong>).</p> </blockquote> <p>For example, $0 = 1$, $0 = 0$ are both decidable propositions, as proven above.</p> <blockquote class="block-tip"> <p>Theorem: Any proposition cannot be both true and false.</p> </blockquote> <ul id="both-bool-prop" class="tab" data-tab="487ef579-2e74-43ac-a34b-a855002ab0a8" data-name="both-bool-prop"> <li class="active" id="both-bool-prop-english"> <a href="#">English </a> </li> <li id="both-bool-prop-coq"> <a href="#">Coq </a> </li> </ul> <ul class="tab-content" id="487ef579-2e74-43ac-a34b-a855002ab0a8" data-name="both-bool-prop"> <li class="active"> <p>Proof: Suppose that $p$ is some proposition that is both true and false. Because it is true, there is some proof of it, call it $A$. Because it is false, then by definition, assuming that it is true, you can derive a contradiction. But because we have a proof that it is true ($A$), we can feed it into the proof that it is false, and derive a contradiction.</p> </li> <li> <div class="language-coq highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">Theorem</span><span class="w"> </span><span class="no">not_both_true_false</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="kr">forall</span><span class="w"> </span><span class="no">p</span><span class="p">,</span><span class="w"> </span><span class="no">not</span><span class="w"> </span><span class="p">(</span><span class="no">p</span><span class="w"> </span><span class="o">/\</span><span class="w"> </span><span class="no">not</span><span class="w"> </span><span class="no">p</span><span class="p">)</span><span class="pi">.</span><span class="w">
</span><span class="k">Proof</span><span class="pi">.</span><span class="w">
  </span><span class="kp">intros</span><span class="pi">.</span><span class="w"> </span><span class="kp">unfold</span><span class="w"> </span><span class="no">not</span><span class="pi">.</span><span class="w">
  </span><span class="kp">intros</span><span class="w"> </span><span class="no">Hpboth</span><span class="pi">.</span><span class="w"> </span><span class="kp">destruct</span><span class="w"> </span><span class="no">Hpboth</span><span class="w"> </span><span class="kr">as</span><span class="w"> </span><span class="p">(</span><span class="no">Hptrue</span><span class="w"> </span><span class="err">&amp;</span><span class="w"> </span><span class="no">Hpfalse</span><span class="p">)</span><span class="pi">.</span><span class="w">
  </span><span class="kp">apply</span><span class="w"> </span><span class="p">(</span><span class="no">Hpfalse</span><span class="w"> </span><span class="no">Hptrue</span><span class="p">)</span><span class="pi">.</span><span class="w">
</span><span class="k">Qed</span><span class="pi">.</span><span class="w">

</span></code></pre></div></div> </li> </ul> <p>So far everything is believable? Congratulations, you now believe in constructive mathematics!</p> <h1 id="the-problem">The Problem</h1> <p>So the real question here is: what is classical mathematics? In classical mathematics, everything I’ve written above is believable. The problem is that in addition to all those definitions, it also believes in one more proposition called the Law of Excluded Middle (LEM).</p> <blockquote class="block-warning"> <p>LEM: For <em>every</em> proposition $p$, it is either true or false. In other words, <em>all</em> propositions are decidable/boolean.</p> </blockquote> <p>Now this statement is much more problematic. We have already shown that decidability does hold for <em>some</em> propositions ($0 = 0$, $0 = 1$), but LEM states that it holds for <em>every</em> proposition, and that is the distinguishing feature of classical mathematics. Before we go further, we shall first establish some facts about it.</p> <h3 id="equivalence-with-double-negation">Equivalence with Double Negation</h3> <p>There is a slightly different statement of LEM, called Double Negation Elimination (DNE), that says:</p> <blockquote class="block-warning"> <p>DNE: For <em>every</em> proposition $p$, if $p$ is false is false, then it is true. In other words, if assuming that $p$ is false, we end up deriving a contradiction, then it is true.</p> </blockquote> <p>Note that intuitively this is also a departure from constructive mathematics. In constructive mathematics, to show that a proposition is true requires giving a proof of it. With DNE in classical mathematics on the other hand, instead of actually proving the proposition, your argument can instead end up looking like this:</p> <blockquote class="block-danger"> <p>Suppose that $p$ is false, fill in reasoning here, contradiction.</p> </blockquote> <p>This is what is sometimes called <strong>Proof by Contradiction</strong>. Contrast this with <strong>Proof of a Contradiction</strong> above: they are proving decidedly different things. A <strong>Proof of a Contradiction</strong> tries to prove that a contradiction exists, by the very definition of what it means for something to be false. A <strong>Proof by Contradiction</strong> does something a lot more sneaky: to prove that $p$ is true, it tries to first assume that the statement $p$ is inconsistent/false, prove that it can’t be false, and uses DNE to conclude “because it can’t be false, therefore it must be true”. Sometimes people also call proofs of this kind <strong>indirect proofs</strong>: instead of proving it directly, it gives a proof of why the proposition cannot be falsified.</p> <p><strong>Proof by Contradiction</strong> is what we avoid in constructive mathematics. <strong>Proof of a Contradiction</strong> on the other hand is perfectly fine, since it is just a definition.</p> <p>A highly important theorem is that LEM and DNE are equivalent: if you believe in LEM, then you must believe in DNE, and vice versa.</p> <blockquote class="block-tip"> <p>Theorem: LEM and DNE are equivalent.</p> </blockquote> <ul id="lem-dne-prop" class="tab" data-tab="0af0db47-5661-4e37-9cc7-83cb4365207e" data-name="lem-dne-prop"> <li class="active" id="lem-dne-prop-english"> <a href="#">English </a> </li> <li id="lem-dne-prop-coq"> <a href="#">Coq </a> </li> </ul> <ul class="tab-content" id="0af0db47-5661-4e37-9cc7-83cb4365207e" data-name="lem-dne-prop"> <li class="active"> <p>Proof: (LEM =&gt; DNE) Suppose that LEM holds, let $p$ be any proposition, and we need to show that if $p$ is false is false, then it is true.</p> <p>Suppose that $p$ is false derives a contradiction. Because LEM holds, $p$ is also either true or false. We look at both cases since we don’t know whether it is true or false.</p> <p>If $p$ is false, then by assumption in DNE, we derive a contradiction, and from a contradiction we can derive anything (ex falso quodlibet), so we derive that $p$ is therefore true.</p> <p>If $p$ is true, we are done.</p> <p>Hence in all cases, we know that $p$ is true.</p> <p>(DNE =&gt; LEM) Suppose that DNE holds, let $p$ be any proposition, we need to show that $p$ is either true or false, aka $p$ is decidable.</p> <p>It suffices to show that (($p$ is decidable) is false) is false, then by DNE, we get the final result.</p> <p>In other words, it suffices to show that it is not the case that $p$ is decidable is false (or the decidability of $p$ cannot be falsified). Which we will show two sections later.</p> </li> <li> <div class="language-coq highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">Theorem</span><span class="w"> </span><span class="no">lem_dne_equiv</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="no">LEM</span><span class="w"> </span><span class="o">&lt;-&gt;</span><span class="w"> </span><span class="no">DNE</span><span class="pi">.</span><span class="w">
</span><span class="k">Proof</span><span class="pi">.</span><span class="w">
  </span><span class="kp">split</span><span class="p">;</span><span class="w"> </span><span class="kp">intros</span><span class="p">;</span><span class="w"> </span><span class="kp">unfold</span><span class="w"> </span><span class="no">LEM</span><span class="w"> </span><span class="kr">in</span><span class="w"> </span><span class="o">*</span><span class="p">;</span><span class="w"> </span><span class="kp">unfold</span><span class="w"> </span><span class="no">DNE</span><span class="w"> </span><span class="kr">in</span><span class="w"> </span><span class="o">*</span><span class="p">;</span><span class="w"> </span><span class="kp">unfold</span><span class="w"> </span><span class="no">decidable</span><span class="w"> </span><span class="kr">in</span><span class="w"> </span><span class="o">*.</span><span class="w">
  </span><span class="c">(* LEM -&gt; DNE *)</span><span class="w">
  </span><span class="o">-</span><span class="w"> </span><span class="kp">intros</span><span class="w"> </span><span class="no">p</span><span class="w"> </span><span class="no">Hnotnotp</span><span class="pi">.</span><span class="w">
  </span><span class="kp">specialize</span><span class="w"> </span><span class="p">(</span><span class="no">H</span><span class="w"> </span><span class="no">p</span><span class="p">)</span><span class="pi">.</span><span class="w">
  </span><span class="kp">induction</span><span class="w"> </span><span class="no">H</span><span class="pi">.</span><span class="w">
  </span><span class="p">+</span><span class="w"> </span><span class="ne">assumption</span><span class="pi">.</span><span class="w">
  </span><span class="p">+</span><span class="w"> </span><span class="kp">specialize</span><span class="w"> </span><span class="p">(</span><span class="no">Hnotnotp</span><span class="w"> </span><span class="no">H</span><span class="p">)</span><span class="pi">.</span><span class="w"> </span><span class="kp">destruct</span><span class="w"> </span><span class="no">Hnotnotp</span><span class="pi">.</span><span class="w">

  </span><span class="c">(* DNE -&gt; LEM *)</span><span class="w">
  </span><span class="p">-</span><span class="w"> </span><span class="kp">intros</span><span class="pi">.</span><span class="w">
    </span><span class="kp">apply</span><span class="w"> </span><span class="no">H</span><span class="pi">.</span><span class="w">
    </span><span class="kp">apply</span><span class="w"> </span><span class="no">lem_not_false</span><span class="pi">.</span><span class="w">
</span><span class="k">Qed</span><span class="pi">.</span><span class="w">
</span></code></pre></div></div> </li> </ul> <h3 id="lem-cannot-be-proven-within-constructive-logic-in-particular-intuitionistic-logic">LEM cannot be proven within constructive logic (in particular, intuitionistic logic)</h3> <p>There is a proof of this, but it is fairly involved, since it is reasoning about metatheory (aka the proof system itself). Bob Harper once mentioned that it is usually not too hard to show that you <em>can</em> prove something, but it is generally very hard to show that you <em>cannot</em> prove something, since it almost always involves some kind of trick, which is the case here.</p> <p>This was first done by Gerhard Gentzen in <a class="citation" href="#Gentzen1935">(Gentzen, 1935)</a>, which was written in German so I can’t actually read it. Instead, I will refer to the excellent notes <a class="citation" href="#Pfenning2023">(Pfenning, 2023)</a> by Frank in his course where I first learned this argument.</p> <p>Here’s a high level sketch: you can prove that the natural deduction style of intuitionistic logic is equivalent to the sequent calculus LJ. Then by induction on the rules within sequent calculus, show that LEM cannot be proven by exhaustively running through all cases. Since it cannot be proven in LJ, it thus cannot be proven in natural deduction.</p> <p>Using the same technique, you can also prove that false is not provable within LJ, and therefore not provable in natural deduction. Hence intuitionistic logic is also internally consistent. A similar technique can also be used to prove internal consistency for classical logic, and was what the original paper did.</p> <p>What is important here is the implication: there is <em>no</em> proof of LEM, and therefore, <strong>no mathematical justification for it can possibly exist</strong>. The only way of accepting LEM, if we were to do so, is to accept it as an <em>axiom</em>.</p> <h3 id="decidability-is-not-falsifiable">Decidability is not Falsifiable</h3> <p>This is a very subtle point: you can prove that for every proposition $p$, decidability for it cannot be false.</p> <blockquote class="block-tip"> <p>Theorem: For any proposition, decidability is not false.</p> </blockquote> <ul id="lemnotfalse-prop" class="tab" data-tab="0ea90813-94a6-409f-b404-2265cec8e341" data-name="lemnotfalse-prop"> <li class="active" id="lemnotfalse-prop-english"> <a href="#">English </a> </li> <li id="lemnotfalse-prop-coq"> <a href="#">Coq </a> </li> </ul> <ul class="tab-content" id="0ea90813-94a6-409f-b404-2265cec8e341" data-name="lemnotfalse-prop"> <li class="active"> <p>This proof can be a bit confusing. Given any proposition $p$, it suffices to prove that if $p$ is undecidable (aka not decidable), then we derive a contradiction. Assume that $p$ is undecidable, and call this fact Hpnotdecidable. We split this to two steps.</p> <p>($p$ is false). We first show that $p$ is false. To see this, suppose that $p$ is true, then by definition, $p$ is decidable. However, $p$ is not decidable by Hpnotdecidable, contradiction. Hence, $p$ is false.</p> <p>(A contradiction). Since we’ve just shown that $p$ is false, by definition, $p$ is decidable, however, by Hpnotdecdiable, $p$ is not decidable, contradiction.</p> </li> <li> <div class="language-coq highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">Theorem</span><span class="w"> </span><span class="no">lem_not_false</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="kr">forall</span><span class="w"> </span><span class="no">p</span><span class="p">,</span><span class="w"> </span><span class="no">not</span><span class="w"> </span><span class="p">(</span><span class="no">not</span><span class="w"> </span><span class="p">(</span><span class="no">decidable</span><span class="w"> </span><span class="no">p</span><span class="p">))</span><span class="pi">.</span><span class="w">
</span><span class="k">Proof</span><span class="pi">.</span><span class="w">
  </span><span class="kp">unfold</span><span class="w"> </span><span class="no">not</span><span class="pi">.</span><span class="w">
  </span><span class="kp">intros</span><span class="w"> </span><span class="no">p</span><span class="w"> </span><span class="no">Hpnotdecidable</span><span class="pi">.</span><span class="w">

  </span><span class="no">assert</span><span class="w"> </span><span class="p">(</span><span class="no">not</span><span class="w"> </span><span class="no">p</span><span class="p">)</span><span class="pi">.</span><span class="w">
  </span><span class="p">-</span><span class="w"> </span><span class="kp">unfold</span><span class="w"> </span><span class="no">not</span><span class="pi">.</span><span class="w"> </span><span class="kp">intros</span><span class="pi">.</span><span class="w">
    </span><span class="no">assert</span><span class="w"> </span><span class="p">(</span><span class="no">Hpdecidable</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="no">decidable</span><span class="w"> </span><span class="no">p</span><span class="p">)</span><span class="pi">.</span><span class="w">
    </span><span class="p">{</span><span class="w"> </span><span class="no">left</span><span class="pi">.</span><span class="w"> </span><span class="ne">assumption</span><span class="pi">.</span><span class="w"> </span><span class="p">}</span><span class="w">
    </span><span class="kp">apply</span><span class="w"> </span><span class="p">(</span><span class="no">Hpnotdecidable</span><span class="w"> </span><span class="no">Hpdecidable</span><span class="p">)</span><span class="pi">.</span><span class="w">

  </span><span class="c">(* not (decidable p) /\ not p =&gt; False *)</span><span class="w">
  </span><span class="p">-</span><span class="w"> </span><span class="no">assert</span><span class="w"> </span><span class="p">(</span><span class="no">Hpdecidable</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="no">decidable</span><span class="w"> </span><span class="no">p</span><span class="p">)</span><span class="pi">.</span><span class="w">
    </span><span class="p">{</span><span class="w"> </span><span class="no">right</span><span class="pi">.</span><span class="w"> </span><span class="ne">assumption</span><span class="pi">.</span><span class="w"> </span><span class="p">}</span><span class="w">
    </span><span class="kp">apply</span><span class="w"> </span><span class="p">(</span><span class="no">Hpnotdecidable</span><span class="w"> </span><span class="no">Hpdecidable</span><span class="p">)</span><span class="pi">.</span><span class="w">
</span><span class="k">Qed</span><span class="pi">.</span><span class="w">
</span></code></pre></div></div> </li> </ul> <p>So what does this actually say? To say that that decidability is not false is exactly as what the definition implies: pick any proposition $p$, you cannot prove that decidability is false. Or more literally, you cannot have some third value that is neither true or false.</p> <p>What it does <strong>not</strong> imply, is that you can prove decidability is true, or in other words, $p$ is either true or false. This can be particularly vexing. Previously I mentioned that LEM cannot be proven within constructive mathematics at all, the very definition of what it means to be true. To reemphasize, unless the proposition is <strong>decidable</strong>, you cannot conclude that it is true simply by showing that it cannot be false, since it requires you to use DNE.</p> <p>Here’s how I think about it intuitively: give me any proposition $p$. Regardless of what $p$ is, it cannot be something other than true or false. But does it allow me to conclude that $p$ must be either true or false? <strong>No</strong>. Because a proof of $p$ cannot be neither true nor false is too <em>weak</em> to make this conclusion. Very early on we have established what it means for a proposition to be true and what it means for a proposition to be false, and this proof <strong>does not satisfy either requirement</strong>: it gives me neither a proof of $p$ nor a proof of $p$ is false. DNE is the magic hoop to jump from a weak proof like this to a much stronger one, but we are not allowed to use it.</p> <p>Here’s a subtlety: what this also says is that constructive mathematics does not, and cannot, believe that LEM is false. In particular, it does not, and cannot, postulate something as ridiculous as a 3rd option. But the point of constructive mathematics is to say that we don’t believe LEM is true either, because there is no possible proof of it, per Gentzen. And therefore we cannot use it since we cannot trust it.</p> <p>It just occured to me: here’s a truly crazy sounding subtlety since what I wrote can seem very self contradictory. I highly recommend that you skip this particular paragraph unless you have seen these ideas before. Here I’ve just shown that you cannot prove for any proposition, that it is undecidable. But isn’t LEM undecidable? It cannot be true because Gentzen proved that it is not provable. It cannot be false because decidability is not falsifiable for any proposition. Therefore it is undecidable, yet we’ve just shown such a proof of undecidability cannot exist for any proposition, and LEM is a proposition. So what went wrong? In short, it has to do with <em>where</em> the proof is done. The proof I wrote in this section is the statement that you cannot prove undecidability <em>within the object language</em>. Gentzen’s proof is done with the <em>metalanguage</em>, aka, reasoning <em>about</em> the language rather than <em>in</em> the language.</p> <h1 id="the-arguments-about-lem">The Arguments About LEM</h1> <p>Given that we cannot prove LEM, the direct consequence is that arguments for including LEM as an axiom become entirely a matter of <strong>philosophy</strong>, since there is nothing <em>mathematics</em> can do here. Here I discuss some of them that I know of, though this is likely not an exhaustive list.</p> <h3 id="if-it-is-not-true-and-it-is-not-false-then-what-is-it">If it is not true, and it is not false, then what is it?</h3> <p>This is a really good question and a great source of confusion for folks looking at these results for the first time. Myself included, many many years ago, when I was 19. It really shows that I’m getting old. There are true propositions, there are false propositions, but then bizarrely, there are propositions that are not quite either, even though it is not possible to have a third value either. So for those propositions, exactly what are they?</p> <p>The way I understand it is to quote one of my favorite propositions: <a href="https://en.wikipedia.org/wiki/Collatz_conjecture">Collatz Conjecture</a>. Collatz Conjecture states that: start with some positive natural number $x$. If it is even, divide by 2 $(x / 2)$. If it is odd, multiply by 3 and add 1 $(3x + 1)$. Keep repeating this procedure until you end up with the number $1$. Is there any $x$ where it will never end up with $1$ no matter how many times you repeat this procedure? The conjecture posulates that all positive natural numbers will end up with $1$ eventually.</p> <p>This is one of my favorite propositions because it is particularly easy to explain to anyone with any amount of understanding of elementary school mathematics. It also comes in handy to emphasize a particular point about decidability. Moreover, it makes for a very fun prank to pull on your more mathematically guillible friends if they don’t know that this problem is still unsolved after almost a century at this point.</p> <p>Now, we can ask:</p> <ul> <li>Is Collatz Conjecture true? If so, surely you can give me a proof of it.</li> <li>Is Collatz Conjecture false? If so, surely you can give me a number where it doesn’t end up with a 1 at the end of this procedure.</li> <li>Is Collatz Conjecture neither? No.</li> </ul> <p>But to emphasize a point: practically nobody denies that this is a <strong>valid proposition</strong>, despite that it resisted multiple attempts over generations of mathematicians to find an answer.</p> <p>This example illustrates what constructive mathematics is <em>really</em> all about. It is, in essence, saying that the <em>only</em> criteria of truth is a proof of it. In particular, a human proof that you can write it out and give it to me. If you can give me a proof, it is true. If you can give me a proof that it leads to an inconsistency, and the system is internally consistent, then it is false. If you cannot, then nothing can be concluded about the proposition at all. Hence, mathematics is a human activity. Solved problems are decidable, whereas unsolved problems are not yet known to be decideable.</p> <p>So in this light, what does LEM say, constructively? It says that <em>all</em> propositions can either be proven, or it can be proven to be false. What does DNE say, constructively? It says that given proposition $p$, if I can prove that no such proof of a contradiction exists, then a proof of $p$ <em>must exist</em> or <em>be accepted</em>.</p> <h3 id="how-to-believe-in-lem">How to Believe in LEM</h3> <p>This brings us to what I thought to be the most coherent argument for LEM that I know of philosophically. There exists some Oracle (some people use the terminology “God”. I deliberately avoid this term because it tends to give off religious vibes despite religion having nothing to do with this) who knows all and sees all. That given a proposition, there is some “inherent” (or “objective”) mathematical truth out there no matter what the proposition is, the Oracle (be it some deity, or just the Universe itself) decides whether it is true or false and knows the reason, whereas humans are just too foolish to see them without plenty of time, effort and dedication. So mathematics is not a human activity, but an exercise in discovering what is known to the Oracle. We have some known proofs for some propositions, but there are a lot of propositions that we don’t know is true or false, even though a proof is there by the Oracle/Universe and we have yet to discover it.</p> <p>Now there is nothing wrong with this belief, since this is fundamentally a philosophical stance. Given that classical logic is internally consistent, there isn’t really a right or wrong here. Personally, I found this perhaps too optimistic that all mathematical truths have some inherent solution somewhere.</p> <p>If you do hold this belief, I think that this is a truly valid reason to dislike constructive mathematics, since the notion of truth being relative to human advancement can be unpalatable to some. Weirdly enough, most people who have objections to constructive mathematics that I’ve talked to seem to not hold this view either.</p> <h3 id="the-practicality-of-avoiding-lem">The Practicality of Avoiding LEM</h3> <p>Another often cited reason is that LEM cannot be avoided in mathematics. I found this to be highly suspect at best. There are two ways of avoiding LEM:</p> <h4 id="try-and-find-direct-proofs-of-theorems">Try and find direct proofs of theorems</h4> <p>There are a few fields where it was once thought that LEM is necessary, the more famous of them being Analysis. Even more famously, Errett Bishop managed to find constructive proofs for a lot of theorems, but they generally requires redoing a few definitions. <a class="citation" href="#BishopBridges">(Bishop &amp; Bridges, 1985)</a></p> <p>It also turns out that most proofs in the wild are already constructive. When you try to prove something, what comes to mind is usually <em>not</em> “Suppose that the proposition is false, …”. If you want to prove that a sorting algorithm exists, you give the sorting algorithm. You don’t generally say “Suppose that no algorithm exists, …., but it cannot be”.</p> <h4 id="rephrasing-the-theorem">Rephrasing the theorem</h4> <p>Suppose that you have some proposition $p$, where your proof critically depends on $q$ being decidable. Yet you are unable to prove that $q$ is decidable (say $q$ is Collatz Conjecture, $P = NP$, pick your favorite unsolved problem). What do you do?</p> <p>A simple fix is to rewrite your theorem so that your proof is valid in constructive logic. In short, instead of saying that you managed to prove $p$, say that you managed to prove “assuming that $q$ is decidable, $p$ holds”. This is a weaker statement, but the proof becomes perfectly valid without assuming LEM, because you stated it as an assumption. Similarly, when instead of giving a Proof of a Truth, you ended up giving a Proof by Contradiction, you can always rewrite your theorem to say that you managed to prove “it is not that case that $p$ is false”. This is sometimes called the Double Negation Translation.</p> <p>What you don’t want to do is state that “Assuming LEM holds (aka, assuming that all propositions are decidable), $p$ holds”. Because as shown by Gentzen, LEM is not provable. However, decidability of $q$, be it true or false, is something you <em>might</em> have some hope of proving in the future. If someone managed to prove decidability of $q$ at some point, you can plug in that proof and the requirement is no longer necessary anymore. Alternatively, you can even go as far as to state decidability of $q$ as an axiom, which can save you the hassle of repeating this requirement in every subsequent theorem that uses the result of $p$. It still gives you a stronger proof than using LEM outright.</p> <h3 id="historical-reasons">Historical Reasons</h3> <p>Finally, here is what I think to be the real reason why so much of mathematics lean towards classical: because people were taught that way. And their teachers taught them that way. And the teachers of those teachers taught them that way, sometimes repeating a bunch of misconceptions. I have seen, even today, a rather horrifying number of textbooks in elementary mathematics stating that “a proposition is a statement that is either true or false”, in actual departments of mathematics of all places, despite that the notion of a proposition should be a priori to the notion of truth. (Yes, I am aware that historically this is not the case, but Gentzen has shown through the sequent calculus that LJ is perfectly consistent without needing to resort to LEM, meaning that the notion of a proposition is, in fact, not related to the notion of truth at all. See this <a href="https://www.google.com/search?q=definition+of+proposition+in+math">Hall of Shame</a> asserting the contrary) And at the very top of the tree stands David Hilbert, who very (in)famously made this mysteriously oft repeated quote:</p> <blockquote> <p>Taking the principle of excluded middle from the mathematician would be the same, say, as proscribing the telescope to the astronomer or to the boxer the use of his fists. To prohibit existence statements and the principle of excluded middle is tantamount to relinquishing the science of mathematics altogether.</p> </blockquote> <p>Now there is a fair bit of <a href="https://en.wikipedia.org/wiki/Brouwer%E2%80%93Hilbert_controversy">mathematical history in the Hilbert-Brouwer controversy</a> that is more entertaining than it is informative, as a lot of the arguments ended up disintegrating into personal attacks than anything at all related to mathematics. Ignoring that, it did not seem to me that Hilbert was really making a philosophical argument of any sort, but rather is more of a statement about the (lack of) practical value in doing mathematics without LEM.</p> <p>And if that was the point he was trying to make, we can very conclusively say today that Hilbert was simply <strong>completely wrong</strong>. There are extremely good, practical reasons to not use LEM.</p> <h1 id="why-not-believe-in-lem">Why Not Believe in LEM</h1> <h3 id="fewer-axioms-means-better-system">Fewer Axioms Means Better System</h3> <p>This is a very simple fact: the fewer axioms or assumptions you have, the better your theorems are.</p> <p>Consider any proposition $p$, and any proposition $q$. The proposition “$p$ is true” is simply a stronger statement than the proposition “assuming that $q$ is true, then $p$ is true”. In particular, the former implies that latter.</p> <blockquote class="block-tip"> <p>Theorem: For any propositions $p$, $q$, if $p$ is true, then $q$ implies $p$ is true.</p> </blockquote> <ul id="weaken-prop" class="tab" data-tab="7b80be83-014b-45c5-84b5-5f1e8226314f" data-name="weaken-prop"> <li class="active" id="weaken-prop-english"> <a href="#">English </a> </li> <li id="weaken-prop-coq"> <a href="#">Coq </a> </li> </ul> <ul class="tab-content" id="7b80be83-014b-45c5-84b5-5f1e8226314f" data-name="weaken-prop"> <li class="active"> <p>Proof: Suppose that $p$ is true, we show that if $q$ is true, then $p$ is true. Ignore $q$, we already know $p$ is true.</p> </li> <li> <div class="language-coq highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">Theorem</span><span class="w"> </span><span class="no">weaken</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="kr">forall</span><span class="w"> </span><span class="no">p</span><span class="w"> </span><span class="no">q</span><span class="p">,</span><span class="w"> </span><span class="no">p</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="p">(</span><span class="no">q</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="no">p</span><span class="p">)</span><span class="pi">.</span><span class="w">
</span><span class="k">Proof</span><span class="pi">.</span><span class="w">
  </span><span class="kp">intros</span><span class="pi">.</span><span class="w">
  </span><span class="ne">assumption</span><span class="pi">.</span><span class="w">
</span><span class="k">Qed</span><span class="pi">.</span><span class="w">
</span></code></pre></div></div> </li> </ul> <p>The other way around does not hold, there are cases where $q$ implies $p$ is true, but $p$ is not true. For example:</p> <p>Theorem: “$0 = 1$ is true implies $1 = 2$ is true”, but $1 = 2$ is false.</p> <ul id="inversefail-prop" class="tab" data-tab="34c2a02c-fead-4cff-b39d-86f0ba270bf5" data-name="inversefail-prop"> <li class="active" id="inversefail-prop-english"> <a href="#">English </a> </li> <li id="inversefail-prop-coq"> <a href="#">Coq </a> </li> </ul> <ul class="tab-content" id="34c2a02c-fead-4cff-b39d-86f0ba270bf5" data-name="inversefail-prop"> <li class="active"> <p>Proof: ($0 = 1$ is true implies $1 = 2$ is true) Suppose that $0 = 1$ holds, then so does $f(0) = f(1)$. Let $f(x) = 1 + x$, then we have $1 + 0 = 1 + 1$ aka $1 = 2$.</p> <p>($1 = 2$ is false) Suppose that $1 = 2$, then $f(1) = f(2)$. Let $f(x) = x - 1$, hence we have $1 - 1 = 2 - 1$, so $0 = 1$, which we have shown earlier, is false, and hence derives a contradiction.</p> </li> <li> <div class="language-coq highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">Theorem</span><span class="w"> </span><span class="no">inverse_fail</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="p">((</span><span class="mi">0</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">1</span><span class="p">)</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="p">(</span><span class="mi">1</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">2</span><span class="p">))</span><span class="w"> </span><span class="o">/\</span><span class="w"> </span><span class="p">(</span><span class="mi">1</span><span class="w"> </span><span class="o">&lt;&gt;</span><span class="w"> </span><span class="mi">2</span><span class="p">)</span><span class="pi">.</span><span class="w">
</span><span class="k">Proof</span><span class="pi">.</span><span class="w">
  </span><span class="kp">split</span><span class="pi">.</span><span class="w">
  </span><span class="c">(* 1 = 2 *)</span><span class="w">
  </span><span class="p">-</span><span class="w"> </span><span class="kp">intros</span><span class="pi">.</span><span class="w"> </span><span class="kp">f_equal</span><span class="pi">.</span><span class="w"> </span><span class="ne">assumption</span><span class="pi">.</span><span class="w">

  </span><span class="c">(* 1 &lt;&gt; 2 *)</span><span class="w">
  </span><span class="p">-</span><span class="w"> </span><span class="kp">unfold</span><span class="w"> </span><span class="no">not</span><span class="pi">.</span><span class="w"> </span><span class="kp">intros</span><span class="pi">.</span><span class="w"> </span><span class="kp">inversion</span><span class="w"> </span><span class="no">H</span><span class="pi">.</span><span class="w">
</span><span class="k">Qed</span><span class="pi">.</span><span class="w">
</span></code></pre></div></div> </li> </ul> <p>In this sense, $p$ is true is simply a “better” or “stronger” theorem most of the time. Now take $q$ to be the law of excluded middle. All this says is that a proof that doesn’t use LEM is simply a stronger proof than one that uses it, and hence in this sense, proofs constructively are better than ones that do depend on LEM, because there are fewer assumptions.</p> <h3 id="proofs-as-programs">Proofs as Programs</h3> <p>So going back to the train of thought (inadvertently) proposed by Hilbert. Is there any practical merit to avoiding LEM? The answer here is definitively, <strong>yes</strong>.</p> <p>Here’s a sketch: if we cease viewing propositions are just true or false, what do we get? In short, we get structure. Propositions are not just statements of true of false, and proofs are not just results of true or false. Instead, proofs themselves are mathematical objects. Propositions can then be thought of having “content”, the content being proofs. In this sense, a proposition can have multiple proofs, some proofs can be the same and some different, by a certain definition of what it means for two proofs to be the “same”. You can also stack two proofs together to make new proofs. For example, if you have a proof of $p$ implies $q$ (call the proof $A$), and $q$ implies $r$ (call the proof $B$), then stacking $A$ and $B$ together gives you a proof of $p$ implies $r$.</p> <p>In the classical world, this will unfortunately end up degrading into truth tables in a way: you look at the table for $p$ implies $r$ and all combinations of true or false for $p, q, r$, then you pick, using LEM, which boolean it results in (if it’s not false, well, it must be true then). But if we don’t use LEM, then we are forced to work with proof structure, and hence we must treat proofs as mathematical objects.</p> <p>What kind of mathematical objects? In short, they are computer programs. And what are the propositions? They are just the types of the programs. And just like that, checking that your proof is correct is <strong>just</strong> a matter of making sure that your program is typechecked, which a computer can do almost automatically practically most of the time today. Hence, all of mathematics is simply just a programming exercise, as long as you have a sufficiently good language to work in.</p> <p>Now I am significantly simplifying this description since I promised that this post is nontechnical, there are actually different kinds of foundational issues that you end up with in this line of thought. What I just described is a tiny fragment of what is sometimes called the <a href="https://ncatlab.org/nlab/show/BHK+interpretation">Brouwer-Heyting-Kolmogorov interpretation</a> (the actual intepretation goes far beyond just programs, there is also a correspondence in category theory). More importantly, <strong>this intepretation is the very foundation of the study of Type Theory, or in other words, the study of programming languages today</strong>. A lot of this in clarified in Per Martin-Lof’s seminal paper: Constructive Mathematics and Computer Programming <a class="citation" href="#MartinLof82">(Martin-Löf, 1982)</a>, the single most important paper in programming languages today, and what I would argue, one of the most important papers in all of computer science.</p> <p>One thing to stress: <strong>this is not just theoretical</strong>. I wrote all the proofs above in Coq, but <em>why</em> does Coq work? Because Coq is based on Martin-Lof Type Theory. And why do you believe proofs typed out in Coq have anything to do with the proofs I did in English? The short answer is Martin-Lof’s paper, and to trace it back, the ideas in BHK itself. And to sum it up, it is because proof checking reduces to <em>just</em> a type checking problem per BHK. Practically, Coq is extremely successful (from a certain perspective, unfortunately a bit too successful, but that’s an actually technical post for a different day), so successful that one of the extremely long proofs that was unrealistic to check by humans, the Four Color Theorem, was finally machine checked without objections <a href="https://github.com/coq-community/fourcolor">in Coq</a>. Any argument you can make against the proof, is an argument you make against either Coq’s implementation, or the foundations of Type Theory itself.</p> <p>Contrast this with the horrible mess that is taught today in certain computer science departments on software testing methodology, that actively encourages you to write bad code in garbage languages, and end up ensuring “correctness” by writing tests that needed to be run continuously instead of checking them once during typechecking, wasting CPU resources, despite being able to ironically prove, for sufficiently interesting types (aka most of the time, for simplicity, pick the natural numbers), that <strong>testing can never be complete</strong> (exercise for the reader, this can be formalized precisely: given a (finite) list of test cases, pick a type ($\mathbb{N}$) and a function for the type ($\mathbb{N} \rightarrow \mathbb{N}$), and pick some simple property (ex. function computes the successor), show that no finite list of test cases will ever cover the property for all inputs by constructing an adversary implementation for the function (easy, iterate over the list of test cases, find a natural number that isn’t there. It must exist because test cases are finite. Construct the right function behavior for every input except for that number. The function passes all tests cases, but is wrong)). Because this quantifies across all possible list of test cases, simply put, unless your code is boring (as in all types have finite number of values), <strong>no amount of testing ever means anything</strong>. This proof is so intuitive to do you can ask a high school student to come up with it within a few minutes, yet the pointlessness testing methodology is emphasized over and over again in so many universities, despite what they really want, is merely as <em>simple</em> as a good language.</p> <p>So what happens if we add LEM as an axiom in Coq? Without going into technicalities, in short, the programs (or proofs) won’t <em>run</em> in a sense. When you have a proof that “there exists some $x$, where $x + 1 = 3$”, then a constructive proof will mention somewhere that it holds for “$x = 2$”, because it is a direct proof. <em>Running</em> it will give you concretely, $x = 2$ as an answer. However, if you start your proof with “Suppose on the contrary that it is the case that every $x + 1 \neq 3$”, …”, there’s a very good chance that you don’t end up getting a concrete value for $x$, and in this way, the program gets “stuck” (not quite, but that’s a different topic). This has some highly annoying consequences for typechecking, especially for dependent types. In this pragmatic sense, having LEM in the system is really inconvenient.</p> <h3 id="technicality-inconsistency-with-higher-inductive-types--univalence">Technicality: Inconsistency with Higher Inductive Types + Univalence</h3> <p>Unfortunately, this particular point likely cannot be explained without some specialist knowledge. If you are not interested, feel free to skip it.</p> <p>In Homotopy Type Theory, there is a theorem that states that you can derive a contradiction with both LEM and the Univalence Axiom in the system. The only proof that I know of (but don’t recall) involves a construction using Higher Inductive Types. I probably won’t be able to reproduce this proof on top of my head anymore, since I recall it requires a bit of brilliance by constructing “swap” paths on a boolean.</p> <p>In either case, there is a concrete result here, is that if we ever want Univalence, constructivity is not just optional. LEM needs to be completely avoided.</p> <h1 id="in-closing-a-personal-belief-in-making-the-right-arguments">In Closing: A Personal Belief in Making the Right Arguments</h1> <p>There is nothing inherently wrong with disliking constructive mathematics, but it is important to have technically correct reasons to do so and to make an effort to not misrepresent it. It is simply, <em>not</em> a belief of constructive mathematics to never mention the word “contradiction”, and the claim that constructive mathematics make it impractical to do math is simply wrong. The majority of mechanized mathematics today is developed in type theory, constructively. And whatever your arguments are for LEM, it is certainly not inherently mathematical, but philosophical, so it is a matter of opinion. Unfortunately, the number of times I’ve heard a technically wrong argument against constructivism at an elementary level significantly dwarfs the number of times I’ve heard a legitimate one, even if it is something like “because I was taught to do so by my professors/textbook”. I would like to invite the reader, regardless of what your opinions are, to hold everyone (including myself) up at at least this level of standards.</p> <p>Wow this is way too long. Hopefully this is the last time I write about philosophy, as it is generally not something I do. Now I can go back to technical writing about programming languages instead.</p>]]></content><author><name></name></author><category term="logic,"/><category term="math,"/><category term="philosophy"/><summary type="html"><![CDATA[where I attempt to start an Internet flame war]]></summary></entry><entry><title type="html">A Hands-on Guide to Implementing DeBruijn Indicies (1)</title><link href="https://www.haoxuany.com/blog/debruijn-1/" rel="alternate" type="text/html" title="A Hands-on Guide to Implementing DeBruijn Indicies (1)"/><published>2025-02-14T00:00:00+00:00</published><updated>2025-02-14T00:00:00+00:00</updated><id>https://www.haoxuany.com/blog/debruijn-1</id><content type="html" xml:base="https://www.haoxuany.com/blog/debruijn-1/"><![CDATA[<p>Cite: The material in this blog post and subsequent related ones are very loosely based on <a class="citation" href="#ExplicitSubstitutions">(Abadi et al., 1991)</a> and my own notes previously from taking <a href="https://www.cs.cmu.edu/~crary/hotc/">15-417 HOT Compilation</a>. I have contributed no original ideas besides some code.</p> <p>So I thought about just calling this article “Suffering with Substitutions”. That’s a equally suitable title at first glance since much of this code is very painful to write. Unsurprisingly I have yet to hear anyone express fondness with DeBruijn indicies, given the sheer amount of work it requires to prove a bajillion substitution theorems.</p> <p>But given that I am getting old and I haven’t written any real serious code in almost 8 years, it turns out that the less you write code the worse you get (surprise!). So I thought it would be a fun (?) coding challenge to at least hone my skills a little bit, and if anything hopefully this would be educational for at least someone out there who is doing this for the first time.</p> <p>So here I will develop the material from scratch, explaining what DeBruijn indicies are and how to actually code them up, in perhaps way too much detail. I assume very little in terms of prerequisites, besides some basic beginner knowledge in programming languages that is taught at an undergraduate level.</p> <h1 id="the-problem">The Problem</h1> <p>As is tradition, we start with the simply typed lambda calculus. The reason we start here is that this is a particularly simple case (first order) to implement, at least relatively speaking. We will work with two sorts: types ($\tau$) and terms ($e$), and two types: the unit type and arrow type.</p> <p>\begin{equation} \tau ::= \mathbb{1} \space | \space \tau \rightarrow \tau’ \end{equation} \begin{equation} e ::= () \space | \space x \space | \space \lambda (x : \tau). e \space | \space app(e, e’) \end{equation}</p> <p>Note that the abstract syntax for lambda is $\lambda(\tau, x.e)$. For those who are not used to this presentation, it just means that $x$ is bound in $e$ and not in $\tau$.</p> <p>With the following rules for the typing judgement $\bbox[5px, border: 2px solid blue]{\Gamma \vdash e : \tau}$:</p> <p>var:</p> \[\begin{align} x : \tau \in \Gamma \nonumber \\ \hline \nonumber \\ \Gamma \vdash x : \tau \nonumber \\ \end{align}\] <p>$\mathbb{1}$-intros:</p> \[\begin{align} \nonumber \\ \hline \nonumber \\ \Gamma \vdash () : \mathbb{1} \nonumber \\ \end{align}\] <p>arrow-intros:</p> \[\begin{align} &amp; \Gamma , x : \tau \vdash e : \tau' \nonumber \\ &amp; \hline \nonumber \\ &amp; \Gamma \vdash \lambda (x : \tau). e : \tau \rightarrow \tau' \nonumber \\ \end{align}\] <p>arrow-elim:</p> \[\begin{align} &amp; \Gamma \vdash e_1 : \tau \rightarrow \tau' &amp; \Gamma \vdash e_2 : \tau \nonumber \\ &amp; \hline \nonumber \\ &amp; \Gamma \vdash app(e_1, e_2) : \tau' \nonumber \\ \end{align}\] <p>Simple enough? Now let’s look at problems in terms of implementation.</p> <p>I’m sure that most people reading this would be able to state and quickly prove some very simple metatheoretic properties, at least on paper. Now the question here is how do you code this up. The most common (and often, painful) issue you would encounter is the representation of variables, binding and substitution.</p> <p>A particularly bad way of representing variables is a naive implementation of variables using names (like some unique integer, or even worse, strings). This is almost always a bad idea, because in particular, we respect equality on trees up to $\alpha$-equivalence, so:</p> \[\lambda (x : \tau).x =_\alpha \lambda (y : \tau).y\] <p>need to hold (we will just write $=$ instead of $=_\alpha$ in the future, since when doing metatheory, equality is always up to $\alpha$-equivalence with no exceptions).</p> <p>This is highly inconvenient to say the least, since you will need to end up stating all your theorems such that they hold up to a custom implementation of equality itself.</p> <p>In a compiler implementation, I personally think it is somewhat more acceptable if you represent variables as globally fresh names (usually by just integers), and do a little bit of tweaking in checking $\alpha$-equivalence, in a language such as ML where any form of definitional equality doesn’t exist anyway. However, relying on such a global state means that your typechecking implementation can’t be parallelized. And then there are some optimization passes you can do that potentially require comparing whether two terms are equal, and that is a huge hassle to implement correctly, though admittedly these use cases are niche.</p> <p>So that aside, what else can you do? Well to my knowledge, you can alternatively:</p> <ul> <li>Mechanize it in LF type theory <a class="citation" href="#LFPaper">(Harper et al., 1993)</a>.</li> <li>Nominal techniques <a class="citation" href="#NominalPaper">(Pitts, 2016)</a>. I admit I didn’t look very deep into this methodology. One day I will get around to it.</li> <li>For certain very simple calculus like this one, intrinsic encodings would also work. For complex type theories where types have nontrivial equalities, it won’t, and hence we won’t discuss it here.</li> </ul> <h1 id="so-why-do-you-care-about-debruijn-indicies">So Why Do You Care About DeBruijn Indicies?</h1> <p>Using HOAS encoding in LF Type Theory works for something simple like this, but as far as I understand it (correct me if I’m wrong), the $\Pi2$ restriction can be pretty limiting. In particular it is not very clear how you would do logical relations proofs in it. There are also a few proofs where you would need some tricks to do <a class="citation" href="#ExplicitContexts">(Crary, 2009)</a>.</p> <p>Then there is a much more practical issue: if you only care about mechanizing metatheory, that’s fine and all, but what if you need to write a compiler? Representing bindings as internal functions in the metalanguage doesn’t work very well in compilers since you will often need to peek into the function to inspect it. This would make functions practically impossible to compile. Hence you need to learn some alternative representation technique regardless.</p> <p>Which brings us to DeBruijn indicies, the representation that makes everyone sad.</p> <h1 id="debruijn-indicies-in-a-nutshell">DeBruijn Indicies in a Nutshell</h1> <p>The idea for DeBruijn Indicies is simple: we represent variables as how many “hops” it takes to find its binder. For example, for the expression:</p> \[\lambda x. \lambda y. app(y, x)\] <p>There is a binder at $\lambda x.$, a binder at $\lambda y.$. Within the application, $y$ here refers to the closest binder and requires $0$ hops. $x$ here needs to jump across $\lambda y.$ to refer to the closest binder, so it requires $1$ hop. Hence, the representation looks like:</p> \[\lambda . \lambda . app(0, 1)\] <p>As you can tell, for sufficiently complicated expressions it can be quite hard to read due to needing to do these jumps yourself. Regardless, it should be clear that because we have wiped out all names, $\alpha$-equivalence is exactly just equality on trees.</p> <p>So this is fine for closed expressions, but what about free variables? There are actually two ways to go about it:</p> <h2 id="locally-nameless-forms">Locally Nameless Forms</h2> <p>We can treat free variables completely differently from bound variables. For bound variables we use their DeBruijn index. For free variables, we can use something like a name that is globally unique. This is called Locally Namelss Forms.</p> <p>This is a really good solution in general, because this means we can encode contexts as just unordered maps (due to structurality), so structurality theorems simply hold by very trivial arguments (exchange, weaken, etc). Substitution is also a lot easier to implement because for free variables it is merely a matter of comparing names. $\alpha$-equivalence still holds trivially, so that’s good.</p> <p>The downside is that again you end up with a bunch of theorems to prove about fresh variables, etc, but at least those are easy, if not annoying. A typical implementation would use something like views to “open up” bindings to turn bound variables free, and that can be mildly annoying to implement and not possible to pattern match.</p> <p>The bigger downside here is performance. If you look at the typechecking rule for lambda-intros, it is quite clear that a typical run of typechecking would almost certainly require “opening up” basically every single binder, and grant each of them fresh names. I suspect that the performance hit isn’t that bad, but it is there.</p> <p>And then for systems where not all the structurality theorems (like exchange) hold, or at least not trivially, in my mind the benefits seem to be not as great since the representation of contexts require assumptions to be ordered anyway. This seems to be a noticable issue for implementation of dependent type theories.</p> <p>In any case, this is the “easy” implementation, and not what we are going to do.</p> <h2 id="the-hard-way">The Hard Way</h2> <p>The hard way is to treat free variables in a term as DeBruijn indicies relative to some context. To illustrate this, consider this judgement:</p> \[\Gamma , x : \tau , y : \tau \rightarrow \tau' \vdash app (y , x) : \tau'\] <p>If we consider the context itself as ordered and contains bindings, then within the application, $y$ needs to jump $0$ hops to get to the closest binding in the context, whereas $x$ needs to jump $1$ hop across $y : \tau$. Hence we have:</p> \[\Gamma , \tau , \tau \rightarrow \tau' \vdash app (0 , 1) : \tau'\] <p>Here, even though $0$ is free within the expression, it is “bound” in a sense relative to the judgement it is in.</p> <p>The benefit here is that “opening up” a binder is free. For example in the lambda-intros rule, if we write it in DeBruijn indicies, it just looks like:</p> \[\begin{align} &amp; \Gamma , \tau \vdash e : \tau' \nonumber \\ &amp; \hline \nonumber \\ &amp; \Gamma \vdash \lambda (\tau). e : \tau \rightarrow \tau' \nonumber \\ \end{align}\] <p>The indicies line up because the references to the variable $x$ within $e$ have the same DeBruijn index, and so does everything else. Hence this rule is very cheap to evaluate.</p> <p>On the downside, it can be hard to keep track of and certainly very hard to read. Even from a mile away, you might be able to see that this can cause a bit of a headache (well, a lot) if we want to prove something like exchange.</p> <p>We haven’t talked about actual substitution yet, but we can already write some starter code.</p> <h2 id="the-code">The Code</h2> <p>We shall code this up in Coq. We represent variables as natural numbers corresponding to their DeBruijn index.</p> <div class="language-coq highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">Require</span><span class="w"> </span><span class="k">Import</span><span class="w"> </span><span class="nn">List</span><span class="p">.</span><span class="no">Lists</span><span class="pi">.</span><span class="w">

</span><span class="k">Inductive</span><span class="w"> </span><span class="no">ty</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="kr">Set</span><span class="w"> </span><span class="p">:=</span><span class="w">
</span><span class="p">|</span><span class="w"> </span><span class="no">Ty_one</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="no">ty</span><span class="w">
</span><span class="p">|</span><span class="w"> </span><span class="no">Ty_arrow</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="no">ty</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="no">ty</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="no">ty</span><span class="w">
</span><span class="pi">.</span><span class="w">

</span><span class="k">Inductive</span><span class="w"> </span><span class="no">term</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="kr">Set</span><span class="w"> </span><span class="p">:=</span><span class="w">
</span><span class="p">|</span><span class="w"> </span><span class="no">Term_var</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="no">nat</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="no">term</span><span class="w">
</span><span class="p">|</span><span class="w"> </span><span class="no">Term_unit</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="no">term</span><span class="w">
</span><span class="p">|</span><span class="w"> </span><span class="no">Term_lam</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="no">ty</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="no">term</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="no">term</span><span class="w">
</span><span class="p">|</span><span class="w"> </span><span class="no">Term_app</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="no">term</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="no">term</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="no">term</span><span class="w">
</span><span class="pi">.</span><span class="w">
</span></code></pre></div></div> <p>Note that because we don’t have variable names anymore, Term_lam here implicitly binds a variable in the subterm that it takes.</p> <p>We also represent contexts as lists of types, but reversed.</p> <div class="language-coq highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">Definition</span><span class="w"> </span><span class="no">ctx</span><span class="w"> </span><span class="p">:=</span><span class="w"> </span><span class="no">list</span><span class="w"> </span><span class="no">ty</span><span class="pi">.</span><span class="w">
</span></code></pre></div></div> <p>Hopefully none of this so far is too surprising.</p> <p>Now to encode the typing judgement.</p> <div class="language-coq highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">Inductive</span><span class="w"> </span><span class="no">checks</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="no">ctx</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="no">term</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="no">ty</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="kr">Set</span><span class="w"> </span><span class="p">:=</span><span class="w">
</span><span class="p">|</span><span class="w"> </span><span class="no">Checks_unit_intros</span><span class="w"> </span><span class="p">:</span><span class="w">
  </span><span class="kr">forall</span><span class="w"> </span><span class="no">C</span><span class="p">,</span><span class="w"> </span><span class="no">checks</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="no">Term_unit</span><span class="w"> </span><span class="no">Ty_one</span><span class="w">
</span><span class="p">|</span><span class="w"> </span><span class="no">Checks_lam_intros</span><span class="w"> </span><span class="p">:</span><span class="w">
  </span><span class="kr">forall</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="no">tau</span><span class="w"> </span><span class="no">tau2</span><span class="w"> </span><span class="no">e</span><span class="p">,</span><span class="w">
    </span><span class="no">checks</span><span class="w"> </span><span class="p">(</span><span class="no">tau</span><span class="w"> </span><span class="p">::</span><span class="w"> </span><span class="no">C</span><span class="p">)</span><span class="w"> </span><span class="no">e</span><span class="w"> </span><span class="no">tau2</span><span class="w"> </span><span class="o">-&gt;</span><span class="w">
    </span><span class="no">checks</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="p">(</span><span class="no">Term_lam</span><span class="w"> </span><span class="no">tau</span><span class="w"> </span><span class="no">e</span><span class="p">)</span><span class="w"> </span><span class="p">(</span><span class="no">Ty_arrow</span><span class="w"> </span><span class="no">tau</span><span class="w"> </span><span class="no">tau2</span><span class="p">)</span><span class="w">
</span><span class="p">|</span><span class="w"> </span><span class="no">Checks_lam_elim</span><span class="w"> </span><span class="p">:</span><span class="w">
  </span><span class="kr">forall</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="no">tau</span><span class="w"> </span><span class="no">tau2</span><span class="w"> </span><span class="no">e</span><span class="w"> </span><span class="no">e2</span><span class="p">,</span><span class="w">
    </span><span class="no">checks</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="no">e</span><span class="w"> </span><span class="p">(</span><span class="no">Ty_arrow</span><span class="w"> </span><span class="no">tau</span><span class="w"> </span><span class="no">tau2</span><span class="p">)</span><span class="w"> </span><span class="o">-&gt;</span><span class="w">
    </span><span class="no">checks</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="no">e2</span><span class="w"> </span><span class="no">tau</span><span class="w"> </span><span class="o">-&gt;</span><span class="w">
    </span><span class="no">checks</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="p">(</span><span class="no">Term_app</span><span class="w"> </span><span class="no">e</span><span class="w"> </span><span class="no">e2</span><span class="p">)</span><span class="w"> </span><span class="no">tau2</span><span class="w">
</span><span class="pi">.</span><span class="w">
</span></code></pre></div></div> <p>So far so good, again in the lambda-intros rule, indicies within $e$ have not been shifted, giving us a straightforward implementation.</p> <p>Now all we are missing is the variable rule. This one is a bit tricky. Note that because we are using the list type, by the type itself it is technically possible to have DeBruijn indicies that overflow the list. We could consider using a length-indexed list, but this would also require us to make statements on, say, the largest DeBruijn index within the term to avoid the bounds check, which could potentially mean indexing the terms on some natural number representing the largest free DeBruijn index. And if we add products to the language, we’d also need to combine this index by taking the max of the two, which means we’d need to end up reasoning a lot about orders on natural numbers anyway.</p> <p>So instead, we take a much more simplistic approach by just encoding the requirement within the judgement. A bit of a very mild performance hit for wrapping something into an Option, but that’s probably fine.</p> <div class="language-coq highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">Inductive</span><span class="w"> </span><span class="no">checks</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="no">ctx</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="no">term</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="no">ty</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="kr">Set</span><span class="w"> </span><span class="p">:=</span><span class="w">
</span><span class="p">|</span><span class="w"> </span><span class="no">Checks_unit_intros</span><span class="w"> </span><span class="p">:</span><span class="w">
  </span><span class="kr">forall</span><span class="w"> </span><span class="no">C</span><span class="p">,</span><span class="w"> </span><span class="no">checks</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="no">Term_unit</span><span class="w"> </span><span class="no">Ty_one</span><span class="w">
</span><span class="p">|</span><span class="w"> </span><span class="no">Checks_lam_intros</span><span class="w"> </span><span class="p">:</span><span class="w">
  </span><span class="kr">forall</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="no">tau</span><span class="w"> </span><span class="no">tau2</span><span class="w"> </span><span class="no">e</span><span class="p">,</span><span class="w">
    </span><span class="no">checks</span><span class="w"> </span><span class="p">(</span><span class="no">tau</span><span class="w"> </span><span class="p">::</span><span class="w"> </span><span class="no">C</span><span class="p">)</span><span class="w"> </span><span class="no">e</span><span class="w"> </span><span class="no">tau2</span><span class="w"> </span><span class="o">-&gt;</span><span class="w">
    </span><span class="no">checks</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="p">(</span><span class="no">Term_lam</span><span class="w"> </span><span class="no">tau</span><span class="w"> </span><span class="no">e</span><span class="p">)</span><span class="w"> </span><span class="p">(</span><span class="no">Ty_arrow</span><span class="w"> </span><span class="no">tau</span><span class="w"> </span><span class="no">tau2</span><span class="p">)</span><span class="w">
</span><span class="p">|</span><span class="w"> </span><span class="no">Checks_lam_elim</span><span class="w"> </span><span class="p">:</span><span class="w">
  </span><span class="kr">forall</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="no">tau</span><span class="w"> </span><span class="no">tau2</span><span class="w"> </span><span class="no">e</span><span class="w"> </span><span class="no">e2</span><span class="p">,</span><span class="w">
    </span><span class="no">checks</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="no">e</span><span class="w"> </span><span class="p">(</span><span class="no">Ty_arrow</span><span class="w"> </span><span class="no">tau</span><span class="w"> </span><span class="no">tau2</span><span class="p">)</span><span class="w"> </span><span class="o">-&gt;</span><span class="w">
    </span><span class="no">checks</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="no">e2</span><span class="w"> </span><span class="no">tau</span><span class="w"> </span><span class="o">-&gt;</span><span class="w">
    </span><span class="no">checks</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="p">(</span><span class="no">Term_app</span><span class="w"> </span><span class="no">e</span><span class="w"> </span><span class="no">e2</span><span class="p">)</span><span class="w"> </span><span class="no">tau2</span><span class="w">
</span><span class="p">|</span><span class="w"> </span><span class="no">Checks_var</span><span class="w"> </span><span class="p">:</span><span class="w">
  </span><span class="kr">forall</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="no">n</span><span class="w"> </span><span class="no">tau</span><span class="p">,</span><span class="w">
    </span><span class="nn">List</span><span class="p">.</span><span class="no">nth_error</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="no">n</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="no">Some</span><span class="w"> </span><span class="no">tau</span><span class="w"> </span><span class="o">-&gt;</span><span class="w">
    </span><span class="no">checks</span><span class="w"> </span><span class="no">C</span><span class="w"> </span><span class="p">(</span><span class="no">Term_var</span><span class="w"> </span><span class="no">n</span><span class="p">)</span><span class="w"> </span><span class="no">tau</span><span class="w">
</span><span class="pi">.</span><span class="w">
</span></code></pre></div></div> <h1 id="next-up">Next Up</h1> <p>I just realised I’ve written quite a bit, so everything else will have to be next time. Next time I plan on proving some basic structurality theorems (painful), and discuss implementation of substitution.</p>]]></content><author><name></name></author><category term="type-theory"/><summary type="html"><![CDATA[where we talk about debruijn indicies in the simple first order case]]></summary></entry><entry><title type="html">First Post!</title><link href="https://www.haoxuany.com/blog/first-post/" rel="alternate" type="text/html" title="First Post!"/><published>2025-02-13T00:00:00+00:00</published><updated>2025-02-13T00:00:00+00:00</updated><id>https://www.haoxuany.com/blog/first-post</id><content type="html" xml:base="https://www.haoxuany.com/blog/first-post/"><![CDATA[<p>Hey if you are seeing this, the post worked!</p>]]></content><author><name></name></author><summary type="html"><![CDATA[testing first blog post]]></summary></entry></feed>