Concepts of Programming Languages

(Sean Pound) #1

268 Chapter 6 Data Types


Fortran, Ada, C#, and F# support rectangular arrays. (C# and F# also support
jagged arrays.) In these cases, all subscript expressions in references to elements
are placed in a single pair of brackets. For example,

myArray[3, 7]

6.5.7 Slices


A slice of an array is some substructure of that array. For example, if A is a
matrix, then the first row of A is one possible slice, as are the last row and the
first column. It is important to realize that a slice is not a new data type. Rather,
it is a mechanism for referencing part of an array as a unit. If arrays cannot be
manipulated as units in a language, that language has no use for slices.
Consider the following Python declarations:

vector = [2, 4, 6, 8, 10, 12, 14, 16]
mat = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]

Recall that the default lower bound for Python arrays is 0. The syntax of a
Python slice reference is a pair of numeric expressions separated by a colon. The
first is the first subscript of the slice; the second is the first subscript after the last
subscript in the slice. Therefore, vector[3:6] is a three-element array with the
fourth through sixth elements of vector (those elements with the subscripts 3 ,
4 , and 5 ). A row of a matrix is specified by giving just one subscript. For example,
mat[1] refers to the second row of mat; a part of a row can be specified with the
same syntax as a part of a single dimensioned array. For example, mat[0][0:2]
refers to the first and second element of the first row of mat, which is [1, 2].
Python also supports more complex slices of arrays. For example, vec-
tor[0:7:2] references every other element of vector, up to but not includ-
ing the element with the subscript 7, starting with the subscript 0 , which is
[2, 6, 10, 14].
Perl supports slices of two forms, a list of specific subscripts or a range of
subscripts. For example,

@list[1..5] = @list2[3, 5, 7, 9, 13];

Notice that slice references use array names, not scalar names, because slices
are arrays (not scalars).
Ruby supports slices with the slice method of its Array object, which
can take three forms of parameters. A single integer expression parameter is
interpreted as a subscript, in which case slice returns the element with the
given subscript. If slice is given two integer expression parameters, the first is
interpreted as a beginning subscript and the second is interpreted as the num-
ber of elements in the slice. For example, suppose list is defined as follows:

list = [2, 4, 6, 8, 10]
Free download pdf