Tuples and Named Tuples
Prerequisites: Arrays
A tuple is a fixed-size, immutable group of values, written with parentheses:
point = (3, 4)
println(point[1], " ", point[2], " ", length(point))
println(typeof(point))
x, y = point
println("x=$x y=$y")
mixed = ("Ada", 36, true)
println(typeof(mixed))
single = (42,)
println(typeof(single))
3 4 2
Tuple{Int64, Int64}
x=3 y=4
Tuple{String, Int64, Bool}
Tuple{Int64}
- A tuple's type records the type of each element.
- Destructuring:
x, y = pointunpacks a tuple into variables. - A one-element tuple needs a trailing comma:
(42,). - Tuples can't be changed after creation —
point[1] = 5is an error. That makes them cheap and fast.
Named tuples
A named tuple gives each value a name:
person = (name = "Ada", born = 1815)
println(person.name, " ", person[:born], " ", person[2])
println(keys(person))
println(person)
older = (; person..., born = 1800)
println(older)
name = "Grace"; born = 1906
p2 = (; name, born)
println(p2)
Ada 1815 1815
(:name, :born)
(name = "Ada", born = 1815)
(name = "Ada", born = 1800)
(name = "Grace", born = 1906)
- Access fields with
.name, by symbol[:name], or by position. (; person..., born = 1800)makes a copy with one field changed.(; name, born)builds a named tuple from variables with the same names.
Returning several values
Functions return several values by returning a tuple:
function min_max(xs)
return minimum(xs), maximum(xs)
end
lo, hi = min_max([5, 3, 9, 1])
println(lo, " ", hi)
stats = (count = 4, mean = 4.5)
println("n=$(stats.count), mean=$(stats.mean)")
1 9
n=4, mean=4.5
Named tuples are a lightweight way to return labeled results without defining a new type.