Tuple
Tuples are fixed-size, ordered collections of values that can have different types. They are commonly used to return multiple values from functions or group related values together.
Tuples vs Records
For structured data with named fields, consider using records instead (see the Language Tour). Tuples are best for simple pairs or when returning multiple values from functions.
Creating Tuples
Tuple Literal
(a, b) : (a, b)
Create a tuple using parentheses and comma-separated values.
# A pair of integers
point = (10, 20)
# Different types
person = ("Alice", 30)
# Nested tuples
nested = ((1, 2), (3, 4))
Accessing Elements
Tuple.fst
(a, b) -> a
Returns the first element of a pair.
pair = (10, 20)
println (Tuple.fst pair)
# => 10
Tuple.snd
(a, b) -> b
Returns the second element of a pair.
pair = (10, 20)
println (Tuple.snd pair)
# => 20
Tuple.first
Tuple -> a
Returns the first element of a tuple (works with tuples of any size).
t = (1, 2, 3)
println (Tuple.first t)
# => 1
Tuple.second
Tuple -> a
Returns the second element of a tuple.
t = (1, 2, 3)
println (Tuple.second t)
# => 2
Tuple.last
Tuple -> a
Returns the last element of a tuple.
t = (1, 2, 3)
println (Tuple.last t)
# => 3
Pattern Matching
Destructuring Tuples
The most common way to work with tuples is through pattern matching, which lets you extract all elements at once.
Tuple Destructuring
(a, b) = tuple
Extract tuple elements into individual bindings using pattern matching.
# Simple destructuring
(x, y) = (10, 20)
println x # => 10
println y # => 20
# In function parameters
add-point = fn((x1, y1), (x2, y2)) =>
(x1 + x2, y1 + y2)
result = add-point (1, 2) (3, 4)
println result
# => (4, 6)
Match Expression
match tuple | pattern -> result
Use pattern matching in match expressions for conditional logic based on tuple contents.
describe = fn(point) =>
match point
| (0, 0) -> "origin"
| (0, _) -> "on y-axis"
| (_, 0) -> "on x-axis"
| (x, y) -> "point at (${x}, ${y})"
println (describe (0, 0)) # => "origin"
println (describe (3, 4)) # => "point at (3, 4)"
Common Use Cases
Tuples are frequently used for:
- Returning multiple values from functions
- Key-value pairs in map operations
- Coordinates and points
- Grouping related values without defining a record