15 September 2006

A strange postgrad class

This is the kind of course I'd like to take: PHYS771: Quantum Computing Since Democritus. There's a tolerably cool math puzzle at the end of the first lecture.

08 September 2006

No, not SOAP. We're talking actual soap here.

Scott Aaronson has a cool article (PDF) that looks at half a dozen proposed ways of solving really difficult computational problems—such as using soap bubbles or black holes, or time-traveling, or playing Russian roulette.

The paper is playful but serious—a serious survey of the far-out. A lot of it is mathematical gibberish to me, but it's amusing all the way through, and there's a fun “think big—no bigger than that” section at the end.

I have one super-geeky nitpick, though:

Even many computer scientists do not seem to appreciate how different the world would be if we could solve NP-complete problems efficiently. I have heard it said, with a straight face, that a proof of P = NP would be important because it would let airlines schedule their flights better, or shipping companies pack more boxes in their trucks! One person who did understand was Gödel. In his celebrated 1956 letter to von Neumann (see [69]), in which he first raised the P versus NP question, Gödel says that a linear or quadratic-time procedure for what we now call NP-complete problems would have “consequences of the greatest magnitude.” For such an procedure “would clearly indicate that, despite the unsolvability of the Entscheidungsproblem, the mental effort of the mathematician in the case of yes-or-no questions could be completely replaced by machines.”

But it would indicate even more.... [Ed.: color added]

Here Scott shifts carelessly between two completely different hypotheticals (blue and orange). The statement he lambasts, that P=NP would be important for logistics, is actually an overstatement. A proof that P=NP (blue) almost certainly would have no practical consequences at all, unless I'm wildly mistaken, because a great many problems in P are not practically solvable. Who cares if every problem that can be solved in O(2n) time can also be solved in O(n1000000) time? In practice the latter is probably worse.

By contrast, a discovery that NP-complete problems can be solved in quadratic time (orange) would be a mind-blowing, probably world-changing event. But this is unlikely in the extreme.

06 September 2006

Gradual typing

Seen on Lambda the Ultimate: Gradual Typing for Functional Languages, a paper that introduces a new flavor of lambda calculus which they call (this is an approximation) λ?→.

Hard to explain why language geeks should be excited about this. I am.

We present a formal type system that supports gradual typing for functional languages, providing the flexibility of dynamically typed languages when type annotations are omitted by the programmer and providing the benefits of static checking when function parameters are annotated.

The proofs in the paper are machine-verified!

Relationships

I have a big file full of thoughts about programming languages. Re-reading it today I found this (edited):

Component-container relationships. I suspect these are all over the place. This is always a hassle. I wish someone would make it easy.

One idea is to put the component class lexically inside the container class:

        class Container {
            class Component {
                // each Component is part of a Container
            }
        }

Hmmm... I need to think about this some more.

And I realized: I now know the solution to this problem. In fact I've implemented it. Relationships.

I mean relationships in the sense of entity-relationship diagrams. Relationships describe how entities relate to each other, like the bolded words below:

His new paper cites 37 sources. (This could perhaps be written in code like this: paper1.cites(paper2))

Tom Hanks starred in the movie Big. (actor.starredIn(movie))

The patient Joe Bloggs is treated in the cardiology ward. (patient.isTreatedIn(ward))

Of course parent-child relationships are one case of this, but there are many others.

Okay. Now consider some hypothetical Python code:

    class Component(object):
        ...

    class Container(Component):
        ...

    # Define the relationship between these two classes...
    containment = OneToManyRel(
        Container, 'container', 'contains', Component, 'contents')

Here's what the OneToManyRel does:

  • Adds a container property to class Component. Each Component's container is always either a Container object or None. It's initially None, but if you like, you can just initialize it in Component.__init__ like any other attribute.

  • Adds the reverse property, contents, to class Container. This property is an object that looks like a set. It's initially empty. The two properties are automatically kept in sync, so if you do thing.container = None, the thing is automatically removed from its container's contents set.

  • Adds a method Container.contains(Component) that can be used to query the relationship.

  • Keeps a data structure of all the relationships, so you can do containment.items(), which returns a list of (Container, Component) pairs.

