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]

julia> x[1]=10
ERROR: MethodError: no method matching setindex!(::Tuple{Int64,Int64,Int64}, ::Int64, ::Int64)
 [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

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

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

julia> first

julia> second

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


  1. Julia Docs

Leave a Reply

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