Tuple

1 minute read

A tuple is very similar to a PHP array and a shape. The key feature of tuples is that they are immutable. You may not change the length or the types of the elements in a tuple. The values within the tuple are mutable.

public function test(): void {
$tup = tuple('3', 2, 4, 'foo');
//change the 4th element
$tup[3] = 'bar';
//add a new element, this will make the type checker scream
$tup[5] = 'Baz';
}

If you are trying to add more values to a tuple you will hear Hack complain, but the code will run on HHVM. The implementation of tuples is actually a pure array. This is the current implementation:

function tuple(...) {
return func_get_args();
}

The best use case I can see for tuples are when you need to return multiple values from a function. Notice how I annotate the return type.

public function foo(): (string, int) {
$tup = tuple("Hello", 3);


return $tup;
}

This is easier to write than using shapes for the same purpose.

Since a tuple is an immutable collection with fixed length, it kind of covers all the use cases for a Pair. The only difference is that a tuple is a data type and the Pair is an object. Why would you ever want to use a Pair when you can use the quick and easy solution with tuples?

Categories:

Updated:

Leave a Comment