Here's a taste of how powerful this can be:

    class BuildStep(object):
        ...

    class File(object):
        ...

    # Each BuildStep produces some Files called its targets.
    # Each File is produced by one BuildStep called its buildStep.
    produces = OneToManyRel(BuildStep, 'buildStep', 'produces', File, 'targets')

    # Each BuildStep depends on some Files called its sources.
    # Each File is depended upon by some BuildSteps called its dependants.
    dependsOn = ManyToManyRel(BuildStep, 'dependants', 'dependsOn', File, 'sources')

That's very brief, compared to what you'd have to type to get this the traditional way.

So I have an implementation. In addition to OneToManyRel and ManyToManyRel, it has things called SymmetricRel and EquivalenceRel. (Warts: My current implementation doesn't use weakrefs, so it keeps objects alive until explicitly removed, which is kind of silly. Also, the properties currently look like iterators, not sets.) The whole thing is 355 lines of Python code.

All this is inspired by Inform 7 relations. I wonder about Ruby. I can only assume Ruby on Rails automatically does stuff like this for databases; I don't know about regular old in-memory objects though. I imagine this would be a breeze to implement in Ruby.

Anyway. I don't know how generally useful it will be, but it's certainly encouraging to come across an old gripe about the exact problem this solves.

15 August 2006

There's a word for that

(Ed. note: More stuff written long ago but never posted...)

A brief piece in the Economist last year decried the fate of a word of which that periodical is particularly fond. In Europe, it has become a slur for the right wing; in America it's an even more pejorative label for the left.

The Economist's own political viewpoint is probably best described as center-right. It couples the leftist idea that government exists for the greater good of all people (not strictly to preserve individual rights) with the right wing's abiding suspicion of centralized government power and its conviction that the way to pursue social justice is to reduce regulation and let free markets work. “There's a word for that,” the essay asserts (echoing a Bush campaign speech), “and we want it back.” The much-abused word is liberalism.

Alas, this impassioned little essay is available only to Economist online or print subscribers. If that's you, read on.

Wiretaps, redux

This is hardly relevant anymore, but I figured I'd post it for the record.

A few times over the last year, JJ and I discussed the warrantless wiretap program. He's all for it. I have never come away from a conversation with him less convinced of his point of view.

I'm clearly missing something fundamental. Here's Power Line Blog arguing back in December 2005 that the program is clearly legal, citing court decisions affirming the President's authority to gather foreign intelligence without having to bother with warrants. Here's the Wall Street Journal doing the same thing.

(Now to begin with, I'm more suspicious of executive power than those courts—I'm even suspicious of the FISC, if it comes to that—but let's set that aside.)

My question is, is this executive power completely without limits? Do American citizens have no rights during wartime? Of course not. There's a line somewhere; the question is where. The pro-snooping blogosphere seems to miss this entirely. Certainly they ignore the Times's allegation that some of the snoopees are American citizens.

The entire Journal op-ed focuses on foreign surveillance. It even goes so far as to attempt this reductio ad absurdum:

The leakers of this sensitive national security activity and their Capitol Hill supporters seem determined to guarantee al Qaeda a secure communications channel into this country so long as they remember to include one sympathetic permanent resident alien not previously identified by NSA or the FBI as a foreign agent on their distribution list.

This simply isn't relevant to the surveillance activity actually described in the original Times article, in which names of American citizens (among others) are put on a list of people whose phone conversations and e-mails are secretly monitored. In other words, American citizens were the target of warrantless snooping.

I've noticed that it's really hard to even talk about this with someone. I think that might be because the question has so many logically incompatible lines of scrimmage.

  • The program is either Constitutional or not;
  • It's either foreign intelligence gathering or it's domestic;
  • It's either legal under FISA or not, or FISA doesn't apply;
  • FISA generally either makes sense, or it ties the President's hands in a potentially disastrous way;
  • Regardless of the particular legal question, the President generally either should or shouldn't exercise absolute power to conduct a war;

...and so on. Now, if you think the program flunks the first test, as I do, then most of the other questions just don't matter—in your nice, little, internally consistent political universe. It's really easy to end up arguing at cross purposes, though. And if you should manage to carry one point, the other guy always thinks he has three or four fallback positions.

I suspect that all of these questions but one are decidable, by any reasonable reading of the law; the sticking point is whether Congress has the authority to constrain the President's ability to conduct war as he sees fit.

But generally I didn't think much of the arguments I was hearing on any level. The President has the authority to take extreme measures in time of war, I'm told: look at the Japanese internment camps in World War II. (But isn't that a strong argument against such unlimited executive power? Is "there have been worse abuses in the past" really the President's best argument?) The three-days retroactive warrant provision in FISA is insufficient because it takes longer than three days to file a case. (I have no idea if this is true or not, but it's awfully hard to see the NSA program as a good-faith response to this difficulty.) The program was not actually secret, because some members of Congress was briefed. (And yet there should be an investigation into who leaked the program, and charges brought? Either it was secret or it wasn't.) As a practical matter, a war can only be fought by a dictator. (Really?)

In any case, it's water under the bridge now.

I blog parts of speech

There's a part of speech in English that I didn't know about before about a week ago. It's called the determiner. Some examples (quoting Wikipedia):

  • Articles: a, an, the
  • Demonstratives: this, that, these, those...
  • Possessive determiners: her, his, its, my, our, their, your
  • Quantifiers: all, few, many, several, some, every...
  • Numbers: one, two, fifty...
  • Ordinals: first, second, last, next...

I always figured they were just adjectives. But in English, determiners appear at the very start of a noun phrase, before any adjectives. Here's a quote; some noun phrases are in bold. The words in red are the determiners.

What are man and woman if not members of two very different and warring tribes? Yet decade after decade, century after century, they attempt in marriage to reconcile and forge a union. Why? I don't know. Biological imperative? Divine law? Or just a desire to connect to that mysterious other? In any case, it's always struck me as a hopeful thing.

—Diane Frolov and Andrew Schneider, writing for the TV show Northern Exposure

This has implications for programming languages, but I'll skip it. Olivia and I are rewatching Northern Exposure show by show, courtesy of Netflix. Great stuff.

09 August 2006

Tables need space to roam (horizontally)

One thing in particular that doesn't fit on half my screen is tables. Most tables need quite a lot of horizontal space. Otherwise you get horizontal scrolling, a nuisance. Examples:

  • A database query screen, like the one in SQL Server Management Studio, wouldn't work in two columns with code on the left and query results on the right. The code would fit nicely, but the results are tabular data. The people who made Management Studio apparently realized this; the app has two wide panels (code in the top half, results in the bottom half) and you can't change it.

  • The Inform 7 language has this ill-conceived feature where you can put tabular data in your program by literally typing in a tab-delimited table. As in:

    Table of Conversation
    topic reply quip
    "dream/dreams/nightmare/nightmares/sleep" "'Sleep well?' you ask solicitously.
    
    'Not really,' she replies, edging away from you. So much for that angle." "'Ghastly nightmares,' she remarks. You nod politely."
    "marriage/love/wedding/boyfriend/beau/lover" "'So,' you say. 'This is a little weird since we just met, but, um. Would you like to get married?'
    
    She looks at you nervously. 'Do I have to? I mean, I'd rather not.'
    
    Well, this could get prickly fast." "'I, er,' she says. 'I hope I'm not supposed to marry you or something.' Uh oh."
    ...
    

    That makes perfect sense, right? Well, I guess having line breaks within table cells makes it a little harder to read. And tabs look too much like spaces. But if you solve those problems, you're still left with this:

    Table of Conversation
    topic reply quip

    "dream/dreams/ nightmare/nightmares/ sleep"

    "'Sleep well?' you ask solicitously.

    'Not really,' she replies, edging away from you. So much for that angle."

    "'Ghastly nightmares,' she remarks. You nod politely."

    "marriage/love/ wedding/boyfriend/ beau/lover"

    "'So,' you say. 'This is a little weird since we just met, but, um. Would you like to get married?'

    She looks at you nervously. 'Do I have to? I mean, I'd rather not.'

    Well, this could get prickly fast."

    "'I, er,' she says. 'I hope I'm not supposed to marry you or something.' Uh oh."

    A table with three columns, two of which can hold large chunks of text, is going to have trouble fitting on half the screen at any reasonable font size.

  • You can force tabular data into non-tabular form. For example, the default view for Windows Explorer isn't tabular. (Or rather, it wasn't in XP. The Mac Finder is the same way.) But geeks tend to set the view to "Details", which is tabular, and leave it that way. We often need to be able to look at the largest files in a directory, or see which ones have changed recently, or select only the .cpp files; and in Details mode we can do those things by clicking on column headers, if not just by looking at the screen. It's a trade-off: determining the size or date-last-modified for a particular file requires a bit of care, because it's not immediately obvious how the rows line up. (Clicking on a file only highlights the filename, not the whole row, so that doesn't help.)

    A compromise UI would show things in a narrow format with the details initially shown in small print. It would be like Explorer's "Tiles" view, but arranging the tiles vertically, not in a grid. Ctrl+Scroll would zoom in and out, showing more or less detail. You could right-click on the small print and say "Break out Date Modified as a separate column". As a pleasant side effect, this UI would fit on half my screen. There's probably a reason I've never seen this, but speaking from innocence, it sounds nice.

07 August 2006

My computer shines

Another endearing feature of the HP Pavilion is the flashing blue power button.

I have no idea how this design ever got manufactured. The power button is about one inch, square, blue, abnormally bright, and blinks when the computer is in power-save mode. Here's how bright it is: before I covered it with duct tape, we had to close our bedroom door before going to bed, because the button blinking in the next room was bright enough to keep us awake. Even with the duct tape, if it's blinking, I can stand with my back to it, facing the opposite wall, and see the blue glow going on, off, on, off.

The blue button by itself is a jaw-dropping example of stupid design. No control with such a drastic effect needs to be made especially inviting to toddlers. But the blinking... I am just floored. It is a masterstroke, a work of sheer, staggering, insane genius. Did no one at HP realize that these things go in people's bedrooms? Did no one understand that blinking per se is considered so annoying that it's no longer used even to convey important information, much less to indicate the default mode in which any home computer will spend most of its life?

(speechless)

Hardware knowhow bleg

I recently added an Ethernet card to my PC at home.* Now whenever my computer hibernates, it doesn't wake up properly.** If I take out the Ethernet card, the power management starts working again. On the other hand, the computer has no reason to exist. Oh, the irony.

The card doesn't appear to have any jumpers on it. My next guess is, buy another Ethernet card (they're cheap) and see if it fixes it. Any other suggestions? Ask your friends. :)

