Fuzion Logo
fuzion-lang.dev — The Fuzion Language Portal
JavaScript seems to be disabled. Functionality is limited.

Tuples

Tuples are a special kind of Record Types that do not give any particular names to the fields.

Tuples are particularly useful for features that return more than one value.

Fuzion provides a generic feature tuple in its standard library for tuples. Some syntactic sugar enables a concise notation. A similar notation is used for record destructuring, which will be explained here as well.

Tuples Example

Imagine you want to implement a feature that takes a 32-bit integer value and splits it into four bytes that start with the highest eight bits of the value and go down to the lowest eight bits. One way to achieve this is to return an instance of tuple as follows:

In this example, feature bytes returns a tuple with the actual formal generic parameters being four times i32. The result is set to an instance of this tuple type with the four values set to the four bytes extracted from the argument value v.

bytes is then called and the result is assigned to a field b of the tuple type with the same actual generic parameters. These values are then extracted into fields b0 through b3 using the tuple's value field with open generic discriminators .0 through .3.

Simplified Tuple Syntax

Syntactic sugar greatly simplifies this code: First an expression that defines a tuple such as

  x tuple T0 T1 := tuple v0 v1

is equivalent to an expression using parentheses

  x := (v0, v1)

This syntax also works for an empty tuple, i.e.,

  e := ()

is equivalent to

  e tuple := tuple

However, to avoid confusion between expressions in parentheses and tuples, a 1-tuple cannot be defined using

  e := (v1)

.

Destructuring

Note: This is called destructuring in other languages. (Javascript etc.)

Destructuring can be used to extract the values from a tuple, i.e., for a tuple with two values, the code

  v0 := x.values.0
  v1 := x.values.1
or (using syntax sugar):
  v0 := x.0
  v1 := x.1

is equivalent to

  (v0, v1) := x

Destructuring can also be used without type inference using = as follows

  (v0 T0, v1 T1) := x

or if T0 and T1 are equal

  (v0, v1 T0) := x

An underscore _ can be used to ignore values:

  (v0, _) := x

Simplified Example

Applying this syntactic sugar and some type inference to the previous example, the code becomes shorter and clearer:

Crazy Stuff

TBW: Does it make sense to inherit from a tuple? At least it does not compile at this point: