nomeata’s mind shares
http://www.joachim-breitner.de//blog
Joachim Breitners Denkblogadehttp://joachim-breitner.de/avatars/avatar_128.pngnomeata’s mind shares
http://www.joachim-breitner.de//blog
128128Spring cleaning: local git branches
http://www.joachim-breitner.de/blog/751-Spring_cleaning__local_git_branches
http://www.joachim-breitner.de/blog/751-Spring_cleaning__local_git_brancheshttp://www.joachim-breitner.de/blog/751-Spring_cleaning__local_git_branches#commentsmail@joachim-breitner.de (Joachim Breitner)<p>This blog post is not for everyone. Look at the top of your screen. Do you see dozens of open tabs? Then this blog post is probably not for you. Do you see a small number of open tabs, (and you use git and GitHub seriously)? Then this might be interesting to you.</p>
<p>In a typical development project using git and GitHub, I have a bunch of local git branches, in various categories:</p>
<ol style="list-style-type: decimal">
<li><code>master</code>, simply tracking upstream’s <code>master</code> branch</li>
<li>Actively developed branches, already pushed to the remote repository.</li>
<li>like 2., but already turned into a pull request.</li>
<li>like 3., but already merged into <code>master</code>, using a merge commit,</li>
<li>like 3., but already merged into <code>master</code>, using squash or rebase,</li>
<li>like 2., but rejected and closed,</li>
<li>like 6., and the corresponding remote branch already removed.</li>
<li>Local commits that never made it remote.</li>
</ol>
<p>This adds up to a fair number of local branches. Some of them are clearly mostly useless (in particular, those accepted into <code>master</code>, i.e. 4. and 5.). So I am motivate to delete as many branches as I can.</p>
<p>But I also do not want to lose any information. So I do not want to delete commits that I could not recover, if I had to.</p>
<p>A simple first thing to do, as <a href="https://stackoverflow.com/a/6127884/946226">recommended on StackExchange</a>, is to delete all branches that have been merged into <code>master</code>:</p>
<pre><code>git branch --merged | egrep -v "(^\*|master)" | xargs git branch -d</code></pre>
<p>but this only catches category 4, and would not even delete branches that were merged using rebase or squash. Can we do better?</p>
<p>The crucial bit to know here is that Github treats each pull request like a branch, you just don’t see it, as they are hidden (they are in a different namespace, apart of the usual branches and tags). These branches stay around and, more importantly, when you merge a pull request using squash or rebase, they still reflect the “old” history of the PR.</p>
<p>In order to make use of that, we can instruct <code>git</code> to retch these pull request branches. To do so, edit <code>.git/config</code> in your repository, and add the following last line to the <code>[remote "origin"]</code> section:</p>
<pre><code>[remote "origin"]
url = …
fetch = +refs/heads/*:refs/remotes/origin/*
fetch = +refs/pull/*/head:refs/remotes/origin/pr/*</code></pre>
<p>If you now run <code>git fetch</code>, you should see a lot of <code>remotes/origin/pr/123</code> references being pushed.</p>
<p>And now that we see the state of all the pull requests that GitHub stores for us, we can delete all local branches that are contained in any of the remote branches:</p>
<pre><code>for r in $(git branch -r --format='%(refname)'); do git branch --merged $r; done | sort -u | grep -v '^\*' | xargs -r git branch -D</code></pre>
<p>Done! This deletes all categories mentioned above besides the last one.</p>
<p>A nice consequence of this is that I now know what to do with branches that did not lead anywhere, but which I did not simply want to remove: I push them to GitHub repository, create a new draft pull request, with a helpful comment for the future, immediately close the PR again and delete the remote and the local branch. If I ever want to come back to it, I find it in the list of closed pull requests, which is a much nicer attic than a ever growing list of branches of unclear status.</p>Sun, 03 Mar 2019 12:43:23 +0100Teaching to read Haskell
http://www.joachim-breitner.de/blog/750-Teaching_to_read_Haskell
http://www.joachim-breitner.de/blog/750-Teaching_to_read_Haskellhttp://www.joachim-breitner.de/blog/750-Teaching_to_read_Haskell#commentsmail@joachim-breitner.de (Joachim Breitner)<p><em>TL;DR:</em> New Haskell tutorial at http://haskell-for-readers.nomeata.de/.</p>
<p>Half a year ago, I left the normal academic career path and joined the <a href="https://dfinity.org/">DFINITY Foundation</a>, a non-profit start-up that builds a blockchain-based “Internet Computer” which will, if everything goes well, provide a general purpose, publicly owned, trustworthy service hosting platform.</p>
<p>DFINITY heavily bets on Haskell as a programming language to quickly develop robust and correct programs (and it was my Haskell experience that opened this door for me). DFINITY also builds heavily on innovative cryptography and cryptographic protocols to make the Internet Computer work, and has assembled an <a href="https://dfinity.org/team/#research">impressive group of crypto researchers</a>.</p>
<p>Crypto is hard, and so is implementing crypto. How do we know that the Haskell code correctly implements what the cryptography researchers designed? Clearly, our researchers will want to review the code and make sure that everything is as intended.</p>
<p>But surprisingly, not everybody is Haskell-literate. This is where I come in, given that I have taught Haskell classes before, and introduce Haskell to those who do not know it well enough yet.</p>
<p>At first I thought I’d just re-use the material I created for the <a href="http://cis.upenn.edu/~cis194/fall16/">CIS 194 Haskell course</a> at the University of Pennsylvania. But I noticed that I am facing quite a different audience. Instead of young students with fairly little computer scientist background who can spent quite a bit of time to learn to <em>write</em> Haskell, I am now addressing senior and very smart computer scientists with many other important things to do, who want to learn to <em>read</em> Haskell.</p>
<p>Certainly, a number of basics are needed in either case; basic functional programming for example. But soon, the needs diverge:</p>
<ul>
<li>In order to write Haskell, I have to learn how to structure a program, how to read error message and deal with Haskell’s layout rule, but I don’t need to know all idioms and syntax features yet.</li>
<li>If I want to read Haskell, I need to navigate possibly big files, recognize existing structure, and deal with a plenitude of syntax, but I don’t need to worry about setting up a compiler or picking the right library.</li>
</ul>
<p>So I set out to create a new Haskell course, “<strong><a href="http://haskell-for-readers.nomeata.de/">Haskell for Readers</a></strong>”, that is specifically tailored to this audience. It leaves out a few things that are not necessary for reading Haskell, is relatively concise and densely packed, but it starts with the basics and does not assume prior exposure to functional programming.</p>
<p>As it behooves for a non-profit-foundation, DFINITY is happy for me to develop the lecture material in the open, and release it to the public under a permissive creative commons license, so I invite you to read the in-progress document, and maybe learn something. Of course, my hope is to also get constructive feedback in return, and hence profit from this public release. <a href="https://github.com/nomeata/haskell-for-readers/">Sources on GitHub.</a></p>Fri, 11 Jan 2019 22:17:03 +0100Nonce sense paper online
http://www.joachim-breitner.de/blog/749-Nonce_sense_paper_online
http://www.joachim-breitner.de/blog/749-Nonce_sense_paper_onlinehttp://www.joachim-breitner.de/blog/749-Nonce_sense_paper_online#commentsmail@joachim-breitner.de (Joachim Breitner)<p><a href="https://www.cis.upenn.edu/~nadiah/">Nadia Heninger</a> and I just have put the preprint version of our paper “<a href="https://eprint.iacr.org/2019/023">Biased Nonce Sense: Lattice Attacks against Weak ECDSA Signatures in Cryptocurrencies</a>”, to be presented at <a href="https://fc19.ifca.ai/">Financial Crypto 2019</a>, online. In this work, we see how many private keys used on the Bitcoin, Ethereum and Ripple blockchain, as well as in HTTPS and SSH, were used in an unsafe way and hence can be compromised. The resulting numbers are not large – 300 Bitcoin keys, with a balance of around $54 – but it shows (again and again) that it can be tricky to get crypto right, and that if you don’t get it right, you can lose your money.</p>
<h3 id="brief-summary">Brief summary</h3>
<p>When you create a cryptographic signatures using ECDSA (the <a href="https://en.wikipedia.org/wiki/ECDSA">elliptic curve digital signature algorithm</a>), you need to come up with the <em>nonce</em>, a 256 bit random number. It is really important to use a different nonce every time, otherwise it is easy for someone else to take your signatures (which might be stored for everyone to read on the Bitcoin blockchain) and calculate your private key using relatively simple math, and with your private key they can spend all your Bitcoins. In fact, there is evidence that people out there continuously monitor the blockchains for signatures with such repeated nonces and immediately extract the money from compromised keys.</p>
<p>Less well known, but still nothing new to the crypto (as in cryptography) community is the that an attacker can calculate the key from signature that use <em>different</em>, but <em>similar</em> nonces: For example if they are close by each other (only the low bits differ), or if they differ by exactly a large power of two (only the high bits differ). This uses a fancy and powerful technique based on <em>lattices</em>. Our main contribution here is to bridge crypto (as in cryptography) and crypto (as in cryptocurrency) and see if such vulnerabilities actually exist out there.</p>
<p>And indeed, there are some. Not many (which is good), but they do exist, and clearly due to more than one source. Unfortunately, it is really hard to find out who made these signatures, and with which code, so we can only guess about the causes of these bugs. A large number of affected signatures are related to multisig transactions, so we believe that maybe hardware tokens could be the cause here.</p>
<h3 id="observing-programming-bugs">Observing programming bugs</h3>
<p>Even though we could not identify the concrete implementations that caused these problems, we could still observe some interesting details about them. The most curious is certainly this one:</p>
<p>One set of signatures, which incidentally were created by an <em>attacker</em> who emptied out accounts of compromised keys (e.g. those that are created with a weak password, or otherwise leaked onto the internet), was using nonces that shared the low 128 bits, and hence revealed the (already compromised) private key of the account he emptied out. Curiously, these low 128 bits are precisely the <em>upper</em> 128 bits of the private key.</p>
<p>So it very much looks like the attacker hacked up a program that monitors the blockchain and empties out accounts, and probably did so using a memory unsafe language like C, and got the size of the buffers for nonce and key wrong, so maybe they did properly filled the nonce with good random data, but when they wrote the secret key, the memory locations overlapped and they overrode parts of their randomness with the very non-random secret key. Oh well.</p>
<h3 id="do-i-need-to-worry">Do I need to worry?</h3>
<p>Probably not. The official blockchain clients get their crypto right (at least this part), and use properly random nonces, so as a user you don’t have to worry. In fact, since 2016, the Bitcoin client uses <em>deterministic signatures</em> (<a href="https://tools.ietf.org/html/rfc6979">RFC6979</a>) which completely removes the need for randomness in the process.</p>
<p>If you are using non-standard libraries, or if you write your own crypto routines (which you should only ever do if you have a really really good reason for it) you should make sure that these use RFC6979. This is even more important on embedded devices or hardware tokens where a good source of randomness might be hard to come by.</p>
<h3 id="discrete-logarithm-in-secp256k1-with-lookup-table">Discrete logarithm in secp256k1 with lookup table</h3>
<p>In the course of this work I wanted to find out if small nonces (<span class="math inline"><2<sup>64</sup></span>) were used even when the key created only one of these – the lattice-based attacks need at least two signatures to work. So I created code that calculates the discrete log in the secp256k1 curve up to an exponent of (<span class="math inline"><2<sup>64</sup></span>). This is made feasible using a lookup table for smaller exponents (<span class="math inline"><2<sup>39</sup></span> in our case – just large enough to still fit into 2.2TB of RAM).</p>
<p>This exercise turned out to be not very useful; we did not find any additional keys, but I had fun writing up the program, implemented in C and working very close to the raw data, juggling big binary files <code>mmap</code>’ed into memory, and implementing custom lookup indices and such. In the hope that this might be useful to someone, I share the code at <a href="https://github.com/nomeata/secp265k1-lookup-table" class="uri">https://github.com/nomeata/secp265k1-lookup-table</a>.</p>Thu, 10 Jan 2019 09:04:47 +0100Thoughts on bootstrapping GHC
http://www.joachim-breitner.de/blog/748-Thoughts_on_bootstrapping_GHC
http://www.joachim-breitner.de/blog/748-Thoughts_on_bootstrapping_GHChttp://www.joachim-breitner.de/blog/748-Thoughts_on_bootstrapping_GHC#commentsmail@joachim-breitner.de (Joachim Breitner)<p>I am returning from the <a href="https://reproducible-builds.org/events/paris2018/">reproducible builds summit 2018</a> in Paris. The latest hottest thing within the reproducible-builds project seems to be bootstrapping: How can we build a whole operating system from just and only <em>source code</em>, using very little, or even no, binary seeds or auto-generated files. This is actually concern that is somewhat orthogonal to reproducibility: <a href="https://bootstrappable.org/">Bootstrappable builds</a> help me in trusting programs that <em>I</em> built, while reproducible builds help me in trusting programs that <em>others</em> built.</p>
<p>And while they make good progress bootstrapping a full system from just a C compiler written in Scheme, and a Scheme interpreter written in C, that can build each other (Janneke’s <a href="https://gitlab.com/janneke/mes">mes</a> project), and there are plans to build that on top of <a href="http://savannah.nongnu.org/projects/stage0">stage0</a>, which starts with a 280 bytes of binary, the situation looks pretty bad when it comes to Haskell.</p>
<h3 id="unreachable-ghc">Unreachable GHC</h3>
<p>The problem is that contemporary Haskell has only one viable implementation, <a href="https://www.haskell.org/ghc/">GHC</a>. And GHC, written in contemporary Haskell, needs GHC to be build. So essentially everybody out there either just downloads a binary distribution of GHC. Or they build GHC from source, using a possibly older (but not much older) version of GHC that they already have. Even distributions like Debian do nothing different: When they build the GHC package, the builders use, well, the GHC package.</p>
<p>There are other <a href="https://wiki.haskell.org/Implementations">Haskell implementations</a> out there. But if they are mature and active developed, then they are implemented in Haskell themselves, often even using advanced features that only GHC provides. And even those are insufficient to build GHC itself, let alone the some old and abandoned Haskell implementations.</p>
<p>In all these cases, at some point an untrusted binary is used. This is very unsatisfying. What can we do? I don’t have the answers, but please allow me to outline some venues of attack.</p>
<h3 id="retracing-history">Retracing history</h3>
<p>Obviously, even GHC does not exist since the beginning of time, and the first versions surely were built using something else than GHC. The oldest version of GHC for which we can find a release on the GHC web page is <a href="https://downloads.haskell.org/~ghc/0.29/">version 0.29 from July 1996</a>. But the installation instructions write:</p>
<blockquote>
<p>GHC 0.26 doesn't build with HBC. (It could, but we haven't put in the effort to maintain it.)</p>
<p>GHC 0.26 is best built with itself, GHC 0.26. We heartily recommend it. GHC 0.26 can certainly be built with GHC 0.23 or 0.24, and with some earlier versions, with some effort.</p>
<p>GHC has never been built with compilers other than GHC and HBC.</p>
</blockquote>
<p>So it seems that besides GHC, only ever HBC was used to compiler GHC. HBC is a Haskell compiler where we find <a href="https://archive.org/details/haskell-b-compiler">the sources of one random version</a> only thanks to archive.org. Parts of it are written in C, so I looked into this: Compile HBC, use it to compile GHC-0.29, and then step for step build every (major) version of GHC until today.</p>
<p>The problem is that it is non-trivial to build software from the 90s using today's compilers. I briefly looked at the HBC code base, and had to change some <a href="https://en.wikipedia.org/wiki/Stdarg.h#varargs.h">files from using <code>varargs.h</code> to <code>stdargs.v</code></a>, and this is surely just one of many similar stumbling blocks trying to build that tools. Oh, and even the <code>hbc</code> source state</p>
<pre><code># To get everything done: make universe
# It is impossible to make from scratch.
# You must have a running lmlc, to
# recompile it (of course).</code></pre>
<p>So I learned that actually, most of it is written in LML, and the LML compiler is written in LML. So this is a dead end. (Thanks to Lennart for <a href="https://www.reddit.com/r/haskell/comments/a600zp/thoughts_on_bootstrapping_ghc/ebqt33g/">clearing up a misunderstanding</a> on my side here.</p>
<h3 id="going-back-but-doing-it-differently">Going back, but doing it differently</h3>
<p>Another approach is to go back in time, to some old version of GHC, but maybe not <em>all</em> the way to the beginning, and then try to use another, officially unsupported, Haskell compiler to build GHC. This is what <a href="https://elephly.net/posts/2017-01-09-bootstrapping-haskell-part-1.html">rekado tried to do in 2017</a>: He use the most contemporary implementation of Haskell in C, the <a href="https://www.haskell.org/hugs/">Hugs interpreter</a>. Using this, he compiled <a href="https://www.haskell.org/nhc98/">nhc98</a> (yet another abandoned Haskell implementation), with the hope of building GHC with nhc98. He made impressive progress back then, but ran into a problem where the runtime crashed. Maybe someone is interested in picking up up from there?</p>
<h3 id="removing-simplifying-extending-in-the-present.">Removing, simplifying, extending, in the present.</h3>
<p>Both approaches so far focus on building an old version of GHC. This adds complexity: other tools (the shell, make, yacc etc.) may behave different now in a way that causes hard to debug problems. So maybe it is more fun and more rewarding to focus on today’s GHC? (At this point I am starting to hypothesize).</p>
<p>I said before that no other existing Haskell implementation can compile today’s GHC code base, because of features like mutually recursive modules, the foreign function interface etc. And also other existing Haskell implementations often come with a different, smaller set of standard libraries, but GHC assumes <a href="http://hackage.haskell.org/package/base"><code>base</code></a>, so we would have to build that as well...</p>
<p>But we don’t need to build it all. Surely there is much code in <code>base</code> that is not used by GHC. Also, much code in GHC that we do not need to build GHC, and . So by <em>removing</em> that, we reduce the amount of Haskell code that we need to feed to the other implementation.</p>
<p>The remaining code might use some features that are not supported by our bootstrapping implementation. Mutually recursive module could be manually merged. GADTs that are only used for additional type safety could be replaced by normal ones, which might make some pattern matches incomplete. Syntactic sugar can be desugared. By <em>simplifying</em> the code base in that way, one might be able a fork of GHC that is within reach of the likes of Hugs or nhc98.</p>
<p>And if there are features that are hard to remove, maybe we can <em>extend</em> the bootstrapping compiler or interpreter to support them? For example, it was mostly trivial to extend <code>Hugs</code> with support for the <code>#</code> symbol in names – and we can be pragmatic and just allow it always, since we don’t need a standards conforming implementation, but merely one that works on the GHC code base. But how much would we have to implement? Probably this will be more fun in Haskell than in C, so maybe extending nhc98 would be more viable?</p>
<h3 id="help-from-beyond-haskell">Help from beyond Haskell?</h3>
<p>Or maybe it is time to create a new Haskell compiler from scratch, written in something <em>other</em> than Haskell? Maybe some other language that is reasonably pleasant to write a compiler in (Ocaml? Scala?), but that has the bootstrappability story already sorted out somehow.</p>
<p>But in the end, all variants come down to the same problem: Writing a Haskell compiler for full, contemporary Haskell as used by GHC is hard and really a lot of work – if it were not, there would at least be implementations in Haskell out there. And as long as nobody comes along and does that work, I fear that we will continue to be unable to build our nice Haskell ecosystem from scratch. Which I find somewhat dissatisfying.</p>Thu, 13 Dec 2018 14:02:08 +0100Sliding Right into Information Theory
http://www.joachim-breitner.de/blog/747-Sliding_Right_into_Information_Theory
http://www.joachim-breitner.de/blog/747-Sliding_Right_into_Information_Theoryhttp://www.joachim-breitner.de/blog/747-Sliding_Right_into_Information_Theory#commentsmail@joachim-breitner.de (Joachim Breitner)<p>It's hardly news any more, but it seems I have not blogged about my involvement last year with an interesting cryptanalysis project, which resulted in the publication <em>Sliding right into disaster: Left-to-right sliding windows leak</em> by Daniel J. Bernstein, me, Daniel Genkin, Leon Groot Bruinderink, Nadia Heninger, Tanja Lange, Christine van Vredendaal and Yuval Yarom, which was published at <a href="https://link.springer.com/chapter/10.1007%2F978-3-319-66787-4_27">CHES 2017</a> and on <a href="https://eprint.iacr.org/2017/627">ePrint</a> (ePrint is the cryptographer’s version of arXiv).</p>
<p>This project nicely touched upon many fields of computer science: First we need systems expertise to mount a side-channel attack that uses cache timing difference to observe which line of a square-and-multiply algorithm the target process is executing. Then we need algorithm analysis required to learn from these observations partial information about the bits of the private key. This part includes nice PLy concepts like rewrite rules (see Section 3.2). Oncee we know enough about the secret keys, we can use fancy cryptography to recover the whole secret key (Section 3.4). And finally, some theoretical questions arise, such as: “How much information do we need for the attack to succeed?” and “Do we obtain this much information”, and we need some nice math and information theory to answer these.</p>
<p>Initially, I focused on the PL-related concepts. We programming language people are yak-shavers, and in particular “rewrite rules” just demands the creation of a DSL to express them, and an interpreter to execute them, doesn’t it? But it turned out that these rules are actually not necessary, as the key recovery can use the side-channel observation directly, as we found out later (see Section 4 of the paper). But now I was already hooked, and turned towards the theoretical questions mentioned above.</p>
<h3 id="shannon-vs.-rényi">Shannon vs. Rényi</h3>
<p>It felt good to shake the dust of some of the probability theory that I learned for my maths degree, and I also learned some new stuff. For example, it was intuitively clear that whether the attack succeeds depends on the amount of information obtained by the side channel attack, and based on prior work, the expectation was that if we know more than half the bits, then the attack would succeed. Note that for this purpose, two known “half bits” are as good as knowing one full bit; for example knowing that the secret key is either <code>01</code> or <code>11</code> (one bit known for sure) is just as good as knowing that the key is either <code>00</code> or <code>11</code>.</p>
<p>Cleary, this is related to entropy somehow -- but how? Trying to prove that the attack works if the entropy rate of the leak is <span class="math inline">>0.5</span> just did not work, against all intuition. But when we started with a formula that describes when the attack succeeds, and then simplified it, we found a condition that looked suspiciously like what we wanted, namely <span class="math inline"><em>H</em> > 0.5</span>, only that <span class="math inline"><em>H</em></span> was not the conventional entropy (also known as the <em>Shannon entropy</em>, <span class="math inline"><em>H</em> = −∑<em>p</em> ⋅ log <em>p</em></span>), but rather something else: <span class="math inline"><em>H</em> = −∑<em>p</em><sup>2</sup></span>, which turned to be called the <em>collision entropy</em> or <a href="https://en.wikipedia.org/wiki/Rényi_entropy"><em>Rényi entropy</em></a>.</p>
<p>This resulted in Theorem 3 in the paper, and neatly answers the question when the <a href="https://eprint.iacr.org/2008/510.pdf">Heninger and Shacham key recovery algorithm</a>, extended to partial information, can be expected to succeed in a much more general setting that just this particular side-channel attack.</p>
<h3 id="markov-chains-and-an-information-theoretical-spin-off">Markov chains and an information theoretical spin-off</h3>
<p>The other theoretical question is now: Why does this particular side channel attack succeed, i.e. why is the entropy rate <span class="math inline"><em>H</em> > 0.5</span>. As so often, Markov chains are an immensly powerful tool to answer that question. After some transformations, I managed to model the state of the square-and-multiply algorithm, together with the side-channel leak, as a markov chain with a hidden state. Now I just had to calculate its Rényi entropy rate, right? I wrote some Haskell code to do this transformation, and also came up with an ad-hoc, intuitive way of calculating the rate. So when it was time to write up the paper, I was searching for a reference that describes the algorithm that I was using…</p>
<p>Only I could find none! I contacted researchers who have published related to Markov chains and entropies, but they just referred me in circles, until one of them, Maciej Skórski responded. Our conversation, highly condendensed, went like this: “Nice idea, but it can’t be right, it would solve problem X” – “Hmm, but it feels so right. Here is a proof sketch.” – “Oh, indeed, cool. I can even generalize this! Let’s write a paper”. Which we did! <a href="http://arxiv.org/abs/1709.09699"><em>Analytic Formulas for Renyi Entropy of Hidden Markov Models</em></a> (preprint only, it is still under submission).</p>
<h3 id="more-details">More details</h3>
<p>Because I joined the sliding-right project late, not all my contributions made it into the actual paper, and therefore I published an <a href="https://eprint.iacr.org/2018/1163">“inofficial appendix”</a> separately on ePrint. It contains</p>
<ol style="list-style-type: decimal">
<li>an alternative way to find the definitively knowable bits of the secret exponent, which is complete and can (in rare corner cases) find more bits than the rewrite rules in Section 3.1</li>
<li>an algorithm to calculate the collision entropy <span class="math inline"><em>H</em></span>, including how to model a side-channel attack like this one as a markov chain, and how to calculate the entropy of such a markov chain, and</li>
<li>the proof of Theorem 3.</li>
</ol>
<p>I also published the <a href="https://github.com/nomeata/slidingright">Haskell code</a> that I wrote for this projects, including the markov chain collision entropy stuff. It is not written with public consumption in mind, but feel free to ask if you have questions about this.</p>
<p>Note that all errors, typos and irrelevancies in that document and the code are purely mine and not of any of the other authors of the sliding-right paper. I’d like to thank my coauthors for the opportunity to join this project.</p>Mon, 03 Dec 2018 10:56:49 +0100Swing Dancer Profile
http://www.joachim-breitner.de/blog/746-Swing_Dancer_Profile
http://www.joachim-breitner.de/blog/746-Swing_Dancer_Profilehttp://www.joachim-breitner.de/blog/746-Swing_Dancer_Profile#commentsmail@joachim-breitner.de (Joachim Breitner)<p>During my two years in Philadelphia (I was a post-doc with <a href="http://www.seas.upenn.edu/~sweirich/">Stephanie Weirich at the University of Pennsylvania</a>) I danced a lot of Swing, in particular at the weekly social “<a href="https://www.jazzattackswings.com/">Jazz Attack</a>”.</p>
<p>They run a blog, that blog features dancers, and this week – just in time for my last dance – they <a href="https://www.jazzattackswings.com/blog/community-spotlight-joachim/">featured me with a short interview</a>.</p>Tue, 07 Aug 2018 12:16:14 -0400The merits of a yellow-red phase
http://www.joachim-breitner.de/blog/745-The_merits_of_a_yellow-red_phase
http://www.joachim-breitner.de/blog/745-The_merits_of_a_yellow-red_phasehttp://www.joachim-breitner.de/blog/745-The_merits_of_a_yellow-red_phase#commentsmail@joachim-breitner.de (Joachim Breitner)<p>In my yesterday <a href="/blog/744">post on Continuity Lines in North America</a> I mentioned in passing that I am big fan of German<a href="#fn1" class="footnoteRef" id="fnref1"><sup>1</sup></a> traffic lights, which have a brief yellow-red phase between the red and and the green phase (3 to 5 seconds, depending on road speed). A German reader of my blog was surprised by this, said that he considers it pointless, and would like to hear my reasons. So where we go…</p>
<h3 id="life-without-yellow-red">Life without Yellow-Red</h3>
<p>Lights that switch directly from red to green cause more stress. Picture yourself at the first car waiting at a traffic light, with a bunch of cars behind you. Can you relax, maybe observe the cars passing in front of you, switch the radio station, or simply look somewhere else for a moment? Well, you can, but you risk missing how the light switches from red to green. When your look at the traffic light again and see it bright green, you have no idea how long it has been on green. Hyper-aware of all the cars behind you waiting to get going, you’ll rush to get started, and if you don’t do that really fast now, surely one of the people waiting behind you will have honked.</p>
<p>So at the next intersection, you better don’t take your eyes off the light – or, alternatively, you develop a screw-you-I-don’t-care-attitude towards the other cars, which might allow you to relax in this situation, but is in general not desirable.</p>
<p>Maybe this is less of a problem on the West Coast, where supposedly everybody is nice, relaxed, and patient, and you can take all the time you want to get rolling. But in the stereotypical East Coast traffic full of angry, impatient and antisocial drivers, you really don’t get away with that.</p>
<h3 id="life-with-yellow-red">Life with Yellow-Red</h3>
<p>The yellow-red phase solves this problem elegantly: As long as the light is red, you don’t have to watch the light constantly and with maximum attention. You can relax: it suffices to check it often enough to catch the red-yellow phase, once every two or three seconds. When you see it, you get ready to start; and when it actually turns green, you start on time.</p>
<p>I would expect that it is not only less stressful, it is also more efficient: Because every car in the lane has the heads-up warning “green in a moment”, the cars can start rolling in quicker succession. Without the warning, every car to account much more for the possible slower reaction of the car before.</p>
<p>PS: A friend of mine wonders whether the German Yellow-Red is needed because cars with manual transmissions are much more common in Germany than in the US, and you need more time to, well, get into gear with these cars.</p>
<div class="footnotes">
<hr/>
<ol>
<li id="fn1"><p>Also Great Britain, Croatia, Latvia, Norway, Austria, Poland, Russia, Saudi-Arabia, Sweden, Switzerland, Hungary and others.<a href="#fnref1">↩</a></p></li>
</ol>
</div>Mon, 30 Jul 2018 17:41:44 -0400Continuity Lines
http://www.joachim-breitner.de/blog/744-Continuity_Lines
http://www.joachim-breitner.de/blog/744-Continuity_Lineshttp://www.joachim-breitner.de/blog/744-Continuity_Lines#commentsmail@joachim-breitner.de (Joachim Breitner)<p>I am currently on a road trip going from Philly going North along the Atlantic Coast into Canada, and aiming for Nova Scotia. When I passed from the US into Canada, I made had an unexpected emotional response to the highways there: I felt more at home!</p>
<p>And I believe it has to do with the pavement markings on US vs. Canadian freeways.</p>
<p>Consider this image, taken from the <em>Manual on Uniform Traffic Control Devices</em> of the United States, an official document describing (among other things) <a href="https://mutcd.fhwa.dot.gov/services/publications/fhwaop02090/fwymarkings_lgview.htm">how the pavement of a freeway ought to be paved</a>:</p>
<div class="figure">
<img src="//www.joachim-breitner.de/various/exit-lane-us.png" alt="Parallel Deceleration Lane for Exit Ramp"/>
<p class="caption">Parallel Deceleration Lane for Exit Ramp</p>
</div>
<p>This is a typical exit ramp from the freeway. On ramps and cloverleaf ramps look similar. Note that the right-most lane goes somewhere else than the left and the middle lane, yet the lanes look completely identical. In particular, the lines between the lanes are shaped the same!</p>
<p>Now, for comparison, the corresponding image in a Canadian manual, namely the <a href="https://www2.gov.bc.ca/assets/gov/driving-and-transportation/transportation-infrastructure/engineering-standards-and-guidelines/traffic-engineering-and-safety/traffic-engineering/traffic-signs-and-pavement-markings/manual_signs_pavement_marking.pdf"><em>Manual of Standard Traffic Signs & Pavement Markings</em> for British Columbia</a>:</p>
<div class="figure">
<img src="//www.joachim-breitner.de/various/exit-lane-ca.png" alt="Canadian off-ramps"/>
<p class="caption">Canadian off-ramps</p>
</div>
<p>Here, there are <em>different</em> lines between the different lanes: normal lane lines left, but a so-called <em>continuity line</em>, with a distinctly different pattern, between the normal lanes and the exit lane. It’s like in Germany!</p>
<p>With this is mind I understand one reason<a href="#fn1" class="footnoteRef" id="fnref1"><sup>1</sup></a> why driving in the US<a href="#fn2" class="footnoteRef" id="fnref2"><sup>2</sup></a> noticeably more stressful: There is just always anxiety whether you are accidentally in an exit lane!</p>
<p><strong>Update (2018-07-30)</strong>: AS Paul Johnson pointed out (see comment below), I was looking at an old version of the MUTCD. The <a href="https://mutcd.fhwa.dot.gov/pdfs/2009r1r2/pdf_index.htm">current version, from 2009</a>, has these lines:</p>
<div class="figure">
<img src="//www.joachim-breitner.de/various/exit-lane-us2.png" alt="Current US off-ramps"/>
<p class="caption">Current US off-ramps</p>
</div>
<p>They have published a (very long) document describing the <a href="http://edocket.access.gpo.gov/2009/pdf/E9-28322.pdf">changes in the new version of the manual</a> , and Section 306 describes the rationale:</p>
<blockquote>
<p>[..] the FHWA adopts language to clarify that dotted lane lines, rather than broken lane lines, are to be used for non-continuing lanes, including acceleration lanes, deceleration lanes, and auxiliary lanes. [..] a number of States and other jurisdictions currently follow this practice, which is also the standard practice in Europe and most other developed countries. The FHWA believes that the existing use of a normal broken lane line for these non- continuing lanes does not adequately inform road users of the lack of lane continuity ahead and that the standardized use of dotted lane lines for non-continuing lanes as adopted in this final rule will better serve this important purpose in enhancing safety and uniformity.</p>
</blockquote>
<p>So all is well! But it means that either Pennsylvania was slower than allowed in implementing these changes (the deadline was December 2016), or it was something else alltogether that made me feel more at home on the Canadian freeway.</p>
<div class="footnotes">
<hr/>
<ol>
<li id="fn1"><p>I say “one reason”, not “the reason”, because there are many more – “Rechtsfahrgebot”, no red-and-yellow-phase in the traffic light, Pennsylvanian road quality…<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>Supposedly, Pennsylvania is particularly bad with roads in general, but also with this particular problem, and California has exit lanes clearly separated. But, of course, because this is the US, not using the same patter as the others (Canada, Europe), but using spaced dots…<a href="#fnref2">↩</a></p></li>
</ol>
</div>Sun, 29 Jul 2018 20:25:07 -0400Build tool semantic aware build systems
http://www.joachim-breitner.de/blog/743-Build_tool_semantic_aware_build_systems
http://www.joachim-breitner.de/blog/743-Build_tool_semantic_aware_build_systemshttp://www.joachim-breitner.de/blog/743-Build_tool_semantic_aware_build_systems#commentsmail@joachim-breitner.de (Joachim Breitner)<p>I just had a lovely visit at Ben Gamari and Laura Dietz, and at the breakfast table we had an idea that I want to record here.</p>
<h3 id="the-problem">The problem</h3>
<p>Laura and Ben talked about the struggles they had using build systems like <code>make</code> or <a href="http://nixos.org/nix/">Nix</a> in data science applications. A build system like nix is designed around the idea that builds are relatively cheap, and that any change in a dependency ought to trigger a rebuild, just to be sure that all build outputs are up-to-date. This is a perfectly valid assumption when building software, where build times are usually minutes, or maybe hours. But when some of the data processing takes days, then you really really want to avoid any unnecessary builds.</p>
<p>One way of avoiding unnecessary rebuilds that is supported by build systems like <a href="https://shakebuild.com/"><code>shake</code></a> and (I presume, maybe with some extra work) Nix, is to do output hashing: If one build stage has its input changed and need to be re-run, but its <em>output</em> is actually unchanged, then later build stages do not have to be re-run. Great!</p>
<p>But even with this feature in place, there one common problem remains: Build tools! Your multi-gigabyte data is going to be processed by some code you write. What if the code changes? Clearly, if you change the algorithm, or fix a bug in your code, you want the output to be re-run. But if you just change some strings in the <code>--help</code> flag, or update some libraries, or do something else that does <em>not</em> change the program in a way that is significant for the task at hand, wouldn’t you prefer to not pay for that by futile multi-day data processing step?</p>
<h3 id="existing-approaches">Existing approaches</h3>
<p>There are various ways you can tackle this these days:</p>
<ul>
<li><p>You bite the bullet, add the build tool as a dependency of the processing step. You get the assurance that your data always reflects the output of the latest version of your tool, but you get lots of rebuilds.</p></li>
<li><p>You don’t track the tool as part of your build system. It is now completely up to you to decide when the tool has changed in significant ways. When you think it has, you throw away all build artifacts and start from scratch. Very crude, and easy to get wrong.</p></li>
<li><p>You keep track of a “build tool version”, e.g. a text file with a number, that you depend on in lieu of the build tool itself. When you make a change that you think is significant, you bump that version number. This is similar to the previous approach, but more precise: Only the build outputs that used this particular tools will be invalidated, and it also scales better to working in a team. But of course, you can still easily get it wrong.</p></li>
</ul>
<h3 id="build-tool-semantics">Build tool semantics</h3>
<p>Why are all these approaches so unsatisfying? Because none allow you to express the <em>intent</em>, which is to say “this build step depends on the <em>semantics</em> (i.e. behaviour) of the build tool”. If we could somehow specify that, then all would be great: Build tool changes, but its semantics is unaffected? no rebuild. Build tool changes, semantics change? rebuild.</p>
<p>This ideal is not reachable (blah blah halting problem blah blah) – but I believe we can approximate it. At least if good practices were used and the tool has a test suite!</p>
<p>Assume for now that the tool is a simple patch-processing tool, i.e. takes some input and produces some output. Assume further that there is a test suite with a small but representative set of example inputs, or maybe some randomly generated inputs (using a fixed seed). If the test suite is good, then <strong>the <em>(hash of)</em> the output on the test suite example is an approximation of the programs semantic</strong>.</p>
<p>And the build system can use this “semantics hash”. If the build tool changes, the build system can re-run the test suite and compare the output with the previous run. If they change, then the tools seems to have changed in significant ways, and it needs to re-run the data processing. But if the test suite outputs are unchanged, then it can assume that the behaviour of the tool has not changed, re-use the existing data outputs.</p>
<p>That is the core idea! A few additional thoughts, though:</p>
<ul>
<li>What if the test suite changes? If the above idea is implemented naively, then adding a test case to the test suite will change the semantics, and re-build everything. That would be horrible in terms of incentives! So instead, the build systems should keep the old version of the build tool around, re-calculate its semantics hash based on the new test suite, and then compare that. This way, extending the test suite does not cause recompilation.</li>
</ul>
<p>Hash-and-store-based build systems like Nix should have no problem keeping the previous version of the build tool around as long there is output that depends on it.</p>
<ul>
<li><p>A consequence of this approach is that if you find and fix a bug in your tool that is not covered by the existing test suite, then you absolutely have to add a test for that to your test suite, otherwise the bug fix will not actually make it to your data output. This might be the biggest downside of the approach, but at least it sets incentives right in that it makes you maintain a good regression test suite.</p></li>
<li><p>What if things go wrong, the test suite is incomplete and the build system re-uses build output because it wrongly assumes that two versions of the build tool have the same semantics?</p></li>
</ul>
<p>If done right, this can be detected and fixed: The build system needs to record which tool version (and not just which “semantics hash”) was used to produce a particular output. So once the test suite uncovers the difference, the build systems will no longer consider the two versions equivalent and – after the fact – invalidate the re-used of the previous build output, and re-build what needs to be rebuild</p>
<p>I am curious to hear if anybody has played with these or similar ideas before? How did it go? Would it be possible to implement this in Nix? In Shake? Other systems? Tell me your thoughts!</p>Sat, 28 Jul 2018 11:03:31 -0400WebGL, Fragment Shader, GHCJS and reflex-dom
http://www.joachim-breitner.de/blog/742-WebGL%2C_Fragment_Shader%2C_GHCJS_and_reflex-dom
http://www.joachim-breitner.de/blog/742-WebGL%2C_Fragment_Shader%2C_GHCJS_and_reflex-domhttp://www.joachim-breitner.de/blog/742-WebGL%2C_Fragment_Shader%2C_GHCJS_and_reflex-dom#commentsmail@joachim-breitner.de (Joachim Breitner)<p>What a potpourri of topics... too long to read? <a href="https://nomeata.github.io/reflex-dom-fragment-shader-canvas/">Click here!</a></p>
<p>On the side and very slowly I am working on a little game that involves breeding spherical patterns… more on that later (maybe). I want to implement it in Haskell, but have it run in the browser, so I reached for GHCJS, the Haskell-to-Javascript compiler.</p>
<h2 id="webgl-for-2d-images">WebGL for 2D images</h2>
<p>A crucial question was: How do I draw a generative pattern onto a HTML <code>canvas</code> element. My first attempt was to calculate the pixel data into a bit array and use <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/putImageData"><code>putImageData()</code></a> to push it onto the canvas, but it was prohibitively slow. I might have done something stupid along the way, and some optimization might have helped, but I figured that I should not myself calculate the colors of each pixel, but leave this to who is best at it: The browser and (ideally) the graphic card.</p>
<p>So I took this as an opportunity to learn about WebGL, in particular fragment shaders. The term shader is misleading, and should mentally be replaced with “program”, because it is no longer (just) about shading. WebGL is intended to do 3D graphics, and one sends a bunch of coordinates for triangles, a vertex shader and a fragment shader to the browser. The vertex shader can places the vertices, while the fragment shader colors each pixel on the visible triangles. This is a gross oversimplification, but that is fine: We only really care about the last step, and if our coordinates always just define a rectangle that fills the whole canvas, and the vertex shader does not do anything interesting, then what remains is a HTML canvas that takes a program (written in the GL shader language), which is run for each pixel and calculates the color to be shown at that pixel.</p>
<p>Perfect! Just what I need. Dynamically creating a program that renders the pattern I want to show is squarely within Haskell’s strengths.</p>
<h2 id="a-reflex-dom-widget">A <code>reflex-dom</code> widget</h2>
<p>As my game UI grows, I will at some point no longer want to deal with raw DOM access, events etc., and the abstraction that makes creating such user interfaces painless is Functional Reactive Programming (FRP). One of the main mature implementations is Ryan Trinkle's <a href="https://reflex-frp.org/"><code>reflex-dom</code></a>, and I want to use this project to get more hands-on experience with it.</p>
<p>Based on my description above, once I hide all the details of the WebGL canvas setup, what I really have is a widget that takes a text string (representing the fragment shader), and creates a DOM element for it. This would suggest a function with this type signature</p>
<pre><code>fragmentShaderCanvas ::
MonadWidget t m =>
Dynamic t Text ->
m ()</code></pre>
<p>where the input text is <em>dynamic</em>, meaning it can change over time (and the canvas will be updated) accordingly. In fact, I also want to specify attributes for the canvas (especially <code>width</code> and <code>height</code>), and if the supplied fragment shader source is invalid and does not compile, I want to get my hands on error messages, as provided by the browser. So I ended up with this:</p>
<pre><code>fragmentShaderCanvas ::
MonadWidget t m =>
Map Text Text ->
Dynamic t Text ->
m (Dynamic t (Maybe Text))</code></pre>
<p>which very pleasingly hides all the complexity of setting up the WebGL context from the user. This is abstraction at excellence!</p>
<p>I published this widget in the <a href="%60reflex-dom-fragment-shader-canvas%60">hackage.haskell.org/package/reflex-dom-fragment-shader-canvas</a> package on Hackage.</p>
<h2 id="a-demo">A Demo</h2>
<p>And because <code>reflex-dom</code> make it so nice, I created a little demo program; it is essentially a fragment shader playground!</p>
<p>On <a href="https://nomeata.github.io/reflex-dom-fragment-shader-canvas/" class="uri">https://nomeata.github.io/reflex-dom-fragment-shader-canvas/</a> you will find a text area where you can edit the fragment shader code. All your changes are immediately reflected in the canvas on the right, and in the list of warnings and errors below the text area. The <a href="https://github.com/nomeata/reflex-dom-fragment-shader-canvas/blob/6d64129c9bfb3b1171a86b9f7007467733e8009b/demo/Main.hs#L8">code for this demo</a> is pretty short.</p>
<p>A few things could be improved, of course: For example, the <code>canvas</code> element should have its resolution automatically adjusted to the actual size on screen, but it is somewhat tricky to find out when and if a DOM element has changed size. Also, the WebGL setup should be rewritten to be more defensively, and fail more gracefully if things go wrong.</p>
<p>BTW, if you need a proper shader playground, check out <a href="https://www.shadertoy.com/">Shadertoy</a>.</p>
<h2 id="development-and-automatic-deployment">Development and automatic deployment</h2>
<p>The <code>reflex</code> authors all use Nix as their development environment, and if you want to use <code>reflex-dom</code>, then using Nix is certainly the path of least resistance. But I would like to point out that it is not a necessity, and you can stay squarely in <code>cabal</code> land if you want:</p>
<ul>
<li><p>You don’t actually need <code>ghcjs</code> to <em>develop</em> your web application: <code>reflex-dom</code> builds on <code>jsaddle</code> which has a mode where you build your program using normal GHC, and it runs a web server that your browser connects to. It works better with Chrome <a href="https://github.com/ghcjs/jsaddle/issues/64">than with Firefox</a> at the moment, but is totally adequate to develop a program.</p></li>
<li><p>If you do want to install <code>ghcjs</code>, then it is actually relatively easily: The <a href="https://github.com/ghcjs/ghcjs/tree/ghc-8.2">README on the <code>ghc-8.2</code> branch of GHCJS</a> tells you how to build and install <code>GHCJS</code> with <code>cabal new-build</code>.</p></li>
<li><p><code>cabal</code> itself supports <code>ghcjs</code> just like <code>ghc</code>! Just pass <code>--ghcjs -w ghcjs</code> to it.</p></li>
<li><p>Because few people use <code>ghcjs</code> and <code>reflex</code> with <code>cabal</code> some important packages (<code>ghcjs-base</code>, <code>reflex</code>, <code>reflex-dom</code>) are not on Hackage, or only with old versions. You can point <code>cabal</code> to local checkouts using a <code>cabal.project</code> file or even directly to the git repositories. But it is simpler to just use <a href="https://hackage-ghcjs-overlay.nomeata.de/">a Hackage overlay</a> that I created with these three packages, until they are uploaded to Hackage.</p></li>
<li><p>If the application you create is a pure client-based program and could therefore be hosted on any static web host, wouldn’t it be nice if you could just have it appear somewhere in the internet whenever you push to your project? Even that is possible, as I describe in an <a href="https://github.com/nomeata/ghcjs2gh-pages/">example repository</a>!</p></li>
</ul>
<p>It uses Travis CI to build GHCJS and the dependencies, caches them, builds your program and – if successful – uploads the result to GitHub Pages. In fact, the demo linked above is produced using that. Just push, and 5 minutes later the changes available online!</p>
<p>I know about rumors that Herbert’s excellent <a href="https://github.com/haskell-CI/haskell-ci">multi-GHC PPA repository</a> might provide <code>.deb</code> packages with GHCJS prebuilt soon. Once that happens, and maybe <code>ghcjs-base</code> and <code>reflex</code> get uploaded to Hackage, then the power of reflex-based web development will be conveniently available to all Haskell developers (even those who shunned Nix so far), and I am looking forward to many cool projects coming out of that.</p>Sun, 22 Jul 2018 10:41:27 -0400The diameter of German+English
http://www.joachim-breitner.de/blog/741-The_diameter_of_German%2BEnglish
http://www.joachim-breitner.de/blog/741-The_diameter_of_German%2BEnglishhttp://www.joachim-breitner.de/blog/741-The_diameter_of_German%2BEnglish#commentsmail@joachim-breitner.de (Joachim Breitner)<p>Languages never map directly onto each other. The English word <strong>fresh</strong> can mean <strong>frisch</strong> or <strong>frech</strong>, but <strong>frish</strong> can also be <strong>cool</strong>. Jumping from one words to another like this yields entertaining sequences that take you to completely different things. Here is one I came up with:</p>
<blockquote>
<p><strong>frech</strong> – <strong>fresh</strong> – <strong>frish</strong> – <strong>cool</strong> – <strong>abweisend</strong> – <strong>dismissive</strong> – <strong>wegwerfend</strong> – <strong>trashing</strong> – <strong>verhauend</strong> – <strong>banging</strong> – <strong>Geklopfe</strong> – <strong>knocking</strong> – …</p>
</blockquote>
<p>And I could go on … but how far? So here is a little experiment I ran:</p>
<ol style="list-style-type: decimal">
<li><p>I obtained a German-English dictionary. Conveniently, after registration, you can get <a href="https://www1.dict.cc/translation_file_request.php">dict.cc’s translation file</a>, which is simply a text file with three columns: German, English, Word form.</p></li>
<li><p>I wrote a program that takes these words and first canonicalizes them a bit: Removing attributes like <code>[ugs.]</code> <code>[regional]</code>, <code>{f}</code>, the <code>to</code> in front of verbs and other embellishment.</p></li>
<li><p>I created the undirected, bipartite graph of all these words. This is a pretty big graph – ~750k words in each language, a million edges. A path in this graph is precisely a sequence like the one above.</p></li>
<li><p>In this graph, I tried to find a <em>diameter</em>. The diameter of a graph is the longest path between two nodes that you cannot connect with a shorter path.</p></li>
</ol>
<p>Because the graph is big (and my code maybe not fully optimized), it ran a few hours, but here it is: The English expression <strong>be annoyed by sb.</strong> and the German noun <strong>Icterus</strong> are related by 55 translations. Here is the full list:</p>
<ul>
<li>be annoyed by sb.</li>
<li>durch jdn. verärgert sein</li>
<li>be vexed with sb.</li>
<li>auf jdn. böse sein</li>
<li>be angry with sb.</li>
<li>jdm. böse sein</li>
<li>have a grudge against sb.</li>
<li>jdm. grollen</li>
<li>bear sb. a grudge</li>
<li>jdm. etw. nachtragen</li>
<li>hold sth. against sb.</li>
<li>jdm. etw. anlasten</li>
<li>charge sb. with sth.</li>
<li>jdn. mit etw. [Dat.] betrauen</li>
<li>entrust sb. with sth.</li>
<li>jdm. etw. anvertrauen</li>
<li>entrust sth. to sb.</li>
<li>jdm. etw. befehlen</li>
<li>tell sb. to do sth.</li>
<li>jdn. etw. heißen</li>
<li>call sb. names</li>
<li>jdn. beschimpfen</li>
<li>abuse sb.</li>
<li>jdn. traktieren</li>
<li>pester sb.</li>
<li>jdn. belästigen</li>
<li>accost sb.</li>
<li>jdn. ansprechen</li>
<li>address oneself to sb.</li>
<li>sich an jdn. wenden</li>
<li>approach</li>
<li>erreichen</li>
<li>hit</li>
<li>Treffer</li>
<li>direct hit</li>
<li>Volltreffer</li>
<li>bullseye</li>
<li>Hahnenfuß-ähnlicher Wassernabel</li>
<li>pennywort</li>
<li>Mauer-Zimbelkraut</li>
<li>Aaron's beard</li>
<li>Großkelchiges Johanniskraut</li>
<li>Jerusalem star</li>
<li>Austernpflanze</li>
<li>goatsbeard</li>
<li>Geißbart</li>
<li>goatee</li>
<li>Ziegenbart</li>
<li>buckhorn plantain</li>
<li>Breitwegerich / Breit-Wegerich</li>
<li>birdseed</li>
<li>Acker-Senf / Ackersenf</li>
<li>yellows</li>
<li>Gelbsucht</li>
<li>icterus</li>
<li>Icterus</li>
</ul>
<p>Pretty neat!</p>
<p>So what next?</p>
<p>I could try to obtain an even longer chain by forgetting whether a word is English or German (and lower-casing everything), thus allowing wild jumps like <strong>hat</strong> – <strong>hut</strong> – <strong>hütte</strong> – <strong>lodge</strong>.</p>
<p>Or write a tool where you can enter two arbitrary words and it finds such a path between them, if there exists one. Unfortunately, it seems that the terms of the dict.cc data dump would not allow me to create such a tool as a web site (but maybe I can ask).</p>
<p>Or I could throw in additional languages!</p>
<p>What would you do?</p>
<p><strong>Update (2018-06-17):</strong></p>
<p>I ran the code again, this time lower-casing all words, and allowing false-friends translations, as suggested above. The resulting graph has – surprisingly – precisely the same diamater (55), but with a partly different list:</p>
<ul>
<li>peyote</li>
<li>peyote</li>
<li>mescal</li>
<li>meskal</li>
<li>mezcal</li>
<li>blaue agave</li>
<li>maguey</li>
<li>amerikanische agave</li>
<li>american agave</li>
<li>jahrhundertpflanze</li>
<li>century plant</li>
<li>fächerlilie</li>
<li>tumbleweed</li>
<li>weißer fuchsschwanz</li>
<li>common tumbleweed</li>
<li>acker-fuchsschwanz / ackerfuchsschwanz</li>
<li>rough pigweed</li>
<li>grünähriger fuchsschwanz</li>
<li>love-lies-bleeding</li>
<li>stiefmütterchen</li>
<li>pansy</li>
<li>schwuchtel</li>
<li>fruit</li>
<li>ertrag</li>
<li>gain</li>
<li>vorgehen</li>
<li>approach</li>
<li>sich an jdn. wenden</li>
<li>address oneself to sb.</li>
<li>jdn. ansprechen</li>
<li>accost sb.</li>
<li>jdn. belästigen</li>
<li>pester sb.</li>
<li>jdn. traktieren</li>
<li>abuse sb.</li>
<li>jdn. beschimpfen</li>
<li>call sb. names</li>
<li>jdn. etw. heißen</li>
<li>tell sb. to do sth.</li>
<li>jdm. etw. befehlen</li>
<li>entrust sth. to sb.</li>
<li>jdm. etw. anvertrauen</li>
<li>entrust sb. with sth.</li>
<li>jdn. mit etw. [dat.] betrauen</li>
<li>charge sb. with sth.</li>
<li>jdm. etw. zur last legen</li>
<li>hold sth. against sb.</li>
<li>jdm. etw. nachtragen</li>
<li>bear sb. a grudge</li>
<li>jdm. grollen</li>
<li>have a grudge against sb.</li>
<li>jdm. böse sein</li>
<li>be angry with sb.</li>
<li>auf jdn. böse sein</li>
<li>be mad at sb.</li>
<li>auf jdn. einen (dicken) hals haben</li>
</ul>
<p>Note that there is not actually a false-friend in this list – it seems that adding the edges just changed the order of edges in the graph representation and my code just happened to find a different diamer.</p>Wed, 23 May 2018 08:35:24 +0200Proof reuse in Coq using existential variables
http://www.joachim-breitner.de/blog/740-Proof_reuse_in_Coq_using_existential_variables
http://www.joachim-breitner.de/blog/740-Proof_reuse_in_Coq_using_existential_variableshttp://www.joachim-breitner.de/blog/740-Proof_reuse_in_Coq_using_existential_variables#commentsmail@joachim-breitner.de (Joachim Breitner)<p>This is another technical post that is only of interest only to Coq users.</p>
<p>TL;DR: Using existential variable for hypotheses allows you to easily refactor a complicated proof into an induction schema and the actual proofs.</p>
<h3 id="setup">Setup</h3>
<p>As a running example, I will use a small theory of “bags”, which you can think of as lists represented as trees, to allow an <span class="math inline"><em>O</em>(1)</span> append operation:</p>
<pre><code>Require Import Coq.Arith.Arith.
Require Import Psatz.
Require FunInd.
(* The data type *)
Inductive Bag a : Type :=
| Empty : Bag a
| Unit : a -> Bag a
| Two : Bag a -> Bag a -> Bag a.
Arguments Empty {_}.
Arguments Unit {_}.
Arguments Two {_}.
Fixpoint length {a} (b : Bag a) : nat :=
match b with
| Empty => 0
| Unit _ => 1
| Two b1 b2 => length b1 + length b2
end.
(* A smart constructor that ensures that a [Two] never
has [Empty] as subtrees. *)
Definition two {a} (b1 b2 : Bag a) : Bag a := match b1 with
| Empty => b2
| _ => match b2 with | Empty => b1
| _ => Two b1 b2 end end.
Lemma length_two {a} (b1 b2 : Bag a) :
length (two b1 b2) = length b1 + length b2.
Proof. destruct b1, b2; simpl; lia. Qed.
(* A first non-trivial function *)
Function take {a : Type} (n : nat) (b : Bag a) : Bag a :=
if n =? 0
then Empty
else match b with
| Empty => b
| Unit x => b
| Two b1 b2 => two (take n b1) (take (n - length b1) b2)
end.</code></pre>
<h3 id="the-theorem">The theorem</h3>
<p>The theorem that I will be looking at in this proof describes how <code>length</code> and <code>take</code> interact:</p>
<pre><code>Theorem length_take''':
forall {a} n (b : Bag a),
length (take n b) = min n (length b).</code></pre>
<p>Before I dive into it, let me point out that this example itself is too simple to warrant the techniques that I will present in this post. I have to rely on your imagination to scale this up to appreciate the effect on significantly bigger proofs.</p>
<h3 id="naive-induction">Naive induction</h3>
<p>How would we go about proving this lemma? Surely, <a href="https://coq.inria.fr/refman/proof-engine/tactics.html#coq:tacn.induction"><code>induction</code></a> is the way to go! And indeed, this is provable using induction (on the <code>Bag</code>) just fine:</p>
<pre><code>Proof.
intros.
revert n.
induction b; intros n.
* simpl.
destruct (Nat.eqb_spec n 0).
+ subst. rewrite Nat.min_0_l. reflexivity.
+ rewrite Nat.min_0_r. reflexivity.
* simpl.
destruct (Nat.eqb_spec n 0).
+ subst. rewrite Nat.min_0_l. reflexivity.
+ simpl. lia.
* simpl.
destruct (Nat.eqb_spec n 0).
+ subst. rewrite Nat.min_0_l. reflexivity.
+ simpl. rewrite length_two, IHb1, IHb2. lia.
Qed.</code></pre>
<p>But there is a problem: A proof by induction on the <code>Bag</code> argument immediately creates three subgoals, one for each constructor. But that is not how <code>take</code> is defined, which <em>first</em> checks the value of <code>n</code>, independent of the constructor. This means that we have to do the case-split and the proof for the case <code>n = 0</code> three times, although they are identical. It’s a one-line proof here, but imagine something bigger...</p>
<h3 id="proof-by-fixpoint">Proof by fixpoint</h3>
<p>Can we refactor the proof to handle the case <code>n = 0</code> first? Yes, but not with a simple invocation of the <code>induction</code> tactic. We could do well-founded induction on the <code>length</code> of the argument, or we can do the proof using the more primitive <a href="https://coq.inria.fr/refman/proof-engine/tactics.html#coq:tacn.fix"><code>fix</code> tactic</a>. The latter is a bit hairy, you won’t know if your proof is accepted until you do <code>Qed</code> (or check with <a href="https://coq.inria.fr/refman/proof-engine/proof-handling.html#coq:cmd.guarded"><code>Guarded</code></a>), but when it works it can yield some nice proofs.</p>
<pre><code>Proof.
intros a.
fix IH 2.
intros.
rewrite take_equation.
destruct (Nat.eqb_spec n 0).
+ subst n. rewrite Nat.min_0_l. reflexivity.
+ destruct b.
* rewrite Nat.min_0_r. reflexivity.
* simpl. lia.
* simpl. rewrite length_two, !IH. lia.
Qed.</code></pre>
<p>Nice: we eliminated the duplication of proofs!</p>
<h3 id="a-functional-induction-lemma">A functional induction lemma</h3>
<p>Again, imagine that we jumped through more hoops here ... maybe some well-founded recursion with a tricky size measure and complex proofs that the measure decreases ... or maybe you need to carry around an invariant about your arguments and you have to work hard to satisfy the assumption of the induction hypothesis.</p>
<p>As long as you do only one proof about <code>take</code>, that is fine. As soon as you do a second proof, you will notice that you have to repeat all of that, and it can easily make up most of your proof...</p>
<p>Wouldn’t it be nice if you can do the common parts of the proofs only once, obtain a generic proof scheme that you can use for (most) proofs about <code>take</code>, and then just fill in the blanks?</p>
<p>Incidentally, the <a href="https://coq.inria.fr/refman/language/gallina-extensions.html#coq:cmd.function"><code>Function</code> command</a> provides precisely that:</p>
<pre><code>take_ind
: forall (a : Type) (P : nat -> Bag a -> Bag a -> Prop),
(forall (n : nat) (b : Bag a), (n =? 0) = true -> P n b Empty) ->
(forall (n : nat) (b : Bag a), (n =? 0) = false -> b = Empty -> P n Empty b) ->
(forall (n : nat) (b : Bag a), (n =? 0) = false -> forall x : a, b = Unit x -> P n (Unit x) b) ->
(forall (n : nat) (b : Bag a),
(n =? 0) = false ->
forall b1 b2 : Bag a,
b = Two b1 b2 ->
P n b1 (take n b1) ->
P (n - length b1) b2 (take (n - length b1) b2) ->
P n (Two b1 b2) (two (take n b1) (take (n - length b1) b2))) ->
forall (n : nat) (b : Bag a), P n b (take n b)</code></pre>
<p>which is great if you can use <code>Function</code> (although not perfect – we’d rather see <code>n = 0</code> instead of <code>(n =? 0) = true</code>), but often <code>Function</code> is not powerful enough to define the function you care about.</p>
<h3 id="extracting-the-scheme-from-a-proof">Extracting the scheme from a proof</h3>
<p>We could define our own <code>take_ind'</code> by hand, but that is a lot of work, and we may not get it right easily, and when we change out functions, there is now this big proof statement to update.</p>
<p>Instead, let us use existentials, which are variables where Coq infers their type from how we use them, so we don’t have to declare them. Unfortunately, Coq does not support writing just</p>
<pre><code>Lemma take_ind':
forall (a : Type) (P : nat -> Bag a -> Bag a -> Prop),
forall (IH1 : ?) (IH2 : ?) (IH3 : ?) (IH4 : ?),
forall n b, P n b (take n b).</code></pre>
<p>where we just leave out the type of the assumptions (Isabelle does...), but we can fake it using some generic technique.</p>
<p>We begin with stating an auxiliary lemma using a sigma type to say “there exist some assumption that are sufficient to show the conclusion”:</p>
<pre><code>Lemma take_ind_aux:
forall a (P : _ -> _ -> _ -> Prop),
{ Hs : Prop |
Hs -> forall n (b : Bag a), P n b (take n b)
}.</code></pre>
<p>We use the [<code>eexist</code> tactic])(https://coq.inria.fr/refman/proof-engine/tactics.html#coq:tacv.eexists) (existential <code>exists</code>) to construct the sigma type without committing to the type of <code>Hs</code> yet.</p>
<pre><code>Proof.
intros a P.
eexists.
intros Hs.</code></pre>
<p>This gives us an assumption <code>Hs : ?Hs</code> – note the existential type. We need four of those, which we can achieve by writing</p>
<pre><code> pose proof Hs as H1. eapply proj1 in H1. eapply proj2 in Hs.
pose proof Hs as H2. eapply proj1 in H2. eapply proj2 in Hs.
pose proof Hs as H3. eapply proj1 in H3. eapply proj2 in Hs.
rename Hs into H4.</code></pre>
<p>we now have this goal state:</p>
<pre><code>1 subgoal
a : Type
P : nat -> Bag a -> Bag a -> Prop
H4 : ?Goal2
H1 : ?Goal
H2 : ?Goal0
H3 : ?Goal1
______________________________________(1/1)
forall (n : nat) (b : Bag a), P n b (take n b)</code></pre>
<p>At this point, we start reproducing the proof of <code>length_take</code>: The same approach to induction, the same case splits:</p>
<pre><code> fix IH 2.
intros.
rewrite take_equation.
destruct (Nat.eqb_spec n 0).
+ subst n.
revert b.
refine H1.
+ rename n0 into Hnot_null.
destruct b.
* revert n Hnot_null.
refine H2.
* rename a0 into x.
revert x n Hnot_null.
refine H3.
* assert (IHb1 : P n b1 (take n b1)) by apply IH.
assert (IHb2 : P (n - length b1) b2 (take (n - length b1) b2)) by apply IH.
revert n b1 b2 Hnot_null IHb1 IHb2.
refine H4.
Defined. (* Important *)</code></pre>
<p>Inside each case, we move all relevant hypotheses into the goal using <a href="https://coq.inria.fr/refman/proof-engine/tactics.html#coq:tacn.revert"><code>revert</code></a> and <a href="https://coq.inria.fr/refman/proof-engine/tactics.html#coq:tacn.refine"><code>refine</code></a> with the corresponding assumption, thus instantiating it. In the recursive case (<code>Two</code>), we assert that <code>P</code> holds for the subterms, by induction.</p>
<p>It is important to end this proofs with <a href="https://coq.inria.fr/refman/proof-engine/vernacular-commands.html#vernac-controlling-the-reduction-strategies"><code>Defined</code>, and not <code>Qed</code>,</a> as we will see later.</p>
<p>In a next step, we can remove the sigma type:</p>
<pre><code>Definition take_ind' a P := proj2_sig (take_ind_aux a P).</code></pre>
<p>The type of <code>take_ind'</code> is as follows:</p>
<pre><code>take_ind'
: forall (a : Type) (P : nat -> Bag a -> Bag a -> Prop),
proj1_sig (take_ind_aux a P) ->
forall n b, P n b (take n b)</code></pre>
<p>This looks almost like an induction lemma. The assumptions of this lemma have the not very helpful type <code>proj1_sig (take_ind_aux a P)</code>, but we can already use this to prove <code>length_take</code>:</p>
<pre><code>Theorem length_take:
forall {a} n (b : Bag a),
length (take n b) = min n (length b).
Proof.
intros a.
intros.
apply take_ind' with (P := fun n b r => length r = min n (length b)).
repeat apply conj; intros.
* rewrite Nat.min_0_l. reflexivity.
* rewrite Nat.min_0_r. reflexivity.
* simpl. lia.
* simpl. rewrite length_two, IHb1, IHb2. lia.
Qed.</code></pre>
<p>In this case I have to explicitly state <code>P</code> where I invoke <code>take_ind'</code>, because Coq cannot figure out this instantiation on its own (it requires higher-order unification, which is undecidable and unpredictable). In other cases I had more luck.</p>
<p>After I <code>apply take_ind'</code>, I have this proof goal:</p>
<pre><code>______________________________________(1/1)
proj1_sig (take_ind_aux a (fun n b r => length r = min n (length b)))</code></pre>
<p>which is the type that Coq inferred for <code>Hs</code> above. We know that this is a conjunction of a bunch of assumptions, and we can split it as such, using <code>repeat apply conj</code>. At this point, Coq needs to look inside <code>take_ind_aux</code>; this would fail if we used <code>Qed</code> to conclude the proof of <code>take_ind_aux</code>.</p>
<p>This gives me four goals, one for each case of <code>take</code>, and the remaining proofs really only deals with the specifics of <code>length_take</code> – no more general dealing with worrying about getting the induction right and doing the case-splitting the right way.</p>
<p>Also note that, very conveniently, Coq uses the same name for the induction hypotheses <code>IHb1</code> and <code>IHb2</code> that we used in <code>take_ind_aux</code>!</p>
<h3 id="making-it-prettier">Making it prettier</h3>
<p>It may be a bit confusing to have this <code>proj1_sig</code> in the type, especially when working in a team where others will use your induction lemma without knowing its internals. But we can resolve that, and also turn the conjunctions into normal arrows, using a bit of tactic support. This is completely generic, so if you follow this procedure, you can just copy most of that:</p>
<pre><code>Lemma uncurry_and: forall {A B C}, (A /\ B -> C) -> (A -> B -> C).
Proof. intros. intuition. Qed.
Lemma under_imp: forall {A B C}, (B -> C) -> (A -> B) -> (A -> C).
Proof. intros. intuition. Qed.
Ltac iterate n f x := lazymatch n with
| 0 => x
| S ?n => iterate n f uconstr:(f x)
end.
Ltac uncurryN n x :=
let n' := eval compute in n in
lazymatch n' with
| 0 => x
| S ?n => let uc := iterate n uconstr:(under_imp) uconstr:(uncurry_and) in
let x' := uncurryN n x in
uconstr:(uc x')
end.</code></pre>
<p>With this in place, we can define our final proof scheme lemma:</p>
<pre><code>Definition take_ind'' a P
:= ltac:(let x := uncurryN 3 (proj2_sig (take_ind_aux a P)) in exact x).
Opaque take_ind''.</code></pre>
<p>The type of <code>take_ind''</code> is now exactly what we’d wish for: All assumptions spelled out, and the <code>n =? 0</code> already taken of (compare this to the <code>take_ind</code> provided by the <code>Function</code> command above):</p>
<pre><code>take_ind''
: forall (a : Type) (P : nat -> Bag a -> Bag a -> Prop),
(forall b : Bag a, P 0 b Empty) ->
(forall n : nat, n <> 0 -> P n Empty Empty) ->
(forall (x : a) (n : nat), n <> 0 -> P n (Unit x) (Unit x)) ->
(forall (n : nat) (b1 b2 : Bag a),
n <> 0 ->
P n b1 (take n b1) ->
P (n - length b1) b2 (take (n - length b1) b2) ->
P n (Two b1 b2) (two (take n b1) (take (n - length b1) b2))) ->
forall (n : nat) (b : Bag a), P n b (take n b)</code></pre>
<p>At this point we can mark <code>take_ind''</code> as <code>Opaque</code>, to hide how we obtained this lemma.</p>
<p>Our proof does not change a lot; we merely no longer have to use <code>repeat apply conj</code>:</p>
<pre><code>Theorem length_take''':
forall {a} n (b : Bag a),
length (take n b) = min n (length b).
Proof.
intros a.
intros.
apply take_ind'' with (P := fun n b r => length r = min n (length b)); intros.
* rewrite Nat.min_0_l. reflexivity.
* rewrite Nat.min_0_r. reflexivity.
* simpl. lia.
* simpl. rewrite length_two, IHb1, IHb2. lia.
Qed.</code></pre>
<h3 id="is-it-worth-it">Is it worth it?</h3>
<p>It was in my case: <a href="https://github.com/antalsz/hs-to-coq/compare/de89fd0...b5b8ff7">Applying this trick</a> in our ongoing work of verifying parts of the Haskell compiler GHC separated a somewhat proof into a re-usable proof scheme (<code>go_ind</code>), making the actual proofs (<code>go_all_WellScopedFloats</code>, <code>go_res_WellScoped</code>) much neater and to the point. It saved “only” 60 lines (if I don’t count the 20 “generic” lines above), but the pay-off will increase as I do even more proofs about this function.</p>Fri, 18 May 2018 08:51:19 -0400Avoid the dilemma of the trailing comma
http://www.joachim-breitner.de/blog/739-Avoid_the_dilemma_of_the_trailing_comma
http://www.joachim-breitner.de/blog/739-Avoid_the_dilemma_of_the_trailing_commahttp://www.joachim-breitner.de/blog/739-Avoid_the_dilemma_of_the_trailing_comma#commentsmail@joachim-breitner.de (Joachim Breitner)<p>The Haskell syntax uses comma-separated lists in various places and does, in contrast to other programming language, not allow a trailing comma. If everything goes on one line you write</p>
<pre><code> (foo, bar, baz)</code></pre>
<p>and everything is nice.</p>
<h3 id="lining-up">Lining up</h3>
<p>But if you want to have one entry on each line, then the obvious plan</p>
<pre><code> (foo,
bar,
baz
)</code></pre>
<p>is aesthetically unpleasing and moreover, extending the list by <em>one</em> to</p>
<pre><code> (foo,
bar,
baz,
quux
)</code></pre>
<p>modifies <em>two</em> lines, which produces less pretty diffs.</p>
<p>Because it is much more common to append to lists rather than to prepend, Haskellers have developed the idiom of leading comma:</p>
<pre><code> ( foo
, bar
, baz
, quux
)</code></pre>
<p>which looks strange until you are used to it, but solves the problem of appending to a list. And we see this idiom in many places:</p>
<ul>
<li><p>In Cabal files:</p>
<pre><code> build-depends: base >= 4.3 && < 5
, array
, deepseq >= 1.2 && < 1.5</code></pre></li>
<li><p>In module headers:</p>
<pre><code>{-# LANGUAGE DefaultSignatures
, EmptyCase
, ExistentialQuantification
, FlexibleContexts
, FlexibleInstances
, GADTs
, InstanceSigs
, KindSignatures
, RankNTypes
, ScopedTypeVariables
, TemplateHaskell
, TypeFamilies
, TypeInType
, TypeOperators
, UndecidableInstances #-}</code></pre></li>
</ul>
<h3 id="think-outside-the-list">Think outside the list!</h3>
<p>I started to avoid this pattern where possible. And it is possible everywhere instead of having a declaration with a list, you can just have multiple declarations. I.e.:</p>
<ul>
<li><p>In Cabal files:</p>
<pre><code> build-depends: base >= 4.3 && < 5
build-depends: array
build-depends: deepseq >= 1.2 && < 1.5</code></pre></li>
<li><p>In module headers:</p>
<pre><code>{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}</code></pre></li>
</ul>
<p>It is a bit heavier, but it has a number of advantages:</p>
<ol style="list-style-type: decimal">
<li>Both appending and prepending works without touching other lines.</li>
<li>It is visually more homogeneous, making it – despite the extra words – easier to spot mistakes visually.</li>
<li>You can easily sort the declarations alphabetically with your editor.</li>
<li>Especially in <code>Cabal</code> files: If you have syntax error in your dependency specification (which I always have, writing <code><<</code> instead of <code><</code> due to my Debian background), <code>cabal</code> will actually give you a helpful error location – it always only tells you which <code>build-depends</code> stanza was wrong, so if you have only one, then <a href="https://stackoverflow.com/q/32751149/946226">that’s not helpful</a>.</li>
</ol>
<h3 id="what-when-it-does-not-work">What when it does not work?</h3>
<p>Unfortunately, not every list in Haskell can have that treatment, and that’s why <a href="https://github.com/ghc-proposals/ghc-proposals/pull/87">the recent GHC proposal on <code>ExtraCommas</code></a> wants to lift the restriction. In particular, it wants to allow trailing commas in subexport lists:</p>
<pre><code>module Foo
( Foo(
A,
B,
),
fromFoo,
)</code></pre>
<p>(Weirdly, export lists already allow trailing commas). An alternative here might be to write</p>
<pre><code>module Foo
( Foo(A),
Foo(B),
fromFoo,
)</code></pre>
<p>and teach the compiler to not warn about the duplicate export of the <code>Foo</code> type.</p>
<p>For plain lists, this idiom can be useful:</p>
<pre><code>list :: [Int]
list = let (>>) = (++) in do
[ 1 ]
[ 2 ]
[ 3 ]
[ 4 ]</code></pre>
<p>It requires <code>RebindableSyntax</code>, so I do not recommend it for regular code, but it can be useful in a module that is dedicated to hold some generated data or configuration. And of course it works with any binary operator, not just <code>(++)</code></p>Mon, 30 Apr 2018 22:19:47 -0400Verifying local definitions in Coq
http://www.joachim-breitner.de/blog/738-Verifying_local_definitions_in_Coq
http://www.joachim-breitner.de/blog/738-Verifying_local_definitions_in_Coqhttp://www.joachim-breitner.de/blog/738-Verifying_local_definitions_in_Coq#commentsmail@joachim-breitner.de (Joachim Breitner)<p>TL;DR: We can give top-level names to local definitions, so that we can state and prove stuff about them without having to rewrite the programs.</p>
<h3 id="when-a-haskeller-writes-coq">When a Haskeller writes Coq</h3>
<p>Imagine you teach Coq to a Haskell programmer, and give them the task of pairing each element in a list with its index. The Haskell programmer might have</p>
<pre><code>addIndex :: [a] -> [(Integer, a)]
addIndex xs = go 0 xs
where go n [] = []
go n (x:xs) = (n,x) : go (n+1) xs</code></pre>
<p>in mind and write this Gallina function (Gallina is the programming language of Coq):</p>
<pre><code>Require Import Coq.Lists.List.
Import ListNotations.
Definition addIndex {a} (xs : list a) : list (nat * a) :=
let fix go n xs := match xs with
| [] => []
| x::xs => (n, x) :: go (S n) xs
end
in go 0 xs.</code></pre>
<p>Alternatively, imagine you are using <a href="https://github.com/antalsz/hs-to-coq"><code>hs-to-coq</code></a> to mechanically convert the Haskell definition into Coq.</p>
<h3 id="when-a-coq-user-tries-to-verify-that">When a Coq user tries to verify that</h3>
<p>Now your task is to prove something about this function, for example</p>
<pre><code>Theorem addIndex_spec:
forall {a} n (xs : list a),
nth n (map fst (addIndex xs)) n = n.</code></pre>
<p>If you just have learned Coq, you will think “I can do this, this surely holds by induction on <code>xs</code>.” But if you have a bit more experience, you will already see a problem with this (if you do not see the problem yet, I encourage you to stop reading, copy the few lines above, and try to prove it).</p>
<p>The problem is that – as so often – you have to generalize the statement for the induction to go through. The theorem as stated says something about <code>addIndex</code> or, in other words, about <code>go 0</code>. But in the inductive case, you will need some information about <code>go 1</code>. In fact, you need a lemma like this:</p>
<pre><code>Lemma go_spec:
forall {a} n m k (xs : list a), k = n + m ->
nth n (map fst (go m xs)) k = k.</code></pre>
<p>But <code>go</code> is not a (top-level) function! How can we fix that?</p>
<ul>
<li>We can try to awkwardly work-around not having a name for <code>go</code> in our proofs, and essentially prove <code>go_spec</code> inside the proof of <code>addIndex_spec</code>. Might work in this small case, but does not scale up to larger proofs.</li>
<li>We can ask the programmer to avoid using local functions, and first define <code>go</code> as a top-level fixed point. But maybe we don’t want to bother them because of that. (Or, more likely, we are using <code>hs-to-coq</code> and that tool stubbornly tries to make the output as similar to the given Haskell code as possible.)</li>
<li>We can copy’n’paste the definition of <code>go</code> and make a separate, after-the-fact top-level definition. But this is not nice from a maintenance point of view: If the code changes, we have to update this copy.</li>
<li>Or we apply this one weird trick...</li>
</ul>
<h3 id="the-weird-trick">The weird trick</h3>
<p>We can define <code>go</code> after-the-fact, but instead of copy’n’pasting the definition, we can use Coq’s tactics to define it. Here it goes:</p>
<pre><code>Definition go {a} := ltac:(
let e := eval cbv beta delta [addIndex] in (@addIndex a []) in
(* idtac e; *)
lazymatch e with | let x := ?def in _ =>
exact def
end).</code></pre>
<p>Let us take it apart:</p>
<ol style="list-style-type: decimal">
<li>We define <code>go</code>, and give the parameters that <code>go</code> depends upon. Note that of the two parameters of <code>addIndex</code>, the definition of <code>go</code> only depends on (“captures”) <code>a</code>, but not <code>xs</code>.</li>
<li>We do <em>not</em> give a type to <code>go</code>. We could, but that would again just be copying information that is already there.</li>
<li>We define go via an <code>ltac</code> expression: Instead of a term we give a tactic that calculates the term.</li>
<li>This tactic first binds <code>e</code> to the body of <code>addIndex</code>. To do so, it needs to pass enough arguments to <code>addIndex</code>. The concrete value of the list argument does not matter, so we pass <code>[]</code>. The term <code>@addIndex a []</code> is now evaluated with the evaluation flags <code>eval cbv beta delta [addIndex]</code>, which says “unfold <code>addIndex</code> and do beta reduction, but nothing else”. In particularly, we do not do <code>zeta</code> reduction, which would reduce the <code>let go := …</code> definition. (The <a href="https://coq.inria.fr/refman/proof-engine/tactics.html#performing-computations">user manual</a> very briefly describes these flags.)</li>
<li>The <code>idtac e</code> line can be used to peek at <code>e</code>, for example when the next tactic fails. We can use this to check that <code>e</code> really is of the form <code>let fix go := … in …</code>.</li>
<li>The <code>lazymatch</code> line matches <code>e</code> against the pattern <code>let x := ?def in _</code>, and binds the definition of <code>go</code> to the name <code>def</code>.</li>
<li>And the <code>exact def</code> tactic tells Coq to use <code>def</code> as the definition of <code>go</code>.</li>
</ol>
<p>We now have defined <code>go</code>, of type <code>go : forall {a}, nat -> list a -> list (nat * a)</code>, and can state and prove the auxiliary lemma:</p>
<pre><code>Lemma go_spec:
forall {a} n m k (xs : list a), k = n + m ->
nth n (map fst (go m xs)) k = k.
Proof.
intros ?????.
revert n m k.
induction xs; intros; destruct n; subst; simpl.
1-3:reflexivity.
apply IHxs; lia.
Qed.</code></pre>
<p>When we come to the theorem about <code>addIndex</code>, we can play a little trick with <code>fold</code> to make the proof goal pretty:</p>
<pre><code>Theorem addIndex_spec:
forall {a} n (xs : list a),
nth n (map fst (addIndex xs)) n = n.
Proof.
intros.
unfold addIndex.
fold (@go a).
(* goal here: nth n (map fst (go 0 xs)) n = n *)
apply go_spec; lia.
Qed.</code></pre>
<h3 id="multiple-local-definitions">Multiple local definitions</h3>
<p>The trick extends to multiple local definitions, but needs some extra considerations to ensure that terms are closed. A bit contrived, but let us assume that we have this function definition:</p>
<pre><code>Definition addIndex' {a} (xs : list a) : list (nat * a) :=
let inc := length xs in
let fix go n xs := match xs with
| [] => []
| x::xs => (n, x) :: go (inc + n) xs
end in
go 0 xs.</code></pre>
<p>We now want to give names to <code>inc</code> <em>and</em> to <code>go</code>. I like to use a section to collect the common parameters, but that is not essential here. The trick above works flawlessly for `inc':</p>
<pre><code>Section addIndex'.
Context {a} (xs : list a).
Definition inc := ltac:(
let e := eval cbv beta delta [addIndex'] in (@addIndex' a xs) in
lazymatch e with | let x := ?def in _ =>
exact def
end).</code></pre>
<p>But if we try it for <code>go'</code>, like such:</p>
<pre><code>Definition go' := ltac:(
let e := eval cbv beta delta [addIndex'] in (@addIndex' a xs) in
lazymatch e with | let x := _ in let y := ?def in _ =>
exact def
end).</code></pre>
<p>we get “Ltac variable def depends on pattern variable name x which is not bound in current context”. To fix this, we use higher-order pattern matchin (<code>@?def</code>) to substitute “our” <code>inc</code> for the local <code>inc</code>:</p>
<pre><code>Definition go' := ltac:(
let e := eval cbv beta delta [addIndex'] in (@addIndex' a xs) in
lazymatch e with | let x := _ in let y := @?def x in _ =>
let def' := eval cbv beta in (def inc) in
exact def'
end).</code></pre>
<p>instead. We have now defined both <code>inc</code> and <code>go'</code> and can use them in proofs about <code>addIndex'</code>:</p>
<pre><code>Theorem addIndex_spec':
forall n, nth n (map fst (addIndex' xs)) n = n * length xs.
Proof.
intros.
unfold addIndex'.
fold inc go'. (* order matters! *)
(* goal here: nth n (map fst (go' 0 xs)) n = n * inc *)</code></pre>
<h3 id="reaching-into-a-match">Reaching into a match</h3>
<p>This trick also works when the local definition we care about is inside a match statement. Consider:</p>
<pre><code>Definition addIndex_weird {a} (oxs : option (list a))
:= match oxs with
| None => []
| Some xs =>
let fix go n xs := match xs with
| [] => []
| x::xs => (n, x) :: go (S n) xs
end in
go 0 xs
end.
Definition go_weird {a} := ltac:(
let e := eval cbv beta match delta [addIndex_weird]
in (@addIndex_weird a (Some [])) in
idtac e;
lazymatch e with | let x := ?def in _ =>
exact def
end).</code></pre>
<p>Note the addition of <code>match</code> to the list of evaluation flags passed to <code>cbv</code>.</p>
<h3 id="conclusion">Conclusion</h3>
<p>While local definitions are idiomatic in Haskell (in particular thanks to the <code>where</code> syntax), they are usually avoided in Coq, because they get in the way of verification. If, for some reason, one is stuck with such definitions, then this trick presents a reasonable way out.</p>Sun, 22 Apr 2018 17:47:24 -0400Reservoir sampling with few random bits
http://www.joachim-breitner.de/blog/737-Reservoir_sampling_with_few_random_bits
http://www.joachim-breitner.de/blog/737-Reservoir_sampling_with_few_random_bitshttp://www.joachim-breitner.de/blog/737-Reservoir_sampling_with_few_random_bits#commentsmail@joachim-breitner.de (Joachim Breitner)<p>Assume you are Nisus, the <a href="https://www.youtube.com/watch?v=8lN4TSslz-0">“one cross each” guy</a> in Monty Python’s “Life of Brian” movie. Condemned prisoners file past you one by one, on their way to crucifixion. Now it happens that this particular day, feel both both benevolent <em>and</em> very indecisive. Because you feel benevolent, you want to liberate one of the condemned. But because you feel indecisive, you don’t want to pick the lucky one yourself, so you have to leave it to chance. And you don’t want anybody to have grounds to to complain, so you want to give each prisoner exactly the same chance.</p>
<p>This would be a relatively simple task if you knew the number of prisoners, <span class="math inline"><em>n</em></span>, ahead of time: Pick a random number <span class="math inline"><em>k</em> ∈ {1, …, <em>n</em>}</span>, count while you hand our the crosses, and tell the <span class="math inline"><em>k</em></span>th prisoner to get lost.</p>
<p>But alas, the Romans judiciary system is big and effective, and you have no idea how many prisoners will emerge from the dungeons today. So you might plan to just let them all wait next to you while you count them (to figure out what <span class="math inline"><em>n</em></span> is), but that won’t work either: There is not enough space to have them waiting, and some might try to escape in the confusion before you are done counting. So in fact, you can only have one prisoner waiting at a time. As soon as the next one comes, you have to send one of them towards execution.</p>
<p>This is still a solvable problem, and the solution is <a href="https://en.wikipedia.org/wiki/Reservoir_sampling">Reservoir sampling</a>: You let the first prisoner wait. When the second one comes, you pick one of them with probability <span class="math inline">½</span>, and let him wait. When the third one comes, with probability <span class="math inline">⅔</span> you send him on, and with probability <span class="math inline">⅓</span> to let him wait. The fourth is sent forth with probability <span class="math inline">¼</span> and kept waiting with probability <span class="math inline">¼</span>. And so on. When finally the dungeon master tells you that all prisoners have emerged, whoever is waiting next to you is the lucky guy.</p>
<p>Before you do that, you should convince yourself that this is fair: The <span class="math inline"><em>k</em></span>th prisoner is the lucky one if you let him wait <em>and</em> from then on, all other prisoners are sent forth. The probability of this happening is <span class="math inline">¹ ⁄ <em>ₖ</em> ⋅ <em>ᵏ</em> ⁄ <em>ₖ</em>₊₁ ⋅ <em>ᵏ</em>⁺¹ ⁄ <em>ₖ</em>₊₂ ⋅ ⋯ ⋅ <em>ⁿ</em>⁻¹ ⁄ <em>ₙ</em></span> which, after a number of cancellations, resolves to <span class="math inline">¹ ⁄ <em>ₙ</em></span>. Because <span class="math inline"><em>k</em></span> does no longer show up in this calculation, the probability is the same for everybody, and hence fair.</p>
<h3 id="how-to-not-make-a-decision">How to not make a decision</h3>
<div class="figure">
<img src="https://upload.wikimedia.org/wikipedia/commons/c/c7/Roman_coin_commemorating_the_secret_ballot_law_of_137_BC.jpg" alt="A fair RNG"/>
<p class="caption">A fair RNG</p>
</div>
<p>So far so good. But the story misses an important point: Where do you get your randomness from? Just <a href="http://web.media.mit.edu/~guysatat/MindReader/index.html">picking randomly is hardly random</a>. Luckily, you just have been given your guerdon, and you have a Roman coin in your pocket. Let us assume the coin is perfectly fair: With probability <span class="math inline">½</span> it shows the head of Libertas, and with probability <span class="math inline">½</span> a bunch of horses. It is easy to use this coin to distinguish between the first and second prisoners, but when the third comes out, things get hairy.</p>
<p>You can try to throw the coin many times; say, 10 times. This has <span class="math inline">2<sup>10</sup> = 1024</span> outcomes, which we can interpret as a number between 1 and 1024. If you give the third prisoner his freedom when this number is between 1 and 341, and you give him a cross if the number is between 342 and 1024, then you made pretty fair call. Not yet fully satisfying, but let’s go with it for now.</p>
<p>There is, however, another problem with this: You have to throw the coin a lot of times: For each prisoner, you toss it 10 times! This is too slow, and the plebs will get impatient. And it clearly is wasteful. The great philosopher Shannonus taught you that throwing the coin ten times gives you 10 bits of entropy, but you actually need only <span class="math inline">−(⅓ ⋅ log(⅓)+⅔⋅log(⅔)) = 0.918…</span> bits to make this <span class="math inline">⅓</span>-<span class="math inline">⅔</span> decision. We should use those left-over 9.81 bits! How do we do that?</p>
<h3 id="unreal-real-randomness">Unreal real randomness</h3>
<p>To come up with a better (and maybe even optimal) plan, imagine for a moment that you had a source of randomness that gives you a real real number in the range <span class="math inline">(0, 1)</span>, uniformly. Clearly, that would solve your problem, because when prisoner <span class="math inline"><em>k</em></span> emerges, you can draw a random number <span class="math inline"><em>r</em></span> and let this prisoner wait if <span class="math inline"><em>r</em> < ¹ ⁄ <em>ₖ</em></span>.</p>
<p>But you don’t actually have to draw a random number more than once: It suffices to pick a single <span class="math inline"><em>r</em> ∈ (0, 1)</span> at the very beginning. You just have to be a bit cleverer when deciding whether to keep the <span class="math inline"><em>k</em></span>ths prisoner next to you. Let’s go through it step by step:</p>
<ul>
<li>When Augustus, the first prisoner, comes out, you simply keep him.</li>
<li>When Brutus, the second prisoner, comes out, you keep him with probability <span class="math inline">½</span>. You do that if <span class="math inline"><em>r</em> < ½</span>. You also start some bookkeeping, by remembering the range of <span class="math inline"><em>r</em></span> that has led to this outcome; in this case, the range is <span class="math inline">(0, ½)</span>. If you picked Augustus, the range is <span class="math inline">(½,1)</span>.</li>
<li><p>Now Claudius comes out, and you want to keep him with probability <span class="math inline">⅓</span>. If the range that you remembered is <span class="math inline">(0, ½)</span>, you keep him if <span class="math inline"><em>r</em> < ⅙</span>. Similarly, if the range is <span class="math inline">(½,1)</span> you keep him if <span class="math inline"><em>r</em> < ½ + ⅙ = ⁴ ⁄ ₆</span>.</p>
The currently remembered range is now <span class="math inline">(⁴⁄₆,1)</span> if Augustus is waiting, <span class="math inline">(⅙,½)</span> if Brutus is waiting and either <span class="math inline">(0, ⅙)</span> or <span class="math inline">(½,⁴⁄₆)</span> if Claudius is waiting. Notice that the ranges are not all of the same size, but if you add the lengths of each prisoner’s range, you have <span class="math inline">⅓</span>, which means that every prisoner has the same chance to be waiting so far.</li>
<li><p>Finally, Decimus shows up. You repeat this procedure: Look at the current interval; if <span class="math inline"><em>r</em></span> is in the left quarter of it, Decimus stays, otherwise he leaves.</p></li>
</ul>
<p>I tried to visualize this, and came up with this. Pick <span class="math inline"><em>r</em></span>, locate the right spot on the <span class="math inline"><em>x</em></span> axis, and you can read off, by going down, who is waiting next you.</p>
<div class="figure">
<img src="//www.joachim-breitner.de/various/nisus-coins.svg" alt="A table for Nisus"/>
<p class="caption">A table for Nisus</p>
</div>
<h3 id="back-to-using-coins">Back to using coins</h3>
<p>With this strategy in mind, we can go back to using a coin. Now, a single coin flip does not give us <span class="math inline"><em>r</em></span>. 1000 coin flips don’t either. If we could flip the coin an infinite number of times, yes, then we could get <span class="math inline"><em>r</em></span> out of this: The first coin flip decides the first bit after the <del>decimal</del> binary point: Head is 0, horses are 1. The second the second bit. And so on.</p>
<p>But note that you don’t need to know precisely <span class="math inline"><em>r</em></span>. To decide whether Augustus or Brutus stay, you only need to know if <span class="math inline"><em>r</em></span> is in the left or the right half -- and you know that after the first coin flip. You can also tell whether Claudius stays as soon as you threw the coin often enough to determine if <span class="math inline"><em>r</em> < ⅙</span>. This might already be the case after a single coin throw (if it shows horses), or after a few more. The likelihood that you can’t decide with certainty whether <span class="math inline"><em>r</em> < ⅓</span> goes down exponentially, so with probability <span class="math inline">1</span>, you will come to a conclusion eventually.</p>
<p>And the good thing is: If you were unlucky and had to throw the coin very often, then you learned a lot about <span class="math inline"><em>r</em></span>, and you can decide the next few prisoners without throwing a coin at all! In this sense, we managed to use “left-over entropy”.</p>
<p>And the other good thing is: There are no rounding errors any more. Every prisoner has the same chance to be freed.</p>
<h3 id="a-visualization">A visualization</h3>
<p>I tried to visualize the whole story, using <a href="https://code.world/">CodeWorld</a>. In <a href="https://code.world/run.html?mode=haskell&dhash=DlHROcVzrb6vCozi0UCqM6A">this not very pretty animation</a>, you see the prisoners (so far just simple numbers) coming from the left. Nisus (not shown) either lets them wait in the slot in the top, or sends them to the right. Sometimes he needs to toss a coin. Below you can see, in numbers and in a bar, what ranges of <span class="math inline"><em>r</em></span> are interesting: In green, the range which indicates that the current prisoner can stay, in red the range where he has to go, and in blue the range that <span class="math inline"><em>r</em></span> is known so far.</p>
<div class="figure">
<img src="//www.joachim-breitner.de/various/nisus-coins-animation.png" alt="Nisus (not shown) at work"/>
<p class="caption">Nisus (not shown) at work</p>
</div>
<p>Probably, by the time you have read this until now, the animation is not at the beginning any more. Move the mouse over it, and you will see controls in the lower left corner; the first button resets the animation. You can also check out the <a href="https://code.world/haskell#P47oXtz3j5Ar4Sc8Bm8NTnA">source code</a>.</p>
<h3 id="open-questions">Open questions</h3>
<p>So Nisus is happy, because with few coin tosses, he can fairly pick a random prisoner to free. I am not fully satisfied yet, because of two option questions:</p>
<ul>
<li>Is this algorithm optimal? (And what does it mean to be optimal?)</li>
<li>What is the expected number of coin throws for <span class="math inline"><em>n</em></span> prisoners? Does this number converge to <span class="math inline">log(<em>n</em>)</span>, which is the entropy of the result?</li>
</ul>
<p>If you know the anwers, let me know!</p>
<h3 id="related-ideas">Related ideas</h3>
<p>Brent Yorgey pointed me to a <a href="https://patternsinfp.wordpress.com/2017/12/05/arithmetic-coding/">sequence of blog posts</a> by Jeremy Gibbons, on “Arithmetic Coding”, which use a similar structure of dividing the unit intervals.</p>Sun, 25 Mar 2018 16:31:57 -0400