Tuples

A tuple is a fixed-sized group of values, separated by commas and optionally surrounded by parentheses ( ). The type of these values can be the same, but it doesn't have to be; a tuple can contain values of different types, unlike arrays. A tuple is a heterogeneous container, whereas an array is a homogeneous container. The type of a tuple is just a tuple of the types of the values it contains. So, in this sense, a tuple is very much the counterpart of an array in Julia. Also, changing a value in a tuple is not allowed; tuples are immutable.

In Chapter 2, Variables, Types, and Operations, we saw fast assignment, which is made possible by tuples:

// code in Chapter 5	uples.jl:
a, b, c, d = 1, 22.0, "World", 'x'

This expression assigns a value 1, b becomes 22.0, c takes up the value World, and d becomes x.

The expression returns a tuple (1, 22.0,"World",'x'), as the REPL shows as follows:

If we assign this tuple to a variable t1 and ask for its type, we get the following result:

typeof(t1) #> Tuple{Int64,Float64,String,Char}

The argument list of a function (refer to the Defining functions section in Chapter 3, Functions) is, in fact, also a tuple. Similarly, Julia simulates the possibility of returning multiple values by packaging them into a single tuple, and a tuple also appears when using functions with variable argument lists. ( ) represents the empty tuple, and (1,) is a one-element tuple. The type of a tuple can be specified explicitly through a type annotation (refer to the Types section in Chapter 2, Variables, Types, and Operations), such as ('z', 3.14)::Tuple{Char, Float64}.

The following snippet shows that we can index tuples in the same way as arrays by using brackets, indexing starting from 1, slicing, and index control:

t3 = (5, 6, 7, 8) 
t3[1] #> 5 
t3[end] #> 8 
t3[2:3] #> (6, 7) 
t3[5] #> BoundsError: attempt to access (5, 6, 7, 8) at index [5]
t3[3] = 9 #> Error: 'setindex' has no matching ... author = ("Ivo", "Balbaert", 62) author[2] #> "Balbaert"

To iterate over the elements of a tuple, use a for loop:

for i in t3 
    println(i) 
end # #> 5  6  7  8 

A tuple can be unpacked or deconstructed like this: a, b = t3; now a is 5 and b is 6. Notice that we don't get an error despite the left-hand side not being able to take all the values of t3. To do this, we would have to write a, b, c, d = t3.

In the preceding example, the elements of the author tuple are unpacked into separate variables: first_name, last_name, and age = author.

So, tuples are nice and simple types that make a lot of things possible. We'll find them again in the next section as elements of a dictionary.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.206.112