Footnotes:

* Long story—Yes, it came with an Ethernet port, but stopped working at some point, and as it's an on-board Ethernet port, I figured there was no hope of fixing it without obliterating my computer. Besides, I don't have a multimeter anymore. Anyway, since then I've been using my USB port instead, but my new router will have none of that nonsense. And honestly, who can blame it.

** I hit a key, and I know it knows it's supposed to wake up, because the fan turns on; but it never gets to the point of actually displaying anything on the screen.

P.S. The computer is an HP Pavilion, if anyone wants to avoid buying one at all costs.

02 August 2006

On the importance of being the right width

This shambolic post is about the width of things, specifically C++ code, Python code, and GUI windows.

I ran a script on some C++ code today, looking at line width. This probably raises more questions than it answers, but here are the results:

    2-5: #############
   6-10: ###########################
  11-15: ########################################
  16-20: ##################################################
  21-25: #########################################
  26-30: #####################################
  31-35: ###############################
  36-40: ###########################
  41-45: ########################
  46-50: #####################
  51-55: ################
  56-60: ###############
  61-65: ############
  66-70: ##########
  71-75: #########
  76-80: ########
  81-85: #########
  86-90: ###
  91-95: ##
 96-100: ##
101-105: #
106-110: #
111-115: #
116-120: #
121-125: #
126-130: #
131-135: 
136-140: #

