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.

No comments: