Tuples in Julia

Due to functions being chosen via multiple-dispatch, tuples are inextricably linked to functions. Tuples decide which function is to be chosen for execution as well as what is later returned. Hence, tuples are in fact rendered immutable. That is, once defined, you cannot modify a tuple:

julia> x=(1,2,3)
(1, 2, 3)

julia> x[1]
1

julia> x[1]=10
ERROR: MethodError: no method matching setindex!(::Tuple{Int64,Int64,Int64}, ::Int64, ::Int64)
Stacktrace:
 [1] top-level scope at REPL[70]:1

Again, remembering the link to functions, we have named tuples

julia> x = (a=1, b="two")
(a = 1, b = "two")

julia> x[1],x[2]
(1, "two")

julia> x.a #We can use Javascript-like syntax to access tuple's elements
1

Another familiar way of accessing the values of a tuple is destructuring:

julia> first,second=x
(a = 1, b = "two")

julia> first
1

julia> second
"two"

That’s a wrap! In the next article we’ll talk about dictionaries and sets in Julia.

References

  1. Julia Docs

Leave a Reply

Your email address will not be published. Required fields are marked *