Wednesday, December 13, 2006

Programs As Stories

I came across this article that talks about implementing "a Haskell toy to visualize twos-complement binary numbers". I know, it doesn't sound like exciting reading. What's cool about it isn't so much the content of the code, but how the code is presented. The author made use of literate programming to write up this program.

Literate programming more or less reverses the roles of comments and code. Instead of code with delimited comments, it's comments with delimited code. Traditionally, you run one program to extract the code from your source file, and another program to extract the text/documentation.

I haven't seen many uses of literate programming that seemed genuinely useful. But, the above article may change my mind on that. See what I mean:

Almost 30 years ago I wrote code on my Radio Shack TRS-80 to make my 
dot-matrix printer spit out bitmaps of binary numbers, which made 
pretty recursive patterns. This program commemorates that long-ago 
geekery from my early teenage hacking days.

First, we need the bits library:

>import Data.Bits

...lots of code skipped...

I can give foldl an empty string as the starting accumulator value
and my function can concatenate strings onto it: 

>stringify_vals =
>  foldl (\ x y -> if y then x ++ "#" else x ++ " ") ""

Now you might want to try to apply our list of lists to this
function:

...more code skipped...

In the above example, code is marked by a > in the left hand column and everything else is just passed through as text. The end result reads like a story that one can both read and execute.

This whole approach seems like a powerful means of communication. While I can't imagine large systems being written like this, I can begin to see some really interesting possibilities.

And lest you think that literate programming is just for academics, consider that every time you run Javadoc you are effectively practicing literate programming.

No comments:

Post a Comment