By Weijun on Feb 27, 2007
Gilad Bracha just writes an article on Java tuples support, in which he claims that every language should have it. While we all know there's even no Pair inside Java, why comes him suddenly saying that Java must have it? Maybe he's struggled for it for many years but always turned down by Graham Hamilton? Now that Graham himself also left Sun, and Gilad believes he can pick up this topic again? Just kidding.
n-Tuple is nice and I also like it. Some people commenting on Gilad's post want it be implemented in JVM because that will help the performance. I don't like the idea, partly because I don't like JVM changes, which means a whole bunch of operators on the new data type, but mostly because I think Tuple is just another language element, and must be a generic class. What's more important is how to express it in an elegant style so that it looks natural, slim, and easy to use.
The following is my proposal:
- First create a new immutable class Pair<A,B> (in the java.util package), which has a constructor with 2 arguments, and have 2 methods calls car() and cdr().
- Tuple<A,B,...,C> is syntactic sugar/macro of Pair<A,Pair<B,Pair<...,Pair<C,Void>...>>. Javac knows this.
- Javac also knows that new Tuple<A,B,C>(a,b,c) is new Pair<A,Pair<B,Pair<C,Void>>>(a,new Pair<B,Pair<C,Void>>(b, new Pair<C,Void>(c, null))), and it writes this translation much faster than I do.
- and .caddr means .cdr().cdr().car(), and it automatically finds out if you write too many d at compile time.
- Maybe tuple knows about variant arguments, but seems not necessary.