Tuple types

Tuple objects are common in Alore programs, and the type system has a rich set of types for representing tuples.

Tuple basics

For example, consider a simple 2-tuple type (Int, Str). The first item is an integer and the second item a string. The program below defines t with type (Int, Str) and assigns a tuple value to it:

var t as (Int, Str)
t = 2, 'foo'

When you access tuple items using an integer literal, the type checker infers the type precisely:

t[0]       -- Type Int
t[1]       -- Type Str

Variable definition and type inference

You can use tuples as rvalues in multiple variable definition (and assignment). Type inference works for local variables:

def f() as void
  var s, i = 'foo', 1   -- Infer s to be Str and i to be Int
end

Next we willl show how to give the variable types explicitly.

Variable definition with explicit types

If you define multiple variables using var and cannot use type inference, you can define the variable types using a tuple type:

var i, s as (Int, Str)     -- i has type Int, s has type Str
i = 1
s = 'foo'

The same syntax also supports an initializer:

var i, s = (1, 'foo') as (Int, Str)

Note that in the above example the as (...) construct applies to the variable definition (var i, s = ...), not to the tuple expression.

Tuple types and multiple assignment

You can use tuple types for multiple assignment:

var i as Int
var s as Str
i, s = 1, 'foo'      -- Rvalue type is (Int, Str)

Note that parentheses are optional in tuple expressions, but not in tuple types.

Here is the above example spelled out with added steps for clarity:

var t as (Int, Str)  -- Parentheses are required here
var i as Int
var s as Str
t = (1, 'foo')       -- Parentheses are optional here
i, s = t

General tuple types

More generally, a tuple type (T1, T2, ...) represents a tuple that has T1 as the first item type, T2 as the second item type, etc. Empty tuples and 1-tuples are special:

Constructing tuples with explicit types

The example programs above relied on type inference when constructing tuples. You can also give the types explicitly using the now-familiar syntax (note that the parentheses are necessary due to precedence):

t = (2, 'foo') as <Int, Str>

The Tuple type

The runtime type of all tuples is Tuple, independent of the number of items and their types. Tuple also acts as the supertype of all tuple types. Values of type Tuple support all tuple operations, but they do not include precise tuple item type information.

All tuple items have type Object when accessed using a Tuple value:

var t as Tuple
t = (1, 'x')     -- Ok
t[0]             -- Type Object, not Int, since accessing using type Tuple