Wednesday, 30 March 2016

Julia: Tuples


Tuple is a collection of values separated by comma and optionally surrounded by parentheses. Unlike arrays, tuple is immutable, you can’t change the value in a tuple.
julia> a,b=10,20
(10,20)

julia> a
10

julia> b
20

julia> (a,b)=(10,20)
(10,20)

julia> a
10

julia> b
20


You can get the type of every element in a tuple using typeof operator.
julia> tuple1=(1,2.3,"Hi",true,3+10im)
(1,2.3,"Hi",true,3 + 10im)

julia> typeof(tuple1)
Tuple{Int64,Float64,ASCIIString,Bool,Complex{Int64}}
 
Access elements of tuples
It is just like arrays, you can access the elements of tuple using index notation.
julia> tuple1
(1,2.3,"Hi",true,3 + 10im)

julia> tuple1[1]
1

julia> tuple1[2]
2.3

julia> tuple1[3]
"Hi"

julia> tuple1[end]
3 + 10im


tuple[1] gets the element at 1st position, tuple[2] gets the element at 2nd position and tuple[end] gets the element at last position.

Iterate over the elements of tuple
julia> for i in tuple1
           println(i)
       end
1
2.3
Hi
true
3 + 10im


We can unpack the variables of tuple like below also.
julia> tuple1
(1,2.3,"Hi",true,3 + 10im)

julia> a,b=tuple1
(1,2.3,"Hi",true,3 + 10im)

julia> a
1

julia> b
2.3

julia> (a,b,c,d)=tuple1
(1,2.3,"Hi",true,3 + 10im)

julia> a
1

julia> b
2.3

julia> c
"Hi"

julia> d
true







Previous                                                 Next                                                 Home

No comments:

Post a Comment