Tuples: Introduction

Tuples are a way to bundle together a fixed number of values of possibly different types.

Syntax

The syntax for a tuple type is a parenthesis-enclosed, comma-separated list of:

  • values, when creating a tuple.
  • types, when annotating with a tuple.
tuple(value1, ..., value n); // for creation
(type1, ..., type n); // for annotation.

The types in a tuple annotation can be any type in the type system, except for void.

The following example shows you both the creation of and annotating with a tuple

<?hh

namespace Hack\UserDocumentation\Tuples\Introduction\Examples\CreateAndAnnotate;

function find_longest_and_index(array<string> $strs): (string, int) {
  $longest_index = -1;
  $longest_str = "";
  foreach ($strs as $index => $str) {
    if (strlen($str) > strlen($longest_str)) {
      $longest_str = $str;
      $longest_index = $index;
    }
  }
  return tuple($longest_str, $longest_index);
}

function run(): void {
  $strs = array("ABCDE", "tjkdsfjkwewowe", "Hello, this is an intro of tuples");
  var_dump(find_longest_and_index($strs));
}

run();
Output
array(2) {
  [0]=>
  string(33) "Hello, this is an intro of tuples"
  [1]=>
  int(2)
}

Initializers

Tuples can also be used in initializer expressions for class properties.

<?hh

namespace Hack\UserDocumentation\Tuples\Introduction\Examples\Initializers;

class A {
  private $inst = tuple(2, "hi");
  public static $stat = tuple(array(1, 2), Vector {3, 4});
}

function run(): void {
  var_dump(new A());
  var_dump(A::$stat);
}

run();
Output
object(Hack\UserDocumentation\Tuples\Introduction\Examples\Initializers\A)#2 (1) {
  ["inst":"Hack\UserDocumentation\Tuples\Introduction\Examples\Initializers\A":private]=>
  array(2) {
    [0]=>
    int(2)
    [1]=>
    string(2) "hi"
  }
}
array(2) {
  [0]=>
  array(2) {
    [0]=>
    int(1)
    [1]=>
    int(2)
  }
  [1]=>
  object(HH\Vector)#1 (2) {
    [0]=>
    int(3)
    [1]=>
    int(4)
  }
}