Tuples
Tuple is a data structure which contains a fixed set values, where each value can have a different type.
- they are useful when you don't want to declare a record
- they can contain any number of items
- their items can be destuctured and matched against
Type
The type of a tuple is
Tuple(...)
where each parameter is an item of a tuple.
For example the type
Tuple(String, Number, Bool)
represents a tuple where the first element is a
String
the second is a
Number
the third is a
Bool
Syntax
Tuples can be created with the following syntax:
{"First Value", 10, true}
Destructuring
To get the items of a tuple we need to destructure it: assign each item to a variable:
{first, second, third} =
{"First Value", 10, true}
Destructuring can be used in
try
,
sequence
,
parallel
,
case
expressions
and
where
statements.
case ({"First Value", 10, true}) {
/* match by value (will not match) */
{"A", 0, false} => "A"
/* match by value (will match) */
{"First Value", 10, true} => "B"
/* destructure */
{a, b, c} => a
}
try {
{first, second, third} =
{"First Value", 10, true}
first
}
fun tuples : String {
first
} where {
{first, second, third} =
{"First Value", 10, true}
}
When matching tuples in a case expression a destructuring will make it exhaustive.