Tuples in JavaScript

A tuple is a box containing a few objects not necessarily of the same type. I usually try to avoid using the word tuple and leave it gladly to the Architects.

The only tuple I have used so far is the pair (tuple-2). Well, actually I like also triples.

Having at your disposal a generic JavaScript way to build lists as binary trees (in my case that’s geieslists, but you may easily implement it using JS arrays as Douglas Crockford does in The Little Javascripter) it is pretty straightforward to build a pair by applying cons two times in a row:

function pair(first) {
return function(second) {
return cons(first,cons(second,EMPTY));

You build a Javascript pair this way:

var myPair = pair('a')('b');

You may then access first and second by using head/car and tail/cdr. You may add a little guard that your argument be actually a pair.

function first(aPair) {
if (size(aPair)!==2) throw 'Not a pair!'
else return head(aPair)
function second(aPair) {
if (size(aPair)!==2) throw 'Not a pair!'
else return head(tail(aPair))

At the end of all this, we get;

var myHead = first(myPair) // 'a'
var myHead = second(myPair) // 'b'

To mock Scala a bit, we may also create the functions _1 and _2:

var _1 = first, _2 = second;

These functions are put at work in various pages of this blog:
– State Monad in JavaScript
– Fold Right in JavaScript
– Fold Left in JavaScript

Tuples in Java

Note: This is a remainder from the older version of this page. Tuples on the JVM are Scala’s business

Apparently Java is not the best way to manage tuples; tuples may be very, very flexible; the things that get closer are varargs, but they are all of the same type. Too bad for them.

Examples of heterogeneous tuples:

  1. State-content pairs in the State monad
  2. T4<ARG1,ARG2,ARG3,RET> that becomes T3<ARG2,ARG3,RET> after having a good curry

Big deal. I’ll put T1,  T2, T3, T4 and T5 in my classpath.

What am I missing?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s