tuple
A tuple is an ordered collection of elements, potentially of heterogeneous kinds, similar to a fixed-length list.
Syntax
Tuples are defined using parentheses () with elements separated by commas.
(1, true)
("Hello", 42, false)
(1, ("Hello", false))
When parsed and rendered, this code will appear as:
(1,true)--two-tuple of f64 and bool
("Hello",42,false)--three-tuple of string, f64, and bool
(1,("Hello",false))--nested tuple
There is no such thing as a single-element tuple in Mech. A single value in parentheses is just that value. For example, (42) is just 42, not a one-tuple containing 42.
Kind
The kind of a tuple is determined by the kinds of its elements. For example:
(1,true)--kind: <(f64,bool)>
("Hello",42)--kind: <(string,f64)>
Tuples can be nested, and the kind reflects the structure:
(1,("Hello",false))-- kind: <(f64,(string,bool))>
Construction
There are two ways to construct tuples:
Tuple literals
Comprehensions
Tuple Literals
Comprehensions
Tuples can be constructed using comprehensions:
The above comprehension generates a set of tuples containing all combinations of elements from sets x and y.
Accessing Elements
Elements can be accessed in two ways:
Dot access
Destructuring
Dot Access
Tuple elements are accessed by their 1-based index using the . operator.
Similarly:
Nested tuples are accessed recursively:
Access the second element, which is a tuple
To access elements within the nested tuple:
Access "Hello"
Destructuring
Tuples can be destructured into variables:
Destructuring works recursively for nested tuples:
Assigning Elements
Mutable tuples allow assignment via dot indexing:
Updates the first element
qImmutable tuples cannot be modified. The following code raises an error:
q:=(10,"b",true) q.1 = 42 --Error: cannot assign to element of immutable tuple