Saturday, September 06, 2008

Improved tuple literal syntax

Suppose we define a tuple class:
TUPLE: color red green blue ;

We can make a new instance as follows:
1 2 3 color boa

Or like this:
color new
1 >>red
2 >>green
3 >>blue

You can also write a tuple literal. This creates the tuple at parse time, not at compile time, so every time the surrounding quotation evaluates, the same tuple is pushed on the stack:
T{ color f 1 2 3 }

Notice how when constructing a tuple, we have a choice between either positional slot values (boa, which means by order of arguments) or named slot values (using new, which makes an empty tuple). However no such possibility exists with the literal syntax, which only supports positional slot values.

Formerly, the first slot in the tuple was the delegate, and this was almost always f. After removing delegation, I kept the f as part of the syntax has been removed, because I didn't want to go through and update all usages of literal tuples in the source tree to not contain the f. That's a lot of pain for little gain.

What I did instead was turn the tables and change the meaning of the f. Now, if the first token after the class name is f, the remaining tokens are the slot values in positional order. If it is any other token, then the slot values are a list of name/value pairs, like so:
T{ color { red 1 } { green 2 } { blue 3 } }

A syntax for literal tuples where the slots are named was originally proposed by Daniel Ehrenberg; however his syntax was different:
T{ color red: 1 green: 2 blue: 3 }

His syntax is more concise, but it was inconsistent with hashtable syntax. However he got the ball rolling and made us all think about possible improvements to tuple literal syntax.

Originally I was going to introduce the new syntax and remove the old one, but Eduardo mentioned on the mailing list that he likes the "BOA" literal syntax sometimes too, for shorter tuples with fewer slots (such as colors above). So at that time, we came up with this trick of changing the meaning of the f.

I think this is very clever, because it creates less work for me than removing all occurrences of the initial f from tuple literals, and it creates a new way to describe literal tuples which have many slots, or where only a few slots need to be set, which is more readable than the BOA syntax. And of course the BOA syntax is still there in the cases where it makes sense too.

Six months ago, I set out a roadmap for language evolution. Multi-methods still remain, and they're coming up soon. I proposed a syntax for multimethods a few months ago and since then I've thought about it some more and the final syntax will likely be different. I will blog about this in detail when my thoughts on the matter are more concrete.

No comments: