03/07/22
Most programmers haven’t heard of literate programming,
and the few that have tend to think it means writing a lot of comments around your code.
However, simply explaining code with prose, does not constitute literate programming.
Consider the following quote from it’s inventor:
Some of my major programs could not have been written with any other methodology that I’ve ever heard of.
The complexity was simply too daunting for my limited brain to handle;
without literate programming, the whole enterprise would have flopped miserably.
… Literate programming is what you need to rise above the ordinary level of achievement – Donald Knuth
Does this extraordinary leap in effectiveness sound like something that comes from re-explaining what code does?
I didn’t think so.
The real advantages of literate programming come from two principles:
-
Code should be written for humans not machines.
-
Program designers utilize many types of information, not just code.
Literate programming systems help programmers apply these principles
by providing two standard operations tangle and weave which
manipulate and organize source code.
1. Tangle
Literate programs are written in plain text documents,
but between the traditional prose, blocks of code (in any language) are interleaved.
For example:
console.log( subsets([1, 2, 3, 4]) );
Used by 1
You can think of them like markdown documents, but with an important addition.
In a literate program, blocks of code have identifiers, and they can reference each other.
Each reference modifies the contents of a prior block,
or includes it at the specificied location.
The operation tangle resolves all these references and produces normal source code to be read by the compiler.
Example
Let’s try it out.
In the block above we introduced a subsets
function, also known as the powerset:
begin{equation} mathcal{P}(A) = { S text{ is a set } colon S subseteq A }end{equation}
Implementing it can be a little bit tricky.
If you have never done it before, I recommend you write out some examples
on paper and see if you can figure it out.
begin{align} mathcal{P}({1, 2, 3}) = { &{1, 2, 3}, \
&{1, 2}, {1, 3}, {2, 3}, \
&{1}, {2}, {3}, \
&emptyset } \end{align}
The key insight, is that if we take an element out of the original set,
and all th