This graph shows how many lines are 2-5 characters wide, how many are 6-10 characters wide, and so on. The script ignores indentation and comment lines, and lines that are blank or just have one character (usually }).

So you can see that, for example, about 75% of nontrivial code lines are 50 characters wide or less.

The trailing end of the curve actually goes all the way out to 500 characters, but almost all of these extreme cases involve very long strings.

Looking at some C++ code I personally wrote, the curve is similar, but for me about 75% are 40 or fewer characters wide, and the curve dies out entirely at 115 characters. I habitually break up long lines. Of the longish lines (40+ characters), most are not all that complex. They're long because the things involved have really long names:

  bool ImageGenerator::isImageObjTypeReloadable(uint64_t uObjectType)

  initCustomBasket(pOldBasket->getLocalResourceNameObject());

  Boa::WebBoaSubnetStartAttributes networkAttributes = wbNetwork.getDefaultStartAttributes();

(Disclaimer: Identifiers have been changed to protect the innocent. I'm just talking about line length and complexity, and in these respects the examples are genuine.)

Okay. Now, same script, totally different code sample:

    1-5: #################
   6-10: ######################
  11-15: ###########################################
  16-20: ##################################################
  21-25: #############################################
  26-30: ########################################
  31-35: ##################################
  36-40: ############################
  41-45: ######################
  46-50: ###################
  51-55: #################
  56-60: ################
  61-65: ###############
  66-70: ########
  71-75: ###
  76-80: #
  86-90: 

This graph describes the idlelib directory of Python 2.4. This is Python code, not C++. It's a similar curve, though.

Python and C++ are very different languages, but they (and all modern languages) have this in common: they'll let you write arbitrarily complex code lines. The compiler will accept a 3000-character line without batting an eye.

The teams that wrote these two code samples are undoubtedly very different, but they have this in common: they tend to break complex thoughts into two or more lines.

Part of this is just that it's easier to understand several simple, independent lines than one complicated one. I think part of it is visual, too. But the why doesn't matter; IDEs should take advantage of programmers' tendency to work in lines of a certain size.

Microsoft Visual Studio is an excellent example of an IDE that completely fails to do this. The current MSVS is all about the myriad gadgets and capabilities it offers—in ten trillion fiddly docking panels, none of which shows any tendency to make itself the right size or shape for the information displayed. Least of all the central code window, which initially gapes some 200 characters wide, but spinelessly cedes screen area to each new gadget you open until practically nothing is left.

By contrast, the Inform 7 GUI shows source on the left half of the screen and uses the right half for documentation and play-testing.

I can't rave enough about this arrangement. It works extremely well, at least partly because each half is a comfortable width.

It's possible to mimic this layout in Visual Studio: put Solution Explorer in a narrow strip on the left, code in the center, and a wide tabbed panel for everything else on the right. I'll try it out.

One last note. I have a program called HalfMax in my Startup folder. It runs in the background, and when I hit Windows+1 or Windows+2, it moves the current window to fill the left or right half of the screen, respectively. It so happens that a lot of the programs I use are almost ideal when filling half of my screen (given my font sizes, screen resolution, and so on). Right now I have the following applications open: Microsoft Outlook, an Outlook e-mail message, Perforce, some Command Prompts, SysInternals DebugView, some Notepads, some file Explorers, Microsoft SQL Server Query Analyzer, the Windows Services control panel, TestTrack, a Python shell, Emacs, Araxis Merge, Adobe Reader, Word, Visual Studio, and Internet Explorer. (I think this is just about all the applications I ever use. :) Most of these are either simple browser-like apps, Notepad-like editors, or shells: the kind of app that is significantly better half-maxed than maximized. The rest—Visual Studio, Windows Explorer, TestTrack—use that horizontal space for stuff like docking panels or table-view UIs.

28 July 2006

Human visual navigation

I think the region of the screen I can concentrate on at once is quite small, maybe twelve words wide and six lines tall. But then why do I prefer two large high-resolution screens to one low-res screen? I can't really use all that screen space, can I?

Let's talk about the navigation features provided by human vision. Although I have this 12x6 mental "window", the window doesn't stay still. I can read a whole screenful of text without touching the mouse. Human vision has built-in scrolling. I can take in more of the screen at once by sacrificing attention to detail; or I can concentrate on one line of code, at the cost of ignoring everything else for a moment: visual zoom. If I look away, then when I look back, my eyes easily snap to where I was. This is kind of like Alt+Tab in that it lets me hop back and forth between different things; call it visual switching. If I need to look for something, I'll zoom out, skim down without reading, find it, and zoom back in, all without thinking: visual search.

With a huge screen, I can scroll, zoom, switch, and search without touching the keyboard or mouse. With a smaller screen, I have to use the mouse or keyboard to navigate. Each motion takes time and a little bit of brainpower; and each time the screen changes, it takes me a moment to find my place. Eyeball scrolling is superior to software scrolling. Eyeball switching is superior to Alt+Tab.

Having dispensed with that paradox, I want to talk about the 12x6 window and what it means for PL and IDE design. More to come.

25 July 2006

To do

More possible side projects:

  • Blog about irrationality and game theory. I promised D.E. something about this many months ago.
  • Implement long integers for Try Scheme. (Java's implementation is about 4400 lines; Python's is about 3200 lines, including comments and boilerplate junk. Neither one uses two's complement to represent negative numbers, which surprises me. Maybe division is a lot harder to implement in two's complement?)
  • Get Try Scheme working in Safari (the most obvious problem is that Safari doesn't have Object.isPrototypeOf).
  • Implement a built-in manual and tutorial for Try Scheme.
  • Write a story.

18 July 2006

Hiding algorithms and data structures

In Java, you might write:
class Thing {
    ...
    public int getCurrentSize() {
        int size = getBaseSize();
        for (SizeEffect se : getWorld().getAllEffectsEnchanting(this)) {
            size += se.getMagnitude();
        }
    }
}

In Python 2.4 or later, you might write this instead:

class Thing:
    ...
    def getCurrentSize(self):
        return self.baseSize + sum(
          se.magnitude for se in self.world.getAllEffectsEnchanting(self))

If that's not entirely clear yet, just read on. I'll come back to it.

In Inform 7, you would write this:

To decide which number is the current size of (subject - a thing):

Decide on the base size of the subject plus the total magnitude of the size effects enchanting the subject.

I hope that clarifies what the Python version is trying to say. The Python expression sum(se.magnitude for se in ...) is just a way of saying “the total magnitude of ...”.

Ah, but in Inform, you don't use anything that resembles loop syntax to iterate through the size effects. And you don't explicitly query anybody to get the set of relevant objects. You just state your requirements. You don't build data structures explicitly, either—I wouldn't want to post an example World object here, but I can show you the complete Inform code:

A thing has a number called the base size. The base size of a thing is usually 1. The base size of a person is usually 5.

A size effect is a kind of thing. A size effect has a number called the magnitude.

Enchantment relates various size effects to various things. The verb to enchant (he enchants, they enchant, he enchanted, it is enchanted, it is enchanting) implies the enchantment relation.

That's all. The last sentence is just a convenience so that later in your program, you can write “The giant growth spell is a size effect with magnitude 3. It enchants the wombat.” or “Now the wicked ginormosity spell enchants everything.” or “Every turn, if anything is enchanting the player, say ‘You feel prickles all over your skin.’”

Of course, Inform is probably cheating a little bit: in its niche problem domain, there are only ever a few hundred objects in an entire program. So it can implement the implied searches naively. Still, with a little whole-program analysis, the technique could scale.

Why does this feel so new? We've been there with Prolog and SQL, right? I guess Prolog had unrelated problems, and SQL is still awfully cumbersome to get to. I'm awfully impatient about these features showing up in a language I can use every day.

07 July 2006

Duck-typing and Scheme

Duck-typing advocates occasionally say that querying the type of an object is unnecessary. Certain Pythonistas are fond of this idea. I just don't see it.

Maybe querying the concrete type is unnecessary. (Aside: Python has a builtin, isinstance(), that does just that—but I found out a week or two ago that an object can lie to isinstance() about its type. It's just the most absurd design ever.) But once in a while, I need to know whether a given object can swim, at runtime, preferably without having to put it in the water. Surely in a well-designed language, these questions can be answered without unduly revealing how an object is implemented.

For example, in Scheme, you can't ask if a number is a floating point number, as opposed to a native int (fixnum in Scheme jargon), big-integer, rational, or big-decimal. But you can ask if the number is exact, meaning basically that it hasn't been subjected to rounding. You can ask if a number is an integer or not: (integer? x); but you are actually asking about the number, not its type. So (integer? 1.79e123) is true, as is (real? 1).

For numbers, the difference between querying an object's characteristics and querying its concrete type might seem unimportant. Also, numbers are a special case where the concrete type matters a whole lot, for performance. (The next Scheme standard will add a bunch of procedures like (fx+) that only work on fixnums.) But when you start talking about objects, the difference is whether or not you support duck typing, which I think is a big deal. Languages should make it easy to query an object's interface and inconvenient to query its implementation.