Skip to content

Tuples

In Zolo, tuples are represented as arrays at the value level. What sets them apart is how they are used: instead of accessing by index, you destructure with let (a, b, c) = ....

This is especially useful for returning multiple values from a function:

Destructuring a literal, multiple return values, iterating over pairs, and nesting.

03-tuples.zolo
Playground
// Feature: Tuples — group positional values

// Syntax: literal = array `[a, b, c]`; destructuring `let (a,b,c) = ...`

// When to use: group 2-3 related values without naming; return

// multiple values; iterate over pairs.

//

// In Zolo, tuples at the value-site are represented as arrays.

// Positional destructuring is the idiomatic way to extract.


// Destructure directly from a literal.

let (a, b, c) = [1, "alice", true]
print(a)  // 1

print(b)  // alice

print(c)  // true


// Useful for multi-return (see 05-functions/05-multi-return).

fn min_max(arr: [int]) -> [int] {
  var lo = arr[0]
  var hi = arr[0]
  for x in arr {
    if x < lo { lo = x }
    if x > hi { hi = x }
  }
  return [lo, hi]
}

let (lo, hi) = min_max([3, 1, 4, 1, 5, 9, 2, 6])
print("lo={lo} hi={hi}")  // lo=1 hi=9


// Destructure in a loop over an array of pairs.

let pairs = [[1, 2], [3, 4], [5, 6]]
for pair in pairs {
  let (l, r) = pair
  print("{l},{r}")
}

// expected:

// 1,2

// 3,4

// 5,6


// Tuples as "lightweight records" — group data without a struct.

let person = ["Alice", 30, "[email protected]"]
let (name, age, email) = person
print("{name} ({age}) <{email}>")

// Nesting: array of tuples.

let grid = [[0, 0, "a"], [0, 1, "b"], [1, 0, "c"], [1, 1, "d"]]
for cell in grid {
  let (x, y, label) = cell
  print("({x},{y}) = {label}")
}

Pattern summary:

  • let (a, b) = [1, 2] — extracts a = 1, b = 2.
  • Functions returning [T] with two elements become "tuples" at the call site.
  • For groups with 3+ named fields, prefer a struct — the names make the code more readable.

See also

enespt-br